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.

283540 lines
7.7MB

  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 int");
  1868. AtomicTester <int>::testInteger (*this);
  1869. beginTest ("Atomic unsigned int");
  1870. AtomicTester <unsigned int>::testInteger (*this);
  1871. beginTest ("Atomic int32");
  1872. AtomicTester <int32>::testInteger (*this);
  1873. beginTest ("Atomic uint32");
  1874. AtomicTester <uint32>::testInteger (*this);
  1875. beginTest ("Atomic long");
  1876. AtomicTester <long>::testInteger (*this);
  1877. beginTest ("Atomic void*");
  1878. AtomicTester <void*>::testInteger (*this);
  1879. beginTest ("Atomic int*");
  1880. AtomicTester <int*>::testInteger (*this);
  1881. beginTest ("Atomic float");
  1882. AtomicTester <float>::testFloat (*this);
  1883. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1884. beginTest ("Atomic int64");
  1885. AtomicTester <int64>::testInteger (*this);
  1886. beginTest ("Atomic uint64");
  1887. AtomicTester <uint64>::testInteger (*this);
  1888. beginTest ("Atomic double");
  1889. AtomicTester <double>::testFloat (*this);
  1890. #endif
  1891. }
  1892. template <typename Type>
  1893. class AtomicTester
  1894. {
  1895. public:
  1896. AtomicTester() {}
  1897. static void testInteger (UnitTest& test)
  1898. {
  1899. Atomic<Type> a, b;
  1900. a.set ((Type) 10);
  1901. test.expect (a.value == (Type) 10);
  1902. test.expect (a.get() == (Type) 10);
  1903. a += (Type) 15;
  1904. test.expect (a.get() == (Type) 25);
  1905. a.memoryBarrier();
  1906. a -= (Type) 5;
  1907. test.expect (a.get() == (Type) 20);
  1908. test.expect (++a == (Type) 21);
  1909. ++a;
  1910. test.expect (--a == (Type) 21);
  1911. test.expect (a.get() == (Type) 21);
  1912. a.memoryBarrier();
  1913. testFloat (test);
  1914. }
  1915. static void testFloat (UnitTest& test)
  1916. {
  1917. Atomic<Type> a, b;
  1918. a = (Type) 21;
  1919. a.memoryBarrier();
  1920. /* These are some simple test cases to check the atomics - let me know
  1921. if any of these assertions fail on your system!
  1922. */
  1923. test.expect (a.get() == (Type) 21);
  1924. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1925. test.expect (a.get() == (Type) 21);
  1926. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1927. test.expect (a.get() == (Type) 101);
  1928. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1929. test.expect (a.get() == (Type) 101);
  1930. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1931. test.expect (a.get() == (Type) 200);
  1932. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1933. test.expect (a.get() == (Type) 300);
  1934. b = a;
  1935. test.expect (b.get() == a.get());
  1936. }
  1937. };
  1938. };
  1939. static AtomicTests atomicUnitTests;
  1940. #endif
  1941. END_JUCE_NAMESPACE
  1942. /*** End of inlined file: juce_Initialisation.cpp ***/
  1943. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1944. BEGIN_JUCE_NAMESPACE
  1945. AbstractFifo::AbstractFifo (const int capacity) throw()
  1946. : bufferSize (capacity)
  1947. {
  1948. jassert (bufferSize > 0);
  1949. }
  1950. AbstractFifo::~AbstractFifo() {}
  1951. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1952. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1953. int AbstractFifo::getNumReady() const throw()
  1954. {
  1955. const int vs = validStart.get();
  1956. const int ve = validEnd.get();
  1957. return ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  1958. }
  1959. void AbstractFifo::reset() throw()
  1960. {
  1961. validEnd = 0;
  1962. validStart = 0;
  1963. }
  1964. void AbstractFifo::setTotalSize (int newSize) throw()
  1965. {
  1966. jassert (newSize > 0);
  1967. reset();
  1968. bufferSize = newSize;
  1969. }
  1970. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1971. {
  1972. const int vs = validStart.get();
  1973. const int ve = validEnd.value;
  1974. const int freeSpace = ve >= vs ? (bufferSize - (ve - vs)) : (vs - ve);
  1975. numToWrite = jmin (numToWrite, freeSpace - 1);
  1976. if (numToWrite <= 0)
  1977. {
  1978. startIndex1 = 0;
  1979. startIndex2 = 0;
  1980. blockSize1 = 0;
  1981. blockSize2 = 0;
  1982. }
  1983. else
  1984. {
  1985. startIndex1 = ve;
  1986. startIndex2 = 0;
  1987. blockSize1 = jmin (bufferSize - ve, numToWrite);
  1988. numToWrite -= blockSize1;
  1989. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, vs);
  1990. }
  1991. }
  1992. void AbstractFifo::finishedWrite (int numWritten) throw()
  1993. {
  1994. jassert (numWritten >= 0 && numWritten < bufferSize);
  1995. int newEnd = validEnd.value + numWritten;
  1996. if (newEnd >= bufferSize)
  1997. newEnd -= bufferSize;
  1998. validEnd = newEnd;
  1999. }
  2000. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  2001. {
  2002. const int vs = validStart.value;
  2003. const int ve = validEnd.get();
  2004. const int numReady = ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  2005. numWanted = jmin (numWanted, numReady);
  2006. if (numWanted <= 0)
  2007. {
  2008. startIndex1 = 0;
  2009. startIndex2 = 0;
  2010. blockSize1 = 0;
  2011. blockSize2 = 0;
  2012. }
  2013. else
  2014. {
  2015. startIndex1 = vs;
  2016. startIndex2 = 0;
  2017. blockSize1 = jmin (bufferSize - vs, numWanted);
  2018. numWanted -= blockSize1;
  2019. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, ve);
  2020. }
  2021. }
  2022. void AbstractFifo::finishedRead (int numRead) throw()
  2023. {
  2024. jassert (numRead >= 0 && numRead <= bufferSize);
  2025. int newStart = validStart.value + numRead;
  2026. if (newStart >= bufferSize)
  2027. newStart -= bufferSize;
  2028. validStart = newStart;
  2029. }
  2030. #if JUCE_UNIT_TESTS
  2031. class AbstractFifoTests : public UnitTest
  2032. {
  2033. public:
  2034. AbstractFifoTests() : UnitTest ("Abstract Fifo") {}
  2035. class WriteThread : public Thread
  2036. {
  2037. public:
  2038. WriteThread (AbstractFifo& fifo_, int* buffer_)
  2039. : Thread ("fifo writer"), fifo (fifo_), buffer (buffer_)
  2040. {
  2041. startThread();
  2042. }
  2043. ~WriteThread()
  2044. {
  2045. stopThread (5000);
  2046. }
  2047. void run()
  2048. {
  2049. int n = 0;
  2050. while (! threadShouldExit())
  2051. {
  2052. int num = Random::getSystemRandom().nextInt (2000) + 1;
  2053. int start1, size1, start2, size2;
  2054. fifo.prepareToWrite (num, start1, size1, start2, size2);
  2055. jassert (size1 >= 0 && size2 >= 0);
  2056. jassert (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()));
  2057. jassert (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize()));
  2058. int i;
  2059. for (i = 0; i < size1; ++i)
  2060. buffer [start1 + i] = n++;
  2061. for (i = 0; i < size2; ++i)
  2062. buffer [start2 + i] = n++;
  2063. fifo.finishedWrite (size1 + size2);
  2064. }
  2065. }
  2066. private:
  2067. AbstractFifo& fifo;
  2068. int* buffer;
  2069. };
  2070. void runTest()
  2071. {
  2072. beginTest ("AbstractFifo");
  2073. int buffer [5000];
  2074. AbstractFifo fifo (numElementsInArray (buffer));
  2075. WriteThread writer (fifo, buffer);
  2076. int n = 0;
  2077. for (int count = 1000000; --count >= 0;)
  2078. {
  2079. int num = Random::getSystemRandom().nextInt (6000) + 1;
  2080. int start1, size1, start2, size2;
  2081. fifo.prepareToRead (num, start1, size1, start2, size2);
  2082. if (! (size1 >= 0 && size2 >= 0)
  2083. && (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()))
  2084. && (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize())))
  2085. {
  2086. expect (false, "prepareToRead returned -ve values");
  2087. break;
  2088. }
  2089. bool failed = false;
  2090. int i;
  2091. for (i = 0; i < size1; ++i)
  2092. failed = (buffer [start1 + i] != n++) || failed;
  2093. for (i = 0; i < size2; ++i)
  2094. failed = (buffer [start2 + i] != n++) || failed;
  2095. if (failed)
  2096. {
  2097. expect (false, "read values were incorrect");
  2098. break;
  2099. }
  2100. fifo.finishedRead (size1 + size2);
  2101. }
  2102. }
  2103. };
  2104. static AbstractFifoTests fifoUnitTests;
  2105. #endif
  2106. END_JUCE_NAMESPACE
  2107. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2108. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2109. BEGIN_JUCE_NAMESPACE
  2110. BigInteger::BigInteger()
  2111. : numValues (4),
  2112. highestBit (-1),
  2113. negative (false)
  2114. {
  2115. values.calloc (numValues + 1);
  2116. }
  2117. BigInteger::BigInteger (const int32 value)
  2118. : numValues (4),
  2119. highestBit (31),
  2120. negative (value < 0)
  2121. {
  2122. values.calloc (numValues + 1);
  2123. values[0] = abs (value);
  2124. highestBit = getHighestBit();
  2125. }
  2126. BigInteger::BigInteger (const uint32 value)
  2127. : numValues (4),
  2128. highestBit (31),
  2129. negative (false)
  2130. {
  2131. values.calloc (numValues + 1);
  2132. values[0] = value;
  2133. highestBit = getHighestBit();
  2134. }
  2135. BigInteger::BigInteger (int64 value)
  2136. : numValues (4),
  2137. highestBit (63),
  2138. negative (value < 0)
  2139. {
  2140. values.calloc (numValues + 1);
  2141. if (value < 0)
  2142. value = -value;
  2143. values[0] = (uint32) value;
  2144. values[1] = (uint32) (value >> 32);
  2145. highestBit = getHighestBit();
  2146. }
  2147. BigInteger::BigInteger (const BigInteger& other)
  2148. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2149. highestBit (other.getHighestBit()),
  2150. negative (other.negative)
  2151. {
  2152. values.malloc (numValues + 1);
  2153. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2154. }
  2155. BigInteger::~BigInteger()
  2156. {
  2157. }
  2158. void BigInteger::swapWith (BigInteger& other) throw()
  2159. {
  2160. values.swapWith (other.values);
  2161. swapVariables (numValues, other.numValues);
  2162. swapVariables (highestBit, other.highestBit);
  2163. swapVariables (negative, other.negative);
  2164. }
  2165. BigInteger& BigInteger::operator= (const BigInteger& other)
  2166. {
  2167. if (this != &other)
  2168. {
  2169. highestBit = other.getHighestBit();
  2170. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2171. negative = other.negative;
  2172. values.malloc (numValues + 1);
  2173. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2174. }
  2175. return *this;
  2176. }
  2177. void BigInteger::ensureSize (const int numVals)
  2178. {
  2179. if (numVals + 2 >= numValues)
  2180. {
  2181. int oldSize = numValues;
  2182. numValues = ((numVals + 2) * 3) / 2;
  2183. values.realloc (numValues + 1);
  2184. while (oldSize < numValues)
  2185. values [oldSize++] = 0;
  2186. }
  2187. }
  2188. bool BigInteger::operator[] (const int bit) const throw()
  2189. {
  2190. return bit <= highestBit && bit >= 0
  2191. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2192. }
  2193. int BigInteger::toInteger() const throw()
  2194. {
  2195. const int n = (int) (values[0] & 0x7fffffff);
  2196. return negative ? -n : n;
  2197. }
  2198. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2199. {
  2200. BigInteger r;
  2201. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2202. r.ensureSize (bitToIndex (numBits));
  2203. r.highestBit = numBits;
  2204. int i = 0;
  2205. while (numBits > 0)
  2206. {
  2207. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2208. numBits -= 32;
  2209. startBit += 32;
  2210. }
  2211. r.highestBit = r.getHighestBit();
  2212. return r;
  2213. }
  2214. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2215. {
  2216. if (numBits > 32)
  2217. {
  2218. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2219. numBits = 32;
  2220. }
  2221. numBits = jmin (numBits, highestBit + 1 - startBit);
  2222. if (numBits <= 0)
  2223. return 0;
  2224. const int pos = bitToIndex (startBit);
  2225. const int offset = startBit & 31;
  2226. const int endSpace = 32 - numBits;
  2227. uint32 n = ((uint32) values [pos]) >> offset;
  2228. if (offset > endSpace)
  2229. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2230. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2231. }
  2232. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2233. {
  2234. if (numBits > 32)
  2235. {
  2236. jassertfalse;
  2237. numBits = 32;
  2238. }
  2239. for (int i = 0; i < numBits; ++i)
  2240. {
  2241. setBit (startBit + i, (valueToSet & 1) != 0);
  2242. valueToSet >>= 1;
  2243. }
  2244. }
  2245. void BigInteger::clear()
  2246. {
  2247. if (numValues > 16)
  2248. {
  2249. numValues = 4;
  2250. values.calloc (numValues + 1);
  2251. }
  2252. else
  2253. {
  2254. zeromem (values, sizeof (uint32) * (numValues + 1));
  2255. }
  2256. highestBit = -1;
  2257. negative = false;
  2258. }
  2259. void BigInteger::setBit (const int bit)
  2260. {
  2261. if (bit >= 0)
  2262. {
  2263. if (bit > highestBit)
  2264. {
  2265. ensureSize (bitToIndex (bit));
  2266. highestBit = bit;
  2267. }
  2268. values [bitToIndex (bit)] |= bitToMask (bit);
  2269. }
  2270. }
  2271. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2272. {
  2273. if (shouldBeSet)
  2274. setBit (bit);
  2275. else
  2276. clearBit (bit);
  2277. }
  2278. void BigInteger::clearBit (const int bit) throw()
  2279. {
  2280. if (bit >= 0 && bit <= highestBit)
  2281. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2282. }
  2283. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2284. {
  2285. while (--numBits >= 0)
  2286. setBit (startBit++, shouldBeSet);
  2287. }
  2288. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2289. {
  2290. if (bit >= 0)
  2291. shiftBits (1, bit);
  2292. setBit (bit, shouldBeSet);
  2293. }
  2294. bool BigInteger::isZero() const throw()
  2295. {
  2296. return getHighestBit() < 0;
  2297. }
  2298. bool BigInteger::isOne() const throw()
  2299. {
  2300. return getHighestBit() == 0 && ! negative;
  2301. }
  2302. bool BigInteger::isNegative() const throw()
  2303. {
  2304. return negative && ! isZero();
  2305. }
  2306. void BigInteger::setNegative (const bool neg) throw()
  2307. {
  2308. negative = neg;
  2309. }
  2310. void BigInteger::negate() throw()
  2311. {
  2312. negative = (! negative) && ! isZero();
  2313. }
  2314. #if JUCE_USE_INTRINSICS
  2315. #pragma intrinsic (_BitScanReverse)
  2316. #endif
  2317. namespace BitFunctions
  2318. {
  2319. inline int countBitsInInt32 (uint32 n) throw()
  2320. {
  2321. n -= ((n >> 1) & 0x55555555);
  2322. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2323. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2324. n += (n >> 8);
  2325. n += (n >> 16);
  2326. return n & 0x3f;
  2327. }
  2328. inline int highestBitInInt (uint32 n) throw()
  2329. {
  2330. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2331. #if JUCE_GCC
  2332. return 31 - __builtin_clz (n);
  2333. #elif JUCE_USE_INTRINSICS
  2334. unsigned long highest;
  2335. _BitScanReverse (&highest, n);
  2336. return (int) highest;
  2337. #else
  2338. n |= (n >> 1);
  2339. n |= (n >> 2);
  2340. n |= (n >> 4);
  2341. n |= (n >> 8);
  2342. n |= (n >> 16);
  2343. return countBitsInInt32 (n >> 1);
  2344. #endif
  2345. }
  2346. }
  2347. int BigInteger::countNumberOfSetBits() const throw()
  2348. {
  2349. int total = 0;
  2350. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2351. total += BitFunctions::countBitsInInt32 (values[i]);
  2352. return total;
  2353. }
  2354. int BigInteger::getHighestBit() const throw()
  2355. {
  2356. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2357. {
  2358. const uint32 n = values[i];
  2359. if (n != 0)
  2360. return BitFunctions::highestBitInInt (n) + (i << 5);
  2361. }
  2362. return -1;
  2363. }
  2364. int BigInteger::findNextSetBit (int i) const throw()
  2365. {
  2366. for (; i <= highestBit; ++i)
  2367. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2368. return i;
  2369. return -1;
  2370. }
  2371. int BigInteger::findNextClearBit (int i) const throw()
  2372. {
  2373. for (; i <= highestBit; ++i)
  2374. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2375. break;
  2376. return i;
  2377. }
  2378. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2379. {
  2380. if (other.isNegative())
  2381. return operator-= (-other);
  2382. if (isNegative())
  2383. {
  2384. if (compareAbsolute (other) < 0)
  2385. {
  2386. BigInteger temp (*this);
  2387. temp.negate();
  2388. *this = other;
  2389. operator-= (temp);
  2390. }
  2391. else
  2392. {
  2393. negate();
  2394. operator-= (other);
  2395. negate();
  2396. }
  2397. }
  2398. else
  2399. {
  2400. if (other.highestBit > highestBit)
  2401. highestBit = other.highestBit;
  2402. ++highestBit;
  2403. const int numInts = bitToIndex (highestBit) + 1;
  2404. ensureSize (numInts);
  2405. int64 remainder = 0;
  2406. for (int i = 0; i <= numInts; ++i)
  2407. {
  2408. if (i < numValues)
  2409. remainder += values[i];
  2410. if (i < other.numValues)
  2411. remainder += other.values[i];
  2412. values[i] = (uint32) remainder;
  2413. remainder >>= 32;
  2414. }
  2415. jassert (remainder == 0);
  2416. highestBit = getHighestBit();
  2417. }
  2418. return *this;
  2419. }
  2420. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2421. {
  2422. if (other.isNegative())
  2423. return operator+= (-other);
  2424. if (! isNegative())
  2425. {
  2426. if (compareAbsolute (other) < 0)
  2427. {
  2428. BigInteger temp (other);
  2429. swapWith (temp);
  2430. operator-= (temp);
  2431. negate();
  2432. return *this;
  2433. }
  2434. }
  2435. else
  2436. {
  2437. negate();
  2438. operator+= (other);
  2439. negate();
  2440. return *this;
  2441. }
  2442. const int numInts = bitToIndex (highestBit) + 1;
  2443. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2444. int64 amountToSubtract = 0;
  2445. for (int i = 0; i <= numInts; ++i)
  2446. {
  2447. if (i <= maxOtherInts)
  2448. amountToSubtract += (int64) other.values[i];
  2449. if (values[i] >= amountToSubtract)
  2450. {
  2451. values[i] = (uint32) (values[i] - amountToSubtract);
  2452. amountToSubtract = 0;
  2453. }
  2454. else
  2455. {
  2456. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2457. values[i] = (uint32) n;
  2458. amountToSubtract = 1;
  2459. }
  2460. }
  2461. return *this;
  2462. }
  2463. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2464. {
  2465. BigInteger total;
  2466. highestBit = getHighestBit();
  2467. const bool wasNegative = isNegative();
  2468. setNegative (false);
  2469. for (int i = 0; i <= highestBit; ++i)
  2470. {
  2471. if (operator[](i))
  2472. {
  2473. BigInteger n (other);
  2474. n.setNegative (false);
  2475. n <<= i;
  2476. total += n;
  2477. }
  2478. }
  2479. total.setNegative (wasNegative ^ other.isNegative());
  2480. swapWith (total);
  2481. return *this;
  2482. }
  2483. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2484. {
  2485. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2486. const int divHB = divisor.getHighestBit();
  2487. const int ourHB = getHighestBit();
  2488. if (divHB < 0 || ourHB < 0)
  2489. {
  2490. // division by zero
  2491. remainder.clear();
  2492. clear();
  2493. }
  2494. else
  2495. {
  2496. const bool wasNegative = isNegative();
  2497. swapWith (remainder);
  2498. remainder.setNegative (false);
  2499. clear();
  2500. BigInteger temp (divisor);
  2501. temp.setNegative (false);
  2502. int leftShift = ourHB - divHB;
  2503. temp <<= leftShift;
  2504. while (leftShift >= 0)
  2505. {
  2506. if (remainder.compareAbsolute (temp) >= 0)
  2507. {
  2508. remainder -= temp;
  2509. setBit (leftShift);
  2510. }
  2511. if (--leftShift >= 0)
  2512. temp >>= 1;
  2513. }
  2514. negative = wasNegative ^ divisor.isNegative();
  2515. remainder.setNegative (wasNegative);
  2516. }
  2517. }
  2518. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2519. {
  2520. BigInteger remainder;
  2521. divideBy (other, remainder);
  2522. return *this;
  2523. }
  2524. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2525. {
  2526. // this operation doesn't take into account negative values..
  2527. jassert (isNegative() == other.isNegative());
  2528. if (other.highestBit >= 0)
  2529. {
  2530. ensureSize (bitToIndex (other.highestBit));
  2531. int n = bitToIndex (other.highestBit) + 1;
  2532. while (--n >= 0)
  2533. values[n] |= other.values[n];
  2534. if (other.highestBit > highestBit)
  2535. highestBit = other.highestBit;
  2536. highestBit = getHighestBit();
  2537. }
  2538. return *this;
  2539. }
  2540. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2541. {
  2542. // this operation doesn't take into account negative values..
  2543. jassert (isNegative() == other.isNegative());
  2544. int n = numValues;
  2545. while (n > other.numValues)
  2546. values[--n] = 0;
  2547. while (--n >= 0)
  2548. values[n] &= other.values[n];
  2549. if (other.highestBit < highestBit)
  2550. highestBit = other.highestBit;
  2551. highestBit = getHighestBit();
  2552. return *this;
  2553. }
  2554. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2555. {
  2556. // this operation will only work with the absolute values
  2557. jassert (isNegative() == other.isNegative());
  2558. if (other.highestBit >= 0)
  2559. {
  2560. ensureSize (bitToIndex (other.highestBit));
  2561. int n = bitToIndex (other.highestBit) + 1;
  2562. while (--n >= 0)
  2563. values[n] ^= other.values[n];
  2564. if (other.highestBit > highestBit)
  2565. highestBit = other.highestBit;
  2566. highestBit = getHighestBit();
  2567. }
  2568. return *this;
  2569. }
  2570. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2571. {
  2572. BigInteger remainder;
  2573. divideBy (divisor, remainder);
  2574. swapWith (remainder);
  2575. return *this;
  2576. }
  2577. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2578. {
  2579. shiftBits (numBitsToShift, 0);
  2580. return *this;
  2581. }
  2582. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2583. {
  2584. return operator<<= (-numBitsToShift);
  2585. }
  2586. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2587. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2588. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2589. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2590. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2591. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2592. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2593. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2594. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2595. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2596. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2597. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2598. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2599. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2600. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2601. int BigInteger::compare (const BigInteger& other) const throw()
  2602. {
  2603. if (isNegative() == other.isNegative())
  2604. {
  2605. const int absComp = compareAbsolute (other);
  2606. return isNegative() ? -absComp : absComp;
  2607. }
  2608. else
  2609. {
  2610. return isNegative() ? -1 : 1;
  2611. }
  2612. }
  2613. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2614. {
  2615. const int h1 = getHighestBit();
  2616. const int h2 = other.getHighestBit();
  2617. if (h1 > h2)
  2618. return 1;
  2619. else if (h1 < h2)
  2620. return -1;
  2621. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2622. if (values[i] != other.values[i])
  2623. return (values[i] > other.values[i]) ? 1 : -1;
  2624. return 0;
  2625. }
  2626. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2627. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2628. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2629. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2630. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2631. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2632. void BigInteger::shiftBits (int bits, const int startBit)
  2633. {
  2634. if (highestBit < 0)
  2635. return;
  2636. if (startBit > 0)
  2637. {
  2638. if (bits < 0)
  2639. {
  2640. // right shift
  2641. for (int i = startBit; i <= highestBit; ++i)
  2642. setBit (i, operator[] (i - bits));
  2643. highestBit = getHighestBit();
  2644. }
  2645. else if (bits > 0)
  2646. {
  2647. // left shift
  2648. for (int i = highestBit + 1; --i >= startBit;)
  2649. setBit (i + bits, operator[] (i));
  2650. while (--bits >= 0)
  2651. clearBit (bits + startBit);
  2652. }
  2653. }
  2654. else
  2655. {
  2656. if (bits < 0)
  2657. {
  2658. // right shift
  2659. bits = -bits;
  2660. if (bits > highestBit)
  2661. {
  2662. clear();
  2663. }
  2664. else
  2665. {
  2666. const int wordsToMove = bitToIndex (bits);
  2667. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2668. highestBit -= bits;
  2669. if (wordsToMove > 0)
  2670. {
  2671. int i;
  2672. for (i = 0; i < top; ++i)
  2673. values [i] = values [i + wordsToMove];
  2674. for (i = 0; i < wordsToMove; ++i)
  2675. values [top + i] = 0;
  2676. bits &= 31;
  2677. }
  2678. if (bits != 0)
  2679. {
  2680. const int invBits = 32 - bits;
  2681. --top;
  2682. for (int i = 0; i < top; ++i)
  2683. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2684. values[top] = (values[top] >> bits);
  2685. }
  2686. highestBit = getHighestBit();
  2687. }
  2688. }
  2689. else if (bits > 0)
  2690. {
  2691. // left shift
  2692. ensureSize (bitToIndex (highestBit + bits) + 1);
  2693. const int wordsToMove = bitToIndex (bits);
  2694. int top = 1 + bitToIndex (highestBit);
  2695. highestBit += bits;
  2696. if (wordsToMove > 0)
  2697. {
  2698. int i;
  2699. for (i = top; --i >= 0;)
  2700. values [i + wordsToMove] = values [i];
  2701. for (i = 0; i < wordsToMove; ++i)
  2702. values [i] = 0;
  2703. bits &= 31;
  2704. }
  2705. if (bits != 0)
  2706. {
  2707. const int invBits = 32 - bits;
  2708. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2709. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2710. values [wordsToMove] = values [wordsToMove] << bits;
  2711. }
  2712. highestBit = getHighestBit();
  2713. }
  2714. }
  2715. }
  2716. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2717. {
  2718. while (! m->isZero())
  2719. {
  2720. if (n->compareAbsolute (*m) > 0)
  2721. swapVariables (m, n);
  2722. *m -= *n;
  2723. }
  2724. return *n;
  2725. }
  2726. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2727. {
  2728. BigInteger m (*this);
  2729. while (! n.isZero())
  2730. {
  2731. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2732. return simpleGCD (&m, &n);
  2733. BigInteger temp1 (m), temp2;
  2734. temp1.divideBy (n, temp2);
  2735. m = n;
  2736. n = temp2;
  2737. }
  2738. return m;
  2739. }
  2740. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2741. {
  2742. BigInteger exp (exponent);
  2743. exp %= modulus;
  2744. BigInteger value (1);
  2745. swapWith (value);
  2746. value %= modulus;
  2747. while (! exp.isZero())
  2748. {
  2749. if (exp [0])
  2750. {
  2751. operator*= (value);
  2752. operator%= (modulus);
  2753. }
  2754. value *= value;
  2755. value %= modulus;
  2756. exp >>= 1;
  2757. }
  2758. }
  2759. void BigInteger::inverseModulo (const BigInteger& modulus)
  2760. {
  2761. if (modulus.isOne() || modulus.isNegative())
  2762. {
  2763. clear();
  2764. return;
  2765. }
  2766. if (isNegative() || compareAbsolute (modulus) >= 0)
  2767. operator%= (modulus);
  2768. if (isOne())
  2769. return;
  2770. if (! (*this)[0])
  2771. {
  2772. // not invertible
  2773. clear();
  2774. return;
  2775. }
  2776. BigInteger a1 (modulus);
  2777. BigInteger a2 (*this);
  2778. BigInteger b1 (modulus);
  2779. BigInteger b2 (1);
  2780. while (! a2.isOne())
  2781. {
  2782. BigInteger temp1, temp2, multiplier (a1);
  2783. multiplier.divideBy (a2, temp1);
  2784. temp1 = a2;
  2785. temp1 *= multiplier;
  2786. temp2 = a1;
  2787. temp2 -= temp1;
  2788. a1 = a2;
  2789. a2 = temp2;
  2790. temp1 = b2;
  2791. temp1 *= multiplier;
  2792. temp2 = b1;
  2793. temp2 -= temp1;
  2794. b1 = b2;
  2795. b2 = temp2;
  2796. }
  2797. while (b2.isNegative())
  2798. b2 += modulus;
  2799. b2 %= modulus;
  2800. swapWith (b2);
  2801. }
  2802. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2803. {
  2804. return stream << value.toString (10);
  2805. }
  2806. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2807. {
  2808. String s;
  2809. BigInteger v (*this);
  2810. if (base == 2 || base == 8 || base == 16)
  2811. {
  2812. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2813. static const char* const hexDigits = "0123456789abcdef";
  2814. for (;;)
  2815. {
  2816. const int remainder = v.getBitRangeAsInt (0, bits);
  2817. v >>= bits;
  2818. if (remainder == 0 && v.isZero())
  2819. break;
  2820. s = String::charToString (hexDigits [remainder]) + s;
  2821. }
  2822. }
  2823. else if (base == 10)
  2824. {
  2825. const BigInteger ten (10);
  2826. BigInteger remainder;
  2827. for (;;)
  2828. {
  2829. v.divideBy (ten, remainder);
  2830. if (remainder.isZero() && v.isZero())
  2831. break;
  2832. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2833. }
  2834. }
  2835. else
  2836. {
  2837. jassertfalse; // can't do the specified base!
  2838. return String::empty;
  2839. }
  2840. s = s.paddedLeft ('0', minimumNumCharacters);
  2841. return isNegative() ? "-" + s : s;
  2842. }
  2843. void BigInteger::parseString (const String& text, const int base)
  2844. {
  2845. clear();
  2846. String::CharPointerType t (text.getCharPointer());
  2847. if (base == 2 || base == 8 || base == 16)
  2848. {
  2849. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2850. for (;;)
  2851. {
  2852. const juce_wchar c = t.getAndAdvance();
  2853. const int digit = CharacterFunctions::getHexDigitValue (c);
  2854. if (((uint32) digit) < (uint32) base)
  2855. {
  2856. operator<<= (bits);
  2857. operator+= (digit);
  2858. }
  2859. else if (c == 0)
  2860. {
  2861. break;
  2862. }
  2863. }
  2864. }
  2865. else if (base == 10)
  2866. {
  2867. const BigInteger ten ((uint32) 10);
  2868. for (;;)
  2869. {
  2870. const juce_wchar c = t.getAndAdvance();
  2871. if (c >= '0' && c <= '9')
  2872. {
  2873. operator*= (ten);
  2874. operator+= ((int) (c - '0'));
  2875. }
  2876. else if (c == 0)
  2877. {
  2878. break;
  2879. }
  2880. }
  2881. }
  2882. setNegative (text.trimStart().startsWithChar ('-'));
  2883. }
  2884. const MemoryBlock BigInteger::toMemoryBlock() const
  2885. {
  2886. const int numBytes = (getHighestBit() + 8) >> 3;
  2887. MemoryBlock mb ((size_t) numBytes);
  2888. for (int i = 0; i < numBytes; ++i)
  2889. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2890. return mb;
  2891. }
  2892. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2893. {
  2894. clear();
  2895. for (int i = (int) data.getSize(); --i >= 0;)
  2896. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2897. }
  2898. END_JUCE_NAMESPACE
  2899. /*** End of inlined file: juce_BigInteger.cpp ***/
  2900. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2901. BEGIN_JUCE_NAMESPACE
  2902. MemoryBlock::MemoryBlock() throw()
  2903. : size (0)
  2904. {
  2905. }
  2906. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2907. {
  2908. if (initialSize > 0)
  2909. {
  2910. size = initialSize;
  2911. data.allocate (initialSize, initialiseToZero);
  2912. }
  2913. else
  2914. {
  2915. size = 0;
  2916. }
  2917. }
  2918. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2919. : size (other.size)
  2920. {
  2921. if (size > 0)
  2922. {
  2923. jassert (other.data != 0);
  2924. data.malloc (size);
  2925. memcpy (data, other.data, size);
  2926. }
  2927. }
  2928. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2929. : size (jmax ((size_t) 0, sizeInBytes))
  2930. {
  2931. jassert (sizeInBytes >= 0);
  2932. if (size > 0)
  2933. {
  2934. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2935. data.malloc (size);
  2936. if (dataToInitialiseFrom != 0)
  2937. memcpy (data, dataToInitialiseFrom, size);
  2938. }
  2939. }
  2940. MemoryBlock::~MemoryBlock() throw()
  2941. {
  2942. jassert (size >= 0); // should never happen
  2943. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2944. }
  2945. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2946. {
  2947. if (this != &other)
  2948. {
  2949. setSize (other.size, false);
  2950. memcpy (data, other.data, size);
  2951. }
  2952. return *this;
  2953. }
  2954. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2955. {
  2956. return matches (other.data, other.size);
  2957. }
  2958. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2959. {
  2960. return ! operator== (other);
  2961. }
  2962. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2963. {
  2964. return size == dataSize
  2965. && memcmp (data, dataToCompare, size) == 0;
  2966. }
  2967. // this will resize the block to this size
  2968. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2969. {
  2970. if (size != newSize)
  2971. {
  2972. if (newSize <= 0)
  2973. {
  2974. data.free();
  2975. size = 0;
  2976. }
  2977. else
  2978. {
  2979. if (data != 0)
  2980. {
  2981. data.realloc (newSize);
  2982. if (initialiseToZero && (newSize > size))
  2983. zeromem (data + size, newSize - size);
  2984. }
  2985. else
  2986. {
  2987. data.allocate (newSize, initialiseToZero);
  2988. }
  2989. size = newSize;
  2990. }
  2991. }
  2992. }
  2993. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2994. {
  2995. if (size < minimumSize)
  2996. setSize (minimumSize, initialiseToZero);
  2997. }
  2998. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2999. {
  3000. swapVariables (size, other.size);
  3001. data.swapWith (other.data);
  3002. }
  3003. void MemoryBlock::fillWith (const uint8 value) throw()
  3004. {
  3005. memset (data, (int) value, size);
  3006. }
  3007. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  3008. {
  3009. if (numBytes > 0)
  3010. {
  3011. const size_t oldSize = size;
  3012. setSize (size + numBytes);
  3013. memcpy (data + oldSize, srcData, numBytes);
  3014. }
  3015. }
  3016. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  3017. {
  3018. const char* d = static_cast<const char*> (src);
  3019. if (offset < 0)
  3020. {
  3021. d -= offset;
  3022. num -= offset;
  3023. offset = 0;
  3024. }
  3025. if (offset + num > size)
  3026. num = size - offset;
  3027. if (num > 0)
  3028. memcpy (data + offset, d, num);
  3029. }
  3030. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  3031. {
  3032. char* d = static_cast<char*> (dst);
  3033. if (offset < 0)
  3034. {
  3035. zeromem (d, -offset);
  3036. d -= offset;
  3037. num += offset;
  3038. offset = 0;
  3039. }
  3040. if (offset + num > size)
  3041. {
  3042. const size_t newNum = size - offset;
  3043. zeromem (d + newNum, num - newNum);
  3044. num = newNum;
  3045. }
  3046. if (num > 0)
  3047. memcpy (d, data + offset, num);
  3048. }
  3049. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  3050. {
  3051. if (startByte + numBytesToRemove >= size)
  3052. {
  3053. setSize (startByte);
  3054. }
  3055. else if (numBytesToRemove > 0)
  3056. {
  3057. memmove (data + startByte,
  3058. data + startByte + numBytesToRemove,
  3059. size - (startByte + numBytesToRemove));
  3060. setSize (size - numBytesToRemove);
  3061. }
  3062. }
  3063. const String MemoryBlock::toString() const
  3064. {
  3065. return String (static_cast <const char*> (getData()), size);
  3066. }
  3067. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  3068. {
  3069. int res = 0;
  3070. size_t byte = bitRangeStart >> 3;
  3071. int offsetInByte = (int) bitRangeStart & 7;
  3072. size_t bitsSoFar = 0;
  3073. while (numBits > 0 && (size_t) byte < size)
  3074. {
  3075. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3076. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  3077. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  3078. bitsSoFar += bitsThisTime;
  3079. numBits -= bitsThisTime;
  3080. ++byte;
  3081. offsetInByte = 0;
  3082. }
  3083. return res;
  3084. }
  3085. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  3086. {
  3087. size_t byte = bitRangeStart >> 3;
  3088. int offsetInByte = (int) bitRangeStart & 7;
  3089. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3090. while (numBits > 0 && (size_t) byte < size)
  3091. {
  3092. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3093. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3094. const unsigned int tempBits = bitsToSet << offsetInByte;
  3095. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3096. ++byte;
  3097. numBits -= bitsThisTime;
  3098. bitsToSet >>= bitsThisTime;
  3099. mask >>= bitsThisTime;
  3100. offsetInByte = 0;
  3101. }
  3102. }
  3103. void MemoryBlock::loadFromHexString (const String& hex)
  3104. {
  3105. ensureSize (hex.length() >> 1);
  3106. char* dest = data;
  3107. int i = 0;
  3108. for (;;)
  3109. {
  3110. int byte = 0;
  3111. for (int loop = 2; --loop >= 0;)
  3112. {
  3113. byte <<= 4;
  3114. for (;;)
  3115. {
  3116. const juce_wchar c = hex [i++];
  3117. if (c >= '0' && c <= '9')
  3118. {
  3119. byte |= c - '0';
  3120. break;
  3121. }
  3122. else if (c >= 'a' && c <= 'z')
  3123. {
  3124. byte |= c - ('a' - 10);
  3125. break;
  3126. }
  3127. else if (c >= 'A' && c <= 'Z')
  3128. {
  3129. byte |= c - ('A' - 10);
  3130. break;
  3131. }
  3132. else if (c == 0)
  3133. {
  3134. setSize (static_cast <size_t> (dest - data));
  3135. return;
  3136. }
  3137. }
  3138. }
  3139. *dest++ = (char) byte;
  3140. }
  3141. }
  3142. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3143. const String MemoryBlock::toBase64Encoding() const
  3144. {
  3145. const size_t numChars = ((size << 3) + 5) / 6;
  3146. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3147. const int initialLen = destString.length();
  3148. destString.preallocateStorage (initialLen + 2 + numChars);
  3149. String::CharPointerType d (destString.getCharPointer());
  3150. d += initialLen;
  3151. d.write ('.');
  3152. for (size_t i = 0; i < numChars; ++i)
  3153. d.write (encodingTable [getBitRange (i * 6, 6)]);
  3154. d.writeNull();
  3155. return destString;
  3156. }
  3157. bool MemoryBlock::fromBase64Encoding (const String& s)
  3158. {
  3159. const int startPos = s.indexOfChar ('.') + 1;
  3160. if (startPos <= 0)
  3161. return false;
  3162. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3163. setSize (numBytesNeeded, true);
  3164. const int numChars = s.length() - startPos;
  3165. String::CharPointerType srcChars (s.getCharPointer());
  3166. srcChars += startPos;
  3167. int pos = 0;
  3168. for (int i = 0; i < numChars; ++i)
  3169. {
  3170. const char c = (char) srcChars.getAndAdvance();
  3171. for (int j = 0; j < 64; ++j)
  3172. {
  3173. if (encodingTable[j] == c)
  3174. {
  3175. setBitRange (pos, 6, j);
  3176. pos += 6;
  3177. break;
  3178. }
  3179. }
  3180. }
  3181. return true;
  3182. }
  3183. END_JUCE_NAMESPACE
  3184. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3185. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3186. BEGIN_JUCE_NAMESPACE
  3187. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3188. : properties (ignoreCaseOfKeyNames),
  3189. fallbackProperties (0),
  3190. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3191. {
  3192. }
  3193. PropertySet::PropertySet (const PropertySet& other)
  3194. : properties (other.properties),
  3195. fallbackProperties (other.fallbackProperties),
  3196. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3197. {
  3198. }
  3199. PropertySet& PropertySet::operator= (const PropertySet& other)
  3200. {
  3201. properties = other.properties;
  3202. fallbackProperties = other.fallbackProperties;
  3203. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3204. propertyChanged();
  3205. return *this;
  3206. }
  3207. PropertySet::~PropertySet()
  3208. {
  3209. }
  3210. void PropertySet::clear()
  3211. {
  3212. const ScopedLock sl (lock);
  3213. if (properties.size() > 0)
  3214. {
  3215. properties.clear();
  3216. propertyChanged();
  3217. }
  3218. }
  3219. const String PropertySet::getValue (const String& keyName,
  3220. const String& defaultValue) const throw()
  3221. {
  3222. const ScopedLock sl (lock);
  3223. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3224. if (index >= 0)
  3225. return properties.getAllValues() [index];
  3226. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3227. : defaultValue;
  3228. }
  3229. int PropertySet::getIntValue (const String& keyName,
  3230. const int defaultValue) const throw()
  3231. {
  3232. const ScopedLock sl (lock);
  3233. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3234. if (index >= 0)
  3235. return properties.getAllValues() [index].getIntValue();
  3236. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3237. : defaultValue;
  3238. }
  3239. double PropertySet::getDoubleValue (const String& keyName,
  3240. const double defaultValue) const throw()
  3241. {
  3242. const ScopedLock sl (lock);
  3243. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3244. if (index >= 0)
  3245. return properties.getAllValues()[index].getDoubleValue();
  3246. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3247. : defaultValue;
  3248. }
  3249. bool PropertySet::getBoolValue (const String& keyName,
  3250. const bool defaultValue) const throw()
  3251. {
  3252. const ScopedLock sl (lock);
  3253. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3254. if (index >= 0)
  3255. return properties.getAllValues() [index].getIntValue() != 0;
  3256. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3257. : defaultValue;
  3258. }
  3259. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3260. {
  3261. return XmlDocument::parse (getValue (keyName));
  3262. }
  3263. void PropertySet::setValue (const String& keyName, const var& v)
  3264. {
  3265. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3266. if (keyName.isNotEmpty())
  3267. {
  3268. const String value (v.toString());
  3269. const ScopedLock sl (lock);
  3270. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3271. if (index < 0 || properties.getAllValues() [index] != value)
  3272. {
  3273. properties.set (keyName, value);
  3274. propertyChanged();
  3275. }
  3276. }
  3277. }
  3278. void PropertySet::removeValue (const String& keyName)
  3279. {
  3280. if (keyName.isNotEmpty())
  3281. {
  3282. const ScopedLock sl (lock);
  3283. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3284. if (index >= 0)
  3285. {
  3286. properties.remove (keyName);
  3287. propertyChanged();
  3288. }
  3289. }
  3290. }
  3291. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3292. {
  3293. setValue (keyName, xml == 0 ? var::null
  3294. : var (xml->createDocument (String::empty, true)));
  3295. }
  3296. bool PropertySet::containsKey (const String& keyName) const throw()
  3297. {
  3298. const ScopedLock sl (lock);
  3299. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3300. }
  3301. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3302. {
  3303. const ScopedLock sl (lock);
  3304. fallbackProperties = fallbackProperties_;
  3305. }
  3306. XmlElement* PropertySet::createXml (const String& nodeName) const
  3307. {
  3308. const ScopedLock sl (lock);
  3309. XmlElement* const xml = new XmlElement (nodeName);
  3310. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3311. {
  3312. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3313. e->setAttribute ("name", properties.getAllKeys()[i]);
  3314. e->setAttribute ("val", properties.getAllValues()[i]);
  3315. }
  3316. return xml;
  3317. }
  3318. void PropertySet::restoreFromXml (const XmlElement& xml)
  3319. {
  3320. const ScopedLock sl (lock);
  3321. clear();
  3322. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3323. {
  3324. if (e->hasAttribute ("name")
  3325. && e->hasAttribute ("val"))
  3326. {
  3327. properties.set (e->getStringAttribute ("name"),
  3328. e->getStringAttribute ("val"));
  3329. }
  3330. }
  3331. if (properties.size() > 0)
  3332. propertyChanged();
  3333. }
  3334. void PropertySet::propertyChanged()
  3335. {
  3336. }
  3337. END_JUCE_NAMESPACE
  3338. /*** End of inlined file: juce_PropertySet.cpp ***/
  3339. /*** Start of inlined file: juce_Identifier.cpp ***/
  3340. BEGIN_JUCE_NAMESPACE
  3341. StringPool& Identifier::getPool()
  3342. {
  3343. static StringPool pool;
  3344. return pool;
  3345. }
  3346. Identifier::Identifier() throw()
  3347. : name (0)
  3348. {
  3349. }
  3350. Identifier::Identifier (const Identifier& other) throw()
  3351. : name (other.name)
  3352. {
  3353. }
  3354. Identifier& Identifier::operator= (const Identifier& other) throw()
  3355. {
  3356. name = other.name;
  3357. return *this;
  3358. }
  3359. Identifier::Identifier (const String& name_)
  3360. : name (Identifier::getPool().getPooledString (name_))
  3361. {
  3362. /* An Identifier string must be suitable for use as a script variable or XML
  3363. attribute, so it can only contain this limited set of characters.. */
  3364. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3365. }
  3366. Identifier::Identifier (const char* const name_)
  3367. : name (Identifier::getPool().getPooledString (name_))
  3368. {
  3369. /* An Identifier string must be suitable for use as a script variable or XML
  3370. attribute, so it can only contain this limited set of characters.. */
  3371. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3372. }
  3373. Identifier::~Identifier()
  3374. {
  3375. }
  3376. END_JUCE_NAMESPACE
  3377. /*** End of inlined file: juce_Identifier.cpp ***/
  3378. /*** Start of inlined file: juce_Variant.cpp ***/
  3379. BEGIN_JUCE_NAMESPACE
  3380. enum VariantStreamMarkers
  3381. {
  3382. varMarker_Int = 1,
  3383. varMarker_BoolTrue = 2,
  3384. varMarker_BoolFalse = 3,
  3385. varMarker_Double = 4,
  3386. varMarker_String = 5,
  3387. varMarker_Int64 = 6
  3388. };
  3389. class var::VariantType
  3390. {
  3391. public:
  3392. VariantType() {}
  3393. virtual ~VariantType() {}
  3394. virtual int toInt (const ValueUnion&) const { return 0; }
  3395. virtual int64 toInt64 (const ValueUnion&) const { return 0; }
  3396. virtual double toDouble (const ValueUnion&) const { return 0; }
  3397. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3398. virtual bool toBool (const ValueUnion&) const { return false; }
  3399. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3400. virtual bool isVoid() const throw() { return false; }
  3401. virtual bool isInt() const throw() { return false; }
  3402. virtual bool isInt64() const throw() { return false; }
  3403. virtual bool isBool() const throw() { return false; }
  3404. virtual bool isDouble() const throw() { return false; }
  3405. virtual bool isString() const throw() { return false; }
  3406. virtual bool isObject() const throw() { return false; }
  3407. virtual bool isMethod() const throw() { return false; }
  3408. virtual void cleanUp (ValueUnion&) const throw() {}
  3409. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3410. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3411. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3412. };
  3413. class var::VariantType_Void : public var::VariantType
  3414. {
  3415. public:
  3416. VariantType_Void() {}
  3417. static const VariantType_Void instance;
  3418. bool isVoid() const throw() { return true; }
  3419. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3420. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3421. };
  3422. class var::VariantType_Int : public var::VariantType
  3423. {
  3424. public:
  3425. VariantType_Int() {}
  3426. static const VariantType_Int instance;
  3427. int toInt (const ValueUnion& data) const { return data.intValue; };
  3428. int64 toInt64 (const ValueUnion& data) const { return (int64) data.intValue; };
  3429. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3430. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3431. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3432. bool isInt() const throw() { return true; }
  3433. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3434. {
  3435. return otherType.toInt (otherData) == data.intValue;
  3436. }
  3437. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3438. {
  3439. output.writeCompressedInt (5);
  3440. output.writeByte (varMarker_Int);
  3441. output.writeInt (data.intValue);
  3442. }
  3443. };
  3444. class var::VariantType_Int64 : public var::VariantType
  3445. {
  3446. public:
  3447. VariantType_Int64() {}
  3448. static const VariantType_Int64 instance;
  3449. int toInt (const ValueUnion& data) const { return (int) data.int64Value; };
  3450. int64 toInt64 (const ValueUnion& data) const { return data.int64Value; };
  3451. double toDouble (const ValueUnion& data) const { return (double) data.int64Value; }
  3452. const String toString (const ValueUnion& data) const { return String (data.int64Value); }
  3453. bool toBool (const ValueUnion& data) const { return data.int64Value != 0; }
  3454. bool isInt64() const throw() { return true; }
  3455. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3456. {
  3457. return otherType.toInt64 (otherData) == data.int64Value;
  3458. }
  3459. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3460. {
  3461. output.writeCompressedInt (9);
  3462. output.writeByte (varMarker_Int64);
  3463. output.writeInt64 (data.int64Value);
  3464. }
  3465. };
  3466. class var::VariantType_Double : public var::VariantType
  3467. {
  3468. public:
  3469. VariantType_Double() {}
  3470. static const VariantType_Double instance;
  3471. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3472. int64 toInt64 (const ValueUnion& data) const { return (int64) data.doubleValue; };
  3473. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3474. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3475. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3476. bool isDouble() const throw() { return true; }
  3477. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3478. {
  3479. return otherType.toDouble (otherData) == data.doubleValue;
  3480. }
  3481. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3482. {
  3483. output.writeCompressedInt (9);
  3484. output.writeByte (varMarker_Double);
  3485. output.writeDouble (data.doubleValue);
  3486. }
  3487. };
  3488. class var::VariantType_Bool : public var::VariantType
  3489. {
  3490. public:
  3491. VariantType_Bool() {}
  3492. static const VariantType_Bool instance;
  3493. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3494. int64 toInt64 (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3495. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3496. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3497. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3498. bool isBool() const throw() { return true; }
  3499. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3500. {
  3501. return otherType.toBool (otherData) == data.boolValue;
  3502. }
  3503. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3504. {
  3505. output.writeCompressedInt (1);
  3506. output.writeByte (data.boolValue ? (char) varMarker_BoolTrue : (char) varMarker_BoolFalse);
  3507. }
  3508. };
  3509. class var::VariantType_String : public var::VariantType
  3510. {
  3511. public:
  3512. VariantType_String() {}
  3513. static const VariantType_String instance;
  3514. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3515. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3516. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3517. int64 toInt64 (const ValueUnion& data) const { return data.stringValue->getLargeIntValue(); };
  3518. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3519. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3520. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3521. || data.stringValue->trim().equalsIgnoreCase ("true")
  3522. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3523. bool isString() const throw() { return true; }
  3524. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3525. {
  3526. return otherType.toString (otherData) == *data.stringValue;
  3527. }
  3528. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3529. {
  3530. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3531. output.writeCompressedInt (len + 1);
  3532. output.writeByte (varMarker_String);
  3533. HeapBlock<char> temp (len);
  3534. data.stringValue->copyToUTF8 (temp, len);
  3535. output.write (temp, len);
  3536. }
  3537. };
  3538. class var::VariantType_Object : public var::VariantType
  3539. {
  3540. public:
  3541. VariantType_Object() {}
  3542. static const VariantType_Object instance;
  3543. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3544. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3545. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3546. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3547. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3548. bool isObject() const throw() { return true; }
  3549. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3550. {
  3551. return otherType.toObject (otherData) == data.objectValue;
  3552. }
  3553. void writeToStream (const ValueUnion&, OutputStream& output) const
  3554. {
  3555. jassertfalse; // Can't write an object to a stream!
  3556. output.writeCompressedInt (0);
  3557. }
  3558. };
  3559. class var::VariantType_Method : public var::VariantType
  3560. {
  3561. public:
  3562. VariantType_Method() {}
  3563. static const VariantType_Method instance;
  3564. const String toString (const ValueUnion&) const { return "Method"; }
  3565. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3566. bool isMethod() const throw() { return true; }
  3567. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3568. {
  3569. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3570. }
  3571. void writeToStream (const ValueUnion&, OutputStream& output) const
  3572. {
  3573. jassertfalse; // Can't write a method to a stream!
  3574. output.writeCompressedInt (0);
  3575. }
  3576. };
  3577. const var::VariantType_Void var::VariantType_Void::instance;
  3578. const var::VariantType_Int var::VariantType_Int::instance;
  3579. const var::VariantType_Int64 var::VariantType_Int64::instance;
  3580. const var::VariantType_Bool var::VariantType_Bool::instance;
  3581. const var::VariantType_Double var::VariantType_Double::instance;
  3582. const var::VariantType_String var::VariantType_String::instance;
  3583. const var::VariantType_Object var::VariantType_Object::instance;
  3584. const var::VariantType_Method var::VariantType_Method::instance;
  3585. var::var() throw() : type (&VariantType_Void::instance)
  3586. {
  3587. }
  3588. var::~var() throw()
  3589. {
  3590. type->cleanUp (value);
  3591. }
  3592. const var var::null;
  3593. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3594. {
  3595. type->createCopy (value, valueToCopy.value);
  3596. }
  3597. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3598. {
  3599. value.intValue = value_;
  3600. }
  3601. var::var (const int64 value_) throw() : type (&VariantType_Int64::instance)
  3602. {
  3603. value.int64Value = value_;
  3604. }
  3605. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3606. {
  3607. value.boolValue = value_;
  3608. }
  3609. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3610. {
  3611. value.doubleValue = value_;
  3612. }
  3613. var::var (const String& value_) : type (&VariantType_String::instance)
  3614. {
  3615. value.stringValue = new String (value_);
  3616. }
  3617. var::var (const char* const value_) : type (&VariantType_String::instance)
  3618. {
  3619. value.stringValue = new String (value_);
  3620. }
  3621. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3622. {
  3623. value.stringValue = new String (value_);
  3624. }
  3625. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3626. {
  3627. value.objectValue = object;
  3628. if (object != 0)
  3629. object->incReferenceCount();
  3630. }
  3631. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3632. {
  3633. value.methodValue = method_;
  3634. }
  3635. bool var::isVoid() const throw() { return type->isVoid(); }
  3636. bool var::isInt() const throw() { return type->isInt(); }
  3637. bool var::isInt64() const throw() { return type->isInt64(); }
  3638. bool var::isBool() const throw() { return type->isBool(); }
  3639. bool var::isDouble() const throw() { return type->isDouble(); }
  3640. bool var::isString() const throw() { return type->isString(); }
  3641. bool var::isObject() const throw() { return type->isObject(); }
  3642. bool var::isMethod() const throw() { return type->isMethod(); }
  3643. var::operator int() const { return type->toInt (value); }
  3644. var::operator int64() const { return type->toInt64 (value); }
  3645. var::operator bool() const { return type->toBool (value); }
  3646. var::operator float() const { return (float) type->toDouble (value); }
  3647. var::operator double() const { return type->toDouble (value); }
  3648. const String var::toString() const { return type->toString (value); }
  3649. var::operator const String() const { return type->toString (value); }
  3650. DynamicObject* var::getObject() const { return type->toObject (value); }
  3651. void var::swapWith (var& other) throw()
  3652. {
  3653. swapVariables (type, other.type);
  3654. swapVariables (value, other.value);
  3655. }
  3656. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3657. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3658. var& var::operator= (int64 newValue) { var v (newValue); swapWith (v); return *this; }
  3659. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3660. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3661. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3662. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3663. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3664. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3665. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3666. bool var::equals (const var& other) const throw()
  3667. {
  3668. return type->equals (value, other.value, *other.type);
  3669. }
  3670. bool var::equalsWithSameType (const var& other) const throw()
  3671. {
  3672. return type == other.type && equals (other);
  3673. }
  3674. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3675. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3676. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3677. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3678. void var::writeToStream (OutputStream& output) const
  3679. {
  3680. type->writeToStream (value, output);
  3681. }
  3682. const var var::readFromStream (InputStream& input)
  3683. {
  3684. const int numBytes = input.readCompressedInt();
  3685. if (numBytes > 0)
  3686. {
  3687. switch (input.readByte())
  3688. {
  3689. case varMarker_Int: return var (input.readInt());
  3690. case varMarker_Int64: return var (input.readInt64());
  3691. case varMarker_BoolTrue: return var (true);
  3692. case varMarker_BoolFalse: return var (false);
  3693. case varMarker_Double: return var (input.readDouble());
  3694. case varMarker_String:
  3695. {
  3696. MemoryOutputStream mo;
  3697. mo.writeFromInputStream (input, numBytes - 1);
  3698. return var (mo.toUTF8());
  3699. }
  3700. default: input.skipNextBytes (numBytes - 1); break;
  3701. }
  3702. }
  3703. return var::null;
  3704. }
  3705. const var var::operator[] (const Identifier& propertyName) const
  3706. {
  3707. DynamicObject* const o = getObject();
  3708. return o != 0 ? o->getProperty (propertyName) : var::null;
  3709. }
  3710. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3711. {
  3712. DynamicObject* const o = getObject();
  3713. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3714. }
  3715. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3716. {
  3717. if (isMethod())
  3718. {
  3719. DynamicObject* const target = targetObject.getObject();
  3720. if (target != 0)
  3721. return (target->*(value.methodValue)) (arguments, numArguments);
  3722. }
  3723. return var::null;
  3724. }
  3725. const var var::call (const Identifier& method) const
  3726. {
  3727. return invoke (method, 0, 0);
  3728. }
  3729. const var var::call (const Identifier& method, const var& arg1) const
  3730. {
  3731. return invoke (method, &arg1, 1);
  3732. }
  3733. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3734. {
  3735. var args[] = { arg1, arg2 };
  3736. return invoke (method, args, 2);
  3737. }
  3738. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3739. {
  3740. var args[] = { arg1, arg2, arg3 };
  3741. return invoke (method, args, 3);
  3742. }
  3743. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3744. {
  3745. var args[] = { arg1, arg2, arg3, arg4 };
  3746. return invoke (method, args, 4);
  3747. }
  3748. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3749. {
  3750. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3751. return invoke (method, args, 5);
  3752. }
  3753. END_JUCE_NAMESPACE
  3754. /*** End of inlined file: juce_Variant.cpp ***/
  3755. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3756. BEGIN_JUCE_NAMESPACE
  3757. NamedValueSet::NamedValue::NamedValue() throw()
  3758. {
  3759. }
  3760. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3761. : name (name_), value (value_)
  3762. {
  3763. }
  3764. NamedValueSet::NamedValue::NamedValue (const NamedValue& other)
  3765. : name (other.name), value (other.value)
  3766. {
  3767. }
  3768. NamedValueSet::NamedValue& NamedValueSet::NamedValue::operator= (const NamedValueSet::NamedValue& other)
  3769. {
  3770. name = other.name;
  3771. value = other.value;
  3772. return *this;
  3773. }
  3774. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3775. {
  3776. return name == other.name && value == other.value;
  3777. }
  3778. NamedValueSet::NamedValueSet() throw()
  3779. {
  3780. }
  3781. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3782. {
  3783. values.addCopyOfList (other.values);
  3784. }
  3785. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3786. {
  3787. clear();
  3788. values.addCopyOfList (other.values);
  3789. return *this;
  3790. }
  3791. NamedValueSet::~NamedValueSet()
  3792. {
  3793. clear();
  3794. }
  3795. void NamedValueSet::clear()
  3796. {
  3797. values.deleteAll();
  3798. }
  3799. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3800. {
  3801. const NamedValue* i1 = values;
  3802. const NamedValue* i2 = other.values;
  3803. while (i1 != 0 && i2 != 0)
  3804. {
  3805. if (! (*i1 == *i2))
  3806. return false;
  3807. i1 = i1->nextListItem;
  3808. i2 = i2->nextListItem;
  3809. }
  3810. return true;
  3811. }
  3812. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3813. {
  3814. return ! operator== (other);
  3815. }
  3816. int NamedValueSet::size() const throw()
  3817. {
  3818. return values.size();
  3819. }
  3820. const var& NamedValueSet::operator[] (const Identifier& name) const
  3821. {
  3822. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3823. if (i->name == name)
  3824. return i->value;
  3825. return var::null;
  3826. }
  3827. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3828. {
  3829. const var* v = getVarPointer (name);
  3830. return v != 0 ? *v : defaultReturnValue;
  3831. }
  3832. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3833. {
  3834. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3835. if (i->name == name)
  3836. return &(i->value);
  3837. return 0;
  3838. }
  3839. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3840. {
  3841. LinkedListPointer<NamedValue>* i = &values;
  3842. while (i->get() != 0)
  3843. {
  3844. NamedValue* const v = i->get();
  3845. if (v->name == name)
  3846. {
  3847. if (v->value == newValue)
  3848. return false;
  3849. v->value = newValue;
  3850. return true;
  3851. }
  3852. i = &(v->nextListItem);
  3853. }
  3854. i->insertNext (new NamedValue (name, newValue));
  3855. return true;
  3856. }
  3857. bool NamedValueSet::contains (const Identifier& name) const
  3858. {
  3859. return getVarPointer (name) != 0;
  3860. }
  3861. bool NamedValueSet::remove (const Identifier& name)
  3862. {
  3863. LinkedListPointer<NamedValue>* i = &values;
  3864. for (;;)
  3865. {
  3866. NamedValue* const v = i->get();
  3867. if (v == 0)
  3868. break;
  3869. if (v->name == name)
  3870. {
  3871. delete i->removeNext();
  3872. return true;
  3873. }
  3874. i = &(v->nextListItem);
  3875. }
  3876. return false;
  3877. }
  3878. const Identifier NamedValueSet::getName (const int index) const
  3879. {
  3880. const NamedValue* const v = values[index];
  3881. jassert (v != 0);
  3882. return v->name;
  3883. }
  3884. const var NamedValueSet::getValueAt (const int index) const
  3885. {
  3886. const NamedValue* const v = values[index];
  3887. jassert (v != 0);
  3888. return v->value;
  3889. }
  3890. void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
  3891. {
  3892. clear();
  3893. LinkedListPointer<NamedValue>::Appender appender (values);
  3894. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  3895. for (int i = 0; i < numAtts; ++i)
  3896. appender.append (new NamedValue (xml.getAttributeName (i), var (xml.getAttributeValue (i))));
  3897. }
  3898. void NamedValueSet::copyToXmlAttributes (XmlElement& xml) const
  3899. {
  3900. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3901. {
  3902. jassert (! i->value.isObject()); // DynamicObjects can't be stored as XML!
  3903. xml.setAttribute (i->name.toString(),
  3904. i->value.toString());
  3905. }
  3906. }
  3907. END_JUCE_NAMESPACE
  3908. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3909. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3910. BEGIN_JUCE_NAMESPACE
  3911. DynamicObject::DynamicObject()
  3912. {
  3913. }
  3914. DynamicObject::~DynamicObject()
  3915. {
  3916. }
  3917. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3918. {
  3919. var* const v = properties.getVarPointer (propertyName);
  3920. return v != 0 && ! v->isMethod();
  3921. }
  3922. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3923. {
  3924. return properties [propertyName];
  3925. }
  3926. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3927. {
  3928. properties.set (propertyName, newValue);
  3929. }
  3930. void DynamicObject::removeProperty (const Identifier& propertyName)
  3931. {
  3932. properties.remove (propertyName);
  3933. }
  3934. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3935. {
  3936. return getProperty (methodName).isMethod();
  3937. }
  3938. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3939. const var* parameters,
  3940. int numParameters)
  3941. {
  3942. return properties [methodName].invoke (var (this), parameters, numParameters);
  3943. }
  3944. void DynamicObject::setMethod (const Identifier& name,
  3945. var::MethodFunction methodFunction)
  3946. {
  3947. properties.set (name, var (methodFunction));
  3948. }
  3949. void DynamicObject::clear()
  3950. {
  3951. properties.clear();
  3952. }
  3953. END_JUCE_NAMESPACE
  3954. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3955. /*** Start of inlined file: juce_Expression.cpp ***/
  3956. BEGIN_JUCE_NAMESPACE
  3957. class Expression::Term : public ReferenceCountedObject
  3958. {
  3959. public:
  3960. Term() {}
  3961. virtual ~Term() {}
  3962. virtual Type getType() const throw() = 0;
  3963. virtual Term* clone() const = 0;
  3964. virtual const ReferenceCountedObjectPtr<Term> resolve (const Scope&, int recursionDepth) = 0;
  3965. virtual const String toString() const = 0;
  3966. virtual double toDouble() const { return 0; }
  3967. virtual int getInputIndexFor (const Term*) const { return -1; }
  3968. virtual int getOperatorPrecedence() const { return 0; }
  3969. virtual int getNumInputs() const { return 0; }
  3970. virtual Term* getInput (int) const { return 0; }
  3971. virtual const ReferenceCountedObjectPtr<Term> negated();
  3972. virtual const ReferenceCountedObjectPtr<Term> createTermToEvaluateInput (const Scope&, const Term* /*inputTerm*/,
  3973. double /*overallTarget*/, Term* /*topLevelTerm*/) const
  3974. {
  3975. jassertfalse;
  3976. return 0;
  3977. }
  3978. virtual const String getName() const
  3979. {
  3980. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  3981. return String::empty;
  3982. }
  3983. virtual void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  3984. {
  3985. for (int i = getNumInputs(); --i >= 0;)
  3986. getInput (i)->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  3987. }
  3988. class SymbolVisitor
  3989. {
  3990. public:
  3991. virtual ~SymbolVisitor() {}
  3992. virtual void useSymbol (const Symbol&) = 0;
  3993. };
  3994. virtual void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  3995. {
  3996. for (int i = getNumInputs(); --i >= 0;)
  3997. getInput(i)->visitAllSymbols (visitor, scope, recursionDepth);
  3998. }
  3999. private:
  4000. JUCE_DECLARE_NON_COPYABLE (Term);
  4001. };
  4002. class Expression::Helpers
  4003. {
  4004. public:
  4005. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  4006. // This helper function is needed to work around VC6 scoping bugs
  4007. static inline const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  4008. static void checkRecursionDepth (const int depth)
  4009. {
  4010. if (depth > 256)
  4011. throw EvaluationError ("Recursive symbol references");
  4012. }
  4013. friend class Expression::Term; // (also only needed as a VC6 workaround)
  4014. /** An exception that can be thrown by Expression::evaluate(). */
  4015. class EvaluationError : public std::exception
  4016. {
  4017. public:
  4018. EvaluationError (const String& description_)
  4019. : description (description_)
  4020. {
  4021. DBG ("Expression::EvaluationError: " + description);
  4022. }
  4023. String description;
  4024. };
  4025. class Constant : public Term
  4026. {
  4027. public:
  4028. Constant (const double value_, const bool isResolutionTarget_)
  4029. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  4030. Type getType() const throw() { return constantType; }
  4031. Term* clone() const { return new Constant (value, isResolutionTarget); }
  4032. const TermPtr resolve (const Scope&, int) { return this; }
  4033. double toDouble() const { return value; }
  4034. const TermPtr negated() { return new Constant (-value, isResolutionTarget); }
  4035. const String toString() const
  4036. {
  4037. String s (value);
  4038. if (isResolutionTarget)
  4039. s = "@" + s;
  4040. return s;
  4041. }
  4042. double value;
  4043. bool isResolutionTarget;
  4044. };
  4045. class BinaryTerm : public Term
  4046. {
  4047. public:
  4048. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  4049. {
  4050. jassert (left_ != 0 && right_ != 0);
  4051. }
  4052. int getInputIndexFor (const Term* possibleInput) const
  4053. {
  4054. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  4055. }
  4056. Type getType() const throw() { return operatorType; }
  4057. int getNumInputs() const { return 2; }
  4058. Term* getInput (int index) const { return index == 0 ? left.getObject() : (index == 1 ? right.getObject() : 0); }
  4059. virtual double performFunction (double left, double right) const = 0;
  4060. virtual void writeOperator (String& dest) const = 0;
  4061. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4062. {
  4063. return new Constant (performFunction (left->resolve (scope, recursionDepth)->toDouble(),
  4064. right->resolve (scope, recursionDepth)->toDouble()), false);
  4065. }
  4066. const String toString() const
  4067. {
  4068. String s;
  4069. const int ourPrecendence = getOperatorPrecedence();
  4070. if (left->getOperatorPrecedence() > ourPrecendence)
  4071. s << '(' << left->toString() << ')';
  4072. else
  4073. s = left->toString();
  4074. writeOperator (s);
  4075. if (right->getOperatorPrecedence() >= ourPrecendence)
  4076. s << '(' << right->toString() << ')';
  4077. else
  4078. s << right->toString();
  4079. return s;
  4080. }
  4081. protected:
  4082. const TermPtr left, right;
  4083. const TermPtr createDestinationTerm (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4084. {
  4085. jassert (input == left || input == right);
  4086. if (input != left && input != right)
  4087. return 0;
  4088. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4089. if (dest == 0)
  4090. return new Constant (overallTarget, false);
  4091. return dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm);
  4092. }
  4093. };
  4094. class SymbolTerm : public Term
  4095. {
  4096. public:
  4097. explicit SymbolTerm (const String& symbol_) : symbol (symbol_) {}
  4098. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4099. {
  4100. checkRecursionDepth (recursionDepth);
  4101. return getTermFor (scope.getSymbolValue (symbol))->resolve (scope, recursionDepth + 1);
  4102. }
  4103. Type getType() const throw() { return symbolType; }
  4104. Term* clone() const { return new SymbolTerm (symbol); }
  4105. const String toString() const { return symbol; }
  4106. const String getName() const { return symbol; }
  4107. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4108. {
  4109. checkRecursionDepth (recursionDepth);
  4110. visitor.useSymbol (Symbol (scope.getScopeUID(), symbol));
  4111. getTermFor (scope.getSymbolValue (symbol))->visitAllSymbols (visitor, scope, recursionDepth + 1);
  4112. }
  4113. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int /*recursionDepth*/)
  4114. {
  4115. if (oldSymbol.symbolName == symbol && scope.getScopeUID() == oldSymbol.scopeUID)
  4116. symbol = newName;
  4117. }
  4118. String symbol;
  4119. };
  4120. class Function : public Term
  4121. {
  4122. public:
  4123. explicit Function (const String& functionName_) : functionName (functionName_) {}
  4124. Function (const String& functionName_, const Array<Expression>& parameters_)
  4125. : functionName (functionName_), parameters (parameters_)
  4126. {}
  4127. Type getType() const throw() { return functionType; }
  4128. Term* clone() const { return new Function (functionName, parameters); }
  4129. int getNumInputs() const { return parameters.size(); }
  4130. Term* getInput (int i) const { return getTermFor (parameters [i]); }
  4131. const String getName() const { return functionName; }
  4132. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4133. {
  4134. checkRecursionDepth (recursionDepth);
  4135. double result = 0;
  4136. const int numParams = parameters.size();
  4137. if (numParams > 0)
  4138. {
  4139. HeapBlock<double> params (numParams);
  4140. for (int i = 0; i < numParams; ++i)
  4141. params[i] = getTermFor (parameters.getReference(i))->resolve (scope, recursionDepth + 1)->toDouble();
  4142. result = scope.evaluateFunction (functionName, params, numParams);
  4143. }
  4144. else
  4145. {
  4146. result = scope.evaluateFunction (functionName, 0, 0);
  4147. }
  4148. return new Constant (result, false);
  4149. }
  4150. int getInputIndexFor (const Term* possibleInput) const
  4151. {
  4152. for (int i = 0; i < parameters.size(); ++i)
  4153. if (getTermFor (parameters.getReference(i)) == possibleInput)
  4154. return i;
  4155. return -1;
  4156. }
  4157. const String toString() const
  4158. {
  4159. if (parameters.size() == 0)
  4160. return functionName + "()";
  4161. String s (functionName + " (");
  4162. for (int i = 0; i < parameters.size(); ++i)
  4163. {
  4164. s << getTermFor (parameters.getReference(i))->toString();
  4165. if (i < parameters.size() - 1)
  4166. s << ", ";
  4167. }
  4168. s << ')';
  4169. return s;
  4170. }
  4171. const String functionName;
  4172. Array<Expression> parameters;
  4173. };
  4174. class DotOperator : public BinaryTerm
  4175. {
  4176. public:
  4177. DotOperator (SymbolTerm* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4178. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4179. {
  4180. checkRecursionDepth (recursionDepth);
  4181. EvaluationVisitor visitor (right, recursionDepth + 1);
  4182. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4183. return visitor.output;
  4184. }
  4185. Term* clone() const { return new DotOperator (getSymbol(), right); }
  4186. const String getName() const { return "."; }
  4187. int getOperatorPrecedence() const { return 1; }
  4188. void writeOperator (String& dest) const { dest << '.'; }
  4189. double performFunction (double, double) const { return 0.0; }
  4190. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4191. {
  4192. checkRecursionDepth (recursionDepth);
  4193. visitor.useSymbol (Symbol (scope.getScopeUID(), getSymbol()->symbol));
  4194. SymbolVisitingVisitor v (right, visitor, recursionDepth + 1);
  4195. try
  4196. {
  4197. scope.visitRelativeScope (getSymbol()->symbol, v);
  4198. }
  4199. catch (...) {}
  4200. }
  4201. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  4202. {
  4203. checkRecursionDepth (recursionDepth);
  4204. getSymbol()->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  4205. SymbolRenamingVisitor visitor (right, oldSymbol, newName, recursionDepth + 1);
  4206. try
  4207. {
  4208. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4209. }
  4210. catch (...) {}
  4211. }
  4212. private:
  4213. class EvaluationVisitor : public Scope::Visitor
  4214. {
  4215. public:
  4216. EvaluationVisitor (const TermPtr& input_, const int recursionCount_)
  4217. : input (input_), output (input_), recursionCount (recursionCount_) {}
  4218. void visit (const Scope& scope) { output = input->resolve (scope, recursionCount); }
  4219. const TermPtr input;
  4220. TermPtr output;
  4221. const int recursionCount;
  4222. private:
  4223. JUCE_DECLARE_NON_COPYABLE (EvaluationVisitor);
  4224. };
  4225. class SymbolVisitingVisitor : public Scope::Visitor
  4226. {
  4227. public:
  4228. SymbolVisitingVisitor (const TermPtr& input_, SymbolVisitor& visitor_, const int recursionCount_)
  4229. : input (input_), visitor (visitor_), recursionCount (recursionCount_) {}
  4230. void visit (const Scope& scope) { input->visitAllSymbols (visitor, scope, recursionCount); }
  4231. private:
  4232. const TermPtr input;
  4233. SymbolVisitor& visitor;
  4234. const int recursionCount;
  4235. JUCE_DECLARE_NON_COPYABLE (SymbolVisitingVisitor);
  4236. };
  4237. class SymbolRenamingVisitor : public Scope::Visitor
  4238. {
  4239. public:
  4240. SymbolRenamingVisitor (const TermPtr& input_, const Expression::Symbol& symbol_, const String& newName_, const int recursionCount_)
  4241. : input (input_), symbol (symbol_), newName (newName_), recursionCount (recursionCount_) {}
  4242. void visit (const Scope& scope) { input->renameSymbol (symbol, newName, scope, recursionCount); }
  4243. private:
  4244. const TermPtr input;
  4245. const Symbol& symbol;
  4246. const String newName;
  4247. const int recursionCount;
  4248. JUCE_DECLARE_NON_COPYABLE (SymbolRenamingVisitor);
  4249. };
  4250. SymbolTerm* getSymbol() const { return static_cast <SymbolTerm*> (left.getObject()); }
  4251. JUCE_DECLARE_NON_COPYABLE (DotOperator);
  4252. };
  4253. class Negate : public Term
  4254. {
  4255. public:
  4256. explicit Negate (const TermPtr& input_) : input (input_)
  4257. {
  4258. jassert (input_ != 0);
  4259. }
  4260. Type getType() const throw() { return operatorType; }
  4261. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  4262. int getNumInputs() const { return 1; }
  4263. Term* getInput (int index) const { return index == 0 ? input.getObject() : 0; }
  4264. Term* clone() const { return new Negate (input->clone()); }
  4265. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4266. {
  4267. return new Constant (-input->resolve (scope, recursionDepth)->toDouble(), false);
  4268. }
  4269. const String getName() const { return "-"; }
  4270. const TermPtr negated() { return input; }
  4271. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input_, double overallTarget, Term* topLevelTerm) const
  4272. {
  4273. (void) input_;
  4274. jassert (input_ == input);
  4275. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4276. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  4277. : dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm));
  4278. }
  4279. const String toString() const
  4280. {
  4281. if (input->getOperatorPrecedence() > 0)
  4282. return "-(" + input->toString() + ")";
  4283. else
  4284. return "-" + input->toString();
  4285. }
  4286. private:
  4287. const TermPtr input;
  4288. };
  4289. class Add : public BinaryTerm
  4290. {
  4291. public:
  4292. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4293. Term* clone() const { return new Add (left->clone(), right->clone()); }
  4294. double performFunction (double lhs, double rhs) const { return lhs + rhs; }
  4295. int getOperatorPrecedence() const { return 3; }
  4296. const String getName() const { return "+"; }
  4297. void writeOperator (String& dest) const { dest << " + "; }
  4298. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4299. {
  4300. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4301. if (newDest == 0)
  4302. return 0;
  4303. return new Subtract (newDest, (input == left ? right : left)->clone());
  4304. }
  4305. private:
  4306. JUCE_DECLARE_NON_COPYABLE (Add);
  4307. };
  4308. class Subtract : public BinaryTerm
  4309. {
  4310. public:
  4311. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4312. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4313. double performFunction (double lhs, double rhs) const { return lhs - rhs; }
  4314. int getOperatorPrecedence() const { return 3; }
  4315. const String getName() const { return "-"; }
  4316. void writeOperator (String& dest) const { dest << " - "; }
  4317. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4318. {
  4319. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4320. if (newDest == 0)
  4321. return 0;
  4322. if (input == left)
  4323. return new Add (newDest, right->clone());
  4324. else
  4325. return new Subtract (left->clone(), newDest);
  4326. }
  4327. private:
  4328. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4329. };
  4330. class Multiply : public BinaryTerm
  4331. {
  4332. public:
  4333. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4334. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4335. double performFunction (double lhs, double rhs) const { return lhs * rhs; }
  4336. const String getName() const { return "*"; }
  4337. void writeOperator (String& dest) const { dest << " * "; }
  4338. int getOperatorPrecedence() const { return 2; }
  4339. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4340. {
  4341. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4342. if (newDest == 0)
  4343. return 0;
  4344. return new Divide (newDest, (input == left ? right : left)->clone());
  4345. }
  4346. private:
  4347. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4348. };
  4349. class Divide : public BinaryTerm
  4350. {
  4351. public:
  4352. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4353. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4354. double performFunction (double lhs, double rhs) const { return lhs / rhs; }
  4355. const String getName() const { return "/"; }
  4356. void writeOperator (String& dest) const { dest << " / "; }
  4357. int getOperatorPrecedence() const { return 2; }
  4358. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4359. {
  4360. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4361. if (newDest == 0)
  4362. return 0;
  4363. if (input == left)
  4364. return new Multiply (newDest, right->clone());
  4365. else
  4366. return new Divide (left->clone(), newDest);
  4367. }
  4368. private:
  4369. JUCE_DECLARE_NON_COPYABLE (Divide);
  4370. };
  4371. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4372. {
  4373. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4374. if (inputIndex >= 0)
  4375. return topLevel;
  4376. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4377. {
  4378. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4379. if (t != 0)
  4380. return t;
  4381. }
  4382. return 0;
  4383. }
  4384. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4385. {
  4386. {
  4387. Constant* const c = dynamic_cast<Constant*> (term);
  4388. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4389. return c;
  4390. }
  4391. if (dynamic_cast<Function*> (term) != 0)
  4392. return 0;
  4393. int i;
  4394. const int numIns = term->getNumInputs();
  4395. for (i = 0; i < numIns; ++i)
  4396. {
  4397. Constant* const c = dynamic_cast<Constant*> (term->getInput (i));
  4398. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4399. return c;
  4400. }
  4401. for (i = 0; i < numIns; ++i)
  4402. {
  4403. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4404. if (c != 0)
  4405. return c;
  4406. }
  4407. return 0;
  4408. }
  4409. static bool containsAnySymbols (const Term* const t)
  4410. {
  4411. if (t->getType() == Expression::symbolType)
  4412. return true;
  4413. for (int i = t->getNumInputs(); --i >= 0;)
  4414. if (containsAnySymbols (t->getInput (i)))
  4415. return true;
  4416. return false;
  4417. }
  4418. class SymbolCheckVisitor : public Term::SymbolVisitor
  4419. {
  4420. public:
  4421. SymbolCheckVisitor (const Symbol& symbol_) : wasFound (false), symbol (symbol_) {}
  4422. void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; }
  4423. bool wasFound;
  4424. private:
  4425. const Symbol& symbol;
  4426. JUCE_DECLARE_NON_COPYABLE (SymbolCheckVisitor);
  4427. };
  4428. class SymbolListVisitor : public Term::SymbolVisitor
  4429. {
  4430. public:
  4431. SymbolListVisitor (Array<Symbol>& list_) : list (list_) {}
  4432. void useSymbol (const Symbol& s) { list.addIfNotAlreadyThere (s); }
  4433. private:
  4434. Array<Symbol>& list;
  4435. JUCE_DECLARE_NON_COPYABLE (SymbolListVisitor);
  4436. };
  4437. class Parser
  4438. {
  4439. public:
  4440. Parser (String::CharPointerType& stringToParse)
  4441. : text (stringToParse)
  4442. {
  4443. }
  4444. const TermPtr readUpToComma()
  4445. {
  4446. if (text.isEmpty())
  4447. return new Constant (0.0, false);
  4448. const TermPtr e (readExpression());
  4449. if (e == 0 || ((! readOperator (",")) && ! text.isEmpty()))
  4450. throw ParseError ("Syntax error: \"" + String (text) + "\"");
  4451. return e;
  4452. }
  4453. private:
  4454. String::CharPointerType& text;
  4455. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4456. {
  4457. return c >= '0' && c <= '9';
  4458. }
  4459. bool readChar (const juce_wchar required) throw()
  4460. {
  4461. if (*text == required)
  4462. {
  4463. ++text;
  4464. return true;
  4465. }
  4466. return false;
  4467. }
  4468. bool readOperator (const char* ops, char* const opType = 0) throw()
  4469. {
  4470. text = text.findEndOfWhitespace();
  4471. while (*ops != 0)
  4472. {
  4473. if (readChar (*ops))
  4474. {
  4475. if (opType != 0)
  4476. *opType = *ops;
  4477. return true;
  4478. }
  4479. ++ops;
  4480. }
  4481. return false;
  4482. }
  4483. bool readIdentifier (String& identifier) throw()
  4484. {
  4485. text = text.findEndOfWhitespace();
  4486. String::CharPointerType t (text);
  4487. int numChars = 0;
  4488. if (t.isLetter() || *t == '_')
  4489. {
  4490. ++t;
  4491. ++numChars;
  4492. while (t.isLetterOrDigit() || *t == '_')
  4493. {
  4494. ++t;
  4495. ++numChars;
  4496. }
  4497. }
  4498. if (numChars > 0)
  4499. {
  4500. identifier = String (text, numChars);
  4501. text = t;
  4502. return true;
  4503. }
  4504. return false;
  4505. }
  4506. Term* readNumber() throw()
  4507. {
  4508. text = text.findEndOfWhitespace();
  4509. String::CharPointerType t (text);
  4510. const bool isResolutionTarget = (*t == '@');
  4511. if (isResolutionTarget)
  4512. {
  4513. ++t;
  4514. t = t.findEndOfWhitespace();
  4515. text = t;
  4516. }
  4517. if (*t == '-')
  4518. {
  4519. ++t;
  4520. t = t.findEndOfWhitespace();
  4521. }
  4522. if (isDecimalDigit (*t) || (*t == '.' && isDecimalDigit (t[1])))
  4523. return new Constant (CharacterFunctions::readDoubleValue (text), isResolutionTarget);
  4524. return 0;
  4525. }
  4526. const TermPtr readExpression()
  4527. {
  4528. TermPtr lhs (readMultiplyOrDivideExpression());
  4529. char opType;
  4530. while (lhs != 0 && readOperator ("+-", &opType))
  4531. {
  4532. TermPtr rhs (readMultiplyOrDivideExpression());
  4533. if (rhs == 0)
  4534. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4535. if (opType == '+')
  4536. lhs = new Add (lhs, rhs);
  4537. else
  4538. lhs = new Subtract (lhs, rhs);
  4539. }
  4540. return lhs;
  4541. }
  4542. const TermPtr readMultiplyOrDivideExpression()
  4543. {
  4544. TermPtr lhs (readUnaryExpression());
  4545. char opType;
  4546. while (lhs != 0 && readOperator ("*/", &opType))
  4547. {
  4548. TermPtr rhs (readUnaryExpression());
  4549. if (rhs == 0)
  4550. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4551. if (opType == '*')
  4552. lhs = new Multiply (lhs, rhs);
  4553. else
  4554. lhs = new Divide (lhs, rhs);
  4555. }
  4556. return lhs;
  4557. }
  4558. const TermPtr readUnaryExpression()
  4559. {
  4560. char opType;
  4561. if (readOperator ("+-", &opType))
  4562. {
  4563. TermPtr term (readUnaryExpression());
  4564. if (term == 0)
  4565. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4566. if (opType == '-')
  4567. term = term->negated();
  4568. return term;
  4569. }
  4570. return readPrimaryExpression();
  4571. }
  4572. const TermPtr readPrimaryExpression()
  4573. {
  4574. TermPtr e (readParenthesisedExpression());
  4575. if (e != 0)
  4576. return e;
  4577. e = readNumber();
  4578. if (e != 0)
  4579. return e;
  4580. return readSymbolOrFunction();
  4581. }
  4582. const TermPtr readSymbolOrFunction()
  4583. {
  4584. String identifier;
  4585. if (readIdentifier (identifier))
  4586. {
  4587. if (readOperator ("(")) // method call...
  4588. {
  4589. Function* const f = new Function (identifier);
  4590. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4591. TermPtr param (readExpression());
  4592. if (param == 0)
  4593. {
  4594. if (readOperator (")"))
  4595. return func.release();
  4596. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4597. }
  4598. f->parameters.add (Expression (param));
  4599. while (readOperator (","))
  4600. {
  4601. param = readExpression();
  4602. if (param == 0)
  4603. throw ParseError ("Expected expression after \",\"");
  4604. f->parameters.add (Expression (param));
  4605. }
  4606. if (readOperator (")"))
  4607. return func.release();
  4608. throw ParseError ("Expected \")\"");
  4609. }
  4610. else if (readOperator ("."))
  4611. {
  4612. TermPtr rhs (readSymbolOrFunction());
  4613. if (rhs == 0)
  4614. throw ParseError ("Expected symbol or function after \".\"");
  4615. if (identifier == "this")
  4616. return rhs;
  4617. return new DotOperator (new SymbolTerm (identifier), rhs);
  4618. }
  4619. else // just a symbol..
  4620. {
  4621. jassert (identifier.trim() == identifier);
  4622. return new SymbolTerm (identifier);
  4623. }
  4624. }
  4625. return 0;
  4626. }
  4627. const TermPtr readParenthesisedExpression()
  4628. {
  4629. if (! readOperator ("("))
  4630. return 0;
  4631. const TermPtr e (readExpression());
  4632. if (e == 0 || ! readOperator (")"))
  4633. return 0;
  4634. return e;
  4635. }
  4636. JUCE_DECLARE_NON_COPYABLE (Parser);
  4637. };
  4638. };
  4639. Expression::Expression()
  4640. : term (new Expression::Helpers::Constant (0, false))
  4641. {
  4642. }
  4643. Expression::~Expression()
  4644. {
  4645. }
  4646. Expression::Expression (Term* const term_)
  4647. : term (term_)
  4648. {
  4649. jassert (term != 0);
  4650. }
  4651. Expression::Expression (const double constant)
  4652. : term (new Expression::Helpers::Constant (constant, false))
  4653. {
  4654. }
  4655. Expression::Expression (const Expression& other)
  4656. : term (other.term)
  4657. {
  4658. }
  4659. Expression& Expression::operator= (const Expression& other)
  4660. {
  4661. term = other.term;
  4662. return *this;
  4663. }
  4664. Expression::Expression (const String& stringToParse)
  4665. {
  4666. String::CharPointerType text (stringToParse.getCharPointer());
  4667. Helpers::Parser parser (text);
  4668. term = parser.readUpToComma();
  4669. }
  4670. const Expression Expression::parse (String::CharPointerType& stringToParse)
  4671. {
  4672. Helpers::Parser parser (stringToParse);
  4673. return Expression (parser.readUpToComma());
  4674. }
  4675. double Expression::evaluate() const
  4676. {
  4677. return evaluate (Expression::Scope());
  4678. }
  4679. double Expression::evaluate (const Expression::Scope& scope) const
  4680. {
  4681. try
  4682. {
  4683. return term->resolve (scope, 0)->toDouble();
  4684. }
  4685. catch (Helpers::EvaluationError&)
  4686. {}
  4687. return 0;
  4688. }
  4689. double Expression::evaluate (const Scope& scope, String& evaluationError) const
  4690. {
  4691. try
  4692. {
  4693. return term->resolve (scope, 0)->toDouble();
  4694. }
  4695. catch (Helpers::EvaluationError& e)
  4696. {
  4697. evaluationError = e.description;
  4698. }
  4699. return 0;
  4700. }
  4701. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4702. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4703. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4704. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4705. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4706. const Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); }
  4707. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4708. {
  4709. return Expression (new Helpers::Function (functionName, parameters));
  4710. }
  4711. const Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const
  4712. {
  4713. ScopedPointer<Term> newTerm (term->clone());
  4714. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4715. if (termToAdjust == 0)
  4716. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4717. if (termToAdjust == 0)
  4718. {
  4719. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4720. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4721. }
  4722. jassert (termToAdjust != 0);
  4723. const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4724. if (parent == 0)
  4725. {
  4726. termToAdjust->value = targetValue;
  4727. }
  4728. else
  4729. {
  4730. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm));
  4731. if (reverseTerm == 0)
  4732. return Expression (targetValue);
  4733. termToAdjust->value = reverseTerm->resolve (scope, 0)->toDouble();
  4734. }
  4735. return Expression (newTerm.release());
  4736. }
  4737. const Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const
  4738. {
  4739. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4740. if (oldSymbol.symbolName == newName)
  4741. return *this;
  4742. Expression e (term->clone());
  4743. e.term->renameSymbol (oldSymbol, newName, scope, 0);
  4744. return e;
  4745. }
  4746. bool Expression::referencesSymbol (const Expression::Symbol& symbol, const Scope& scope) const
  4747. {
  4748. Helpers::SymbolCheckVisitor visitor (symbol);
  4749. try
  4750. {
  4751. term->visitAllSymbols (visitor, scope, 0);
  4752. }
  4753. catch (Helpers::EvaluationError&)
  4754. {}
  4755. return visitor.wasFound;
  4756. }
  4757. void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const
  4758. {
  4759. try
  4760. {
  4761. Helpers::SymbolListVisitor visitor (results);
  4762. term->visitAllSymbols (visitor, scope, 0);
  4763. }
  4764. catch (Helpers::EvaluationError&)
  4765. {}
  4766. }
  4767. const String Expression::toString() const { return term->toString(); }
  4768. bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (term); }
  4769. Expression::Type Expression::getType() const throw() { return term->getType(); }
  4770. const String Expression::getSymbolOrFunction() const { return term->getName(); }
  4771. int Expression::getNumInputs() const { return term->getNumInputs(); }
  4772. const Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); }
  4773. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4774. {
  4775. return new Helpers::Negate (this);
  4776. }
  4777. Expression::ParseError::ParseError (const String& message)
  4778. : description (message)
  4779. {
  4780. DBG ("Expression::ParseError: " + message);
  4781. }
  4782. Expression::Symbol::Symbol (const String& scopeUID_, const String& symbolName_)
  4783. : scopeUID (scopeUID_), symbolName (symbolName_)
  4784. {
  4785. }
  4786. bool Expression::Symbol::operator== (const Symbol& other) const throw()
  4787. {
  4788. return symbolName == other.symbolName && scopeUID == other.scopeUID;
  4789. }
  4790. bool Expression::Symbol::operator!= (const Symbol& other) const throw()
  4791. {
  4792. return ! operator== (other);
  4793. }
  4794. Expression::Scope::Scope() {}
  4795. Expression::Scope::~Scope() {}
  4796. const Expression Expression::Scope::getSymbolValue (const String& symbol) const
  4797. {
  4798. throw Helpers::EvaluationError ("Unknown symbol: " + symbol);
  4799. }
  4800. double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4801. {
  4802. if (numParams > 0)
  4803. {
  4804. if (functionName == "min")
  4805. {
  4806. double v = parameters[0];
  4807. for (int i = 1; i < numParams; ++i)
  4808. v = jmin (v, parameters[i]);
  4809. return v;
  4810. }
  4811. else if (functionName == "max")
  4812. {
  4813. double v = parameters[0];
  4814. for (int i = 1; i < numParams; ++i)
  4815. v = jmax (v, parameters[i]);
  4816. return v;
  4817. }
  4818. else if (numParams == 1)
  4819. {
  4820. if (functionName == "sin") return sin (parameters[0]);
  4821. else if (functionName == "cos") return cos (parameters[0]);
  4822. else if (functionName == "tan") return tan (parameters[0]);
  4823. else if (functionName == "abs") return std::abs (parameters[0]);
  4824. }
  4825. }
  4826. throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\"");
  4827. }
  4828. void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const
  4829. {
  4830. throw Helpers::EvaluationError ("Unknown symbol: " + scopeName);
  4831. }
  4832. const String Expression::Scope::getScopeUID() const
  4833. {
  4834. return String::empty;
  4835. }
  4836. END_JUCE_NAMESPACE
  4837. /*** End of inlined file: juce_Expression.cpp ***/
  4838. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4839. BEGIN_JUCE_NAMESPACE
  4840. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4841. {
  4842. jassert (keyData != 0);
  4843. jassert (keyBytes > 0);
  4844. static const uint32 initialPValues [18] =
  4845. {
  4846. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4847. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4848. 0x9216d5d9, 0x8979fb1b
  4849. };
  4850. static const uint32 initialSValues [4 * 256] =
  4851. {
  4852. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4853. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4854. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4855. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4856. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4857. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4858. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4859. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4860. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4861. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4862. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4863. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4864. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4865. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4866. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4867. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4868. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4869. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4870. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4871. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4872. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4873. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4874. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4875. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4876. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4877. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4878. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4879. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4880. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4881. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4882. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4883. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4884. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4885. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4886. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4887. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4888. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4889. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4890. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4891. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4892. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4893. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4894. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4895. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4896. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4897. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4898. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4899. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4900. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4901. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4902. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4903. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4904. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4905. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4906. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4907. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4908. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4909. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4910. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4911. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4912. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4913. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4914. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4915. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4916. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4917. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4918. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4919. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4920. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4921. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4922. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4923. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4924. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4925. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4926. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4927. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4928. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4929. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4930. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4931. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4932. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4933. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4934. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4935. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4936. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4937. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4938. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4939. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4940. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4941. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4942. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4943. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4944. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4945. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4946. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4947. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4948. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4949. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4950. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4951. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4952. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4953. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4954. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4955. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4956. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4957. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4958. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4959. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4960. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4961. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4962. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4963. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4964. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4965. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4966. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4967. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4968. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4969. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4970. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4971. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4972. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4973. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4974. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4975. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4976. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4977. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4978. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4979. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4980. };
  4981. memcpy (p, initialPValues, sizeof (p));
  4982. int i, j = 0;
  4983. for (i = 4; --i >= 0;)
  4984. {
  4985. s[i].malloc (256);
  4986. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4987. }
  4988. for (i = 0; i < 18; ++i)
  4989. {
  4990. uint32 d = 0;
  4991. for (int k = 0; k < 4; ++k)
  4992. {
  4993. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4994. if (++j >= keyBytes)
  4995. j = 0;
  4996. }
  4997. p[i] = initialPValues[i] ^ d;
  4998. }
  4999. uint32 l = 0, r = 0;
  5000. for (i = 0; i < 18; i += 2)
  5001. {
  5002. encrypt (l, r);
  5003. p[i] = l;
  5004. p[i + 1] = r;
  5005. }
  5006. for (i = 0; i < 4; ++i)
  5007. {
  5008. for (j = 0; j < 256; j += 2)
  5009. {
  5010. encrypt (l, r);
  5011. s[i][j] = l;
  5012. s[i][j + 1] = r;
  5013. }
  5014. }
  5015. }
  5016. BlowFish::BlowFish (const BlowFish& other)
  5017. {
  5018. for (int i = 4; --i >= 0;)
  5019. s[i].malloc (256);
  5020. operator= (other);
  5021. }
  5022. BlowFish& BlowFish::operator= (const BlowFish& other)
  5023. {
  5024. memcpy (p, other.p, sizeof (p));
  5025. for (int i = 4; --i >= 0;)
  5026. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  5027. return *this;
  5028. }
  5029. BlowFish::~BlowFish()
  5030. {
  5031. }
  5032. uint32 BlowFish::F (const uint32 x) const throw()
  5033. {
  5034. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  5035. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  5036. }
  5037. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  5038. {
  5039. uint32 l = data1;
  5040. uint32 r = data2;
  5041. for (int i = 0; i < 16; ++i)
  5042. {
  5043. l ^= p[i];
  5044. r ^= F(l);
  5045. swapVariables (l, r);
  5046. }
  5047. data1 = r ^ p[17];
  5048. data2 = l ^ p[16];
  5049. }
  5050. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  5051. {
  5052. uint32 l = data1;
  5053. uint32 r = data2;
  5054. for (int i = 17; i > 1; --i)
  5055. {
  5056. l ^= p[i];
  5057. r ^= F(l);
  5058. swapVariables (l, r);
  5059. }
  5060. data1 = r ^ p[0];
  5061. data2 = l ^ p[1];
  5062. }
  5063. END_JUCE_NAMESPACE
  5064. /*** End of inlined file: juce_BlowFish.cpp ***/
  5065. /*** Start of inlined file: juce_MD5.cpp ***/
  5066. BEGIN_JUCE_NAMESPACE
  5067. MD5::MD5()
  5068. {
  5069. zerostruct (result);
  5070. }
  5071. MD5::MD5 (const MD5& other)
  5072. {
  5073. memcpy (result, other.result, sizeof (result));
  5074. }
  5075. MD5& MD5::operator= (const MD5& other)
  5076. {
  5077. memcpy (result, other.result, sizeof (result));
  5078. return *this;
  5079. }
  5080. MD5::MD5 (const MemoryBlock& data)
  5081. {
  5082. ProcessContext context;
  5083. context.processBlock (data.getData(), data.getSize());
  5084. context.finish (result);
  5085. }
  5086. MD5::MD5 (const void* data, const size_t numBytes)
  5087. {
  5088. ProcessContext context;
  5089. context.processBlock (data, numBytes);
  5090. context.finish (result);
  5091. }
  5092. MD5::MD5 (const String& text)
  5093. {
  5094. ProcessContext context;
  5095. String::CharPointerType t (text.getCharPointer());
  5096. while (! t.isEmpty())
  5097. {
  5098. // force the string into integer-sized unicode characters, to try to make it
  5099. // get the same results on all platforms + compilers.
  5100. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t.getAndAdvance());
  5101. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  5102. }
  5103. context.finish (result);
  5104. }
  5105. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  5106. {
  5107. ProcessContext context;
  5108. if (numBytesToRead < 0)
  5109. numBytesToRead = std::numeric_limits<int64>::max();
  5110. while (numBytesToRead > 0)
  5111. {
  5112. uint8 tempBuffer [512];
  5113. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  5114. if (bytesRead <= 0)
  5115. break;
  5116. numBytesToRead -= bytesRead;
  5117. context.processBlock (tempBuffer, bytesRead);
  5118. }
  5119. context.finish (result);
  5120. }
  5121. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  5122. {
  5123. processStream (input, numBytesToRead);
  5124. }
  5125. MD5::MD5 (const File& file)
  5126. {
  5127. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  5128. if (fin != 0)
  5129. processStream (*fin, -1);
  5130. else
  5131. zerostruct (result);
  5132. }
  5133. MD5::~MD5()
  5134. {
  5135. }
  5136. namespace MD5Functions
  5137. {
  5138. void encode (void* const output, const void* const input, const int numBytes) throw()
  5139. {
  5140. for (int i = 0; i < (numBytes >> 2); ++i)
  5141. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  5142. }
  5143. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  5144. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  5145. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  5146. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  5147. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  5148. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5149. {
  5150. a += F (b, c, d) + x + ac;
  5151. a = rotateLeft (a, s) + b;
  5152. }
  5153. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5154. {
  5155. a += G (b, c, d) + x + ac;
  5156. a = rotateLeft (a, s) + b;
  5157. }
  5158. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5159. {
  5160. a += H (b, c, d) + x + ac;
  5161. a = rotateLeft (a, s) + b;
  5162. }
  5163. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5164. {
  5165. a += I (b, c, d) + x + ac;
  5166. a = rotateLeft (a, s) + b;
  5167. }
  5168. }
  5169. MD5::ProcessContext::ProcessContext()
  5170. {
  5171. state[0] = 0x67452301;
  5172. state[1] = 0xefcdab89;
  5173. state[2] = 0x98badcfe;
  5174. state[3] = 0x10325476;
  5175. count[0] = 0;
  5176. count[1] = 0;
  5177. }
  5178. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  5179. {
  5180. int bufferPos = ((count[0] >> 3) & 0x3F);
  5181. count[0] += (uint32) (dataSize << 3);
  5182. if (count[0] < ((uint32) dataSize << 3))
  5183. count[1]++;
  5184. count[1] += (uint32) (dataSize >> 29);
  5185. const size_t spaceLeft = 64 - bufferPos;
  5186. size_t i = 0;
  5187. if (dataSize >= spaceLeft)
  5188. {
  5189. memcpy (buffer + bufferPos, data, spaceLeft);
  5190. transform (buffer);
  5191. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  5192. transform (static_cast <const char*> (data) + i);
  5193. bufferPos = 0;
  5194. }
  5195. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  5196. }
  5197. void MD5::ProcessContext::finish (void* const result)
  5198. {
  5199. unsigned char encodedLength[8];
  5200. MD5Functions::encode (encodedLength, count, 8);
  5201. // Pad out to 56 mod 64.
  5202. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  5203. const int paddingLength = (index < 56) ? (56 - index)
  5204. : (120 - index);
  5205. uint8 paddingBuffer [64];
  5206. zeromem (paddingBuffer, paddingLength);
  5207. paddingBuffer [0] = 0x80;
  5208. processBlock (paddingBuffer, paddingLength);
  5209. processBlock (encodedLength, 8);
  5210. MD5Functions::encode (result, state, 16);
  5211. zerostruct (buffer);
  5212. }
  5213. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  5214. {
  5215. using namespace MD5Functions;
  5216. uint32 a = state[0];
  5217. uint32 b = state[1];
  5218. uint32 c = state[2];
  5219. uint32 d = state[3];
  5220. uint32 x[16];
  5221. encode (x, bufferToTransform, 64);
  5222. enum Constants
  5223. {
  5224. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  5225. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  5226. };
  5227. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  5228. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  5229. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  5230. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  5231. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  5232. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  5233. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  5234. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  5235. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  5236. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  5237. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  5238. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  5239. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  5240. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  5241. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  5242. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  5243. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  5244. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  5245. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  5246. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  5247. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  5248. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  5249. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  5250. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  5251. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  5252. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  5253. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  5254. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  5255. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  5256. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  5257. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  5258. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  5259. state[0] += a;
  5260. state[1] += b;
  5261. state[2] += c;
  5262. state[3] += d;
  5263. zerostruct (x);
  5264. }
  5265. const MemoryBlock MD5::getRawChecksumData() const
  5266. {
  5267. return MemoryBlock (result, sizeof (result));
  5268. }
  5269. const String MD5::toHexString() const
  5270. {
  5271. return String::toHexString (result, sizeof (result), 0);
  5272. }
  5273. bool MD5::operator== (const MD5& other) const
  5274. {
  5275. return memcmp (result, other.result, sizeof (result)) == 0;
  5276. }
  5277. bool MD5::operator!= (const MD5& other) const
  5278. {
  5279. return ! operator== (other);
  5280. }
  5281. END_JUCE_NAMESPACE
  5282. /*** End of inlined file: juce_MD5.cpp ***/
  5283. /*** Start of inlined file: juce_Primes.cpp ***/
  5284. BEGIN_JUCE_NAMESPACE
  5285. namespace PrimesHelpers
  5286. {
  5287. void createSmallSieve (const int numBits, BigInteger& result)
  5288. {
  5289. result.setBit (numBits);
  5290. result.clearBit (numBits); // to enlarge the array
  5291. result.setBit (0);
  5292. int n = 2;
  5293. do
  5294. {
  5295. for (int i = n + n; i < numBits; i += n)
  5296. result.setBit (i);
  5297. n = result.findNextClearBit (n + 1);
  5298. }
  5299. while (n <= (numBits >> 1));
  5300. }
  5301. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5302. const BigInteger& smallSieve, const int smallSieveSize)
  5303. {
  5304. jassert (! base[0]); // must be even!
  5305. result.setBit (numBits);
  5306. result.clearBit (numBits); // to enlarge the array
  5307. int index = smallSieve.findNextClearBit (0);
  5308. do
  5309. {
  5310. const int prime = (index << 1) + 1;
  5311. BigInteger r (base), remainder;
  5312. r.divideBy (prime, remainder);
  5313. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5314. if (r.isZero())
  5315. i += prime;
  5316. if ((i & 1) == 0)
  5317. i += prime;
  5318. i = (i - 1) >> 1;
  5319. while (i < numBits)
  5320. {
  5321. result.setBit (i);
  5322. i += prime;
  5323. }
  5324. index = smallSieve.findNextClearBit (index + 1);
  5325. }
  5326. while (index < smallSieveSize);
  5327. }
  5328. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5329. const int numBits, BigInteger& result, const int certainty)
  5330. {
  5331. for (int i = 0; i < numBits; ++i)
  5332. {
  5333. if (! sieve[i])
  5334. {
  5335. result = base + (unsigned int) ((i << 1) + 1);
  5336. if (Primes::isProbablyPrime (result, certainty))
  5337. return true;
  5338. }
  5339. }
  5340. return false;
  5341. }
  5342. bool passesMillerRabin (const BigInteger& n, int iterations)
  5343. {
  5344. const BigInteger one (1), two (2);
  5345. const BigInteger nMinusOne (n - one);
  5346. BigInteger d (nMinusOne);
  5347. const int s = d.findNextSetBit (0);
  5348. d >>= s;
  5349. BigInteger smallPrimes;
  5350. int numBitsInSmallPrimes = 0;
  5351. for (;;)
  5352. {
  5353. numBitsInSmallPrimes += 256;
  5354. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5355. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5356. if (numPrimesFound > iterations + 1)
  5357. break;
  5358. }
  5359. int smallPrime = 2;
  5360. while (--iterations >= 0)
  5361. {
  5362. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5363. BigInteger r (smallPrime);
  5364. r.exponentModulo (d, n);
  5365. if (r != one && r != nMinusOne)
  5366. {
  5367. for (int j = 0; j < s; ++j)
  5368. {
  5369. r.exponentModulo (two, n);
  5370. if (r == nMinusOne)
  5371. break;
  5372. }
  5373. if (r != nMinusOne)
  5374. return false;
  5375. }
  5376. }
  5377. return true;
  5378. }
  5379. }
  5380. const BigInteger Primes::createProbablePrime (const int bitLength,
  5381. const int certainty,
  5382. const int* randomSeeds,
  5383. int numRandomSeeds)
  5384. {
  5385. using namespace PrimesHelpers;
  5386. int defaultSeeds [16];
  5387. if (numRandomSeeds <= 0)
  5388. {
  5389. randomSeeds = defaultSeeds;
  5390. numRandomSeeds = numElementsInArray (defaultSeeds);
  5391. Random r (0);
  5392. for (int j = 10; --j >= 0;)
  5393. {
  5394. r.setSeedRandomly();
  5395. for (int i = numRandomSeeds; --i >= 0;)
  5396. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5397. }
  5398. }
  5399. BigInteger smallSieve;
  5400. const int smallSieveSize = 15000;
  5401. createSmallSieve (smallSieveSize, smallSieve);
  5402. BigInteger p;
  5403. for (int i = numRandomSeeds; --i >= 0;)
  5404. {
  5405. BigInteger p2;
  5406. Random r (randomSeeds[i]);
  5407. r.fillBitsRandomly (p2, 0, bitLength);
  5408. p ^= p2;
  5409. }
  5410. p.setBit (bitLength - 1);
  5411. p.clearBit (0);
  5412. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5413. while (p.getHighestBit() < bitLength)
  5414. {
  5415. p += 2 * searchLen;
  5416. BigInteger sieve;
  5417. bigSieve (p, searchLen, sieve,
  5418. smallSieve, smallSieveSize);
  5419. BigInteger candidate;
  5420. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5421. return candidate;
  5422. }
  5423. jassertfalse;
  5424. return BigInteger();
  5425. }
  5426. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5427. {
  5428. using namespace PrimesHelpers;
  5429. if (! number[0])
  5430. return false;
  5431. if (number.getHighestBit() <= 10)
  5432. {
  5433. const int num = number.getBitRangeAsInt (0, 10);
  5434. for (int i = num / 2; --i > 1;)
  5435. if (num % i == 0)
  5436. return false;
  5437. return true;
  5438. }
  5439. else
  5440. {
  5441. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5442. return false;
  5443. return passesMillerRabin (number, certainty);
  5444. }
  5445. }
  5446. END_JUCE_NAMESPACE
  5447. /*** End of inlined file: juce_Primes.cpp ***/
  5448. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5449. BEGIN_JUCE_NAMESPACE
  5450. RSAKey::RSAKey()
  5451. {
  5452. }
  5453. RSAKey::RSAKey (const String& s)
  5454. {
  5455. if (s.containsChar (','))
  5456. {
  5457. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5458. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5459. }
  5460. else
  5461. {
  5462. // the string needs to be two hex numbers, comma-separated..
  5463. jassertfalse;
  5464. }
  5465. }
  5466. RSAKey::~RSAKey()
  5467. {
  5468. }
  5469. bool RSAKey::operator== (const RSAKey& other) const throw()
  5470. {
  5471. return part1 == other.part1 && part2 == other.part2;
  5472. }
  5473. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5474. {
  5475. return ! operator== (other);
  5476. }
  5477. const String RSAKey::toString() const
  5478. {
  5479. return part1.toString (16) + "," + part2.toString (16);
  5480. }
  5481. bool RSAKey::applyToValue (BigInteger& value) const
  5482. {
  5483. if (part1.isZero() || part2.isZero() || value <= 0)
  5484. {
  5485. jassertfalse; // using an uninitialised key
  5486. value.clear();
  5487. return false;
  5488. }
  5489. BigInteger result;
  5490. while (! value.isZero())
  5491. {
  5492. result *= part2;
  5493. BigInteger remainder;
  5494. value.divideBy (part2, remainder);
  5495. remainder.exponentModulo (part1, part2);
  5496. result += remainder;
  5497. }
  5498. value.swapWith (result);
  5499. return true;
  5500. }
  5501. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5502. {
  5503. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5504. // are fast to divide + multiply
  5505. for (int i = 2; i <= 65536; i *= 2)
  5506. {
  5507. const BigInteger e (1 + i);
  5508. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5509. return e;
  5510. }
  5511. BigInteger e (4);
  5512. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5513. ++e;
  5514. return e;
  5515. }
  5516. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5517. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5518. {
  5519. jassert (numBits > 16); // not much point using less than this..
  5520. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5521. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5522. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5523. const BigInteger n (p * q);
  5524. const BigInteger m (--p * --q);
  5525. const BigInteger e (findBestCommonDivisor (p, q));
  5526. BigInteger d (e);
  5527. d.inverseModulo (m);
  5528. publicKey.part1 = e;
  5529. publicKey.part2 = n;
  5530. privateKey.part1 = d;
  5531. privateKey.part2 = n;
  5532. }
  5533. END_JUCE_NAMESPACE
  5534. /*** End of inlined file: juce_RSAKey.cpp ***/
  5535. /*** Start of inlined file: juce_InputStream.cpp ***/
  5536. BEGIN_JUCE_NAMESPACE
  5537. char InputStream::readByte()
  5538. {
  5539. char temp = 0;
  5540. read (&temp, 1);
  5541. return temp;
  5542. }
  5543. bool InputStream::readBool()
  5544. {
  5545. return readByte() != 0;
  5546. }
  5547. short InputStream::readShort()
  5548. {
  5549. char temp[2];
  5550. if (read (temp, 2) == 2)
  5551. return (short) ByteOrder::littleEndianShort (temp);
  5552. return 0;
  5553. }
  5554. short InputStream::readShortBigEndian()
  5555. {
  5556. char temp[2];
  5557. if (read (temp, 2) == 2)
  5558. return (short) ByteOrder::bigEndianShort (temp);
  5559. return 0;
  5560. }
  5561. int InputStream::readInt()
  5562. {
  5563. char temp[4];
  5564. if (read (temp, 4) == 4)
  5565. return (int) ByteOrder::littleEndianInt (temp);
  5566. return 0;
  5567. }
  5568. int InputStream::readIntBigEndian()
  5569. {
  5570. char temp[4];
  5571. if (read (temp, 4) == 4)
  5572. return (int) ByteOrder::bigEndianInt (temp);
  5573. return 0;
  5574. }
  5575. int InputStream::readCompressedInt()
  5576. {
  5577. const unsigned char sizeByte = readByte();
  5578. if (sizeByte == 0)
  5579. return 0;
  5580. const int numBytes = (sizeByte & 0x7f);
  5581. if (numBytes > 4)
  5582. {
  5583. jassertfalse; // trying to read corrupt data - this method must only be used
  5584. // to read data that was written by OutputStream::writeCompressedInt()
  5585. return 0;
  5586. }
  5587. char bytes[4] = { 0, 0, 0, 0 };
  5588. if (read (bytes, numBytes) != numBytes)
  5589. return 0;
  5590. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5591. return (sizeByte >> 7) ? -num : num;
  5592. }
  5593. int64 InputStream::readInt64()
  5594. {
  5595. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5596. if (read (n.asBytes, 8) == 8)
  5597. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5598. return 0;
  5599. }
  5600. int64 InputStream::readInt64BigEndian()
  5601. {
  5602. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5603. if (read (n.asBytes, 8) == 8)
  5604. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5605. return 0;
  5606. }
  5607. float InputStream::readFloat()
  5608. {
  5609. // the union below relies on these types being the same size...
  5610. static_jassert (sizeof (int32) == sizeof (float));
  5611. union { int32 asInt; float asFloat; } n;
  5612. n.asInt = (int32) readInt();
  5613. return n.asFloat;
  5614. }
  5615. float InputStream::readFloatBigEndian()
  5616. {
  5617. union { int32 asInt; float asFloat; } n;
  5618. n.asInt = (int32) readIntBigEndian();
  5619. return n.asFloat;
  5620. }
  5621. double InputStream::readDouble()
  5622. {
  5623. union { int64 asInt; double asDouble; } n;
  5624. n.asInt = readInt64();
  5625. return n.asDouble;
  5626. }
  5627. double InputStream::readDoubleBigEndian()
  5628. {
  5629. union { int64 asInt; double asDouble; } n;
  5630. n.asInt = readInt64BigEndian();
  5631. return n.asDouble;
  5632. }
  5633. const String InputStream::readString()
  5634. {
  5635. MemoryBlock buffer (256);
  5636. char* data = static_cast<char*> (buffer.getData());
  5637. size_t i = 0;
  5638. while ((data[i] = readByte()) != 0)
  5639. {
  5640. if (++i >= buffer.getSize())
  5641. {
  5642. buffer.setSize (buffer.getSize() + 512);
  5643. data = static_cast<char*> (buffer.getData());
  5644. }
  5645. }
  5646. return String::fromUTF8 (data, (int) i);
  5647. }
  5648. const String InputStream::readNextLine()
  5649. {
  5650. MemoryBlock buffer (256);
  5651. char* data = static_cast<char*> (buffer.getData());
  5652. size_t i = 0;
  5653. while ((data[i] = readByte()) != 0)
  5654. {
  5655. if (data[i] == '\n')
  5656. break;
  5657. if (data[i] == '\r')
  5658. {
  5659. const int64 lastPos = getPosition();
  5660. if (readByte() != '\n')
  5661. setPosition (lastPos);
  5662. break;
  5663. }
  5664. if (++i >= buffer.getSize())
  5665. {
  5666. buffer.setSize (buffer.getSize() + 512);
  5667. data = static_cast<char*> (buffer.getData());
  5668. }
  5669. }
  5670. return String::fromUTF8 (data, (int) i);
  5671. }
  5672. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5673. {
  5674. MemoryOutputStream mo (block, true);
  5675. return mo.writeFromInputStream (*this, numBytes);
  5676. }
  5677. const String InputStream::readEntireStreamAsString()
  5678. {
  5679. MemoryOutputStream mo;
  5680. mo.writeFromInputStream (*this, -1);
  5681. return mo.toString();
  5682. }
  5683. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5684. {
  5685. if (numBytesToSkip > 0)
  5686. {
  5687. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5688. HeapBlock<char> temp (skipBufferSize);
  5689. while (numBytesToSkip > 0 && ! isExhausted())
  5690. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5691. }
  5692. }
  5693. END_JUCE_NAMESPACE
  5694. /*** End of inlined file: juce_InputStream.cpp ***/
  5695. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5696. BEGIN_JUCE_NAMESPACE
  5697. #if JUCE_DEBUG
  5698. static Array<void*, CriticalSection> activeStreams;
  5699. void juce_CheckForDanglingStreams()
  5700. {
  5701. /*
  5702. It's always a bad idea to leak any object, but if you're leaking output
  5703. streams, then there's a good chance that you're failing to flush a file
  5704. to disk properly, which could result in corrupted data and other similar
  5705. nastiness..
  5706. */
  5707. jassert (activeStreams.size() == 0);
  5708. };
  5709. #endif
  5710. OutputStream::OutputStream()
  5711. : newLineString (NewLine::getDefault())
  5712. {
  5713. #if JUCE_DEBUG
  5714. activeStreams.add (this);
  5715. #endif
  5716. }
  5717. OutputStream::~OutputStream()
  5718. {
  5719. #if JUCE_DEBUG
  5720. activeStreams.removeValue (this);
  5721. #endif
  5722. }
  5723. void OutputStream::writeBool (const bool b)
  5724. {
  5725. writeByte (b ? (char) 1
  5726. : (char) 0);
  5727. }
  5728. void OutputStream::writeByte (char byte)
  5729. {
  5730. write (&byte, 1);
  5731. }
  5732. void OutputStream::writeRepeatedByte (uint8 byte, int numTimesToRepeat)
  5733. {
  5734. while (--numTimesToRepeat >= 0)
  5735. writeByte (byte);
  5736. }
  5737. void OutputStream::writeShort (short value)
  5738. {
  5739. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5740. write (&v, 2);
  5741. }
  5742. void OutputStream::writeShortBigEndian (short value)
  5743. {
  5744. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5745. write (&v, 2);
  5746. }
  5747. void OutputStream::writeInt (int value)
  5748. {
  5749. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5750. write (&v, 4);
  5751. }
  5752. void OutputStream::writeIntBigEndian (int value)
  5753. {
  5754. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5755. write (&v, 4);
  5756. }
  5757. void OutputStream::writeCompressedInt (int value)
  5758. {
  5759. unsigned int un = (value < 0) ? (unsigned int) -value
  5760. : (unsigned int) value;
  5761. uint8 data[5];
  5762. int num = 0;
  5763. while (un > 0)
  5764. {
  5765. data[++num] = (uint8) un;
  5766. un >>= 8;
  5767. }
  5768. data[0] = (uint8) num;
  5769. if (value < 0)
  5770. data[0] |= 0x80;
  5771. write (data, num + 1);
  5772. }
  5773. void OutputStream::writeInt64 (int64 value)
  5774. {
  5775. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5776. write (&v, 8);
  5777. }
  5778. void OutputStream::writeInt64BigEndian (int64 value)
  5779. {
  5780. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5781. write (&v, 8);
  5782. }
  5783. void OutputStream::writeFloat (float value)
  5784. {
  5785. union { int asInt; float asFloat; } n;
  5786. n.asFloat = value;
  5787. writeInt (n.asInt);
  5788. }
  5789. void OutputStream::writeFloatBigEndian (float value)
  5790. {
  5791. union { int asInt; float asFloat; } n;
  5792. n.asFloat = value;
  5793. writeIntBigEndian (n.asInt);
  5794. }
  5795. void OutputStream::writeDouble (double value)
  5796. {
  5797. union { int64 asInt; double asDouble; } n;
  5798. n.asDouble = value;
  5799. writeInt64 (n.asInt);
  5800. }
  5801. void OutputStream::writeDoubleBigEndian (double value)
  5802. {
  5803. union { int64 asInt; double asDouble; } n;
  5804. n.asDouble = value;
  5805. writeInt64BigEndian (n.asInt);
  5806. }
  5807. void OutputStream::writeString (const String& text)
  5808. {
  5809. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5810. // if lots of large, persistent strings were to be written to streams).
  5811. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5812. HeapBlock<char> temp (numBytes);
  5813. text.copyToUTF8 (temp, numBytes);
  5814. write (temp, numBytes);
  5815. }
  5816. void OutputStream::writeText (const String& text, const bool asUTF16,
  5817. const bool writeUTF16ByteOrderMark)
  5818. {
  5819. if (asUTF16)
  5820. {
  5821. if (writeUTF16ByteOrderMark)
  5822. write ("\x0ff\x0fe", 2);
  5823. String::CharPointerType src (text.getCharPointer());
  5824. bool lastCharWasReturn = false;
  5825. for (;;)
  5826. {
  5827. const juce_wchar c = src.getAndAdvance();
  5828. if (c == 0)
  5829. break;
  5830. if (c == '\n' && ! lastCharWasReturn)
  5831. writeShort ((short) '\r');
  5832. lastCharWasReturn = (c == L'\r');
  5833. writeShort ((short) c);
  5834. }
  5835. }
  5836. else
  5837. {
  5838. const char* src = text.toUTF8();
  5839. const char* t = src;
  5840. for (;;)
  5841. {
  5842. if (*t == '\n')
  5843. {
  5844. if (t > src)
  5845. write (src, (int) (t - src));
  5846. write ("\r\n", 2);
  5847. src = t + 1;
  5848. }
  5849. else if (*t == '\r')
  5850. {
  5851. if (t[1] == '\n')
  5852. ++t;
  5853. }
  5854. else if (*t == 0)
  5855. {
  5856. if (t > src)
  5857. write (src, (int) (t - src));
  5858. break;
  5859. }
  5860. ++t;
  5861. }
  5862. }
  5863. }
  5864. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5865. {
  5866. if (numBytesToWrite < 0)
  5867. numBytesToWrite = std::numeric_limits<int64>::max();
  5868. int numWritten = 0;
  5869. while (numBytesToWrite > 0 && ! source.isExhausted())
  5870. {
  5871. char buffer [8192];
  5872. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5873. if (num <= 0)
  5874. break;
  5875. write (buffer, num);
  5876. numBytesToWrite -= num;
  5877. numWritten += num;
  5878. }
  5879. return numWritten;
  5880. }
  5881. void OutputStream::setNewLineString (const String& newLineString_)
  5882. {
  5883. newLineString = newLineString_;
  5884. }
  5885. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5886. {
  5887. return stream << String (number);
  5888. }
  5889. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5890. {
  5891. return stream << String (number);
  5892. }
  5893. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5894. {
  5895. stream.writeByte (character);
  5896. return stream;
  5897. }
  5898. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5899. {
  5900. stream.write (text, (int) strlen (text));
  5901. return stream;
  5902. }
  5903. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5904. {
  5905. stream.write (data.getData(), (int) data.getSize());
  5906. return stream;
  5907. }
  5908. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5909. {
  5910. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5911. if (in != 0)
  5912. stream.writeFromInputStream (*in, -1);
  5913. return stream;
  5914. }
  5915. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
  5916. {
  5917. return stream << stream.getNewLineString();
  5918. }
  5919. END_JUCE_NAMESPACE
  5920. /*** End of inlined file: juce_OutputStream.cpp ***/
  5921. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5922. BEGIN_JUCE_NAMESPACE
  5923. DirectoryIterator::DirectoryIterator (const File& directory,
  5924. bool isRecursive_,
  5925. const String& wildCard_,
  5926. const int whatToLookFor_)
  5927. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5928. wildCard (wildCard_),
  5929. path (File::addTrailingSeparator (directory.getFullPathName())),
  5930. index (-1),
  5931. totalNumFiles (-1),
  5932. whatToLookFor (whatToLookFor_),
  5933. isRecursive (isRecursive_),
  5934. hasBeenAdvanced (false)
  5935. {
  5936. // you have to specify the type of files you're looking for!
  5937. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5938. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5939. }
  5940. DirectoryIterator::~DirectoryIterator()
  5941. {
  5942. }
  5943. bool DirectoryIterator::next()
  5944. {
  5945. return next (0, 0, 0, 0, 0, 0);
  5946. }
  5947. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5948. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5949. {
  5950. hasBeenAdvanced = true;
  5951. if (subIterator != 0)
  5952. {
  5953. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5954. return true;
  5955. subIterator = 0;
  5956. }
  5957. String filename;
  5958. bool isDirectory, isHidden;
  5959. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5960. {
  5961. ++index;
  5962. if (! filename.containsOnly ("."))
  5963. {
  5964. const File fileFound (path + filename, 0);
  5965. bool matches = false;
  5966. if (isDirectory)
  5967. {
  5968. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5969. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5970. matches = (whatToLookFor & File::findDirectories) != 0;
  5971. }
  5972. else
  5973. {
  5974. matches = (whatToLookFor & File::findFiles) != 0;
  5975. }
  5976. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5977. if (matches && isRecursive)
  5978. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5979. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5980. matches = ! isHidden;
  5981. if (matches)
  5982. {
  5983. currentFile = fileFound;
  5984. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5985. if (isDirResult != 0) *isDirResult = isDirectory;
  5986. return true;
  5987. }
  5988. else if (subIterator != 0)
  5989. {
  5990. return next();
  5991. }
  5992. }
  5993. }
  5994. return false;
  5995. }
  5996. const File DirectoryIterator::getFile() const
  5997. {
  5998. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5999. return subIterator->getFile();
  6000. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  6001. jassert (hasBeenAdvanced);
  6002. return currentFile;
  6003. }
  6004. float DirectoryIterator::getEstimatedProgress() const
  6005. {
  6006. if (totalNumFiles < 0)
  6007. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  6008. if (totalNumFiles <= 0)
  6009. return 0.0f;
  6010. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  6011. : (float) index;
  6012. return detailedIndex / totalNumFiles;
  6013. }
  6014. END_JUCE_NAMESPACE
  6015. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  6016. /*** Start of inlined file: juce_File.cpp ***/
  6017. #if ! JUCE_WINDOWS
  6018. #include <pwd.h>
  6019. #endif
  6020. BEGIN_JUCE_NAMESPACE
  6021. File::File (const String& fullPathName)
  6022. : fullPath (parseAbsolutePath (fullPathName))
  6023. {
  6024. }
  6025. File::File (const String& path, int)
  6026. : fullPath (path)
  6027. {
  6028. }
  6029. const File File::createFileWithoutCheckingPath (const String& path)
  6030. {
  6031. return File (path, 0);
  6032. }
  6033. File::File (const File& other)
  6034. : fullPath (other.fullPath)
  6035. {
  6036. }
  6037. File& File::operator= (const String& newPath)
  6038. {
  6039. fullPath = parseAbsolutePath (newPath);
  6040. return *this;
  6041. }
  6042. File& File::operator= (const File& other)
  6043. {
  6044. fullPath = other.fullPath;
  6045. return *this;
  6046. }
  6047. const File File::nonexistent;
  6048. const String File::parseAbsolutePath (const String& p)
  6049. {
  6050. if (p.isEmpty())
  6051. return String::empty;
  6052. #if JUCE_WINDOWS
  6053. // Windows..
  6054. String path (p.replaceCharacter ('/', '\\'));
  6055. if (path.startsWithChar (File::separator))
  6056. {
  6057. if (path[1] != File::separator)
  6058. {
  6059. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6060. If you're trying to parse a string that may be either a relative path or an absolute path,
  6061. you MUST provide a context against which the partial path can be evaluated - you can do
  6062. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6063. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6064. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6065. */
  6066. jassertfalse;
  6067. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  6068. }
  6069. }
  6070. else if (! path.containsChar (':'))
  6071. {
  6072. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6073. If you're trying to parse a string that may be either a relative path or an absolute path,
  6074. you MUST provide a context against which the partial path can be evaluated - you can do
  6075. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6076. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6077. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6078. */
  6079. jassertfalse;
  6080. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6081. }
  6082. #else
  6083. // Mac or Linux..
  6084. // Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
  6085. // to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
  6086. // If that's why you've ended up here, use File::getChildFile() to build your paths instead.
  6087. jassert ((! p.containsChar ('\\')) || (p.indexOfChar ('/') >= 0 && p.indexOfChar ('/') < p.indexOfChar ('\\')));
  6088. String path (p);
  6089. if (path.startsWithChar ('~'))
  6090. {
  6091. if (path[1] == File::separator || path[1] == 0)
  6092. {
  6093. // expand a name of the form "~/abc"
  6094. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  6095. + path.substring (1);
  6096. }
  6097. else
  6098. {
  6099. // expand a name of type "~dave/abc"
  6100. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  6101. struct passwd* const pw = getpwnam (userName.toUTF8());
  6102. if (pw != 0)
  6103. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  6104. }
  6105. }
  6106. else if (! path.startsWithChar (File::separator))
  6107. {
  6108. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6109. If you're trying to parse a string that may be either a relative path or an absolute path,
  6110. you MUST provide a context against which the partial path can be evaluated - you can do
  6111. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6112. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6113. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6114. */
  6115. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  6116. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6117. }
  6118. #endif
  6119. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  6120. path = path.dropLastCharacters (1);
  6121. return path;
  6122. }
  6123. const String File::addTrailingSeparator (const String& path)
  6124. {
  6125. return path.endsWithChar (File::separator) ? path
  6126. : path + File::separator;
  6127. }
  6128. #if JUCE_LINUX
  6129. #define NAMES_ARE_CASE_SENSITIVE 1
  6130. #endif
  6131. bool File::areFileNamesCaseSensitive()
  6132. {
  6133. #if NAMES_ARE_CASE_SENSITIVE
  6134. return true;
  6135. #else
  6136. return false;
  6137. #endif
  6138. }
  6139. bool File::operator== (const File& other) const
  6140. {
  6141. #if NAMES_ARE_CASE_SENSITIVE
  6142. return fullPath == other.fullPath;
  6143. #else
  6144. return fullPath.equalsIgnoreCase (other.fullPath);
  6145. #endif
  6146. }
  6147. bool File::operator!= (const File& other) const
  6148. {
  6149. return ! operator== (other);
  6150. }
  6151. bool File::operator< (const File& other) const
  6152. {
  6153. #if NAMES_ARE_CASE_SENSITIVE
  6154. return fullPath < other.fullPath;
  6155. #else
  6156. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  6157. #endif
  6158. }
  6159. bool File::operator> (const File& other) const
  6160. {
  6161. #if NAMES_ARE_CASE_SENSITIVE
  6162. return fullPath > other.fullPath;
  6163. #else
  6164. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  6165. #endif
  6166. }
  6167. bool File::setReadOnly (const bool shouldBeReadOnly,
  6168. const bool applyRecursively) const
  6169. {
  6170. bool worked = true;
  6171. if (applyRecursively && isDirectory())
  6172. {
  6173. Array <File> subFiles;
  6174. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6175. for (int i = subFiles.size(); --i >= 0;)
  6176. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  6177. }
  6178. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  6179. }
  6180. bool File::deleteRecursively() const
  6181. {
  6182. bool worked = true;
  6183. if (isDirectory())
  6184. {
  6185. Array<File> subFiles;
  6186. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6187. for (int i = subFiles.size(); --i >= 0;)
  6188. worked = subFiles.getReference(i).deleteRecursively() && worked;
  6189. }
  6190. return deleteFile() && worked;
  6191. }
  6192. bool File::moveFileTo (const File& newFile) const
  6193. {
  6194. if (newFile.fullPath == fullPath)
  6195. return true;
  6196. #if ! NAMES_ARE_CASE_SENSITIVE
  6197. if (*this != newFile)
  6198. #endif
  6199. if (! newFile.deleteFile())
  6200. return false;
  6201. return moveInternal (newFile);
  6202. }
  6203. bool File::copyFileTo (const File& newFile) const
  6204. {
  6205. return (*this == newFile)
  6206. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  6207. }
  6208. bool File::copyDirectoryTo (const File& newDirectory) const
  6209. {
  6210. if (isDirectory() && newDirectory.createDirectory())
  6211. {
  6212. Array<File> subFiles;
  6213. findChildFiles (subFiles, File::findFiles, false);
  6214. int i;
  6215. for (i = 0; i < subFiles.size(); ++i)
  6216. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6217. return false;
  6218. subFiles.clear();
  6219. findChildFiles (subFiles, File::findDirectories, false);
  6220. for (i = 0; i < subFiles.size(); ++i)
  6221. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6222. return false;
  6223. return true;
  6224. }
  6225. return false;
  6226. }
  6227. const String File::getPathUpToLastSlash() const
  6228. {
  6229. const int lastSlash = fullPath.lastIndexOfChar (separator);
  6230. if (lastSlash > 0)
  6231. return fullPath.substring (0, lastSlash);
  6232. else if (lastSlash == 0)
  6233. return separatorString;
  6234. else
  6235. return fullPath;
  6236. }
  6237. const File File::getParentDirectory() const
  6238. {
  6239. return File (getPathUpToLastSlash(), (int) 0);
  6240. }
  6241. const String File::getFileName() const
  6242. {
  6243. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  6244. }
  6245. int File::hashCode() const
  6246. {
  6247. return fullPath.hashCode();
  6248. }
  6249. int64 File::hashCode64() const
  6250. {
  6251. return fullPath.hashCode64();
  6252. }
  6253. const String File::getFileNameWithoutExtension() const
  6254. {
  6255. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  6256. const int lastDot = fullPath.lastIndexOfChar ('.');
  6257. if (lastDot > lastSlash)
  6258. return fullPath.substring (lastSlash, lastDot);
  6259. else
  6260. return fullPath.substring (lastSlash);
  6261. }
  6262. bool File::isAChildOf (const File& potentialParent) const
  6263. {
  6264. if (potentialParent == File::nonexistent)
  6265. return false;
  6266. const String ourPath (getPathUpToLastSlash());
  6267. #if NAMES_ARE_CASE_SENSITIVE
  6268. if (potentialParent.fullPath == ourPath)
  6269. #else
  6270. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  6271. #endif
  6272. {
  6273. return true;
  6274. }
  6275. else if (potentialParent.fullPath.length() >= ourPath.length())
  6276. {
  6277. return false;
  6278. }
  6279. else
  6280. {
  6281. return getParentDirectory().isAChildOf (potentialParent);
  6282. }
  6283. }
  6284. bool File::isAbsolutePath (const String& path)
  6285. {
  6286. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  6287. #if JUCE_WINDOWS
  6288. || (path.isNotEmpty() && path[1] == ':');
  6289. #else
  6290. || path.startsWithChar ('~');
  6291. #endif
  6292. }
  6293. const File File::getChildFile (String relativePath) const
  6294. {
  6295. if (isAbsolutePath (relativePath))
  6296. {
  6297. // the path is really absolute..
  6298. return File (relativePath);
  6299. }
  6300. else
  6301. {
  6302. // it's relative, so remove any ../ or ./ bits at the start.
  6303. String path (fullPath);
  6304. if (relativePath[0] == '.')
  6305. {
  6306. #if JUCE_WINDOWS
  6307. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6308. #else
  6309. relativePath = relativePath.trimStart();
  6310. #endif
  6311. while (relativePath[0] == '.')
  6312. {
  6313. if (relativePath[1] == '.')
  6314. {
  6315. if (relativePath [2] == 0 || relativePath[2] == separator)
  6316. {
  6317. const int lastSlash = path.lastIndexOfChar (separator);
  6318. if (lastSlash >= 0)
  6319. path = path.substring (0, lastSlash);
  6320. relativePath = relativePath.substring (3);
  6321. }
  6322. else
  6323. {
  6324. break;
  6325. }
  6326. }
  6327. else if (relativePath[1] == separator)
  6328. {
  6329. relativePath = relativePath.substring (2);
  6330. }
  6331. else
  6332. {
  6333. break;
  6334. }
  6335. }
  6336. }
  6337. return File (addTrailingSeparator (path) + relativePath);
  6338. }
  6339. }
  6340. const File File::getSiblingFile (const String& fileName) const
  6341. {
  6342. return getParentDirectory().getChildFile (fileName);
  6343. }
  6344. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6345. {
  6346. if (bytes == 1)
  6347. {
  6348. return "1 byte";
  6349. }
  6350. else if (bytes < 1024)
  6351. {
  6352. return String ((int) bytes) + " bytes";
  6353. }
  6354. else if (bytes < 1024 * 1024)
  6355. {
  6356. return String (bytes / 1024.0, 1) + " KB";
  6357. }
  6358. else if (bytes < 1024 * 1024 * 1024)
  6359. {
  6360. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6361. }
  6362. else
  6363. {
  6364. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6365. }
  6366. }
  6367. bool File::create() const
  6368. {
  6369. if (exists())
  6370. return true;
  6371. {
  6372. const File parentDir (getParentDirectory());
  6373. if (parentDir == *this || ! parentDir.createDirectory())
  6374. return false;
  6375. FileOutputStream fo (*this, 8);
  6376. }
  6377. return exists();
  6378. }
  6379. bool File::createDirectory() const
  6380. {
  6381. if (! isDirectory())
  6382. {
  6383. const File parentDir (getParentDirectory());
  6384. if (parentDir == *this || ! parentDir.createDirectory())
  6385. return false;
  6386. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6387. return isDirectory();
  6388. }
  6389. return true;
  6390. }
  6391. const Time File::getCreationTime() const
  6392. {
  6393. int64 m, a, c;
  6394. getFileTimesInternal (m, a, c);
  6395. return Time (c);
  6396. }
  6397. const Time File::getLastModificationTime() const
  6398. {
  6399. int64 m, a, c;
  6400. getFileTimesInternal (m, a, c);
  6401. return Time (m);
  6402. }
  6403. const Time File::getLastAccessTime() const
  6404. {
  6405. int64 m, a, c;
  6406. getFileTimesInternal (m, a, c);
  6407. return Time (a);
  6408. }
  6409. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6410. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6411. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6412. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6413. {
  6414. if (! existsAsFile())
  6415. return false;
  6416. FileInputStream in (*this);
  6417. return getSize() == in.readIntoMemoryBlock (destBlock);
  6418. }
  6419. const String File::loadFileAsString() const
  6420. {
  6421. if (! existsAsFile())
  6422. return String::empty;
  6423. FileInputStream in (*this);
  6424. return in.readEntireStreamAsString();
  6425. }
  6426. int File::findChildFiles (Array<File>& results,
  6427. const int whatToLookFor,
  6428. const bool searchRecursively,
  6429. const String& wildCardPattern) const
  6430. {
  6431. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6432. int total = 0;
  6433. while (di.next())
  6434. {
  6435. results.add (di.getFile());
  6436. ++total;
  6437. }
  6438. return total;
  6439. }
  6440. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6441. {
  6442. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6443. int total = 0;
  6444. while (di.next())
  6445. ++total;
  6446. return total;
  6447. }
  6448. bool File::containsSubDirectories() const
  6449. {
  6450. if (isDirectory())
  6451. {
  6452. DirectoryIterator di (*this, false, "*", findDirectories);
  6453. return di.next();
  6454. }
  6455. return false;
  6456. }
  6457. const File File::getNonexistentChildFile (const String& prefix_,
  6458. const String& suffix,
  6459. bool putNumbersInBrackets) const
  6460. {
  6461. File f (getChildFile (prefix_ + suffix));
  6462. if (f.exists())
  6463. {
  6464. int num = 2;
  6465. String prefix (prefix_);
  6466. // remove any bracketed numbers that may already be on the end..
  6467. if (prefix.trim().endsWithChar (')'))
  6468. {
  6469. putNumbersInBrackets = true;
  6470. const int openBracks = prefix.lastIndexOfChar ('(');
  6471. const int closeBracks = prefix.lastIndexOfChar (')');
  6472. if (openBracks > 0
  6473. && closeBracks > openBracks
  6474. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6475. {
  6476. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6477. prefix = prefix.substring (0, openBracks);
  6478. }
  6479. }
  6480. // also use brackets if it ends in a digit.
  6481. putNumbersInBrackets = putNumbersInBrackets
  6482. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6483. do
  6484. {
  6485. if (putNumbersInBrackets)
  6486. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6487. else
  6488. f = getChildFile (prefix + String (num++) + suffix);
  6489. } while (f.exists());
  6490. }
  6491. return f;
  6492. }
  6493. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6494. {
  6495. if (exists())
  6496. {
  6497. return getParentDirectory()
  6498. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6499. getFileExtension(),
  6500. putNumbersInBrackets);
  6501. }
  6502. else
  6503. {
  6504. return *this;
  6505. }
  6506. }
  6507. const String File::getFileExtension() const
  6508. {
  6509. String ext;
  6510. if (! isDirectory())
  6511. {
  6512. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6513. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6514. ext = fullPath.substring (indexOfDot);
  6515. }
  6516. return ext;
  6517. }
  6518. bool File::hasFileExtension (const String& possibleSuffix) const
  6519. {
  6520. if (possibleSuffix.isEmpty())
  6521. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6522. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6523. if (semicolon >= 0)
  6524. {
  6525. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6526. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6527. }
  6528. else
  6529. {
  6530. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6531. {
  6532. if (possibleSuffix.startsWithChar ('.'))
  6533. return true;
  6534. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6535. if (dotPos >= 0)
  6536. return fullPath [dotPos] == '.';
  6537. }
  6538. }
  6539. return false;
  6540. }
  6541. const File File::withFileExtension (const String& newExtension) const
  6542. {
  6543. if (fullPath.isEmpty())
  6544. return File::nonexistent;
  6545. String filePart (getFileName());
  6546. int i = filePart.lastIndexOfChar ('.');
  6547. if (i >= 0)
  6548. filePart = filePart.substring (0, i);
  6549. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6550. filePart << '.';
  6551. return getSiblingFile (filePart + newExtension);
  6552. }
  6553. bool File::startAsProcess (const String& parameters) const
  6554. {
  6555. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6556. }
  6557. FileInputStream* File::createInputStream() const
  6558. {
  6559. if (existsAsFile())
  6560. return new FileInputStream (*this);
  6561. return 0;
  6562. }
  6563. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6564. {
  6565. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6566. if (out->failedToOpen())
  6567. return 0;
  6568. return out.release();
  6569. }
  6570. bool File::appendData (const void* const dataToAppend,
  6571. const int numberOfBytes) const
  6572. {
  6573. if (numberOfBytes > 0)
  6574. {
  6575. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6576. if (out == 0)
  6577. return false;
  6578. out->write (dataToAppend, numberOfBytes);
  6579. }
  6580. return true;
  6581. }
  6582. bool File::replaceWithData (const void* const dataToWrite,
  6583. const int numberOfBytes) const
  6584. {
  6585. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6586. if (numberOfBytes <= 0)
  6587. return deleteFile();
  6588. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6589. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6590. return tempFile.overwriteTargetFileWithTemporary();
  6591. }
  6592. bool File::appendText (const String& text,
  6593. const bool asUnicode,
  6594. const bool writeUnicodeHeaderBytes) const
  6595. {
  6596. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6597. if (out != 0)
  6598. {
  6599. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6600. return true;
  6601. }
  6602. return false;
  6603. }
  6604. bool File::replaceWithText (const String& textToWrite,
  6605. const bool asUnicode,
  6606. const bool writeUnicodeHeaderBytes) const
  6607. {
  6608. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6609. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6610. return tempFile.overwriteTargetFileWithTemporary();
  6611. }
  6612. bool File::hasIdenticalContentTo (const File& other) const
  6613. {
  6614. if (other == *this)
  6615. return true;
  6616. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6617. {
  6618. FileInputStream in1 (*this), in2 (other);
  6619. const int bufferSize = 4096;
  6620. HeapBlock <char> buffer1, buffer2;
  6621. buffer1.malloc (bufferSize);
  6622. buffer2.malloc (bufferSize);
  6623. for (;;)
  6624. {
  6625. const int num1 = in1.read (buffer1, bufferSize);
  6626. const int num2 = in2.read (buffer2, bufferSize);
  6627. if (num1 != num2)
  6628. break;
  6629. if (num1 <= 0)
  6630. return true;
  6631. if (memcmp (buffer1, buffer2, num1) != 0)
  6632. break;
  6633. }
  6634. }
  6635. return false;
  6636. }
  6637. const String File::createLegalPathName (const String& original)
  6638. {
  6639. String s (original);
  6640. String start;
  6641. if (s[1] == ':')
  6642. {
  6643. start = s.substring (0, 2);
  6644. s = s.substring (2);
  6645. }
  6646. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6647. .substring (0, 1024);
  6648. }
  6649. const String File::createLegalFileName (const String& original)
  6650. {
  6651. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6652. const int maxLength = 128; // only the length of the filename, not the whole path
  6653. const int len = s.length();
  6654. if (len > maxLength)
  6655. {
  6656. const int lastDot = s.lastIndexOfChar ('.');
  6657. if (lastDot > jmax (0, len - 12))
  6658. {
  6659. s = s.substring (0, maxLength - (len - lastDot))
  6660. + s.substring (lastDot);
  6661. }
  6662. else
  6663. {
  6664. s = s.substring (0, maxLength);
  6665. }
  6666. }
  6667. return s;
  6668. }
  6669. const String File::getRelativePathFrom (const File& dir) const
  6670. {
  6671. String thisPath (fullPath);
  6672. while (thisPath.endsWithChar (separator))
  6673. thisPath = thisPath.dropLastCharacters (1);
  6674. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6675. : dir.fullPath));
  6676. const int len = jmin (thisPath.length(), dirPath.length());
  6677. int commonBitLength = 0;
  6678. for (int i = 0; i < len; ++i)
  6679. {
  6680. #if NAMES_ARE_CASE_SENSITIVE
  6681. if (thisPath[i] != dirPath[i])
  6682. #else
  6683. if (CharacterFunctions::toLowerCase (thisPath[i])
  6684. != CharacterFunctions::toLowerCase (dirPath[i]))
  6685. #endif
  6686. {
  6687. break;
  6688. }
  6689. ++commonBitLength;
  6690. }
  6691. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6692. --commonBitLength;
  6693. // if the only common bit is the root, then just return the full path..
  6694. if (commonBitLength <= 0
  6695. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6696. return fullPath;
  6697. thisPath = thisPath.substring (commonBitLength);
  6698. dirPath = dirPath.substring (commonBitLength);
  6699. while (dirPath.isNotEmpty())
  6700. {
  6701. #if JUCE_WINDOWS
  6702. thisPath = "..\\" + thisPath;
  6703. #else
  6704. thisPath = "../" + thisPath;
  6705. #endif
  6706. const int sep = dirPath.indexOfChar (separator);
  6707. if (sep >= 0)
  6708. dirPath = dirPath.substring (sep + 1);
  6709. else
  6710. dirPath = String::empty;
  6711. }
  6712. return thisPath;
  6713. }
  6714. const File File::createTempFile (const String& fileNameEnding)
  6715. {
  6716. const File tempFile (getSpecialLocation (tempDirectory)
  6717. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6718. .withFileExtension (fileNameEnding));
  6719. if (tempFile.exists())
  6720. return createTempFile (fileNameEnding);
  6721. else
  6722. return tempFile;
  6723. }
  6724. #if JUCE_UNIT_TESTS
  6725. class FileTests : public UnitTest
  6726. {
  6727. public:
  6728. FileTests() : UnitTest ("Files") {}
  6729. void runTest()
  6730. {
  6731. beginTest ("Reading");
  6732. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6733. const File temp (File::getSpecialLocation (File::tempDirectory));
  6734. expect (! File::nonexistent.exists());
  6735. expect (home.isDirectory());
  6736. expect (home.exists());
  6737. expect (! home.existsAsFile());
  6738. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6739. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6740. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6741. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6742. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6743. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6744. expect (home.getBytesFreeOnVolume() > 0);
  6745. expect (! home.isHidden());
  6746. expect (home.isOnHardDisk());
  6747. expect (! home.isOnCDRomDrive());
  6748. expect (File::getCurrentWorkingDirectory().exists());
  6749. expect (home.setAsCurrentWorkingDirectory());
  6750. expect (File::getCurrentWorkingDirectory() == home);
  6751. {
  6752. Array<File> roots;
  6753. File::findFileSystemRoots (roots);
  6754. expect (roots.size() > 0);
  6755. int numRootsExisting = 0;
  6756. for (int i = 0; i < roots.size(); ++i)
  6757. if (roots[i].exists())
  6758. ++numRootsExisting;
  6759. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6760. expect (numRootsExisting > 0);
  6761. }
  6762. beginTest ("Writing");
  6763. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6764. expect (demoFolder.deleteRecursively());
  6765. expect (demoFolder.createDirectory());
  6766. expect (demoFolder.isDirectory());
  6767. expect (demoFolder.getParentDirectory() == temp);
  6768. expect (temp.isDirectory());
  6769. {
  6770. Array<File> files;
  6771. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6772. expect (files.contains (demoFolder));
  6773. }
  6774. {
  6775. Array<File> files;
  6776. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6777. expect (files.contains (demoFolder));
  6778. }
  6779. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6780. expect (tempFile.getFileExtension() == ".txt");
  6781. expect (tempFile.hasFileExtension (".txt"));
  6782. expect (tempFile.hasFileExtension ("txt"));
  6783. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6784. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6785. expect (tempFile.hasWriteAccess());
  6786. {
  6787. FileOutputStream fo (tempFile);
  6788. fo.write ("0123456789", 10);
  6789. }
  6790. expect (tempFile.exists());
  6791. expect (tempFile.getSize() == 10);
  6792. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6793. expect (tempFile.loadFileAsString() == "0123456789");
  6794. expect (! demoFolder.containsSubDirectories());
  6795. expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::separatorString + tempFile.getFileName());
  6796. expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::separatorString + ".." + File::separatorString + demoFolder.getParentDirectory().getFileName());
  6797. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6798. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6799. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6800. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6801. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6802. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6803. expect (demoFolder.containsSubDirectories());
  6804. expect (tempFile.hasWriteAccess());
  6805. tempFile.setReadOnly (true);
  6806. expect (! tempFile.hasWriteAccess());
  6807. tempFile.setReadOnly (false);
  6808. expect (tempFile.hasWriteAccess());
  6809. Time t (Time::getCurrentTime());
  6810. tempFile.setLastModificationTime (t);
  6811. Time t2 = tempFile.getLastModificationTime();
  6812. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6813. {
  6814. MemoryBlock mb;
  6815. tempFile.loadFileAsData (mb);
  6816. expect (mb.getSize() == 10);
  6817. expect (mb[0] == '0');
  6818. }
  6819. expect (tempFile.appendData ("abcdefghij", 10));
  6820. expect (tempFile.getSize() == 20);
  6821. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6822. expect (tempFile.getSize() == 10);
  6823. File tempFile2 (tempFile.getNonexistentSibling (false));
  6824. expect (tempFile.copyFileTo (tempFile2));
  6825. expect (tempFile2.exists());
  6826. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6827. expect (tempFile.deleteFile());
  6828. expect (! tempFile.exists());
  6829. expect (tempFile2.moveFileTo (tempFile));
  6830. expect (tempFile.exists());
  6831. expect (! tempFile2.exists());
  6832. expect (demoFolder.deleteRecursively());
  6833. expect (! demoFolder.exists());
  6834. }
  6835. };
  6836. static FileTests fileUnitTests;
  6837. #endif
  6838. END_JUCE_NAMESPACE
  6839. /*** End of inlined file: juce_File.cpp ***/
  6840. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6841. BEGIN_JUCE_NAMESPACE
  6842. int64 juce_fileSetPosition (void* handle, int64 pos);
  6843. FileInputStream::FileInputStream (const File& f)
  6844. : file (f),
  6845. fileHandle (0),
  6846. currentPosition (0),
  6847. totalSize (0),
  6848. needToSeek (true)
  6849. {
  6850. openHandle();
  6851. }
  6852. FileInputStream::~FileInputStream()
  6853. {
  6854. closeHandle();
  6855. }
  6856. int64 FileInputStream::getTotalLength()
  6857. {
  6858. return totalSize;
  6859. }
  6860. int FileInputStream::read (void* buffer, int bytesToRead)
  6861. {
  6862. if (needToSeek)
  6863. {
  6864. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6865. return 0;
  6866. needToSeek = false;
  6867. }
  6868. const size_t num = readInternal (buffer, bytesToRead);
  6869. currentPosition += num;
  6870. return (int) num;
  6871. }
  6872. bool FileInputStream::isExhausted()
  6873. {
  6874. return currentPosition >= totalSize;
  6875. }
  6876. int64 FileInputStream::getPosition()
  6877. {
  6878. return currentPosition;
  6879. }
  6880. bool FileInputStream::setPosition (int64 pos)
  6881. {
  6882. pos = jlimit ((int64) 0, totalSize, pos);
  6883. needToSeek |= (currentPosition != pos);
  6884. currentPosition = pos;
  6885. return true;
  6886. }
  6887. END_JUCE_NAMESPACE
  6888. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6889. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6890. BEGIN_JUCE_NAMESPACE
  6891. int64 juce_fileSetPosition (void* handle, int64 pos);
  6892. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6893. : file (f),
  6894. fileHandle (0),
  6895. currentPosition (0),
  6896. bufferSize (bufferSize_),
  6897. bytesInBuffer (0),
  6898. buffer (jmax (bufferSize_, 16))
  6899. {
  6900. openHandle();
  6901. }
  6902. FileOutputStream::~FileOutputStream()
  6903. {
  6904. flush();
  6905. closeHandle();
  6906. }
  6907. int64 FileOutputStream::getPosition()
  6908. {
  6909. return currentPosition;
  6910. }
  6911. bool FileOutputStream::setPosition (int64 newPosition)
  6912. {
  6913. if (newPosition != currentPosition)
  6914. {
  6915. flush();
  6916. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6917. }
  6918. return newPosition == currentPosition;
  6919. }
  6920. void FileOutputStream::flush()
  6921. {
  6922. if (bytesInBuffer > 0)
  6923. {
  6924. writeInternal (buffer, bytesInBuffer);
  6925. bytesInBuffer = 0;
  6926. }
  6927. flushInternal();
  6928. }
  6929. bool FileOutputStream::write (const void* const src, const int numBytes)
  6930. {
  6931. if (bytesInBuffer + numBytes < bufferSize)
  6932. {
  6933. memcpy (buffer + bytesInBuffer, src, numBytes);
  6934. bytesInBuffer += numBytes;
  6935. currentPosition += numBytes;
  6936. }
  6937. else
  6938. {
  6939. if (bytesInBuffer > 0)
  6940. {
  6941. // flush the reservoir
  6942. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6943. bytesInBuffer = 0;
  6944. if (! wroteOk)
  6945. return false;
  6946. }
  6947. if (numBytes < bufferSize)
  6948. {
  6949. memcpy (buffer + bytesInBuffer, src, numBytes);
  6950. bytesInBuffer += numBytes;
  6951. currentPosition += numBytes;
  6952. }
  6953. else
  6954. {
  6955. const int bytesWritten = writeInternal (src, numBytes);
  6956. if (bytesWritten < 0)
  6957. return false;
  6958. currentPosition += bytesWritten;
  6959. return bytesWritten == numBytes;
  6960. }
  6961. }
  6962. return true;
  6963. }
  6964. END_JUCE_NAMESPACE
  6965. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6966. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6967. BEGIN_JUCE_NAMESPACE
  6968. FileSearchPath::FileSearchPath()
  6969. {
  6970. }
  6971. FileSearchPath::FileSearchPath (const String& path)
  6972. {
  6973. init (path);
  6974. }
  6975. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6976. : directories (other.directories)
  6977. {
  6978. }
  6979. FileSearchPath::~FileSearchPath()
  6980. {
  6981. }
  6982. FileSearchPath& FileSearchPath::operator= (const String& path)
  6983. {
  6984. init (path);
  6985. return *this;
  6986. }
  6987. void FileSearchPath::init (const String& path)
  6988. {
  6989. directories.clear();
  6990. directories.addTokens (path, ";", "\"");
  6991. directories.trim();
  6992. directories.removeEmptyStrings();
  6993. for (int i = directories.size(); --i >= 0;)
  6994. directories.set (i, directories[i].unquoted());
  6995. }
  6996. int FileSearchPath::getNumPaths() const
  6997. {
  6998. return directories.size();
  6999. }
  7000. const File FileSearchPath::operator[] (const int index) const
  7001. {
  7002. return File (directories [index]);
  7003. }
  7004. const String FileSearchPath::toString() const
  7005. {
  7006. StringArray directories2 (directories);
  7007. for (int i = directories2.size(); --i >= 0;)
  7008. if (directories2[i].containsChar (';'))
  7009. directories2.set (i, directories2[i].quoted());
  7010. return directories2.joinIntoString (";");
  7011. }
  7012. void FileSearchPath::add (const File& dir, const int insertIndex)
  7013. {
  7014. directories.insert (insertIndex, dir.getFullPathName());
  7015. }
  7016. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  7017. {
  7018. for (int i = 0; i < directories.size(); ++i)
  7019. if (File (directories[i]) == dir)
  7020. return;
  7021. add (dir);
  7022. }
  7023. void FileSearchPath::remove (const int index)
  7024. {
  7025. directories.remove (index);
  7026. }
  7027. void FileSearchPath::addPath (const FileSearchPath& other)
  7028. {
  7029. for (int i = 0; i < other.getNumPaths(); ++i)
  7030. addIfNotAlreadyThere (other[i]);
  7031. }
  7032. void FileSearchPath::removeRedundantPaths()
  7033. {
  7034. for (int i = directories.size(); --i >= 0;)
  7035. {
  7036. const File d1 (directories[i]);
  7037. for (int j = directories.size(); --j >= 0;)
  7038. {
  7039. const File d2 (directories[j]);
  7040. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  7041. {
  7042. directories.remove (i);
  7043. break;
  7044. }
  7045. }
  7046. }
  7047. }
  7048. void FileSearchPath::removeNonExistentPaths()
  7049. {
  7050. for (int i = directories.size(); --i >= 0;)
  7051. if (! File (directories[i]).isDirectory())
  7052. directories.remove (i);
  7053. }
  7054. int FileSearchPath::findChildFiles (Array<File>& results,
  7055. const int whatToLookFor,
  7056. const bool searchRecursively,
  7057. const String& wildCardPattern) const
  7058. {
  7059. int total = 0;
  7060. for (int i = 0; i < directories.size(); ++i)
  7061. total += operator[] (i).findChildFiles (results,
  7062. whatToLookFor,
  7063. searchRecursively,
  7064. wildCardPattern);
  7065. return total;
  7066. }
  7067. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  7068. const bool checkRecursively) const
  7069. {
  7070. for (int i = directories.size(); --i >= 0;)
  7071. {
  7072. const File d (directories[i]);
  7073. if (checkRecursively)
  7074. {
  7075. if (fileToCheck.isAChildOf (d))
  7076. return true;
  7077. }
  7078. else
  7079. {
  7080. if (fileToCheck.getParentDirectory() == d)
  7081. return true;
  7082. }
  7083. }
  7084. return false;
  7085. }
  7086. END_JUCE_NAMESPACE
  7087. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  7088. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  7089. BEGIN_JUCE_NAMESPACE
  7090. NamedPipe::NamedPipe()
  7091. : internal (0)
  7092. {
  7093. }
  7094. NamedPipe::~NamedPipe()
  7095. {
  7096. close();
  7097. }
  7098. bool NamedPipe::openExisting (const String& pipeName)
  7099. {
  7100. currentPipeName = pipeName;
  7101. return openInternal (pipeName, false);
  7102. }
  7103. bool NamedPipe::createNewPipe (const String& pipeName)
  7104. {
  7105. currentPipeName = pipeName;
  7106. return openInternal (pipeName, true);
  7107. }
  7108. bool NamedPipe::isOpen() const
  7109. {
  7110. return internal != 0;
  7111. }
  7112. const String NamedPipe::getName() const
  7113. {
  7114. return currentPipeName;
  7115. }
  7116. // other methods for this class are implemented in the platform-specific files
  7117. END_JUCE_NAMESPACE
  7118. /*** End of inlined file: juce_NamedPipe.cpp ***/
  7119. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  7120. BEGIN_JUCE_NAMESPACE
  7121. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  7122. {
  7123. createTempFile (File::getSpecialLocation (File::tempDirectory),
  7124. "temp_" + String (Random::getSystemRandom().nextInt()),
  7125. suffix,
  7126. optionFlags);
  7127. }
  7128. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  7129. : targetFile (targetFile_)
  7130. {
  7131. // If you use this constructor, you need to give it a valid target file!
  7132. jassert (targetFile != File::nonexistent);
  7133. createTempFile (targetFile.getParentDirectory(),
  7134. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  7135. targetFile.getFileExtension(),
  7136. optionFlags);
  7137. }
  7138. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  7139. const String& suffix, const int optionFlags)
  7140. {
  7141. if ((optionFlags & useHiddenFile) != 0)
  7142. name = "." + name;
  7143. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  7144. }
  7145. TemporaryFile::~TemporaryFile()
  7146. {
  7147. if (! deleteTemporaryFile())
  7148. {
  7149. /* Failed to delete our temporary file! The most likely reason for this would be
  7150. that you've not closed an output stream that was being used to write to file.
  7151. If you find that something beyond your control is changing permissions on
  7152. your temporary files and preventing them from being deleted, you may want to
  7153. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  7154. handle them appropriately.
  7155. */
  7156. jassertfalse;
  7157. }
  7158. }
  7159. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  7160. {
  7161. // This method only works if you created this object with the constructor
  7162. // that takes a target file!
  7163. jassert (targetFile != File::nonexistent);
  7164. if (temporaryFile.exists())
  7165. {
  7166. // Have a few attempts at overwriting the file before giving up..
  7167. for (int i = 5; --i >= 0;)
  7168. {
  7169. if (temporaryFile.moveFileTo (targetFile))
  7170. return true;
  7171. Thread::sleep (100);
  7172. }
  7173. }
  7174. else
  7175. {
  7176. // There's no temporary file to use. If your write failed, you should
  7177. // probably check, and not bother calling this method.
  7178. jassertfalse;
  7179. }
  7180. return false;
  7181. }
  7182. bool TemporaryFile::deleteTemporaryFile() const
  7183. {
  7184. // Have a few attempts at deleting the file before giving up..
  7185. for (int i = 5; --i >= 0;)
  7186. {
  7187. if (temporaryFile.deleteFile())
  7188. return true;
  7189. Thread::sleep (50);
  7190. }
  7191. return false;
  7192. }
  7193. END_JUCE_NAMESPACE
  7194. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  7195. /*** Start of inlined file: juce_Socket.cpp ***/
  7196. #if JUCE_WINDOWS
  7197. #include <winsock2.h>
  7198. #if JUCE_MSVC
  7199. #pragma warning (push)
  7200. #pragma warning (disable : 4127 4389 4018)
  7201. #endif
  7202. #else
  7203. #if JUCE_LINUX || JUCE_ANDROID
  7204. #include <sys/types.h>
  7205. #include <sys/socket.h>
  7206. #include <sys/errno.h>
  7207. #include <unistd.h>
  7208. #include <netinet/in.h>
  7209. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  7210. #include <CoreServices/CoreServices.h>
  7211. #endif
  7212. #include <fcntl.h>
  7213. #include <netdb.h>
  7214. #include <arpa/inet.h>
  7215. #include <netinet/tcp.h>
  7216. #endif
  7217. BEGIN_JUCE_NAMESPACE
  7218. #if JUCE_LINUX || JUCE_MAC || JUCE_IOS || JUCE_ANDROID
  7219. typedef socklen_t juce_socklen_t;
  7220. #else
  7221. typedef int juce_socklen_t;
  7222. #endif
  7223. #if JUCE_WINDOWS
  7224. namespace SocketHelpers
  7225. {
  7226. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  7227. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  7228. void initWin32Sockets()
  7229. {
  7230. static CriticalSection lock;
  7231. const ScopedLock sl (lock);
  7232. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  7233. {
  7234. WSADATA wsaData;
  7235. const WORD wVersionRequested = MAKEWORD (1, 1);
  7236. WSAStartup (wVersionRequested, &wsaData);
  7237. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  7238. }
  7239. }
  7240. }
  7241. void juce_shutdownWin32Sockets()
  7242. {
  7243. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  7244. (*SocketHelpers::juce_CloseWin32SocketLib)();
  7245. }
  7246. #endif
  7247. namespace SocketHelpers
  7248. {
  7249. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  7250. {
  7251. const int sndBufSize = 65536;
  7252. const int rcvBufSize = 65536;
  7253. const int one = 1;
  7254. return handle > 0
  7255. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  7256. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  7257. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  7258. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  7259. }
  7260. bool bindSocketToPort (const int handle, const int port) throw()
  7261. {
  7262. if (handle <= 0 || port <= 0)
  7263. return false;
  7264. struct sockaddr_in servTmpAddr;
  7265. zerostruct (servTmpAddr);
  7266. servTmpAddr.sin_family = PF_INET;
  7267. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7268. servTmpAddr.sin_port = htons ((uint16) port);
  7269. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  7270. }
  7271. int readSocket (const int handle,
  7272. void* const destBuffer, const int maxBytesToRead,
  7273. bool volatile& connected,
  7274. const bool blockUntilSpecifiedAmountHasArrived) throw()
  7275. {
  7276. int bytesRead = 0;
  7277. while (bytesRead < maxBytesToRead)
  7278. {
  7279. int bytesThisTime;
  7280. #if JUCE_WINDOWS
  7281. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  7282. #else
  7283. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  7284. && errno == EINTR
  7285. && connected)
  7286. {
  7287. }
  7288. #endif
  7289. if (bytesThisTime <= 0 || ! connected)
  7290. {
  7291. if (bytesRead == 0)
  7292. bytesRead = -1;
  7293. break;
  7294. }
  7295. bytesRead += bytesThisTime;
  7296. if (! blockUntilSpecifiedAmountHasArrived)
  7297. break;
  7298. }
  7299. return bytesRead;
  7300. }
  7301. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  7302. {
  7303. struct timeval timeout;
  7304. struct timeval* timeoutp;
  7305. if (timeoutMsecs >= 0)
  7306. {
  7307. timeout.tv_sec = timeoutMsecs / 1000;
  7308. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7309. timeoutp = &timeout;
  7310. }
  7311. else
  7312. {
  7313. timeoutp = 0;
  7314. }
  7315. fd_set rset, wset;
  7316. FD_ZERO (&rset);
  7317. FD_SET (handle, &rset);
  7318. FD_ZERO (&wset);
  7319. FD_SET (handle, &wset);
  7320. fd_set* const prset = forReading ? &rset : 0;
  7321. fd_set* const pwset = forReading ? 0 : &wset;
  7322. #if JUCE_WINDOWS
  7323. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7324. return -1;
  7325. #else
  7326. {
  7327. int result;
  7328. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7329. && errno == EINTR)
  7330. {
  7331. }
  7332. if (result < 0)
  7333. return -1;
  7334. }
  7335. #endif
  7336. {
  7337. int opt;
  7338. juce_socklen_t len = sizeof (opt);
  7339. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7340. || opt != 0)
  7341. return -1;
  7342. }
  7343. if ((forReading && FD_ISSET (handle, &rset))
  7344. || ((! forReading) && FD_ISSET (handle, &wset)))
  7345. return 1;
  7346. return 0;
  7347. }
  7348. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7349. {
  7350. #if JUCE_WINDOWS
  7351. u_long nonBlocking = shouldBlock ? 0 : 1;
  7352. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7353. return false;
  7354. #else
  7355. int socketFlags = fcntl (handle, F_GETFL, 0);
  7356. if (socketFlags == -1)
  7357. return false;
  7358. if (shouldBlock)
  7359. socketFlags &= ~O_NONBLOCK;
  7360. else
  7361. socketFlags |= O_NONBLOCK;
  7362. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7363. return false;
  7364. #endif
  7365. return true;
  7366. }
  7367. bool connectSocket (int volatile& handle,
  7368. const bool isDatagram,
  7369. void** serverAddress,
  7370. const String& hostName,
  7371. const int portNumber,
  7372. const int timeOutMillisecs) throw()
  7373. {
  7374. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7375. if (hostEnt == 0)
  7376. return false;
  7377. struct in_addr targetAddress;
  7378. memcpy (&targetAddress.s_addr,
  7379. *(hostEnt->h_addr_list),
  7380. sizeof (targetAddress.s_addr));
  7381. struct sockaddr_in servTmpAddr;
  7382. zerostruct (servTmpAddr);
  7383. servTmpAddr.sin_family = PF_INET;
  7384. servTmpAddr.sin_addr = targetAddress;
  7385. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7386. if (handle < 0)
  7387. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7388. if (handle < 0)
  7389. return false;
  7390. if (isDatagram)
  7391. {
  7392. *serverAddress = new struct sockaddr_in();
  7393. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7394. return true;
  7395. }
  7396. setSocketBlockingState (handle, false);
  7397. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7398. if (result < 0)
  7399. {
  7400. #if JUCE_WINDOWS
  7401. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7402. #else
  7403. if (errno == EINPROGRESS)
  7404. #endif
  7405. {
  7406. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7407. {
  7408. setSocketBlockingState (handle, true);
  7409. return false;
  7410. }
  7411. }
  7412. }
  7413. setSocketBlockingState (handle, true);
  7414. resetSocketOptions (handle, false, false);
  7415. return true;
  7416. }
  7417. }
  7418. StreamingSocket::StreamingSocket()
  7419. : portNumber (0),
  7420. handle (-1),
  7421. connected (false),
  7422. isListener (false)
  7423. {
  7424. #if JUCE_WINDOWS
  7425. SocketHelpers::initWin32Sockets();
  7426. #endif
  7427. }
  7428. StreamingSocket::StreamingSocket (const String& hostName_,
  7429. const int portNumber_,
  7430. const int handle_)
  7431. : hostName (hostName_),
  7432. portNumber (portNumber_),
  7433. handle (handle_),
  7434. connected (true),
  7435. isListener (false)
  7436. {
  7437. #if JUCE_WINDOWS
  7438. SocketHelpers::initWin32Sockets();
  7439. #endif
  7440. SocketHelpers::resetSocketOptions (handle_, false, false);
  7441. }
  7442. StreamingSocket::~StreamingSocket()
  7443. {
  7444. close();
  7445. }
  7446. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7447. {
  7448. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7449. : -1;
  7450. }
  7451. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7452. {
  7453. if (isListener || ! connected)
  7454. return -1;
  7455. #if JUCE_WINDOWS
  7456. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7457. #else
  7458. int result;
  7459. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7460. && errno == EINTR)
  7461. {
  7462. }
  7463. return result;
  7464. #endif
  7465. }
  7466. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7467. const int timeoutMsecs) const
  7468. {
  7469. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7470. : -1;
  7471. }
  7472. bool StreamingSocket::bindToPort (const int port)
  7473. {
  7474. return SocketHelpers::bindSocketToPort (handle, port);
  7475. }
  7476. bool StreamingSocket::connect (const String& remoteHostName,
  7477. const int remotePortNumber,
  7478. const int timeOutMillisecs)
  7479. {
  7480. if (isListener)
  7481. {
  7482. jassertfalse; // a listener socket can't connect to another one!
  7483. return false;
  7484. }
  7485. if (connected)
  7486. close();
  7487. hostName = remoteHostName;
  7488. portNumber = remotePortNumber;
  7489. isListener = false;
  7490. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7491. remotePortNumber, timeOutMillisecs);
  7492. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7493. {
  7494. close();
  7495. return false;
  7496. }
  7497. return true;
  7498. }
  7499. void StreamingSocket::close()
  7500. {
  7501. #if JUCE_WINDOWS
  7502. if (handle != SOCKET_ERROR || connected)
  7503. closesocket (handle);
  7504. connected = false;
  7505. #else
  7506. if (connected)
  7507. {
  7508. connected = false;
  7509. if (isListener)
  7510. {
  7511. // need to do this to interrupt the accept() function..
  7512. StreamingSocket temp;
  7513. temp.connect ("localhost", portNumber, 1000);
  7514. }
  7515. }
  7516. if (handle != -1)
  7517. ::close (handle);
  7518. #endif
  7519. hostName = String::empty;
  7520. portNumber = 0;
  7521. handle = -1;
  7522. isListener = false;
  7523. }
  7524. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7525. {
  7526. if (connected)
  7527. close();
  7528. hostName = "listener";
  7529. portNumber = newPortNumber;
  7530. isListener = true;
  7531. struct sockaddr_in servTmpAddr;
  7532. zerostruct (servTmpAddr);
  7533. servTmpAddr.sin_family = PF_INET;
  7534. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7535. if (localHostName.isNotEmpty())
  7536. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7537. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7538. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7539. if (handle < 0)
  7540. return false;
  7541. const int reuse = 1;
  7542. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7543. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7544. || listen (handle, SOMAXCONN) < 0)
  7545. {
  7546. close();
  7547. return false;
  7548. }
  7549. connected = true;
  7550. return true;
  7551. }
  7552. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7553. {
  7554. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7555. // prepare this socket as a listener.
  7556. if (connected && isListener)
  7557. {
  7558. struct sockaddr address;
  7559. juce_socklen_t len = sizeof (sockaddr);
  7560. const int newSocket = (int) accept (handle, &address, &len);
  7561. if (newSocket >= 0 && connected)
  7562. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7563. portNumber, newSocket);
  7564. }
  7565. return 0;
  7566. }
  7567. bool StreamingSocket::isLocal() const throw()
  7568. {
  7569. return hostName == "127.0.0.1";
  7570. }
  7571. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7572. : portNumber (0),
  7573. handle (-1),
  7574. connected (true),
  7575. allowBroadcast (allowBroadcast_),
  7576. serverAddress (0)
  7577. {
  7578. #if JUCE_WINDOWS
  7579. SocketHelpers::initWin32Sockets();
  7580. #endif
  7581. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7582. bindToPort (localPortNumber);
  7583. }
  7584. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7585. const int handle_, const int localPortNumber)
  7586. : hostName (hostName_),
  7587. portNumber (portNumber_),
  7588. handle (handle_),
  7589. connected (true),
  7590. allowBroadcast (false),
  7591. serverAddress (0)
  7592. {
  7593. #if JUCE_WINDOWS
  7594. SocketHelpers::initWin32Sockets();
  7595. #endif
  7596. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7597. bindToPort (localPortNumber);
  7598. }
  7599. DatagramSocket::~DatagramSocket()
  7600. {
  7601. close();
  7602. delete static_cast <struct sockaddr_in*> (serverAddress);
  7603. serverAddress = 0;
  7604. }
  7605. void DatagramSocket::close()
  7606. {
  7607. #if JUCE_WINDOWS
  7608. closesocket (handle);
  7609. connected = false;
  7610. #else
  7611. connected = false;
  7612. ::close (handle);
  7613. #endif
  7614. hostName = String::empty;
  7615. portNumber = 0;
  7616. handle = -1;
  7617. }
  7618. bool DatagramSocket::bindToPort (const int port)
  7619. {
  7620. return SocketHelpers::bindSocketToPort (handle, port);
  7621. }
  7622. bool DatagramSocket::connect (const String& remoteHostName,
  7623. const int remotePortNumber,
  7624. const int timeOutMillisecs)
  7625. {
  7626. if (connected)
  7627. close();
  7628. hostName = remoteHostName;
  7629. portNumber = remotePortNumber;
  7630. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7631. remoteHostName, remotePortNumber,
  7632. timeOutMillisecs);
  7633. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7634. {
  7635. close();
  7636. return false;
  7637. }
  7638. return true;
  7639. }
  7640. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7641. {
  7642. struct sockaddr address;
  7643. juce_socklen_t len = sizeof (sockaddr);
  7644. while (waitUntilReady (true, -1) == 1)
  7645. {
  7646. char buf[1];
  7647. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7648. {
  7649. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7650. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7651. -1, -1);
  7652. }
  7653. }
  7654. return 0;
  7655. }
  7656. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7657. const int timeoutMsecs) const
  7658. {
  7659. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7660. : -1;
  7661. }
  7662. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7663. {
  7664. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7665. : -1;
  7666. }
  7667. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7668. {
  7669. // You need to call connect() first to set the server address..
  7670. jassert (serverAddress != 0 && connected);
  7671. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7672. numBytesToWrite, 0,
  7673. (const struct sockaddr*) serverAddress,
  7674. sizeof (struct sockaddr_in))
  7675. : -1;
  7676. }
  7677. bool DatagramSocket::isLocal() const throw()
  7678. {
  7679. return hostName == "127.0.0.1";
  7680. }
  7681. #if JUCE_MSVC
  7682. #pragma warning (pop)
  7683. #endif
  7684. END_JUCE_NAMESPACE
  7685. /*** End of inlined file: juce_Socket.cpp ***/
  7686. /*** Start of inlined file: juce_URL.cpp ***/
  7687. BEGIN_JUCE_NAMESPACE
  7688. URL::URL()
  7689. {
  7690. }
  7691. URL::URL (const String& url_)
  7692. : url (url_)
  7693. {
  7694. int i = url.indexOfChar ('?');
  7695. if (i >= 0)
  7696. {
  7697. do
  7698. {
  7699. const int nextAmp = url.indexOfChar (i + 1, '&');
  7700. const int equalsPos = url.indexOfChar (i + 1, '=');
  7701. if (equalsPos > i + 1)
  7702. {
  7703. if (nextAmp < 0)
  7704. {
  7705. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7706. removeEscapeChars (url.substring (equalsPos + 1)));
  7707. }
  7708. else if (nextAmp > 0 && equalsPos < nextAmp)
  7709. {
  7710. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7711. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7712. }
  7713. }
  7714. i = nextAmp;
  7715. }
  7716. while (i >= 0);
  7717. url = url.upToFirstOccurrenceOf ("?", false, false);
  7718. }
  7719. }
  7720. URL::URL (const URL& other)
  7721. : url (other.url),
  7722. postData (other.postData),
  7723. parameters (other.parameters),
  7724. filesToUpload (other.filesToUpload),
  7725. mimeTypes (other.mimeTypes)
  7726. {
  7727. }
  7728. URL& URL::operator= (const URL& other)
  7729. {
  7730. url = other.url;
  7731. postData = other.postData;
  7732. parameters = other.parameters;
  7733. filesToUpload = other.filesToUpload;
  7734. mimeTypes = other.mimeTypes;
  7735. return *this;
  7736. }
  7737. URL::~URL()
  7738. {
  7739. }
  7740. namespace URLHelpers
  7741. {
  7742. const String getMangledParameters (const StringPairArray& parameters)
  7743. {
  7744. String p;
  7745. for (int i = 0; i < parameters.size(); ++i)
  7746. {
  7747. if (i > 0)
  7748. p << '&';
  7749. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7750. << '='
  7751. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7752. }
  7753. return p;
  7754. }
  7755. int findStartOfDomain (const String& url)
  7756. {
  7757. int i = 0;
  7758. while (CharacterFunctions::isLetterOrDigit (url[i])
  7759. || url[i] == '+' || url[i] == '-' || url[i] == '.')
  7760. ++i;
  7761. return url[i] == ':' ? i + 1 : 0;
  7762. }
  7763. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7764. {
  7765. MemoryOutputStream data (postData, false);
  7766. if (url.getFilesToUpload().size() > 0)
  7767. {
  7768. // need to upload some files, so do it as multi-part...
  7769. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7770. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7771. data << "--" << boundary;
  7772. int i;
  7773. for (i = 0; i < url.getParameters().size(); ++i)
  7774. {
  7775. data << "\r\nContent-Disposition: form-data; name=\""
  7776. << url.getParameters().getAllKeys() [i]
  7777. << "\"\r\n\r\n"
  7778. << url.getParameters().getAllValues() [i]
  7779. << "\r\n--"
  7780. << boundary;
  7781. }
  7782. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7783. {
  7784. const File file (url.getFilesToUpload().getAllValues() [i]);
  7785. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7786. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7787. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7788. const String mimeType (url.getMimeTypesOfUploadFiles()
  7789. .getValue (paramName, String::empty));
  7790. if (mimeType.isNotEmpty())
  7791. data << "Content-Type: " << mimeType << "\r\n";
  7792. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7793. << file << "\r\n--" << boundary;
  7794. }
  7795. data << "--\r\n";
  7796. data.flush();
  7797. }
  7798. else
  7799. {
  7800. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7801. data.flush();
  7802. // just a short text attachment, so use simple url encoding..
  7803. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7804. << (int) postData.getSize() << "\r\n";
  7805. }
  7806. }
  7807. }
  7808. const String URL::toString (const bool includeGetParameters) const
  7809. {
  7810. if (includeGetParameters && parameters.size() > 0)
  7811. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7812. else
  7813. return url;
  7814. }
  7815. bool URL::isWellFormed() const
  7816. {
  7817. //xxx TODO
  7818. return url.isNotEmpty();
  7819. }
  7820. const String URL::getDomain() const
  7821. {
  7822. int start = URLHelpers::findStartOfDomain (url);
  7823. while (url[start] == '/')
  7824. ++start;
  7825. const int end1 = url.indexOfChar (start, '/');
  7826. const int end2 = url.indexOfChar (start, ':');
  7827. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7828. : jmin (end1, end2);
  7829. return url.substring (start, end);
  7830. }
  7831. const String URL::getSubPath() const
  7832. {
  7833. int start = URLHelpers::findStartOfDomain (url);
  7834. while (url[start] == '/')
  7835. ++start;
  7836. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7837. return startOfPath <= 0 ? String::empty
  7838. : url.substring (startOfPath);
  7839. }
  7840. const String URL::getScheme() const
  7841. {
  7842. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7843. }
  7844. const URL URL::withNewSubPath (const String& newPath) const
  7845. {
  7846. int start = URLHelpers::findStartOfDomain (url);
  7847. while (url[start] == '/')
  7848. ++start;
  7849. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7850. URL u (*this);
  7851. if (startOfPath > 0)
  7852. u.url = url.substring (0, startOfPath);
  7853. if (! u.url.endsWithChar ('/'))
  7854. u.url << '/';
  7855. if (newPath.startsWithChar ('/'))
  7856. u.url << newPath.substring (1);
  7857. else
  7858. u.url << newPath;
  7859. return u;
  7860. }
  7861. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7862. {
  7863. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7864. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7865. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7866. return true;
  7867. if (possibleURL.containsChar ('@')
  7868. || possibleURL.containsChar (' '))
  7869. return false;
  7870. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7871. .fromLastOccurrenceOf (".", false, false));
  7872. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7873. }
  7874. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7875. {
  7876. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7877. return atSign > 0
  7878. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7879. && (! possibleEmailAddress.endsWithChar ('.'));
  7880. }
  7881. InputStream* URL::createInputStream (const bool usePostCommand,
  7882. OpenStreamProgressCallback* const progressCallback,
  7883. void* const progressCallbackContext,
  7884. const String& extraHeaders,
  7885. const int timeOutMs,
  7886. StringPairArray* const responseHeaders) const
  7887. {
  7888. String headers;
  7889. MemoryBlock headersAndPostData;
  7890. if (usePostCommand)
  7891. URLHelpers::createHeadersAndPostData (*this, headers, headersAndPostData);
  7892. headers += extraHeaders;
  7893. if (! headers.endsWithChar ('\n'))
  7894. headers << "\r\n";
  7895. return createNativeStream (toString (! usePostCommand), usePostCommand, headersAndPostData,
  7896. progressCallback, progressCallbackContext,
  7897. headers, timeOutMs, responseHeaders);
  7898. }
  7899. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7900. const bool usePostCommand) const
  7901. {
  7902. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7903. if (in != 0)
  7904. {
  7905. in->readIntoMemoryBlock (destData);
  7906. return true;
  7907. }
  7908. return false;
  7909. }
  7910. const String URL::readEntireTextStream (const bool usePostCommand) const
  7911. {
  7912. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7913. if (in != 0)
  7914. return in->readEntireStreamAsString();
  7915. return String::empty;
  7916. }
  7917. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7918. {
  7919. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7920. }
  7921. const URL URL::withParameter (const String& parameterName,
  7922. const String& parameterValue) const
  7923. {
  7924. URL u (*this);
  7925. u.parameters.set (parameterName, parameterValue);
  7926. return u;
  7927. }
  7928. const URL URL::withFileToUpload (const String& parameterName,
  7929. const File& fileToUpload,
  7930. const String& mimeType) const
  7931. {
  7932. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7933. URL u (*this);
  7934. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7935. u.mimeTypes.set (parameterName, mimeType);
  7936. return u;
  7937. }
  7938. const URL URL::withPOSTData (const String& postData_) const
  7939. {
  7940. URL u (*this);
  7941. u.postData = postData_;
  7942. return u;
  7943. }
  7944. const StringPairArray& URL::getParameters() const
  7945. {
  7946. return parameters;
  7947. }
  7948. const StringPairArray& URL::getFilesToUpload() const
  7949. {
  7950. return filesToUpload;
  7951. }
  7952. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7953. {
  7954. return mimeTypes;
  7955. }
  7956. const String URL::removeEscapeChars (const String& s)
  7957. {
  7958. String result (s.replaceCharacter ('+', ' '));
  7959. if (! result.containsChar ('%'))
  7960. return result;
  7961. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7962. // after all the replacements have been made, so that multi-byte chars are handled.
  7963. Array<char> utf8 (result.toUTF8().getAddress(), result.getNumBytesAsUTF8());
  7964. for (int i = 0; i < utf8.size(); ++i)
  7965. {
  7966. if (utf8.getUnchecked(i) == '%')
  7967. {
  7968. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7969. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7970. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7971. {
  7972. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7973. utf8.removeRange (i + 1, 2);
  7974. }
  7975. }
  7976. }
  7977. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7978. }
  7979. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7980. {
  7981. const CharPointer_UTF8 legalChars (isParameter ? "_-.*!'()"
  7982. : ",$_-.*!'()");
  7983. Array<char> utf8 (s.toUTF8().getAddress(), s.getNumBytesAsUTF8());
  7984. for (int i = 0; i < utf8.size(); ++i)
  7985. {
  7986. const char c = utf8.getUnchecked(i);
  7987. if (! (CharacterFunctions::isLetterOrDigit (c)
  7988. || legalChars.indexOf ((juce_wchar) c) >= 0))
  7989. {
  7990. if (c == ' ')
  7991. {
  7992. utf8.set (i, '+');
  7993. }
  7994. else
  7995. {
  7996. static const char* const hexDigits = "0123456789abcdef";
  7997. utf8.set (i, '%');
  7998. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7999. utf8.insert (++i, hexDigits [c & 15]);
  8000. }
  8001. }
  8002. }
  8003. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  8004. }
  8005. bool URL::launchInDefaultBrowser() const
  8006. {
  8007. String u (toString (true));
  8008. if (u.containsChar ('@') && ! u.containsChar (':'))
  8009. u = "mailto:" + u;
  8010. return PlatformUtilities::openDocument (u, String::empty);
  8011. }
  8012. END_JUCE_NAMESPACE
  8013. /*** End of inlined file: juce_URL.cpp ***/
  8014. /*** Start of inlined file: juce_MACAddress.cpp ***/
  8015. BEGIN_JUCE_NAMESPACE
  8016. MACAddress::MACAddress()
  8017. : asInt64 (0)
  8018. {
  8019. }
  8020. MACAddress::MACAddress (const MACAddress& other)
  8021. : asInt64 (other.asInt64)
  8022. {
  8023. }
  8024. MACAddress& MACAddress::operator= (const MACAddress& other)
  8025. {
  8026. asInt64 = other.asInt64;
  8027. return *this;
  8028. }
  8029. MACAddress::MACAddress (const uint8 bytes[6])
  8030. : asInt64 (0)
  8031. {
  8032. memcpy (asBytes, bytes, sizeof (asBytes));
  8033. }
  8034. const String MACAddress::toString() const
  8035. {
  8036. String s;
  8037. s.preallocateStorage (18);
  8038. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  8039. {
  8040. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  8041. if (i < numElementsInArray (asBytes) - 1)
  8042. s << '-';
  8043. }
  8044. return s;
  8045. }
  8046. int64 MACAddress::toInt64() const throw()
  8047. {
  8048. int64 n = 0;
  8049. for (int i = numElementsInArray (asBytes); --i >= 0;)
  8050. n = (n << 8) | asBytes[i];
  8051. return n;
  8052. }
  8053. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  8054. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  8055. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  8056. END_JUCE_NAMESPACE
  8057. /*** End of inlined file: juce_MACAddress.cpp ***/
  8058. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  8059. BEGIN_JUCE_NAMESPACE
  8060. namespace
  8061. {
  8062. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  8063. {
  8064. // You need to supply a real stream when creating a BufferedInputStream
  8065. jassert (source != 0);
  8066. requestedSize = jmax (256, requestedSize);
  8067. const int64 sourceSize = source->getTotalLength();
  8068. if (sourceSize >= 0 && sourceSize < requestedSize)
  8069. requestedSize = jmax (32, (int) sourceSize);
  8070. return requestedSize;
  8071. }
  8072. }
  8073. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  8074. const bool deleteSourceWhenDestroyed)
  8075. : source (sourceStream, deleteSourceWhenDestroyed),
  8076. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  8077. position (sourceStream->getPosition()),
  8078. lastReadPos (0),
  8079. bufferStart (position),
  8080. bufferOverlap (128)
  8081. {
  8082. buffer.malloc (bufferSize);
  8083. }
  8084. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  8085. : source (&sourceStream, false),
  8086. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  8087. position (sourceStream.getPosition()),
  8088. lastReadPos (0),
  8089. bufferStart (position),
  8090. bufferOverlap (128)
  8091. {
  8092. buffer.malloc (bufferSize);
  8093. }
  8094. BufferedInputStream::~BufferedInputStream()
  8095. {
  8096. }
  8097. int64 BufferedInputStream::getTotalLength()
  8098. {
  8099. return source->getTotalLength();
  8100. }
  8101. int64 BufferedInputStream::getPosition()
  8102. {
  8103. return position;
  8104. }
  8105. bool BufferedInputStream::setPosition (int64 newPosition)
  8106. {
  8107. position = jmax ((int64) 0, newPosition);
  8108. return true;
  8109. }
  8110. bool BufferedInputStream::isExhausted()
  8111. {
  8112. return (position >= lastReadPos)
  8113. && source->isExhausted();
  8114. }
  8115. void BufferedInputStream::ensureBuffered()
  8116. {
  8117. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  8118. if (position < bufferStart || position >= bufferEndOverlap)
  8119. {
  8120. int bytesRead;
  8121. if (position < lastReadPos
  8122. && position >= bufferEndOverlap
  8123. && position >= bufferStart)
  8124. {
  8125. const int bytesToKeep = (int) (lastReadPos - position);
  8126. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  8127. bufferStart = position;
  8128. bytesRead = source->read (buffer + bytesToKeep,
  8129. bufferSize - bytesToKeep);
  8130. lastReadPos += bytesRead;
  8131. bytesRead += bytesToKeep;
  8132. }
  8133. else
  8134. {
  8135. bufferStart = position;
  8136. source->setPosition (bufferStart);
  8137. bytesRead = source->read (buffer, bufferSize);
  8138. lastReadPos = bufferStart + bytesRead;
  8139. }
  8140. while (bytesRead < bufferSize)
  8141. buffer [bytesRead++] = 0;
  8142. }
  8143. }
  8144. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  8145. {
  8146. if (position >= bufferStart
  8147. && position + maxBytesToRead <= lastReadPos)
  8148. {
  8149. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  8150. position += maxBytesToRead;
  8151. return maxBytesToRead;
  8152. }
  8153. else
  8154. {
  8155. if (position < bufferStart || position >= lastReadPos)
  8156. ensureBuffered();
  8157. int bytesRead = 0;
  8158. while (maxBytesToRead > 0)
  8159. {
  8160. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  8161. if (bytesAvailable > 0)
  8162. {
  8163. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  8164. maxBytesToRead -= bytesAvailable;
  8165. bytesRead += bytesAvailable;
  8166. position += bytesAvailable;
  8167. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  8168. }
  8169. const int64 oldLastReadPos = lastReadPos;
  8170. ensureBuffered();
  8171. if (oldLastReadPos == lastReadPos)
  8172. break; // if ensureBuffered() failed to read any more data, bail out
  8173. if (isExhausted())
  8174. break;
  8175. }
  8176. return bytesRead;
  8177. }
  8178. }
  8179. const String BufferedInputStream::readString()
  8180. {
  8181. if (position >= bufferStart
  8182. && position < lastReadPos)
  8183. {
  8184. const int maxChars = (int) (lastReadPos - position);
  8185. const char* const src = buffer + (int) (position - bufferStart);
  8186. for (int i = 0; i < maxChars; ++i)
  8187. {
  8188. if (src[i] == 0)
  8189. {
  8190. position += i + 1;
  8191. return String::fromUTF8 (src, i);
  8192. }
  8193. }
  8194. }
  8195. return InputStream::readString();
  8196. }
  8197. END_JUCE_NAMESPACE
  8198. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  8199. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  8200. BEGIN_JUCE_NAMESPACE
  8201. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  8202. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  8203. {
  8204. }
  8205. FileInputSource::~FileInputSource()
  8206. {
  8207. }
  8208. InputStream* FileInputSource::createInputStream()
  8209. {
  8210. return file.createInputStream();
  8211. }
  8212. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  8213. {
  8214. return file.getSiblingFile (relatedItemPath).createInputStream();
  8215. }
  8216. int64 FileInputSource::hashCode() const
  8217. {
  8218. int64 h = file.hashCode();
  8219. if (useFileTimeInHashGeneration)
  8220. h ^= file.getLastModificationTime().toMilliseconds();
  8221. return h;
  8222. }
  8223. END_JUCE_NAMESPACE
  8224. /*** End of inlined file: juce_FileInputSource.cpp ***/
  8225. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  8226. BEGIN_JUCE_NAMESPACE
  8227. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  8228. const size_t sourceDataSize,
  8229. const bool keepInternalCopy)
  8230. : data (static_cast <const char*> (sourceData)),
  8231. dataSize (sourceDataSize),
  8232. position (0)
  8233. {
  8234. if (keepInternalCopy)
  8235. {
  8236. internalCopy.append (data, sourceDataSize);
  8237. data = static_cast <const char*> (internalCopy.getData());
  8238. }
  8239. }
  8240. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  8241. const bool keepInternalCopy)
  8242. : data (static_cast <const char*> (sourceData.getData())),
  8243. dataSize (sourceData.getSize()),
  8244. position (0)
  8245. {
  8246. if (keepInternalCopy)
  8247. {
  8248. internalCopy = sourceData;
  8249. data = static_cast <const char*> (internalCopy.getData());
  8250. }
  8251. }
  8252. MemoryInputStream::~MemoryInputStream()
  8253. {
  8254. }
  8255. int64 MemoryInputStream::getTotalLength()
  8256. {
  8257. return dataSize;
  8258. }
  8259. int MemoryInputStream::read (void* const buffer, const int howMany)
  8260. {
  8261. jassert (howMany >= 0);
  8262. const int num = jmin (howMany, (int) (dataSize - position));
  8263. memcpy (buffer, data + position, num);
  8264. position += num;
  8265. return (int) num;
  8266. }
  8267. bool MemoryInputStream::isExhausted()
  8268. {
  8269. return (position >= dataSize);
  8270. }
  8271. bool MemoryInputStream::setPosition (const int64 pos)
  8272. {
  8273. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8274. return true;
  8275. }
  8276. int64 MemoryInputStream::getPosition()
  8277. {
  8278. return position;
  8279. }
  8280. #if JUCE_UNIT_TESTS
  8281. class MemoryStreamTests : public UnitTest
  8282. {
  8283. public:
  8284. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8285. void runTest()
  8286. {
  8287. beginTest ("Basics");
  8288. int randomInt = Random::getSystemRandom().nextInt();
  8289. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8290. double randomDouble = Random::getSystemRandom().nextDouble();
  8291. String randomString (createRandomWideCharString());
  8292. MemoryOutputStream mo;
  8293. mo.writeInt (randomInt);
  8294. mo.writeIntBigEndian (randomInt);
  8295. mo.writeCompressedInt (randomInt);
  8296. mo.writeString (randomString);
  8297. mo.writeInt64 (randomInt64);
  8298. mo.writeInt64BigEndian (randomInt64);
  8299. mo.writeDouble (randomDouble);
  8300. mo.writeDoubleBigEndian (randomDouble);
  8301. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8302. expect (mi.readInt() == randomInt);
  8303. expect (mi.readIntBigEndian() == randomInt);
  8304. expect (mi.readCompressedInt() == randomInt);
  8305. expectEquals (mi.readString(), randomString);
  8306. expect (mi.readInt64() == randomInt64);
  8307. expect (mi.readInt64BigEndian() == randomInt64);
  8308. expect (mi.readDouble() == randomDouble);
  8309. expect (mi.readDoubleBigEndian() == randomDouble);
  8310. }
  8311. static const String createRandomWideCharString()
  8312. {
  8313. juce_wchar buffer [50];
  8314. zerostruct (buffer);
  8315. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  8316. {
  8317. if (Random::getSystemRandom().nextBool())
  8318. {
  8319. do
  8320. {
  8321. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0x10ffff - 1));
  8322. }
  8323. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  8324. }
  8325. else
  8326. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0xff));
  8327. }
  8328. return buffer;
  8329. }
  8330. };
  8331. static MemoryStreamTests memoryInputStreamUnitTests;
  8332. #endif
  8333. END_JUCE_NAMESPACE
  8334. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8335. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8336. BEGIN_JUCE_NAMESPACE
  8337. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8338. : data (internalBlock),
  8339. position (0),
  8340. size (0)
  8341. {
  8342. internalBlock.setSize (initialSize, false);
  8343. }
  8344. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8345. const bool appendToExistingBlockContent)
  8346. : data (memoryBlockToWriteTo),
  8347. position (0),
  8348. size (0)
  8349. {
  8350. if (appendToExistingBlockContent)
  8351. position = size = memoryBlockToWriteTo.getSize();
  8352. }
  8353. MemoryOutputStream::~MemoryOutputStream()
  8354. {
  8355. flush();
  8356. }
  8357. void MemoryOutputStream::flush()
  8358. {
  8359. if (&data != &internalBlock)
  8360. data.setSize (size, false);
  8361. }
  8362. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8363. {
  8364. data.ensureSize (bytesToPreallocate + 1);
  8365. }
  8366. void MemoryOutputStream::reset() throw()
  8367. {
  8368. position = 0;
  8369. size = 0;
  8370. }
  8371. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8372. {
  8373. if (howMany > 0)
  8374. {
  8375. const size_t storageNeeded = position + howMany;
  8376. if (storageNeeded >= data.getSize())
  8377. data.ensureSize ((storageNeeded + jmin ((int) (storageNeeded / 2), 1024 * 1024) + 32) & ~31);
  8378. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8379. position += howMany;
  8380. size = jmax (size, position);
  8381. }
  8382. return true;
  8383. }
  8384. const void* MemoryOutputStream::getData() const throw()
  8385. {
  8386. void* const d = data.getData();
  8387. if (data.getSize() > size)
  8388. static_cast <char*> (d) [size] = 0;
  8389. return d;
  8390. }
  8391. bool MemoryOutputStream::setPosition (int64 newPosition)
  8392. {
  8393. if (newPosition <= (int64) size)
  8394. {
  8395. // ok to seek backwards
  8396. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8397. return true;
  8398. }
  8399. else
  8400. {
  8401. // trying to make it bigger isn't a good thing to do..
  8402. return false;
  8403. }
  8404. }
  8405. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8406. {
  8407. // before writing from an input, see if we can preallocate to make it more efficient..
  8408. int64 availableData = source.getTotalLength() - source.getPosition();
  8409. if (availableData > 0)
  8410. {
  8411. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8412. availableData = maxNumBytesToWrite;
  8413. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8414. }
  8415. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8416. }
  8417. const String MemoryOutputStream::toUTF8() const
  8418. {
  8419. return String::fromUTF8 (static_cast <const char*> (getData()), getDataSize());
  8420. }
  8421. const String MemoryOutputStream::toString() const
  8422. {
  8423. return String::createStringFromData (getData(), (int) getDataSize());
  8424. }
  8425. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8426. {
  8427. stream.write (streamToRead.getData(), (int) streamToRead.getDataSize());
  8428. return stream;
  8429. }
  8430. END_JUCE_NAMESPACE
  8431. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8432. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8433. BEGIN_JUCE_NAMESPACE
  8434. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8435. const int64 startPositionInSourceStream_,
  8436. const int64 lengthOfSourceStream_,
  8437. const bool deleteSourceWhenDestroyed)
  8438. : source (sourceStream, deleteSourceWhenDestroyed),
  8439. startPositionInSourceStream (startPositionInSourceStream_),
  8440. lengthOfSourceStream (lengthOfSourceStream_)
  8441. {
  8442. setPosition (0);
  8443. }
  8444. SubregionStream::~SubregionStream()
  8445. {
  8446. }
  8447. int64 SubregionStream::getTotalLength()
  8448. {
  8449. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8450. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8451. : srcLen;
  8452. }
  8453. int64 SubregionStream::getPosition()
  8454. {
  8455. return source->getPosition() - startPositionInSourceStream;
  8456. }
  8457. bool SubregionStream::setPosition (int64 newPosition)
  8458. {
  8459. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8460. }
  8461. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8462. {
  8463. if (lengthOfSourceStream < 0)
  8464. {
  8465. return source->read (destBuffer, maxBytesToRead);
  8466. }
  8467. else
  8468. {
  8469. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8470. if (maxBytesToRead <= 0)
  8471. return 0;
  8472. return source->read (destBuffer, maxBytesToRead);
  8473. }
  8474. }
  8475. bool SubregionStream::isExhausted()
  8476. {
  8477. if (lengthOfSourceStream >= 0)
  8478. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8479. else
  8480. return source->isExhausted();
  8481. }
  8482. END_JUCE_NAMESPACE
  8483. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8484. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8485. BEGIN_JUCE_NAMESPACE
  8486. PerformanceCounter::PerformanceCounter (const String& name_,
  8487. int runsPerPrintout,
  8488. const File& loggingFile)
  8489. : name (name_),
  8490. numRuns (0),
  8491. runsPerPrint (runsPerPrintout),
  8492. totalTime (0),
  8493. outputFile (loggingFile)
  8494. {
  8495. if (outputFile != File::nonexistent)
  8496. {
  8497. String s ("**** Counter for \"");
  8498. s << name_ << "\" started at: "
  8499. << Time::getCurrentTime().toString (true, true)
  8500. << newLine;
  8501. outputFile.appendText (s, false, false);
  8502. }
  8503. }
  8504. PerformanceCounter::~PerformanceCounter()
  8505. {
  8506. printStatistics();
  8507. }
  8508. void PerformanceCounter::start()
  8509. {
  8510. started = Time::getHighResolutionTicks();
  8511. }
  8512. void PerformanceCounter::stop()
  8513. {
  8514. const int64 now = Time::getHighResolutionTicks();
  8515. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8516. if (++numRuns == runsPerPrint)
  8517. printStatistics();
  8518. }
  8519. void PerformanceCounter::printStatistics()
  8520. {
  8521. if (numRuns > 0)
  8522. {
  8523. String s ("Performance count for \"");
  8524. s << name << "\" - average over " << numRuns << " run(s) = ";
  8525. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8526. if (micros > 10000)
  8527. s << (micros/1000) << " millisecs";
  8528. else
  8529. s << micros << " microsecs";
  8530. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8531. Logger::outputDebugString (s);
  8532. s << newLine;
  8533. if (outputFile != File::nonexistent)
  8534. outputFile.appendText (s, false, false);
  8535. numRuns = 0;
  8536. totalTime = 0;
  8537. }
  8538. }
  8539. END_JUCE_NAMESPACE
  8540. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8541. /*** Start of inlined file: juce_Uuid.cpp ***/
  8542. BEGIN_JUCE_NAMESPACE
  8543. Uuid::Uuid()
  8544. {
  8545. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8546. // to make it very very unlikely that two UUIDs will ever be the same..
  8547. static int64 macAddresses[2];
  8548. static bool hasCheckedMacAddresses = false;
  8549. if (! hasCheckedMacAddresses)
  8550. {
  8551. hasCheckedMacAddresses = true;
  8552. Array<MACAddress> result;
  8553. MACAddress::findAllAddresses (result);
  8554. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8555. macAddresses[i] = result[i].toInt64();
  8556. }
  8557. value.asInt64[0] = macAddresses[0];
  8558. value.asInt64[1] = macAddresses[1];
  8559. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8560. // whose seed will carry over between calls to this method.
  8561. Random r (macAddresses[0] ^ macAddresses[1]
  8562. ^ Random::getSystemRandom().nextInt64());
  8563. for (int i = 4; --i >= 0;)
  8564. {
  8565. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8566. value.asInt[i] ^= r.nextInt();
  8567. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8568. }
  8569. }
  8570. Uuid::~Uuid() throw()
  8571. {
  8572. }
  8573. Uuid::Uuid (const Uuid& other)
  8574. : value (other.value)
  8575. {
  8576. }
  8577. Uuid& Uuid::operator= (const Uuid& other)
  8578. {
  8579. value = other.value;
  8580. return *this;
  8581. }
  8582. bool Uuid::operator== (const Uuid& other) const
  8583. {
  8584. return value.asInt64[0] == other.value.asInt64[0]
  8585. && value.asInt64[1] == other.value.asInt64[1];
  8586. }
  8587. bool Uuid::operator!= (const Uuid& other) const
  8588. {
  8589. return ! operator== (other);
  8590. }
  8591. bool Uuid::isNull() const throw()
  8592. {
  8593. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8594. }
  8595. const String Uuid::toString() const
  8596. {
  8597. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8598. }
  8599. Uuid::Uuid (const String& uuidString)
  8600. {
  8601. operator= (uuidString);
  8602. }
  8603. Uuid& Uuid::operator= (const String& uuidString)
  8604. {
  8605. MemoryBlock mb;
  8606. mb.loadFromHexString (uuidString);
  8607. mb.ensureSize (sizeof (value.asBytes), true);
  8608. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8609. return *this;
  8610. }
  8611. Uuid::Uuid (const uint8* const rawData)
  8612. {
  8613. operator= (rawData);
  8614. }
  8615. Uuid& Uuid::operator= (const uint8* const rawData)
  8616. {
  8617. if (rawData != 0)
  8618. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8619. else
  8620. zeromem (value.asBytes, sizeof (value.asBytes));
  8621. return *this;
  8622. }
  8623. END_JUCE_NAMESPACE
  8624. /*** End of inlined file: juce_Uuid.cpp ***/
  8625. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8626. BEGIN_JUCE_NAMESPACE
  8627. class ZipFile::ZipEntryInfo
  8628. {
  8629. public:
  8630. ZipFile::ZipEntry entry;
  8631. int streamOffset;
  8632. int compressedSize;
  8633. bool compressed;
  8634. };
  8635. class ZipFile::ZipInputStream : public InputStream
  8636. {
  8637. public:
  8638. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8639. : file (file_),
  8640. zipEntryInfo (zei),
  8641. pos (0),
  8642. headerSize (0),
  8643. inputStream (0)
  8644. {
  8645. inputStream = file_.inputStream;
  8646. if (file_.inputSource != 0)
  8647. {
  8648. inputStream = streamToDelete = file.inputSource->createInputStream();
  8649. }
  8650. else
  8651. {
  8652. #if JUCE_DEBUG
  8653. file_.numOpenStreams++;
  8654. #endif
  8655. }
  8656. char buffer [30];
  8657. if (inputStream != 0
  8658. && inputStream->setPosition (zei.streamOffset)
  8659. && inputStream->read (buffer, 30) == 30
  8660. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8661. {
  8662. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8663. + ByteOrder::littleEndianShort (buffer + 28);
  8664. }
  8665. }
  8666. ~ZipInputStream()
  8667. {
  8668. #if JUCE_DEBUG
  8669. if (inputStream != 0 && inputStream == file.inputStream)
  8670. file.numOpenStreams--;
  8671. #endif
  8672. }
  8673. int64 getTotalLength()
  8674. {
  8675. return zipEntryInfo.compressedSize;
  8676. }
  8677. int read (void* buffer, int howMany)
  8678. {
  8679. if (headerSize <= 0)
  8680. return 0;
  8681. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8682. if (inputStream == 0)
  8683. return 0;
  8684. int num;
  8685. if (inputStream == file.inputStream)
  8686. {
  8687. const ScopedLock sl (file.lock);
  8688. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8689. num = inputStream->read (buffer, howMany);
  8690. }
  8691. else
  8692. {
  8693. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8694. num = inputStream->read (buffer, howMany);
  8695. }
  8696. pos += num;
  8697. return num;
  8698. }
  8699. bool isExhausted()
  8700. {
  8701. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8702. }
  8703. int64 getPosition()
  8704. {
  8705. return pos;
  8706. }
  8707. bool setPosition (int64 newPos)
  8708. {
  8709. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8710. return true;
  8711. }
  8712. private:
  8713. ZipFile& file;
  8714. ZipEntryInfo zipEntryInfo;
  8715. int64 pos;
  8716. int headerSize;
  8717. InputStream* inputStream;
  8718. ScopedPointer<InputStream> streamToDelete;
  8719. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8720. };
  8721. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8722. : inputStream (source_)
  8723. #if JUCE_DEBUG
  8724. , numOpenStreams (0)
  8725. #endif
  8726. {
  8727. if (deleteStreamWhenDestroyed)
  8728. streamToDelete = inputStream;
  8729. init();
  8730. }
  8731. ZipFile::ZipFile (const File& file)
  8732. : inputStream (0)
  8733. #if JUCE_DEBUG
  8734. , numOpenStreams (0)
  8735. #endif
  8736. {
  8737. inputSource = new FileInputSource (file);
  8738. init();
  8739. }
  8740. ZipFile::ZipFile (InputSource* const inputSource_)
  8741. : inputStream (0),
  8742. inputSource (inputSource_)
  8743. #if JUCE_DEBUG
  8744. , numOpenStreams (0)
  8745. #endif
  8746. {
  8747. init();
  8748. }
  8749. ZipFile::~ZipFile()
  8750. {
  8751. #if JUCE_DEBUG
  8752. entries.clear();
  8753. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8754. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8755. Streams can't be kept open after the file is deleted because they need to share the input
  8756. stream that the file uses to read itself.
  8757. */
  8758. jassert (numOpenStreams == 0);
  8759. #endif
  8760. }
  8761. int ZipFile::getNumEntries() const throw()
  8762. {
  8763. return entries.size();
  8764. }
  8765. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8766. {
  8767. ZipEntryInfo* const zei = entries [index];
  8768. return zei != 0 ? &(zei->entry) : 0;
  8769. }
  8770. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8771. {
  8772. for (int i = 0; i < entries.size(); ++i)
  8773. if (entries.getUnchecked (i)->entry.filename == fileName)
  8774. return i;
  8775. return -1;
  8776. }
  8777. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8778. {
  8779. return getEntry (getIndexOfFileName (fileName));
  8780. }
  8781. InputStream* ZipFile::createStreamForEntry (const int index)
  8782. {
  8783. ZipEntryInfo* const zei = entries[index];
  8784. InputStream* stream = 0;
  8785. if (zei != 0)
  8786. {
  8787. stream = new ZipInputStream (*this, *zei);
  8788. if (zei->compressed)
  8789. {
  8790. stream = new GZIPDecompressorInputStream (stream, true, true,
  8791. zei->entry.uncompressedSize);
  8792. // (much faster to unzip in big blocks using a buffer..)
  8793. stream = new BufferedInputStream (stream, 32768, true);
  8794. }
  8795. }
  8796. return stream;
  8797. }
  8798. class ZipFile::ZipFilenameComparator
  8799. {
  8800. public:
  8801. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8802. {
  8803. return first->entry.filename.compare (second->entry.filename);
  8804. }
  8805. };
  8806. void ZipFile::sortEntriesByFilename()
  8807. {
  8808. ZipFilenameComparator sorter;
  8809. entries.sort (sorter);
  8810. }
  8811. void ZipFile::init()
  8812. {
  8813. ScopedPointer <InputStream> toDelete;
  8814. InputStream* in = inputStream;
  8815. if (inputSource != 0)
  8816. {
  8817. in = inputSource->createInputStream();
  8818. toDelete = in;
  8819. }
  8820. if (in != 0)
  8821. {
  8822. int numEntries = 0;
  8823. int pos = findEndOfZipEntryTable (*in, numEntries);
  8824. if (pos >= 0 && pos < in->getTotalLength())
  8825. {
  8826. const int size = (int) (in->getTotalLength() - pos);
  8827. in->setPosition (pos);
  8828. MemoryBlock headerData;
  8829. if (in->readIntoMemoryBlock (headerData, size) == size)
  8830. {
  8831. pos = 0;
  8832. for (int i = 0; i < numEntries; ++i)
  8833. {
  8834. if (pos + 46 > size)
  8835. break;
  8836. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8837. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8838. if (pos + 46 + fileNameLen > size)
  8839. break;
  8840. ZipEntryInfo* const zei = new ZipEntryInfo();
  8841. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8842. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8843. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8844. const int year = 1980 + (date >> 9);
  8845. const int month = ((date >> 5) & 15) - 1;
  8846. const int day = date & 31;
  8847. const int hours = time >> 11;
  8848. const int minutes = (time >> 5) & 63;
  8849. const int seconds = (time & 31) << 1;
  8850. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8851. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8852. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8853. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8854. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8855. entries.add (zei);
  8856. pos += 46 + fileNameLen
  8857. + ByteOrder::littleEndianShort (buffer + 30)
  8858. + ByteOrder::littleEndianShort (buffer + 32);
  8859. }
  8860. }
  8861. }
  8862. }
  8863. }
  8864. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8865. {
  8866. BufferedInputStream in (input, 8192);
  8867. in.setPosition (in.getTotalLength());
  8868. int64 pos = in.getPosition();
  8869. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8870. char buffer [32];
  8871. zeromem (buffer, sizeof (buffer));
  8872. while (pos > lowestPos)
  8873. {
  8874. in.setPosition (pos - 22);
  8875. pos = in.getPosition();
  8876. memcpy (buffer + 22, buffer, 4);
  8877. if (in.read (buffer, 22) != 22)
  8878. return 0;
  8879. for (int i = 0; i < 22; ++i)
  8880. {
  8881. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8882. {
  8883. in.setPosition (pos + i);
  8884. in.read (buffer, 22);
  8885. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8886. return ByteOrder::littleEndianInt (buffer + 16);
  8887. }
  8888. }
  8889. }
  8890. return 0;
  8891. }
  8892. bool ZipFile::uncompressTo (const File& targetDirectory,
  8893. const bool shouldOverwriteFiles)
  8894. {
  8895. for (int i = 0; i < entries.size(); ++i)
  8896. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8897. return false;
  8898. return true;
  8899. }
  8900. bool ZipFile::uncompressEntry (const int index,
  8901. const File& targetDirectory,
  8902. bool shouldOverwriteFiles)
  8903. {
  8904. const ZipEntryInfo* zei = entries [index];
  8905. if (zei != 0)
  8906. {
  8907. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8908. if (zei->entry.filename.endsWithChar ('/'))
  8909. {
  8910. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8911. }
  8912. else
  8913. {
  8914. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8915. if (in != 0)
  8916. {
  8917. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8918. return false;
  8919. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8920. {
  8921. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8922. if (out != 0)
  8923. {
  8924. out->writeFromInputStream (*in, -1);
  8925. out = 0;
  8926. targetFile.setCreationTime (zei->entry.fileTime);
  8927. targetFile.setLastModificationTime (zei->entry.fileTime);
  8928. targetFile.setLastAccessTime (zei->entry.fileTime);
  8929. return true;
  8930. }
  8931. }
  8932. }
  8933. }
  8934. }
  8935. return false;
  8936. }
  8937. END_JUCE_NAMESPACE
  8938. /*** End of inlined file: juce_ZipFile.cpp ***/
  8939. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8940. #if JUCE_MSVC
  8941. #pragma warning (push)
  8942. #pragma warning (disable: 4514 4996)
  8943. #endif
  8944. #if ! JUCE_ANDROID
  8945. #include <cwctype>
  8946. #endif
  8947. #include <cctype>
  8948. #include <ctime>
  8949. BEGIN_JUCE_NAMESPACE
  8950. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8951. {
  8952. return towupper ((wchar_t) character);
  8953. }
  8954. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8955. {
  8956. return towlower ((wchar_t) character);
  8957. }
  8958. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8959. {
  8960. #if JUCE_WINDOWS
  8961. return iswupper ((wchar_t) character) != 0;
  8962. #else
  8963. return toLowerCase (character) != character;
  8964. #endif
  8965. }
  8966. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8967. {
  8968. #if JUCE_WINDOWS
  8969. return iswlower ((wchar_t) character) != 0;
  8970. #else
  8971. return toUpperCase (character) != character;
  8972. #endif
  8973. }
  8974. bool CharacterFunctions::isWhitespace (const char character) throw()
  8975. {
  8976. return character == ' ' || (character <= 13 && character >= 9);
  8977. }
  8978. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8979. {
  8980. return iswspace ((wchar_t) character) != 0;
  8981. }
  8982. bool CharacterFunctions::isDigit (const char character) throw()
  8983. {
  8984. return (character >= '0' && character <= '9');
  8985. }
  8986. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8987. {
  8988. return iswdigit ((wchar_t) character) != 0;
  8989. }
  8990. bool CharacterFunctions::isLetter (const char character) throw()
  8991. {
  8992. return (character >= 'a' && character <= 'z')
  8993. || (character >= 'A' && character <= 'Z');
  8994. }
  8995. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8996. {
  8997. return iswalpha ((wchar_t) character) != 0;
  8998. }
  8999. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9000. {
  9001. return (character >= 'a' && character <= 'z')
  9002. || (character >= 'A' && character <= 'Z')
  9003. || (character >= '0' && character <= '9');
  9004. }
  9005. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9006. {
  9007. return iswalnum ((wchar_t) character) != 0;
  9008. }
  9009. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9010. {
  9011. unsigned int d = digit - '0';
  9012. if (d < (unsigned int) 10)
  9013. return (int) d;
  9014. d += (unsigned int) ('0' - 'a');
  9015. if (d < (unsigned int) 6)
  9016. return (int) d + 10;
  9017. d += (unsigned int) ('a' - 'A');
  9018. if (d < (unsigned int) 6)
  9019. return (int) d + 10;
  9020. return -1;
  9021. }
  9022. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  9023. {
  9024. return (int) strftime (dest, maxChars, format, tm);
  9025. }
  9026. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  9027. {
  9028. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  9029. return (int) wcsftime (dest, maxChars, format, tm);
  9030. #else
  9031. HeapBlock <char> tempDest;
  9032. tempDest.calloc (maxChars + 2);
  9033. int result = ftime (tempDest.getData(), maxChars, String (format).toUTF8(), tm);
  9034. CharPointer_UTF32 (dest).writeAll (CharPointer_UTF8 (tempDest.getData()));
  9035. return result;
  9036. #endif
  9037. }
  9038. #if JUCE_MSVC
  9039. #pragma warning (pop)
  9040. #endif
  9041. double CharacterFunctions::mulexp10 (const double value, int exponent) throw()
  9042. {
  9043. if (exponent == 0)
  9044. return value;
  9045. if (value == 0)
  9046. return 0;
  9047. const bool negative = (exponent < 0);
  9048. if (negative)
  9049. exponent = -exponent;
  9050. double result = 1.0, power = 10.0;
  9051. for (int bit = 1; exponent != 0; bit <<= 1)
  9052. {
  9053. if ((exponent & bit) != 0)
  9054. {
  9055. exponent ^= bit;
  9056. result *= power;
  9057. if (exponent == 0)
  9058. break;
  9059. }
  9060. power *= power;
  9061. }
  9062. return negative ? (value / result) : (value * result);
  9063. }
  9064. END_JUCE_NAMESPACE
  9065. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9066. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9067. BEGIN_JUCE_NAMESPACE
  9068. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9069. {
  9070. loadFromText (fileContents);
  9071. }
  9072. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9073. {
  9074. loadFromText (fileToLoad.loadFileAsString());
  9075. }
  9076. LocalisedStrings::~LocalisedStrings()
  9077. {
  9078. }
  9079. const String LocalisedStrings::translate (const String& text) const
  9080. {
  9081. return translations.getValue (text, text);
  9082. }
  9083. namespace
  9084. {
  9085. CriticalSection currentMappingsLock;
  9086. LocalisedStrings* currentMappings = 0;
  9087. int findCloseQuote (const String& text, int startPos)
  9088. {
  9089. juce_wchar lastChar = 0;
  9090. for (;;)
  9091. {
  9092. const juce_wchar c = text [startPos];
  9093. if (c == 0 || (c == '"' && lastChar != '\\'))
  9094. break;
  9095. lastChar = c;
  9096. ++startPos;
  9097. }
  9098. return startPos;
  9099. }
  9100. const String unescapeString (const String& s)
  9101. {
  9102. return s.replace ("\\\"", "\"")
  9103. .replace ("\\\'", "\'")
  9104. .replace ("\\t", "\t")
  9105. .replace ("\\r", "\r")
  9106. .replace ("\\n", "\n");
  9107. }
  9108. }
  9109. void LocalisedStrings::loadFromText (const String& fileContents)
  9110. {
  9111. StringArray lines;
  9112. lines.addLines (fileContents);
  9113. for (int i = 0; i < lines.size(); ++i)
  9114. {
  9115. String line (lines[i].trim());
  9116. if (line.startsWithChar ('"'))
  9117. {
  9118. int closeQuote = findCloseQuote (line, 1);
  9119. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9120. if (originalText.isNotEmpty())
  9121. {
  9122. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9123. closeQuote = findCloseQuote (line, openingQuote + 1);
  9124. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9125. if (newText.isNotEmpty())
  9126. translations.set (originalText, newText);
  9127. }
  9128. }
  9129. else if (line.startsWithIgnoreCase ("language:"))
  9130. {
  9131. languageName = line.substring (9).trim();
  9132. }
  9133. else if (line.startsWithIgnoreCase ("countries:"))
  9134. {
  9135. countryCodes.addTokens (line.substring (10).trim(), true);
  9136. countryCodes.trim();
  9137. countryCodes.removeEmptyStrings();
  9138. }
  9139. }
  9140. }
  9141. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9142. {
  9143. translations.setIgnoresCase (shouldIgnoreCase);
  9144. }
  9145. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9146. {
  9147. const ScopedLock sl (currentMappingsLock);
  9148. delete currentMappings;
  9149. currentMappings = newTranslations;
  9150. }
  9151. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9152. {
  9153. return currentMappings;
  9154. }
  9155. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9156. {
  9157. const ScopedLock sl (currentMappingsLock);
  9158. if (currentMappings != 0)
  9159. return currentMappings->translate (text);
  9160. return text;
  9161. }
  9162. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9163. {
  9164. return translateWithCurrentMappings (String (text));
  9165. }
  9166. END_JUCE_NAMESPACE
  9167. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9168. /*** Start of inlined file: juce_String.cpp ***/
  9169. #if JUCE_MSVC
  9170. #pragma warning (push)
  9171. #pragma warning (disable: 4514 4996)
  9172. #endif
  9173. #include <locale>
  9174. BEGIN_JUCE_NAMESPACE
  9175. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9176. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9177. #endif
  9178. #if JUCE_NATIVE_WCHAR_IS_UTF8
  9179. typedef CharPointer_UTF8 CharPointer_wchar_t;
  9180. #elif JUCE_NATIVE_WCHAR_IS_UTF16
  9181. typedef CharPointer_UTF16 CharPointer_wchar_t;
  9182. #else
  9183. typedef CharPointer_UTF32 CharPointer_wchar_t;
  9184. #endif
  9185. NewLine newLine;
  9186. class StringHolder
  9187. {
  9188. public:
  9189. StringHolder()
  9190. : refCount (0x3fffffff), allocatedNumChars (0)
  9191. {
  9192. text[0] = 0;
  9193. }
  9194. typedef String::CharPointerType CharPointerType;
  9195. static const CharPointerType createUninitialised (const size_t numChars)
  9196. {
  9197. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9198. s->refCount.value = 0;
  9199. s->allocatedNumChars = numChars;
  9200. return CharPointerType (&(s->text[0]));
  9201. }
  9202. template <class CharPointer>
  9203. static const CharPointerType createFromCharPointer (const CharPointer& text)
  9204. {
  9205. if (text.getAddress() == 0 || text.isEmpty())
  9206. return getEmpty();
  9207. const size_t numChars = text.length();
  9208. const CharPointerType dest (createUninitialised (numChars));
  9209. CharPointerType (dest).writeAll (text);
  9210. return dest;
  9211. }
  9212. template <class CharPointer>
  9213. static const CharPointerType createFromCharPointer (const CharPointer& text, size_t maxChars)
  9214. {
  9215. if (text.getAddress() == 0 || text.isEmpty())
  9216. return getEmpty();
  9217. size_t numChars = text.lengthUpTo (maxChars);
  9218. if (numChars == 0)
  9219. return getEmpty();
  9220. const CharPointerType dest (createUninitialised (numChars));
  9221. CharPointerType (dest).writeWithCharLimit (text, (int) (numChars + 1));
  9222. return dest;
  9223. }
  9224. template <class CharPointer>
  9225. static const CharPointerType createFromCharPointer (const CharPointer& start, const CharPointer& end)
  9226. {
  9227. if (start.getAddress() == 0 || start.isEmpty())
  9228. return getEmpty();
  9229. size_t numChars = start.lengthUpTo (end);
  9230. if (numChars == 0)
  9231. return getEmpty();
  9232. const CharPointerType dest (createUninitialised (numChars));
  9233. CharPointerType (dest).writeWithCharLimit (start, (int) (numChars + 1));
  9234. return dest;
  9235. }
  9236. static CharPointerType createFromFixedLength (const juce_wchar* const src, const size_t numChars)
  9237. {
  9238. CharPointerType dest (createUninitialised (numChars));
  9239. copyChars (dest, CharPointerType (src), (int) numChars);
  9240. return dest;
  9241. }
  9242. static const CharPointerType createFromFixedLength (const char* const src, const size_t numChars)
  9243. {
  9244. const CharPointerType dest (createUninitialised (numChars));
  9245. CharPointerType (dest).writeWithCharLimit (CharPointer_UTF8 (src), (int) (numChars + 1));
  9246. return dest;
  9247. }
  9248. static inline const CharPointerType getEmpty() throw()
  9249. {
  9250. return CharPointerType (&(empty.text[0]));
  9251. }
  9252. static void retain (const CharPointerType& text) throw()
  9253. {
  9254. ++(bufferFromText (text)->refCount);
  9255. }
  9256. static inline void release (StringHolder* const b) throw()
  9257. {
  9258. if (--(b->refCount) == -1 && b != &empty)
  9259. delete[] reinterpret_cast <char*> (b);
  9260. }
  9261. static void release (const CharPointerType& text) throw()
  9262. {
  9263. release (bufferFromText (text));
  9264. }
  9265. static CharPointerType makeUnique (const CharPointerType& text)
  9266. {
  9267. StringHolder* const b = bufferFromText (text);
  9268. if (b->refCount.get() <= 0)
  9269. return text;
  9270. CharPointerType newText (createFromFixedLength (text, b->allocatedNumChars));
  9271. release (b);
  9272. return newText;
  9273. }
  9274. static CharPointerType makeUniqueWithSize (const CharPointerType& text, size_t numChars)
  9275. {
  9276. StringHolder* const b = bufferFromText (text);
  9277. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9278. return text;
  9279. CharPointerType newText (createUninitialised (jmax (b->allocatedNumChars, numChars)));
  9280. copyChars (newText, text, b->allocatedNumChars);
  9281. release (b);
  9282. return newText;
  9283. }
  9284. static size_t getAllocatedNumChars (const CharPointerType& text) throw()
  9285. {
  9286. return bufferFromText (text)->allocatedNumChars;
  9287. }
  9288. static void copyChars (CharPointerType dest, const CharPointerType& src, const size_t numChars) throw()
  9289. {
  9290. jassert (src.getAddress() != 0 && dest.getAddress() != 0);
  9291. memcpy (dest.getAddress(), src.getAddress(), numChars * sizeof (juce_wchar));
  9292. CharPointerType (dest + (int) numChars).writeNull();
  9293. }
  9294. Atomic<int> refCount;
  9295. size_t allocatedNumChars;
  9296. juce_wchar text[1];
  9297. static StringHolder empty;
  9298. private:
  9299. static inline StringHolder* bufferFromText (const CharPointerType& text) throw()
  9300. {
  9301. // (Can't use offsetof() here because of warnings about this not being a POD)
  9302. return reinterpret_cast <StringHolder*> (reinterpret_cast <char*> (text.getAddress())
  9303. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9304. }
  9305. };
  9306. StringHolder StringHolder::empty;
  9307. const String String::empty;
  9308. void String::appendFixedLength (const juce_wchar* const newText, const int numExtraChars)
  9309. {
  9310. if (numExtraChars > 0)
  9311. {
  9312. const int oldLen = length();
  9313. const int newTotalLen = oldLen + numExtraChars;
  9314. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9315. StringHolder::copyChars (text + oldLen, CharPointer_UTF32 (newText), numExtraChars);
  9316. }
  9317. }
  9318. void String::preallocateStorage (const size_t numChars)
  9319. {
  9320. text = StringHolder::makeUniqueWithSize (text, numChars);
  9321. }
  9322. String::String() throw()
  9323. : text (StringHolder::getEmpty())
  9324. {
  9325. }
  9326. String::~String() throw()
  9327. {
  9328. StringHolder::release (text);
  9329. }
  9330. String::String (const String& other) throw()
  9331. : text (other.text)
  9332. {
  9333. StringHolder::retain (text);
  9334. }
  9335. void String::swapWith (String& other) throw()
  9336. {
  9337. swapVariables (text, other.text);
  9338. }
  9339. String& String::operator= (const String& other) throw()
  9340. {
  9341. StringHolder::retain (other.text);
  9342. StringHolder::release (text.atomicSwap (other.text));
  9343. return *this;
  9344. }
  9345. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9346. String::String (const Preallocation& preallocationSize)
  9347. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9348. {
  9349. }
  9350. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9351. : text (0)
  9352. {
  9353. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9354. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9355. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9356. }
  9357. String::String (const char* const t)
  9358. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t)))
  9359. {
  9360. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  9361. that contains values greater than 127. These can NOT be correctly converted to unicode
  9362. because there's no way for the String class to know what encoding was used to
  9363. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  9364. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  9365. string to the String class - so for example if your source data is actually UTF-8,
  9366. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  9367. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  9368. you use UTF-8 with escape characters in your source code to represent extended characters,
  9369. because there's no other way to represent these strings in a way that isn't dependent on
  9370. the compiler, source code editor and platform.
  9371. */
  9372. jassert (t == 0 || CharPointer_ASCII::isValidString (t, std::numeric_limits<int>::max()));
  9373. }
  9374. String::String (const char* const t, const size_t maxChars)
  9375. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t), maxChars))
  9376. {
  9377. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  9378. that contains values greater than 127. These can NOT be correctly converted to unicode
  9379. because there's no way for the String class to know what encoding was used to
  9380. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  9381. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  9382. string to the String class - so for example if your source data is actually UTF-8,
  9383. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  9384. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  9385. you use UTF-8 with escape characters in your source code to represent extended characters,
  9386. because there's no other way to represent these strings in a way that isn't dependent on
  9387. the compiler, source code editor and platform.
  9388. */
  9389. jassert (t == 0 || CharPointer_ASCII::isValidString (t, (int) maxChars));
  9390. }
  9391. String::String (const juce_wchar* const t)
  9392. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t)))
  9393. {
  9394. }
  9395. String::String (const juce_wchar* const t, const size_t maxChars)
  9396. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t), maxChars))
  9397. {
  9398. }
  9399. String::String (const CharPointer_UTF8& t)
  9400. : text (StringHolder::createFromCharPointer (t))
  9401. {
  9402. }
  9403. String::String (const CharPointer_UTF16& t)
  9404. : text (StringHolder::createFromCharPointer (t))
  9405. {
  9406. }
  9407. String::String (const CharPointer_UTF32& t)
  9408. : text (StringHolder::createFromCharPointer (t))
  9409. {
  9410. }
  9411. String::String (const CharPointer_UTF32& t, const size_t maxChars)
  9412. : text (StringHolder::createFromCharPointer (t, maxChars))
  9413. {
  9414. }
  9415. String::String (const CharPointer_UTF32& start, const CharPointer_UTF32& end)
  9416. : text (StringHolder::createFromCharPointer (start, end))
  9417. {
  9418. }
  9419. String::String (const CharPointer_ASCII& t)
  9420. : text (StringHolder::createFromCharPointer (t))
  9421. {
  9422. }
  9423. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  9424. String::String (const wchar_t* const t)
  9425. : text (StringHolder::createFromCharPointer
  9426. (CharPointer_wchar_t (reinterpret_cast <const CharPointer_wchar_t::CharType*> (t))))
  9427. {
  9428. }
  9429. String::String (const wchar_t* const t, size_t maxChars)
  9430. : text (StringHolder::createFromCharPointer
  9431. (CharPointer_wchar_t (reinterpret_cast <const CharPointer_wchar_t::CharType*> (t)), maxChars))
  9432. {
  9433. }
  9434. #endif
  9435. const String String::charToString (const juce_wchar character)
  9436. {
  9437. String result (Preallocation (1));
  9438. CharPointerType t (result.text);
  9439. t.write (character);
  9440. t.writeNull();
  9441. return result;
  9442. }
  9443. namespace NumberToStringConverters
  9444. {
  9445. // pass in a pointer to the END of a buffer..
  9446. juce_wchar* numberToString (juce_wchar* t, const int64 n) throw()
  9447. {
  9448. *--t = 0;
  9449. int64 v = (n >= 0) ? n : -n;
  9450. do
  9451. {
  9452. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9453. v /= 10;
  9454. } while (v > 0);
  9455. if (n < 0)
  9456. *--t = '-';
  9457. return t;
  9458. }
  9459. juce_wchar* numberToString (juce_wchar* t, uint64 v) throw()
  9460. {
  9461. *--t = 0;
  9462. do
  9463. {
  9464. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9465. v /= 10;
  9466. } while (v > 0);
  9467. return t;
  9468. }
  9469. juce_wchar* numberToString (juce_wchar* t, const int n) throw()
  9470. {
  9471. if (n == (int) 0x80000000) // (would cause an overflow)
  9472. return numberToString (t, (int64) n);
  9473. *--t = 0;
  9474. int v = abs (n);
  9475. do
  9476. {
  9477. *--t = (juce_wchar) ('0' + (v % 10));
  9478. v /= 10;
  9479. } while (v > 0);
  9480. if (n < 0)
  9481. *--t = '-';
  9482. return t;
  9483. }
  9484. juce_wchar* numberToString (juce_wchar* t, unsigned int v) throw()
  9485. {
  9486. *--t = 0;
  9487. do
  9488. {
  9489. *--t = (juce_wchar) ('0' + (v % 10));
  9490. v /= 10;
  9491. } while (v > 0);
  9492. return t;
  9493. }
  9494. juce_wchar getDecimalPoint()
  9495. {
  9496. #if JUCE_VC7_OR_EARLIER
  9497. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9498. #else
  9499. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9500. #endif
  9501. return dp;
  9502. }
  9503. char* doubleToString (char* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9504. {
  9505. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9506. {
  9507. char* const end = buffer + numChars;
  9508. char* t = end;
  9509. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9510. *--t = (char) 0;
  9511. while (numDecPlaces >= 0 || v > 0)
  9512. {
  9513. if (numDecPlaces == 0)
  9514. *--t = (char) getDecimalPoint();
  9515. *--t = (char) ('0' + (v % 10));
  9516. v /= 10;
  9517. --numDecPlaces;
  9518. }
  9519. if (n < 0)
  9520. *--t = '-';
  9521. len = end - t - 1;
  9522. return t;
  9523. }
  9524. else
  9525. {
  9526. len = sprintf (buffer, "%.9g", n);
  9527. return buffer;
  9528. }
  9529. }
  9530. template <typename IntegerType>
  9531. const String::CharPointerType createFromInteger (const IntegerType number)
  9532. {
  9533. juce_wchar buffer [32];
  9534. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9535. juce_wchar* const start = numberToString (end, number);
  9536. return StringHolder::createFromFixedLength (start, end - start - 1);
  9537. }
  9538. const String::CharPointerType createFromDouble (const double number, const int numberOfDecimalPlaces)
  9539. {
  9540. char buffer [48];
  9541. size_t len;
  9542. char* const start = doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9543. return StringHolder::createFromFixedLength (start, len);
  9544. }
  9545. }
  9546. String::String (const int number)
  9547. : text (NumberToStringConverters::createFromInteger (number))
  9548. {
  9549. }
  9550. String::String (const unsigned int number)
  9551. : text (NumberToStringConverters::createFromInteger (number))
  9552. {
  9553. }
  9554. String::String (const short number)
  9555. : text (NumberToStringConverters::createFromInteger ((int) number))
  9556. {
  9557. }
  9558. String::String (const unsigned short number)
  9559. : text (NumberToStringConverters::createFromInteger ((unsigned int) number))
  9560. {
  9561. }
  9562. String::String (const int64 number)
  9563. : text (NumberToStringConverters::createFromInteger (number))
  9564. {
  9565. }
  9566. String::String (const uint64 number)
  9567. : text (NumberToStringConverters::createFromInteger (number))
  9568. {
  9569. }
  9570. String::String (const float number, const int numberOfDecimalPlaces)
  9571. : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces))
  9572. {
  9573. }
  9574. String::String (const double number, const int numberOfDecimalPlaces)
  9575. : text (NumberToStringConverters::createFromDouble (number, numberOfDecimalPlaces))
  9576. {
  9577. }
  9578. int String::length() const throw()
  9579. {
  9580. return (int) text.length();
  9581. }
  9582. const juce_wchar String::operator[] (int index) const throw()
  9583. {
  9584. jassert (index == 0 || isPositiveAndNotGreaterThan (index, length()));
  9585. return text [index];
  9586. }
  9587. int String::hashCode() const throw()
  9588. {
  9589. CharPointerType t (text);
  9590. int result = 0;
  9591. while (! t.isEmpty())
  9592. result = 31 * result + t.getAndAdvance();
  9593. return result;
  9594. }
  9595. int64 String::hashCode64() const throw()
  9596. {
  9597. CharPointerType t (text);
  9598. int64 result = 0;
  9599. while (! t.isEmpty())
  9600. result = 101 * result + t.getAndAdvance();
  9601. return result;
  9602. }
  9603. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9604. {
  9605. return string1.compare (string2) == 0;
  9606. }
  9607. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9608. {
  9609. return string1.compare (string2) == 0;
  9610. }
  9611. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9612. {
  9613. return string1.compare (string2) == 0;
  9614. }
  9615. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) throw()
  9616. {
  9617. return string1.getCharPointer().compare (string2) == 0;
  9618. }
  9619. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) throw()
  9620. {
  9621. return string1.getCharPointer().compare (string2) == 0;
  9622. }
  9623. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) throw()
  9624. {
  9625. return string1.getCharPointer().compare (string2) == 0;
  9626. }
  9627. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9628. {
  9629. return string1.compare (string2) != 0;
  9630. }
  9631. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9632. {
  9633. return string1.compare (string2) != 0;
  9634. }
  9635. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9636. {
  9637. return string1.compare (string2) != 0;
  9638. }
  9639. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) throw()
  9640. {
  9641. return string1.getCharPointer().compare (string2) != 0;
  9642. }
  9643. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) throw()
  9644. {
  9645. return string1.getCharPointer().compare (string2) != 0;
  9646. }
  9647. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) throw()
  9648. {
  9649. return string1.getCharPointer().compare (string2) != 0;
  9650. }
  9651. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9652. {
  9653. return string1.compare (string2) > 0;
  9654. }
  9655. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9656. {
  9657. return string1.compare (string2) < 0;
  9658. }
  9659. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9660. {
  9661. return string1.compare (string2) >= 0;
  9662. }
  9663. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9664. {
  9665. return string1.compare (string2) <= 0;
  9666. }
  9667. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9668. {
  9669. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF32 (t)) == 0
  9670. : isEmpty();
  9671. }
  9672. bool String::equalsIgnoreCase (const char* t) const throw()
  9673. {
  9674. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0
  9675. : isEmpty();
  9676. }
  9677. bool String::equalsIgnoreCase (const String& other) const throw()
  9678. {
  9679. return text == other.text
  9680. || text.compareIgnoreCase (other.text) == 0;
  9681. }
  9682. int String::compare (const String& other) const throw()
  9683. {
  9684. return (text == other.text) ? 0 : text.compare (other.text);
  9685. }
  9686. int String::compare (const char* other) const throw()
  9687. {
  9688. return text.compare (CharPointer_UTF8 (other));
  9689. }
  9690. int String::compare (const juce_wchar* other) const throw()
  9691. {
  9692. return text.compare (CharPointer_UTF32 (other));
  9693. }
  9694. int String::compareIgnoreCase (const String& other) const throw()
  9695. {
  9696. return (text == other.text) ? 0 : text.compareIgnoreCase (other.text);
  9697. }
  9698. int String::compareLexicographically (const String& other) const throw()
  9699. {
  9700. CharPointerType s1 (text);
  9701. while (! (s1.isEmpty() || s1.isLetterOrDigit()))
  9702. ++s1;
  9703. CharPointerType s2 (other.text);
  9704. while (! (s2.isEmpty() || s2.isLetterOrDigit()))
  9705. ++s2;
  9706. return s1.compareIgnoreCase (s2);
  9707. }
  9708. void String::append (const String& textToAppend, size_t maxCharsToTake)
  9709. {
  9710. appendCharPointer (textToAppend.text, maxCharsToTake);
  9711. }
  9712. String& String::operator+= (const juce_wchar* const t)
  9713. {
  9714. appendCharPointer (CharPointer_UTF32 (t));
  9715. return *this;
  9716. }
  9717. String& String::operator+= (const String& other)
  9718. {
  9719. if (isEmpty())
  9720. return operator= (other);
  9721. appendCharPointer (other.text);
  9722. return *this;
  9723. }
  9724. String& String::operator+= (const char ch)
  9725. {
  9726. return operator+= ((juce_wchar) ch);
  9727. }
  9728. String& String::operator+= (const juce_wchar ch)
  9729. {
  9730. const juce_wchar asString[] = { ch, 0 };
  9731. return operator+= (static_cast <const juce_wchar*> (asString));
  9732. }
  9733. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  9734. String& String::operator+= (const wchar_t ch)
  9735. {
  9736. return operator+= ((juce_wchar) ch);
  9737. }
  9738. String& String::operator+= (const wchar_t* t)
  9739. {
  9740. return operator+= (String (t));
  9741. }
  9742. #endif
  9743. String& String::operator+= (const int number)
  9744. {
  9745. juce_wchar buffer [16];
  9746. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9747. juce_wchar* const start = NumberToStringConverters::numberToString (end, number);
  9748. appendFixedLength (start, (int) (end - start));
  9749. return *this;
  9750. }
  9751. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9752. {
  9753. String s (string1);
  9754. return s += string2;
  9755. }
  9756. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9757. {
  9758. String s (string1);
  9759. return s += string2;
  9760. }
  9761. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9762. {
  9763. return String::charToString (string1) + string2;
  9764. }
  9765. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9766. {
  9767. return String::charToString (string1) + string2;
  9768. }
  9769. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9770. {
  9771. return string1 += string2;
  9772. }
  9773. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9774. {
  9775. return string1 += string2;
  9776. }
  9777. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9778. {
  9779. return string1 += string2;
  9780. }
  9781. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9782. {
  9783. return string1 += string2;
  9784. }
  9785. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9786. {
  9787. return string1 += string2;
  9788. }
  9789. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  9790. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t string2)
  9791. {
  9792. return string1 += string2;
  9793. }
  9794. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2)
  9795. {
  9796. string1.appendCharPointer (CharPointer_wchar_t (reinterpret_cast <const CharPointer_wchar_t::CharType*> (string2)));
  9797. return string1;
  9798. }
  9799. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2)
  9800. {
  9801. String s (string1);
  9802. return s += string2;
  9803. }
  9804. #endif
  9805. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9806. {
  9807. return string1 += characterToAppend;
  9808. }
  9809. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9810. {
  9811. return string1 += characterToAppend;
  9812. }
  9813. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9814. {
  9815. return string1 += string2;
  9816. }
  9817. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9818. {
  9819. return string1 += string2;
  9820. }
  9821. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9822. {
  9823. return string1 += string2;
  9824. }
  9825. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9826. {
  9827. return string1 += (int) number;
  9828. }
  9829. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9830. {
  9831. return string1 += number;
  9832. }
  9833. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9834. {
  9835. return string1 += (int) number;
  9836. }
  9837. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9838. {
  9839. return string1 += String (number);
  9840. }
  9841. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9842. {
  9843. return string1 += String (number);
  9844. }
  9845. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9846. {
  9847. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9848. // if lots of large, persistent strings were to be written to streams).
  9849. const int numBytes = text.getNumBytesAsUTF8();
  9850. HeapBlock<char> temp (numBytes + 1);
  9851. text.copyToUTF8 (temp, numBytes + 1);
  9852. stream.write (temp, numBytes);
  9853. return stream;
  9854. }
  9855. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  9856. {
  9857. return string1 += NewLine::getDefault();
  9858. }
  9859. int String::indexOfChar (const juce_wchar character) const throw()
  9860. {
  9861. return text.indexOf (character);
  9862. }
  9863. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9864. {
  9865. for (int i = length(); --i >= 0;)
  9866. if (text[i] == character)
  9867. return i;
  9868. return -1;
  9869. }
  9870. int String::indexOf (const String& t) const throw()
  9871. {
  9872. return t.isEmpty() ? 0 : text.indexOf (t.text);
  9873. }
  9874. int String::indexOfChar (const int startIndex,
  9875. const juce_wchar character) const throw()
  9876. {
  9877. const int i = (text + startIndex).indexOf (character);
  9878. return i < 0 ? -1 : (i + startIndex);
  9879. }
  9880. int String::indexOfAnyOf (const String& charactersToLookFor,
  9881. const int startIndex,
  9882. const bool ignoreCase) const throw()
  9883. {
  9884. if (startIndex > 0 && startIndex >= length())
  9885. return -1;
  9886. CharPointerType t (text);
  9887. int i = jmax (0, startIndex);
  9888. t += i;
  9889. while (! t.isEmpty())
  9890. {
  9891. if (charactersToLookFor.text.indexOf (*t, ignoreCase) >= 0)
  9892. return i;
  9893. ++i;
  9894. ++t;
  9895. }
  9896. return -1;
  9897. }
  9898. int String::indexOf (const int startIndex, const String& other) const throw()
  9899. {
  9900. if (startIndex > 0 && startIndex >= length())
  9901. return -1;
  9902. int i = CharPointerType (text + jmax (0, startIndex)).indexOf (other.text);
  9903. return i >= 0 ? i + startIndex : -1;
  9904. }
  9905. int String::indexOfIgnoreCase (const String& other) const throw()
  9906. {
  9907. if (other.isEmpty())
  9908. return 0;
  9909. const int len = other.length();
  9910. const int end = length() - len;
  9911. for (int i = 0; i <= end; ++i)
  9912. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9913. return i;
  9914. return -1;
  9915. }
  9916. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9917. {
  9918. if (other.isNotEmpty())
  9919. {
  9920. const int len = other.length();
  9921. const int end = length() - len;
  9922. for (int i = jmax (0, startIndex); i <= end; ++i)
  9923. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9924. return i;
  9925. }
  9926. return -1;
  9927. }
  9928. int String::lastIndexOf (const String& other) const throw()
  9929. {
  9930. if (other.isNotEmpty())
  9931. {
  9932. const int len = other.length();
  9933. int i = length() - len;
  9934. if (i >= 0)
  9935. {
  9936. CharPointerType n (text + i);
  9937. while (i >= 0)
  9938. {
  9939. if (n.compareUpTo (other.text, len) == 0)
  9940. return i;
  9941. --n;
  9942. --i;
  9943. }
  9944. }
  9945. }
  9946. return -1;
  9947. }
  9948. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9949. {
  9950. if (other.isNotEmpty())
  9951. {
  9952. const int len = other.length();
  9953. int i = length() - len;
  9954. if (i >= 0)
  9955. {
  9956. CharPointerType n (text + i);
  9957. while (i >= 0)
  9958. {
  9959. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  9960. return i;
  9961. --n;
  9962. --i;
  9963. }
  9964. }
  9965. }
  9966. return -1;
  9967. }
  9968. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9969. {
  9970. for (int i = length(); --i >= 0;)
  9971. if (charactersToLookFor.text.indexOf (text[i], ignoreCase) >= 0)
  9972. return i;
  9973. return -1;
  9974. }
  9975. bool String::contains (const String& other) const throw()
  9976. {
  9977. return indexOf (other) >= 0;
  9978. }
  9979. bool String::containsChar (const juce_wchar character) const throw()
  9980. {
  9981. return text.indexOf (character) >= 0;
  9982. }
  9983. bool String::containsIgnoreCase (const String& t) const throw()
  9984. {
  9985. return indexOfIgnoreCase (t) >= 0;
  9986. }
  9987. int String::indexOfWholeWord (const String& word) const throw()
  9988. {
  9989. if (word.isNotEmpty())
  9990. {
  9991. CharPointerType t (text);
  9992. const int wordLen = word.length();
  9993. const int end = (int) t.length() - wordLen;
  9994. for (int i = 0; i <= end; ++i)
  9995. {
  9996. if (t.compareUpTo (word.text, wordLen) == 0
  9997. && (i == 0 || ! (t - 1).isLetterOrDigit())
  9998. && ! (t + wordLen).isLetterOrDigit())
  9999. return i;
  10000. ++t;
  10001. }
  10002. }
  10003. return -1;
  10004. }
  10005. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10006. {
  10007. if (word.isNotEmpty())
  10008. {
  10009. CharPointerType t (text);
  10010. const int wordLen = word.length();
  10011. const int end = (int) t.length() - wordLen;
  10012. for (int i = 0; i <= end; ++i)
  10013. {
  10014. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  10015. && (i == 0 || ! (t + -1).isLetterOrDigit())
  10016. && ! (t + wordLen).isLetterOrDigit())
  10017. return i;
  10018. ++t;
  10019. }
  10020. }
  10021. return -1;
  10022. }
  10023. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10024. {
  10025. return indexOfWholeWord (wordToLookFor) >= 0;
  10026. }
  10027. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10028. {
  10029. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10030. }
  10031. namespace WildCardHelpers
  10032. {
  10033. int indexOfMatch (const String::CharPointerType& wildcard,
  10034. String::CharPointerType test,
  10035. const bool ignoreCase) throw()
  10036. {
  10037. int start = 0;
  10038. while (! test.isEmpty())
  10039. {
  10040. String::CharPointerType t (test);
  10041. String::CharPointerType w (wildcard);
  10042. for (;;)
  10043. {
  10044. const juce_wchar wc = *w;
  10045. const juce_wchar tc = *t;
  10046. if (wc == tc
  10047. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  10048. || (wc == '?' && tc != 0))
  10049. {
  10050. if (wc == 0)
  10051. return start;
  10052. ++t;
  10053. ++w;
  10054. }
  10055. else
  10056. {
  10057. if (wc == '*' && (w[1] == 0 || indexOfMatch (w + 1, t, ignoreCase) >= 0))
  10058. return start;
  10059. break;
  10060. }
  10061. }
  10062. ++start;
  10063. ++test;
  10064. }
  10065. return -1;
  10066. }
  10067. }
  10068. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10069. {
  10070. CharPointerType w (wildcard.text);
  10071. CharPointerType t (text);
  10072. for (;;)
  10073. {
  10074. const juce_wchar wc = *w;
  10075. const juce_wchar tc = *t;
  10076. if (wc == tc
  10077. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  10078. || (wc == '?' && tc != 0))
  10079. {
  10080. if (wc == 0)
  10081. return true;
  10082. ++w;
  10083. ++t;
  10084. }
  10085. else
  10086. {
  10087. return wc == '*' && (w[1] == 0 || WildCardHelpers::indexOfMatch (w + 1, t, ignoreCase) >= 0);
  10088. }
  10089. }
  10090. }
  10091. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10092. {
  10093. if (numberOfTimesToRepeat <= 0)
  10094. return String::empty;
  10095. String result (Preallocation (stringToRepeat.length() * numberOfTimesToRepeat + 1));
  10096. CharPointerType n (result.text);
  10097. while (--numberOfTimesToRepeat >= 0)
  10098. n.writeAll (stringToRepeat.text);
  10099. return result;
  10100. }
  10101. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10102. {
  10103. jassert (padCharacter != 0);
  10104. const int len = length();
  10105. if (len >= minimumLength || padCharacter == 0)
  10106. return *this;
  10107. String result (Preallocation (minimumLength + 1));
  10108. CharPointerType n (result.text);
  10109. minimumLength -= len;
  10110. while (--minimumLength >= 0)
  10111. n.write (padCharacter);
  10112. StringHolder::copyChars (n, text, len);
  10113. return result;
  10114. }
  10115. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10116. {
  10117. jassert (padCharacter != 0);
  10118. const int len = length();
  10119. if (len >= minimumLength || padCharacter == 0)
  10120. return *this;
  10121. String result (*this, (size_t) minimumLength);
  10122. CharPointerType n (result.text + len);
  10123. minimumLength -= len;
  10124. while (--minimumLength >= 0)
  10125. n.write (padCharacter);
  10126. n.writeNull();
  10127. return result;
  10128. }
  10129. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10130. {
  10131. if (index < 0)
  10132. {
  10133. // a negative index to replace from?
  10134. jassertfalse;
  10135. index = 0;
  10136. }
  10137. if (numCharsToReplace < 0)
  10138. {
  10139. // replacing a negative number of characters?
  10140. numCharsToReplace = 0;
  10141. jassertfalse;
  10142. }
  10143. const int len = length();
  10144. if (index + numCharsToReplace > len)
  10145. {
  10146. if (index > len)
  10147. {
  10148. // replacing beyond the end of the string?
  10149. index = len;
  10150. jassertfalse;
  10151. }
  10152. numCharsToReplace = len - index;
  10153. }
  10154. const int newStringLen = stringToInsert.length();
  10155. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10156. if (newTotalLen <= 0)
  10157. return String::empty;
  10158. String result (Preallocation ((size_t) newTotalLen));
  10159. StringHolder::copyChars (result.text, text, index);
  10160. if (newStringLen > 0)
  10161. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10162. const int endStringLen = newTotalLen - (index + newStringLen);
  10163. if (endStringLen > 0)
  10164. StringHolder::copyChars (result.text + (index + newStringLen),
  10165. text + (index + numCharsToReplace),
  10166. endStringLen);
  10167. return result;
  10168. }
  10169. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10170. {
  10171. const int stringToReplaceLen = stringToReplace.length();
  10172. const int stringToInsertLen = stringToInsert.length();
  10173. int i = 0;
  10174. String result (*this);
  10175. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10176. : result.indexOf (i, stringToReplace))) >= 0)
  10177. {
  10178. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10179. i += stringToInsertLen;
  10180. }
  10181. return result;
  10182. }
  10183. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10184. {
  10185. const int index = indexOfChar (charToReplace);
  10186. if (index < 0)
  10187. return *this;
  10188. String result (*this, size_t());
  10189. CharPointerType t (result.text + index);
  10190. while (! t.isEmpty())
  10191. {
  10192. if (*t == charToReplace)
  10193. t.replaceChar (charToInsert);
  10194. ++t;
  10195. }
  10196. return result;
  10197. }
  10198. const String String::replaceCharacters (const String& charactersToReplace,
  10199. const String& charactersToInsertInstead) const
  10200. {
  10201. String result (*this, size_t());
  10202. CharPointerType t (result.text);
  10203. const int len2 = charactersToInsertInstead.length();
  10204. // the two strings passed in are supposed to be the same length!
  10205. jassert (len2 == charactersToReplace.length());
  10206. while (! t.isEmpty())
  10207. {
  10208. const int index = charactersToReplace.indexOfChar (*t);
  10209. if (isPositiveAndBelow (index, len2))
  10210. t.replaceChar (charactersToInsertInstead [index]);
  10211. ++t;
  10212. }
  10213. return result;
  10214. }
  10215. bool String::startsWith (const String& other) const throw()
  10216. {
  10217. return text.compareUpTo (other.text, other.length()) == 0;
  10218. }
  10219. bool String::startsWithIgnoreCase (const String& other) const throw()
  10220. {
  10221. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  10222. }
  10223. bool String::startsWithChar (const juce_wchar character) const throw()
  10224. {
  10225. jassert (character != 0); // strings can't contain a null character!
  10226. return text[0] == character;
  10227. }
  10228. bool String::endsWithChar (const juce_wchar character) const throw()
  10229. {
  10230. jassert (character != 0); // strings can't contain a null character!
  10231. return text[0] != 0
  10232. && text [length() - 1] == character;
  10233. }
  10234. bool String::endsWith (const String& other) const throw()
  10235. {
  10236. const int thisLen = length();
  10237. const int otherLen = other.length();
  10238. return thisLen >= otherLen
  10239. && CharPointerType (text + thisLen - otherLen).compare (other.text) == 0;
  10240. }
  10241. bool String::endsWithIgnoreCase (const String& other) const throw()
  10242. {
  10243. const int thisLen = length();
  10244. const int otherLen = other.length();
  10245. return thisLen >= otherLen
  10246. && CharPointerType (text + thisLen - otherLen).compareIgnoreCase (other.text) == 0;
  10247. }
  10248. const String String::toUpperCase() const
  10249. {
  10250. String result (Preallocation (this->length()));
  10251. CharPointerType dest (result.text);
  10252. CharPointerType src (text);
  10253. for (;;)
  10254. {
  10255. const juce_wchar c = src.toUpperCase();
  10256. dest.write (c);
  10257. if (c == 0)
  10258. break;
  10259. ++src;
  10260. }
  10261. return result;
  10262. }
  10263. const String String::toLowerCase() const
  10264. {
  10265. String result (Preallocation (this->length()));
  10266. CharPointerType dest (result.text);
  10267. CharPointerType src (text);
  10268. for (;;)
  10269. {
  10270. const juce_wchar c = src.toLowerCase();
  10271. dest.write (c);
  10272. if (c == 0)
  10273. break;
  10274. ++src;
  10275. }
  10276. return result;
  10277. }
  10278. juce_wchar String::getLastCharacter() const throw()
  10279. {
  10280. return isEmpty() ? juce_wchar() : text [length() - 1];
  10281. }
  10282. const String String::substring (int start, int end) const
  10283. {
  10284. if (start < 0)
  10285. start = 0;
  10286. else if (end <= start)
  10287. return empty;
  10288. int len = 0;
  10289. while (len <= end && text [len] != 0)
  10290. ++len;
  10291. if (end >= len)
  10292. {
  10293. if (start == 0)
  10294. return *this;
  10295. end = len;
  10296. }
  10297. return String (text + start, end - start);
  10298. }
  10299. const String String::substring (const int start) const
  10300. {
  10301. if (start <= 0)
  10302. return *this;
  10303. const int len = length();
  10304. if (start >= len)
  10305. return empty;
  10306. return String (text + start, len - start);
  10307. }
  10308. const String String::dropLastCharacters (const int numberToDrop) const
  10309. {
  10310. return String (text, jmax (0, length() - numberToDrop));
  10311. }
  10312. const String String::getLastCharacters (const int numCharacters) const
  10313. {
  10314. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10315. }
  10316. const String String::fromFirstOccurrenceOf (const String& sub,
  10317. const bool includeSubString,
  10318. const bool ignoreCase) const
  10319. {
  10320. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10321. : indexOf (sub);
  10322. if (i < 0)
  10323. return empty;
  10324. return substring (includeSubString ? i : i + sub.length());
  10325. }
  10326. const String String::fromLastOccurrenceOf (const String& sub,
  10327. const bool includeSubString,
  10328. const bool ignoreCase) const
  10329. {
  10330. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10331. : lastIndexOf (sub);
  10332. if (i < 0)
  10333. return *this;
  10334. return substring (includeSubString ? i : i + sub.length());
  10335. }
  10336. const String String::upToFirstOccurrenceOf (const String& sub,
  10337. const bool includeSubString,
  10338. const bool ignoreCase) const
  10339. {
  10340. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10341. : indexOf (sub);
  10342. if (i < 0)
  10343. return *this;
  10344. return substring (0, includeSubString ? i + sub.length() : i);
  10345. }
  10346. const String String::upToLastOccurrenceOf (const String& sub,
  10347. const bool includeSubString,
  10348. const bool ignoreCase) const
  10349. {
  10350. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10351. : lastIndexOf (sub);
  10352. if (i < 0)
  10353. return *this;
  10354. return substring (0, includeSubString ? i + sub.length() : i);
  10355. }
  10356. bool String::isQuotedString() const
  10357. {
  10358. const String trimmed (trimStart());
  10359. return trimmed[0] == '"'
  10360. || trimmed[0] == '\'';
  10361. }
  10362. const String String::unquoted() const
  10363. {
  10364. const int len = length();
  10365. if (len == 0)
  10366. return empty;
  10367. const juce_wchar lastChar = text [len - 1];
  10368. const int dropAtStart = (*text == '"' || *text == '\'') ? 1 : 0;
  10369. const int dropAtEnd = (lastChar == '"' || lastChar == '\'') ? 1 : 0;
  10370. return substring (dropAtStart, len - dropAtEnd);
  10371. }
  10372. const String String::quoted (const juce_wchar quoteCharacter) const
  10373. {
  10374. if (isEmpty())
  10375. return charToString (quoteCharacter) + quoteCharacter;
  10376. String t (*this);
  10377. if (! t.startsWithChar (quoteCharacter))
  10378. t = charToString (quoteCharacter) + t;
  10379. if (! t.endsWithChar (quoteCharacter))
  10380. t += quoteCharacter;
  10381. return t;
  10382. }
  10383. static String::CharPointerType findTrimmedEnd (const String::CharPointerType& start, String::CharPointerType end)
  10384. {
  10385. while (end > start)
  10386. {
  10387. if (! (--end).isWhitespace())
  10388. {
  10389. ++end;
  10390. break;
  10391. }
  10392. }
  10393. return end;
  10394. }
  10395. const String String::trim() const
  10396. {
  10397. if (isNotEmpty())
  10398. {
  10399. CharPointerType start (text.findEndOfWhitespace());
  10400. const CharPointerType end (start.findTerminatingNull());
  10401. CharPointerType trimmedEnd (findTrimmedEnd (start, end));
  10402. if (trimmedEnd <= start)
  10403. return empty;
  10404. else if (text < start || trimmedEnd < end)
  10405. return String (start, trimmedEnd);
  10406. }
  10407. return *this;
  10408. }
  10409. const String String::trimStart() const
  10410. {
  10411. if (isNotEmpty())
  10412. {
  10413. const CharPointerType t (text.findEndOfWhitespace());
  10414. if (t != text)
  10415. return String (t);
  10416. }
  10417. return *this;
  10418. }
  10419. const String String::trimEnd() const
  10420. {
  10421. if (isNotEmpty())
  10422. {
  10423. const CharPointerType end (text.findTerminatingNull());
  10424. CharPointerType trimmedEnd (findTrimmedEnd (text, end));
  10425. if (trimmedEnd < end)
  10426. return String (text, trimmedEnd);
  10427. }
  10428. return *this;
  10429. }
  10430. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10431. {
  10432. CharPointerType t (text);
  10433. while (charactersToTrim.containsChar (*t))
  10434. ++t;
  10435. return t == text ? *this : String (t);
  10436. }
  10437. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10438. {
  10439. if (isNotEmpty())
  10440. {
  10441. const CharPointerType end (text.findTerminatingNull());
  10442. CharPointerType trimmedEnd (end);
  10443. while (trimmedEnd > text)
  10444. {
  10445. if (! charactersToTrim.containsChar (*--trimmedEnd))
  10446. {
  10447. ++trimmedEnd;
  10448. break;
  10449. }
  10450. }
  10451. if (trimmedEnd < end)
  10452. return String (text, trimmedEnd);
  10453. }
  10454. return *this;
  10455. }
  10456. const String String::retainCharacters (const String& charactersToRetain) const
  10457. {
  10458. if (isEmpty())
  10459. return empty;
  10460. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10461. CharPointerType dst (result.text);
  10462. CharPointerType src (text);
  10463. for (;;)
  10464. {
  10465. const juce_wchar c = src.getAndAdvance();
  10466. if (c == 0)
  10467. break;
  10468. if (charactersToRetain.containsChar (c))
  10469. dst.write (c);
  10470. }
  10471. dst.writeNull();
  10472. return result;
  10473. }
  10474. const String String::removeCharacters (const String& charactersToRemove) const
  10475. {
  10476. if (isEmpty())
  10477. return empty;
  10478. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10479. CharPointerType dst (result.text);
  10480. CharPointerType src (text);
  10481. for (;;)
  10482. {
  10483. const juce_wchar c = src.getAndAdvance();
  10484. if (c == 0)
  10485. break;
  10486. if (! charactersToRemove.containsChar (c))
  10487. dst.write (c);
  10488. }
  10489. dst.writeNull();
  10490. return result;
  10491. }
  10492. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10493. {
  10494. CharPointerType t (text);
  10495. while (! t.isEmpty())
  10496. {
  10497. if (! permittedCharacters.containsChar (*t))
  10498. return String (text, t);
  10499. ++t;
  10500. }
  10501. return *this;
  10502. }
  10503. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10504. {
  10505. CharPointerType t (text);
  10506. while (! t.isEmpty())
  10507. {
  10508. if (charactersToStopAt.containsChar (*t))
  10509. return String (text, t);
  10510. ++t;
  10511. }
  10512. return *this;
  10513. }
  10514. bool String::containsOnly (const String& chars) const throw()
  10515. {
  10516. CharPointerType t (text);
  10517. while (! t.isEmpty())
  10518. if (! chars.containsChar (t.getAndAdvance()))
  10519. return false;
  10520. return true;
  10521. }
  10522. bool String::containsAnyOf (const String& chars) const throw()
  10523. {
  10524. CharPointerType t (text);
  10525. while (! t.isEmpty())
  10526. if (chars.containsChar (t.getAndAdvance()))
  10527. return true;
  10528. return false;
  10529. }
  10530. bool String::containsNonWhitespaceChars() const throw()
  10531. {
  10532. CharPointerType t (text);
  10533. while (! t.isEmpty())
  10534. {
  10535. if (! t.isWhitespace())
  10536. return true;
  10537. ++t;
  10538. }
  10539. return false;
  10540. }
  10541. const String String::formatted (const juce_wchar* const pf, ... )
  10542. {
  10543. jassert (pf != 0);
  10544. va_list args;
  10545. va_start (args, pf);
  10546. size_t bufferSize = 256;
  10547. String result (Preallocation ((size_t) bufferSize));
  10548. result.text[0] = 0;
  10549. for (;;)
  10550. {
  10551. #if JUCE_LINUX && JUCE_64BIT
  10552. va_list tempArgs;
  10553. va_copy (tempArgs, args);
  10554. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, tempArgs);
  10555. va_end (tempArgs);
  10556. #elif JUCE_WINDOWS
  10557. HeapBlock <wchar_t> temp (bufferSize);
  10558. const int num = (int) _vsnwprintf (temp.getData(), bufferSize - 1, String (pf).toUTF16(), args);
  10559. if (num > 0)
  10560. CharPointerType (result.text).writeAll (CharPointer_UTF16 (temp.getData()));
  10561. #elif JUCE_ANDROID
  10562. HeapBlock <char> temp (bufferSize);
  10563. const int num = (int) vsnprintf (temp.getData(), bufferSize - 1, String (pf).toUTF8(), args);
  10564. if (num > 0)
  10565. CharPointerType (result.text).writeAll (CharPointer_UTF8 (temp.getData()));
  10566. #else
  10567. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, args);
  10568. #endif
  10569. if (num > 0)
  10570. return result;
  10571. bufferSize += 256;
  10572. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10573. break; // returns -1 because of an error rather than because it needs more space.
  10574. result.preallocateStorage (bufferSize);
  10575. }
  10576. return empty;
  10577. }
  10578. int String::getIntValue() const throw()
  10579. {
  10580. return text.getIntValue32();
  10581. }
  10582. int String::getTrailingIntValue() const throw()
  10583. {
  10584. int n = 0;
  10585. int mult = 1;
  10586. CharPointerType t (text.findTerminatingNull());
  10587. while ((--t).getAddress() >= text)
  10588. {
  10589. if (! t.isDigit())
  10590. {
  10591. if (*t == '-')
  10592. n = -n;
  10593. break;
  10594. }
  10595. n += mult * (*t - '0');
  10596. mult *= 10;
  10597. }
  10598. return n;
  10599. }
  10600. int64 String::getLargeIntValue() const throw()
  10601. {
  10602. return text.getIntValue64();
  10603. }
  10604. float String::getFloatValue() const throw()
  10605. {
  10606. return (float) getDoubleValue();
  10607. }
  10608. double String::getDoubleValue() const throw()
  10609. {
  10610. return text.getDoubleValue();
  10611. }
  10612. static const char* const hexDigits = "0123456789abcdef";
  10613. template <typename Type>
  10614. struct HexConverter
  10615. {
  10616. static const String hexToString (Type v)
  10617. {
  10618. juce_wchar buffer[32];
  10619. juce_wchar* const end = buffer + 32;
  10620. juce_wchar* t = end;
  10621. *--t = 0;
  10622. do
  10623. {
  10624. *--t = (juce_wchar) hexDigits [(int) (v & 15)];
  10625. v >>= 4;
  10626. } while (v != 0);
  10627. return String (t, (int) (end - t) - 1);
  10628. }
  10629. static Type stringToHex (String::CharPointerType t) throw()
  10630. {
  10631. Type result = 0;
  10632. while (! t.isEmpty())
  10633. {
  10634. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  10635. if (hexValue >= 0)
  10636. result = (result << 4) | hexValue;
  10637. }
  10638. return result;
  10639. }
  10640. };
  10641. const String String::toHexString (const int number)
  10642. {
  10643. return HexConverter <unsigned int>::hexToString ((unsigned int) number);
  10644. }
  10645. const String String::toHexString (const int64 number)
  10646. {
  10647. return HexConverter <uint64>::hexToString ((uint64) number);
  10648. }
  10649. const String String::toHexString (const short number)
  10650. {
  10651. return toHexString ((int) (unsigned short) number);
  10652. }
  10653. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10654. {
  10655. if (size <= 0)
  10656. return empty;
  10657. int numChars = (size * 2) + 2;
  10658. if (groupSize > 0)
  10659. numChars += size / groupSize;
  10660. String s (Preallocation ((size_t) numChars));
  10661. CharPointerType dest (s.text);
  10662. for (int i = 0; i < size; ++i)
  10663. {
  10664. dest.write ((juce_wchar) hexDigits [(*data) >> 4]);
  10665. dest.write ((juce_wchar) hexDigits [(*data) & 0xf]);
  10666. ++data;
  10667. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10668. dest.write ((juce_wchar) ' ');
  10669. }
  10670. dest.writeNull();
  10671. return s;
  10672. }
  10673. int String::getHexValue32() const throw()
  10674. {
  10675. return HexConverter <int>::stringToHex (text);
  10676. }
  10677. int64 String::getHexValue64() const throw()
  10678. {
  10679. return HexConverter <int64>::stringToHex (text);
  10680. }
  10681. const String String::createStringFromData (const void* const data_, const int size)
  10682. {
  10683. const uint8* const data = static_cast <const uint8*> (data_);
  10684. if (size <= 0 || data == 0)
  10685. {
  10686. return empty;
  10687. }
  10688. else if (size == 1)
  10689. {
  10690. return charToString ((char) data[0]);
  10691. }
  10692. else if ((data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1
  10693. && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkBE2)
  10694. || (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkLE1
  10695. && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkLE1))
  10696. {
  10697. const bool bigEndian = (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1);
  10698. const int numChars = size / 2 - 1;
  10699. String result;
  10700. result.preallocateStorage (numChars + 2);
  10701. const uint16* const src = (const uint16*) (data + 2);
  10702. CharPointerType dst (result.getCharPointer());
  10703. if (bigEndian)
  10704. {
  10705. for (int i = 0; i < numChars; ++i)
  10706. dst.write ((juce_wchar) ByteOrder::swapIfLittleEndian (src[i]));
  10707. }
  10708. else
  10709. {
  10710. for (int i = 0; i < numChars; ++i)
  10711. dst.write ((juce_wchar) ByteOrder::swapIfBigEndian (src[i]));
  10712. }
  10713. dst.writeNull();
  10714. return result;
  10715. }
  10716. else
  10717. {
  10718. if (size >= 3
  10719. && data[0] == (uint8) CharPointer_UTF8::byteOrderMark1
  10720. && data[1] == (uint8) CharPointer_UTF8::byteOrderMark2
  10721. && data[2] == (uint8) CharPointer_UTF8::byteOrderMark3)
  10722. return String::fromUTF8 ((const char*) data + 3, size - 3);
  10723. return String::fromUTF8 ((const char*) data, size);
  10724. }
  10725. }
  10726. void* String::createSpaceAtEndOfBuffer (const size_t numExtraBytes) const
  10727. {
  10728. const int currentLen = length() + 1;
  10729. String& mutableThis = const_cast <String&> (*this);
  10730. mutableThis.preallocateStorage (currentLen + 1 + numExtraBytes / sizeof (juce_wchar));
  10731. return (mutableThis.text + currentLen).getAddress();
  10732. }
  10733. const CharPointer_UTF8 String::toUTF8() const
  10734. {
  10735. if (isEmpty())
  10736. return CharPointer_UTF8 (reinterpret_cast <const CharPointer_UTF8::CharType*> (text.getAddress()));
  10737. const size_t extraBytesNeeded = CharPointer_UTF8::getBytesRequiredFor (text);
  10738. CharPointer_UTF8 extraSpace (static_cast <CharPointer_UTF8::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10739. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10740. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10741. #endif
  10742. CharPointer_UTF8 (extraSpace).writeAll (text);
  10743. return extraSpace;
  10744. }
  10745. CharPointer_UTF16 String::toUTF16() const
  10746. {
  10747. if (isEmpty())
  10748. return CharPointer_UTF16 (reinterpret_cast <const CharPointer_UTF16::CharType*> (text.getAddress()));
  10749. const size_t extraBytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text);
  10750. CharPointer_UTF16 extraSpace (static_cast <CharPointer_UTF16::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10751. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10752. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10753. #endif
  10754. CharPointer_UTF16 (extraSpace).writeAll (text);
  10755. return extraSpace;
  10756. }
  10757. int String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, const int maxBufferSizeBytes) const throw()
  10758. {
  10759. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10760. if (buffer == 0)
  10761. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10762. return CharPointer_UTF8 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10763. }
  10764. int String::copyToUTF16 (CharPointer_UTF16::CharType* const buffer, int maxBufferSizeBytes) const throw()
  10765. {
  10766. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10767. if (buffer == 0)
  10768. return (int) CharPointer_UTF16::getBytesRequiredFor (text);
  10769. return CharPointer_UTF16 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10770. }
  10771. int String::getNumBytesAsUTF8() const throw()
  10772. {
  10773. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10774. }
  10775. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10776. {
  10777. if (buffer == 0)
  10778. return empty;
  10779. const int len = (int) (bufferSizeBytes >= 0 ? CharPointer_UTF8 (buffer).lengthUpTo (bufferSizeBytes)
  10780. : CharPointer_UTF8 (buffer).length());
  10781. String result (Preallocation (len + 1));
  10782. CharPointerType (result.text).writeWithCharLimit (CharPointer_UTF8 (buffer), len + 1);
  10783. return result;
  10784. }
  10785. const char* String::toCString() const
  10786. {
  10787. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  10788. if (isEmpty())
  10789. return reinterpret_cast <const char*> (text.getAddress());
  10790. const int len = getNumBytesAsCString();
  10791. char* const extraSpace = static_cast <char*> (createSpaceAtEndOfBuffer (len + 1));
  10792. wcstombs (extraSpace, text, len);
  10793. extraSpace [len] = 0;
  10794. return extraSpace;
  10795. #else
  10796. return toUTF8();
  10797. #endif
  10798. }
  10799. int String::getNumBytesAsCString() const throw()
  10800. {
  10801. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  10802. return (int) wcstombs (0, text, 0);
  10803. #else
  10804. return getNumBytesAsUTF8();
  10805. #endif
  10806. }
  10807. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10808. {
  10809. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  10810. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10811. if (destBuffer != 0 && numBytes >= 0)
  10812. destBuffer [numBytes] = 0;
  10813. return numBytes;
  10814. #else
  10815. return copyToUTF8 (destBuffer, maxBufferSizeBytes);
  10816. #endif
  10817. }
  10818. #if JUCE_MSVC
  10819. #pragma warning (pop)
  10820. #endif
  10821. String::Concatenator::Concatenator (String& stringToAppendTo)
  10822. : result (stringToAppendTo),
  10823. nextIndex (stringToAppendTo.length())
  10824. {
  10825. }
  10826. String::Concatenator::~Concatenator()
  10827. {
  10828. }
  10829. void String::Concatenator::append (const String& s)
  10830. {
  10831. const int len = s.length();
  10832. if (len > 0)
  10833. {
  10834. result.preallocateStorage (nextIndex + len);
  10835. CharPointerType (result.text + nextIndex).writeAll (s.text);
  10836. nextIndex += len;
  10837. }
  10838. }
  10839. #if JUCE_UNIT_TESTS
  10840. class StringTests : public UnitTest
  10841. {
  10842. public:
  10843. StringTests() : UnitTest ("String class") {}
  10844. template <class CharPointerType>
  10845. struct TestUTFConversion
  10846. {
  10847. static void test (UnitTest& test)
  10848. {
  10849. String s (createRandomWideCharString());
  10850. typename CharPointerType::CharType buffer [300];
  10851. memset (buffer, 0xff, sizeof (buffer));
  10852. CharPointerType (buffer).writeAll (s.toUTF32());
  10853. test.expectEquals (String (CharPointerType (buffer)), s);
  10854. memset (buffer, 0xff, sizeof (buffer));
  10855. CharPointerType (buffer).writeAll (s.toUTF16());
  10856. test.expectEquals (String (CharPointerType (buffer)), s);
  10857. memset (buffer, 0xff, sizeof (buffer));
  10858. CharPointerType (buffer).writeAll (s.toUTF8());
  10859. test.expectEquals (String (CharPointerType (buffer)), s);
  10860. }
  10861. };
  10862. static const String createRandomWideCharString()
  10863. {
  10864. juce_wchar buffer [50];
  10865. zerostruct (buffer);
  10866. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  10867. {
  10868. if (Random::getSystemRandom().nextBool())
  10869. {
  10870. do
  10871. {
  10872. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0x10ffff - 1));
  10873. }
  10874. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  10875. }
  10876. else
  10877. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0xff));
  10878. }
  10879. return buffer;
  10880. }
  10881. void runTest()
  10882. {
  10883. {
  10884. beginTest ("Basics");
  10885. expect (String().length() == 0);
  10886. expect (String() == String::empty);
  10887. String s1, s2 ("abcd");
  10888. expect (s1.isEmpty() && ! s1.isNotEmpty());
  10889. expect (s2.isNotEmpty() && ! s2.isEmpty());
  10890. expect (s2.length() == 4);
  10891. s1 = "abcd";
  10892. expect (s2 == s1 && s1 == s2);
  10893. expect (s1 == "abcd" && s1 == L"abcd");
  10894. expect (String ("abcd") == String (L"abcd"));
  10895. expect (String ("abcdefg", 4) == L"abcd");
  10896. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  10897. expect (String::charToString ('x') == "x");
  10898. expect (String::charToString (0) == String::empty);
  10899. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  10900. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  10901. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  10902. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  10903. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  10904. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  10905. expect (s1.indexOf (String::empty) == 0);
  10906. expect (s1.indexOfIgnoreCase (String::empty) == 0);
  10907. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  10908. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  10909. expect (s1.containsChar ('a'));
  10910. expect (! s1.containsChar ('x'));
  10911. expect (! s1.containsChar (0));
  10912. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  10913. }
  10914. {
  10915. beginTest ("Operations");
  10916. String s ("012345678");
  10917. expect (s.hashCode() != 0);
  10918. expect (s.hashCode64() != 0);
  10919. expect (s.hashCode() != (s + s).hashCode());
  10920. expect (s.hashCode64() != (s + s).hashCode64());
  10921. expect (s.compare (String ("012345678")) == 0);
  10922. expect (s.compare (String ("012345679")) < 0);
  10923. expect (s.compare (String ("012345676")) > 0);
  10924. expect (s.substring (2, 3) == String::charToString (s[2]));
  10925. expect (s.substring (0, 1) == String::charToString (s[0]));
  10926. expect (s.getLastCharacter() == s [s.length() - 1]);
  10927. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  10928. expect (s.substring (0, 3) == L"012");
  10929. expect (s.substring (0, 100) == s);
  10930. expect (s.substring (-1, 100) == s);
  10931. expect (s.substring (3) == "345678");
  10932. expect (s.indexOf (L"45") == 4);
  10933. expect (String ("444445").indexOf ("45") == 4);
  10934. expect (String ("444445").lastIndexOfChar ('4') == 4);
  10935. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  10936. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  10937. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  10938. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("aB") == 6);
  10939. expect (s.indexOfChar (L'4') == 4);
  10940. expect (s + s == "012345678012345678");
  10941. expect (s.startsWith (s));
  10942. expect (s.startsWith (s.substring (0, 4)));
  10943. expect (s.startsWith (s.dropLastCharacters (4)));
  10944. expect (s.endsWith (s.substring (5)));
  10945. expect (s.endsWith (s));
  10946. expect (s.contains (s.substring (3, 6)));
  10947. expect (s.contains (s.substring (3)));
  10948. expect (s.startsWithChar (s[0]));
  10949. expect (s.endsWithChar (s.getLastCharacter()));
  10950. expect (s [s.length()] == 0);
  10951. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  10952. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  10953. String s2 ("123");
  10954. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  10955. s2 += "xyz";
  10956. expect (s2 == "1234567890xyz");
  10957. beginTest ("Numeric conversions");
  10958. expect (String::empty.getIntValue() == 0);
  10959. expect (String::empty.getDoubleValue() == 0.0);
  10960. expect (String::empty.getFloatValue() == 0.0f);
  10961. expect (s.getIntValue() == 12345678);
  10962. expect (s.getLargeIntValue() == (int64) 12345678);
  10963. expect (s.getDoubleValue() == 12345678.0);
  10964. expect (s.getFloatValue() == 12345678.0f);
  10965. expect (String (-1234).getIntValue() == -1234);
  10966. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  10967. expect (String (-1234.56).getDoubleValue() == -1234.56);
  10968. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  10969. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  10970. expect (s.getHexValue32() == 0x12345678);
  10971. expect (s.getHexValue64() == (int64) 0x12345678);
  10972. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10973. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10974. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  10975. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  10976. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  10977. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  10978. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  10979. beginTest ("Subsections");
  10980. String s3;
  10981. s3 = "abcdeFGHIJ";
  10982. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  10983. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  10984. expect (s3.containsIgnoreCase (s3.substring (3)));
  10985. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  10986. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  10987. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  10988. expect (s3.containsAnyOf (L"zzzFs"));
  10989. expect (s3.startsWith ("abcd"));
  10990. expect (s3.startsWithIgnoreCase (L"abCD"));
  10991. expect (s3.startsWith (String::empty));
  10992. expect (s3.startsWithChar ('a'));
  10993. expect (s3.endsWith (String ("HIJ")));
  10994. expect (s3.endsWithIgnoreCase (L"Hij"));
  10995. expect (s3.endsWith (String::empty));
  10996. expect (s3.endsWithChar (L'J'));
  10997. expect (s3.indexOf ("HIJ") == 7);
  10998. expect (s3.indexOf (L"HIJK") == -1);
  10999. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11000. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11001. String s4 (s3);
  11002. s4.append (String ("xyz123"), 3);
  11003. expect (s4 == s3 + "xyz");
  11004. expect (String (1234) < String (1235));
  11005. expect (String (1235) > String (1234));
  11006. expect (String (1234) >= String (1234));
  11007. expect (String (1234) <= String (1234));
  11008. expect (String (1235) >= String (1234));
  11009. expect (String (1234) <= String (1235));
  11010. String s5 ("word word2 word3");
  11011. expect (s5.containsWholeWord (String ("word2")));
  11012. expect (s5.indexOfWholeWord ("word2") == 5);
  11013. expect (s5.containsWholeWord (L"word"));
  11014. expect (s5.containsWholeWord ("word3"));
  11015. expect (s5.containsWholeWord (s5));
  11016. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11017. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11018. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11019. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11020. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11021. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11022. expect (s5.containsNonWhitespaceChars());
  11023. expect (s5.containsOnly ("ordw23 "));
  11024. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11025. expect (s5.matchesWildcard (L"wor*", false));
  11026. expect (s5.matchesWildcard ("wOr*", true));
  11027. expect (s5.matchesWildcard (L"*word3", true));
  11028. expect (s5.matchesWildcard ("*word?", true));
  11029. expect (s5.matchesWildcard (L"Word*3", true));
  11030. expectEquals (s5.fromFirstOccurrenceOf (String::empty, true, false), s5);
  11031. expectEquals (s5.fromFirstOccurrenceOf ("xword2", true, false), s5.substring (100));
  11032. expectEquals (s5.fromFirstOccurrenceOf (L"word2", true, false), s5.substring (5));
  11033. expectEquals (s5.fromFirstOccurrenceOf ("Word2", true, true), s5.substring (5));
  11034. expectEquals (s5.fromFirstOccurrenceOf ("word2", false, false), s5.getLastCharacters (6));
  11035. expectEquals (s5.fromFirstOccurrenceOf (L"Word2", false, true), s5.getLastCharacters (6));
  11036. expectEquals (s5.fromLastOccurrenceOf (String::empty, true, false), s5);
  11037. expectEquals (s5.fromLastOccurrenceOf (L"wordx", true, false), s5);
  11038. expectEquals (s5.fromLastOccurrenceOf ("word", true, false), s5.getLastCharacters (5));
  11039. expectEquals (s5.fromLastOccurrenceOf (L"worD", true, true), s5.getLastCharacters (5));
  11040. expectEquals (s5.fromLastOccurrenceOf ("word", false, false), s5.getLastCharacters (1));
  11041. expectEquals (s5.fromLastOccurrenceOf (L"worD", false, true), s5.getLastCharacters (1));
  11042. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11043. expectEquals (s5.upToFirstOccurrenceOf ("word4", true, false), s5);
  11044. expectEquals (s5.upToFirstOccurrenceOf (L"word2", true, false), s5.substring (0, 10));
  11045. expectEquals (s5.upToFirstOccurrenceOf ("Word2", true, true), s5.substring (0, 10));
  11046. expectEquals (s5.upToFirstOccurrenceOf (L"word2", false, false), s5.substring (0, 5));
  11047. expectEquals (s5.upToFirstOccurrenceOf ("Word2", false, true), s5.substring (0, 5));
  11048. expectEquals (s5.upToLastOccurrenceOf (String::empty, true, false), s5);
  11049. expectEquals (s5.upToLastOccurrenceOf ("zword", true, false), s5);
  11050. expectEquals (s5.upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  11051. expectEquals (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  11052. expectEquals (s5.upToLastOccurrenceOf ("Word", true, true), s5.dropLastCharacters (1));
  11053. expectEquals (s5.upToLastOccurrenceOf ("word", false, false), s5.dropLastCharacters (5));
  11054. expectEquals (s5.upToLastOccurrenceOf ("Word", false, true), s5.dropLastCharacters (5));
  11055. expectEquals (s5.replace ("word", L"xyz", false), String ("xyz xyz2 xyz3"));
  11056. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11057. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11058. expect (s5.replace ("Word", "", true) == " 2 3");
  11059. expectEquals (s5.replace ("Word2", L"xyz", true), String ("word xyz word3"));
  11060. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11061. expectEquals (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w'), s5);
  11062. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11063. expectEquals (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo"), s5);
  11064. expectEquals (s5.retainCharacters ("1wordxya"), String ("wordwordword"));
  11065. expect (s5.retainCharacters (String::empty).isEmpty());
  11066. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11067. expectEquals (s5.removeCharacters (String::empty), s5);
  11068. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11069. expect (String ("word").initialSectionContainingOnly ("word") == L"word");
  11070. expectEquals (s5.initialSectionNotContaining (String ("xyz ")), String ("word"));
  11071. expectEquals (s5.initialSectionNotContaining (String (";[:'/")), s5);
  11072. expect (! s5.isQuotedString());
  11073. expect (s5.quoted().isQuotedString());
  11074. expect (! s5.quoted().unquoted().isQuotedString());
  11075. expect (! String ("x'").isQuotedString());
  11076. expect (String ("'x").isQuotedString());
  11077. String s6 (" \t xyz \t\r\n");
  11078. expectEquals (s6.trim(), String ("xyz"));
  11079. expect (s6.trim().trim() == "xyz");
  11080. expectEquals (s5.trim(), s5);
  11081. expectEquals (s6.trimStart().trimEnd(), s6.trim());
  11082. expectEquals (s6.trimStart().trimEnd(), s6.trimEnd().trimStart());
  11083. expectEquals (s6.trimStart().trimStart().trimEnd().trimEnd(), s6.trimEnd().trimStart());
  11084. expect (s6.trimStart() != s6.trimEnd());
  11085. expectEquals (("\t\r\n " + s6 + "\t\n \r").trim(), s6.trim());
  11086. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11087. }
  11088. {
  11089. beginTest ("UTF conversions");
  11090. TestUTFConversion <CharPointer_UTF32>::test (*this);
  11091. TestUTFConversion <CharPointer_UTF8>::test (*this);
  11092. TestUTFConversion <CharPointer_UTF16>::test (*this);
  11093. }
  11094. {
  11095. beginTest ("StringArray");
  11096. StringArray s;
  11097. for (int i = 5; --i >= 0;)
  11098. s.add (String (i));
  11099. expectEquals (s.joinIntoString ("-"), String ("4-3-2-1-0"));
  11100. s.remove (2);
  11101. expectEquals (s.joinIntoString ("--"), String ("4--3--1--0"));
  11102. expectEquals (s.joinIntoString (String::empty), String ("4310"));
  11103. s.clear();
  11104. expectEquals (s.joinIntoString ("x"), String::empty);
  11105. }
  11106. }
  11107. };
  11108. static StringTests stringUnitTests;
  11109. #endif
  11110. END_JUCE_NAMESPACE
  11111. /*** End of inlined file: juce_String.cpp ***/
  11112. /*** Start of inlined file: juce_StringArray.cpp ***/
  11113. BEGIN_JUCE_NAMESPACE
  11114. StringArray::StringArray() throw()
  11115. {
  11116. }
  11117. StringArray::StringArray (const StringArray& other)
  11118. : strings (other.strings)
  11119. {
  11120. }
  11121. StringArray::StringArray (const String& firstValue)
  11122. {
  11123. strings.add (firstValue);
  11124. }
  11125. namespace StringArrayHelpers
  11126. {
  11127. template <typename CharType>
  11128. void addArray (Array<String>& dest, const CharType* const* strings)
  11129. {
  11130. if (strings != 0)
  11131. while (*strings != 0)
  11132. dest.add (*strings++);
  11133. }
  11134. template <typename CharType>
  11135. void addArray (Array<String>& dest, const CharType* const* const strings, const int numberOfStrings)
  11136. {
  11137. for (int i = 0; i < numberOfStrings; ++i)
  11138. dest.add (strings [i]);
  11139. }
  11140. }
  11141. StringArray::StringArray (const char* const* const initialStrings)
  11142. {
  11143. StringArrayHelpers::addArray (strings, initialStrings);
  11144. }
  11145. StringArray::StringArray (const char* const* const initialStrings, const int numberOfStrings)
  11146. {
  11147. StringArrayHelpers::addArray (strings, initialStrings, numberOfStrings);
  11148. }
  11149. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11150. {
  11151. StringArrayHelpers::addArray (strings, initialStrings);
  11152. }
  11153. StringArray::StringArray (const juce_wchar* const* const initialStrings, const int numberOfStrings)
  11154. {
  11155. StringArrayHelpers::addArray (strings, initialStrings, numberOfStrings);
  11156. }
  11157. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  11158. StringArray::StringArray (const wchar_t* const* const initialStrings)
  11159. {
  11160. StringArrayHelpers::addArray (strings, initialStrings);
  11161. }
  11162. StringArray::StringArray (const wchar_t* const* const initialStrings, const int numberOfStrings)
  11163. {
  11164. StringArrayHelpers::addArray (strings, initialStrings, numberOfStrings);
  11165. }
  11166. #endif
  11167. StringArray& StringArray::operator= (const StringArray& other)
  11168. {
  11169. strings = other.strings;
  11170. return *this;
  11171. }
  11172. StringArray::~StringArray()
  11173. {
  11174. }
  11175. bool StringArray::operator== (const StringArray& other) const throw()
  11176. {
  11177. if (other.size() != size())
  11178. return false;
  11179. for (int i = size(); --i >= 0;)
  11180. if (other.strings.getReference(i) != strings.getReference(i))
  11181. return false;
  11182. return true;
  11183. }
  11184. bool StringArray::operator!= (const StringArray& other) const throw()
  11185. {
  11186. return ! operator== (other);
  11187. }
  11188. void StringArray::clear()
  11189. {
  11190. strings.clear();
  11191. }
  11192. const String& StringArray::operator[] (const int index) const throw()
  11193. {
  11194. if (isPositiveAndBelow (index, strings.size()))
  11195. return strings.getReference (index);
  11196. return String::empty;
  11197. }
  11198. String& StringArray::getReference (const int index) throw()
  11199. {
  11200. jassert (isPositiveAndBelow (index, strings.size()));
  11201. return strings.getReference (index);
  11202. }
  11203. void StringArray::add (const String& newString)
  11204. {
  11205. strings.add (newString);
  11206. }
  11207. void StringArray::insert (const int index, const String& newString)
  11208. {
  11209. strings.insert (index, newString);
  11210. }
  11211. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11212. {
  11213. if (! contains (newString, ignoreCase))
  11214. add (newString);
  11215. }
  11216. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11217. {
  11218. if (startIndex < 0)
  11219. {
  11220. jassertfalse;
  11221. startIndex = 0;
  11222. }
  11223. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11224. numElementsToAdd = otherArray.size() - startIndex;
  11225. while (--numElementsToAdd >= 0)
  11226. strings.add (otherArray.strings.getReference (startIndex++));
  11227. }
  11228. void StringArray::set (const int index, const String& newString)
  11229. {
  11230. strings.set (index, newString);
  11231. }
  11232. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11233. {
  11234. if (ignoreCase)
  11235. {
  11236. for (int i = size(); --i >= 0;)
  11237. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11238. return true;
  11239. }
  11240. else
  11241. {
  11242. for (int i = size(); --i >= 0;)
  11243. if (stringToLookFor == strings.getReference(i))
  11244. return true;
  11245. }
  11246. return false;
  11247. }
  11248. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11249. {
  11250. if (i < 0)
  11251. i = 0;
  11252. const int numElements = size();
  11253. if (ignoreCase)
  11254. {
  11255. while (i < numElements)
  11256. {
  11257. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11258. return i;
  11259. ++i;
  11260. }
  11261. }
  11262. else
  11263. {
  11264. while (i < numElements)
  11265. {
  11266. if (stringToLookFor == strings.getReference (i))
  11267. return i;
  11268. ++i;
  11269. }
  11270. }
  11271. return -1;
  11272. }
  11273. void StringArray::remove (const int index)
  11274. {
  11275. strings.remove (index);
  11276. }
  11277. void StringArray::removeString (const String& stringToRemove,
  11278. const bool ignoreCase)
  11279. {
  11280. if (ignoreCase)
  11281. {
  11282. for (int i = size(); --i >= 0;)
  11283. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11284. strings.remove (i);
  11285. }
  11286. else
  11287. {
  11288. for (int i = size(); --i >= 0;)
  11289. if (stringToRemove == strings.getReference (i))
  11290. strings.remove (i);
  11291. }
  11292. }
  11293. void StringArray::removeRange (int startIndex, int numberToRemove)
  11294. {
  11295. strings.removeRange (startIndex, numberToRemove);
  11296. }
  11297. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11298. {
  11299. if (removeWhitespaceStrings)
  11300. {
  11301. for (int i = size(); --i >= 0;)
  11302. if (! strings.getReference(i).containsNonWhitespaceChars())
  11303. strings.remove (i);
  11304. }
  11305. else
  11306. {
  11307. for (int i = size(); --i >= 0;)
  11308. if (strings.getReference(i).isEmpty())
  11309. strings.remove (i);
  11310. }
  11311. }
  11312. void StringArray::trim()
  11313. {
  11314. for (int i = size(); --i >= 0;)
  11315. {
  11316. String& s = strings.getReference(i);
  11317. s = s.trim();
  11318. }
  11319. }
  11320. class InternalStringArrayComparator_CaseSensitive
  11321. {
  11322. public:
  11323. static int compareElements (String& first, String& second) { return first.compare (second); }
  11324. };
  11325. class InternalStringArrayComparator_CaseInsensitive
  11326. {
  11327. public:
  11328. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11329. };
  11330. void StringArray::sort (const bool ignoreCase)
  11331. {
  11332. if (ignoreCase)
  11333. {
  11334. InternalStringArrayComparator_CaseInsensitive comp;
  11335. strings.sort (comp);
  11336. }
  11337. else
  11338. {
  11339. InternalStringArrayComparator_CaseSensitive comp;
  11340. strings.sort (comp);
  11341. }
  11342. }
  11343. void StringArray::move (const int currentIndex, int newIndex) throw()
  11344. {
  11345. strings.move (currentIndex, newIndex);
  11346. }
  11347. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11348. {
  11349. const int last = (numberToJoin < 0) ? size()
  11350. : jmin (size(), start + numberToJoin);
  11351. if (start < 0)
  11352. start = 0;
  11353. if (start >= last)
  11354. return String::empty;
  11355. if (start == last - 1)
  11356. return strings.getReference (start);
  11357. const int separatorLen = separator.length();
  11358. int charsNeeded = separatorLen * (last - start - 1);
  11359. for (int i = start; i < last; ++i)
  11360. charsNeeded += strings.getReference(i).length();
  11361. String result;
  11362. result.preallocateStorage (charsNeeded);
  11363. String::CharPointerType dest (result.getCharPointer());
  11364. while (start < last)
  11365. {
  11366. const String& s = strings.getReference (start);
  11367. if (! s.isEmpty())
  11368. dest.writeAll (s.getCharPointer());
  11369. if (++start < last && separatorLen > 0)
  11370. dest.writeAll (separator.getCharPointer());
  11371. }
  11372. dest.writeNull();
  11373. return result;
  11374. }
  11375. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11376. {
  11377. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11378. }
  11379. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11380. {
  11381. int num = 0;
  11382. if (text.isNotEmpty())
  11383. {
  11384. bool insideQuotes = false;
  11385. juce_wchar currentQuoteChar = 0;
  11386. String::CharPointerType t (text.getCharPointer());
  11387. String::CharPointerType tokenStart (t);
  11388. int numChars = 0;
  11389. for (;;)
  11390. {
  11391. const juce_wchar c = t.getAndAdvance();
  11392. ++numChars;
  11393. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11394. if (! isBreak)
  11395. {
  11396. if (quoteCharacters.containsChar (c))
  11397. {
  11398. if (insideQuotes)
  11399. {
  11400. // only break out of quotes-mode if we find a matching quote to the
  11401. // one that we opened with..
  11402. if (currentQuoteChar == c)
  11403. insideQuotes = false;
  11404. }
  11405. else
  11406. {
  11407. insideQuotes = true;
  11408. currentQuoteChar = c;
  11409. }
  11410. }
  11411. }
  11412. else
  11413. {
  11414. add (String (tokenStart, numChars - 1));
  11415. ++num;
  11416. tokenStart = t;
  11417. numChars = 0;
  11418. }
  11419. if (c == 0)
  11420. break;
  11421. }
  11422. }
  11423. return num;
  11424. }
  11425. int StringArray::addLines (const String& sourceText)
  11426. {
  11427. int numLines = 0;
  11428. String::CharPointerType text (sourceText.getCharPointer());
  11429. bool finished = text.isEmpty();
  11430. while (! finished)
  11431. {
  11432. String::CharPointerType startOfLine (text);
  11433. int numChars = 0;
  11434. for (;;)
  11435. {
  11436. const juce_wchar c = text.getAndAdvance();
  11437. if (c == 0)
  11438. {
  11439. finished = true;
  11440. break;
  11441. }
  11442. if (c == '\n')
  11443. break;
  11444. if (c == '\r')
  11445. {
  11446. if (*text == '\n')
  11447. ++text;
  11448. break;
  11449. }
  11450. ++numChars;
  11451. }
  11452. add (String (startOfLine, numChars));
  11453. ++numLines;
  11454. }
  11455. return numLines;
  11456. }
  11457. void StringArray::removeDuplicates (const bool ignoreCase)
  11458. {
  11459. for (int i = 0; i < size() - 1; ++i)
  11460. {
  11461. const String s (strings.getReference(i));
  11462. int nextIndex = i + 1;
  11463. for (;;)
  11464. {
  11465. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11466. if (nextIndex < 0)
  11467. break;
  11468. strings.remove (nextIndex);
  11469. }
  11470. }
  11471. }
  11472. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11473. const bool appendNumberToFirstInstance,
  11474. CharPointer_UTF8 preNumberString,
  11475. CharPointer_UTF8 postNumberString)
  11476. {
  11477. CharPointer_UTF8 defaultPre (" ("), defaultPost (")");
  11478. if (preNumberString.getAddress() == 0)
  11479. preNumberString = defaultPre;
  11480. if (postNumberString.getAddress() == 0)
  11481. postNumberString = defaultPost;
  11482. for (int i = 0; i < size() - 1; ++i)
  11483. {
  11484. String& s = strings.getReference(i);
  11485. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11486. if (nextIndex >= 0)
  11487. {
  11488. const String original (s);
  11489. int number = 0;
  11490. if (appendNumberToFirstInstance)
  11491. s = original + String (preNumberString) + String (++number) + String (postNumberString);
  11492. else
  11493. ++number;
  11494. while (nextIndex >= 0)
  11495. {
  11496. set (nextIndex, (*this)[nextIndex] + String (preNumberString) + String (++number) + String (postNumberString));
  11497. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11498. }
  11499. }
  11500. }
  11501. }
  11502. void StringArray::minimiseStorageOverheads()
  11503. {
  11504. strings.minimiseStorageOverheads();
  11505. }
  11506. END_JUCE_NAMESPACE
  11507. /*** End of inlined file: juce_StringArray.cpp ***/
  11508. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11509. BEGIN_JUCE_NAMESPACE
  11510. StringPairArray::StringPairArray (const bool ignoreCase_)
  11511. : ignoreCase (ignoreCase_)
  11512. {
  11513. }
  11514. StringPairArray::StringPairArray (const StringPairArray& other)
  11515. : keys (other.keys),
  11516. values (other.values),
  11517. ignoreCase (other.ignoreCase)
  11518. {
  11519. }
  11520. StringPairArray::~StringPairArray()
  11521. {
  11522. }
  11523. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11524. {
  11525. keys = other.keys;
  11526. values = other.values;
  11527. return *this;
  11528. }
  11529. bool StringPairArray::operator== (const StringPairArray& other) const
  11530. {
  11531. for (int i = keys.size(); --i >= 0;)
  11532. if (other [keys[i]] != values[i])
  11533. return false;
  11534. return true;
  11535. }
  11536. bool StringPairArray::operator!= (const StringPairArray& other) const
  11537. {
  11538. return ! operator== (other);
  11539. }
  11540. const String& StringPairArray::operator[] (const String& key) const
  11541. {
  11542. return values [keys.indexOf (key, ignoreCase)];
  11543. }
  11544. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11545. {
  11546. const int i = keys.indexOf (key, ignoreCase);
  11547. if (i >= 0)
  11548. return values[i];
  11549. return defaultReturnValue;
  11550. }
  11551. void StringPairArray::set (const String& key, const String& value)
  11552. {
  11553. const int i = keys.indexOf (key, ignoreCase);
  11554. if (i >= 0)
  11555. {
  11556. values.set (i, value);
  11557. }
  11558. else
  11559. {
  11560. keys.add (key);
  11561. values.add (value);
  11562. }
  11563. }
  11564. void StringPairArray::addArray (const StringPairArray& other)
  11565. {
  11566. for (int i = 0; i < other.size(); ++i)
  11567. set (other.keys[i], other.values[i]);
  11568. }
  11569. void StringPairArray::clear()
  11570. {
  11571. keys.clear();
  11572. values.clear();
  11573. }
  11574. void StringPairArray::remove (const String& key)
  11575. {
  11576. remove (keys.indexOf (key, ignoreCase));
  11577. }
  11578. void StringPairArray::remove (const int index)
  11579. {
  11580. keys.remove (index);
  11581. values.remove (index);
  11582. }
  11583. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11584. {
  11585. ignoreCase = shouldIgnoreCase;
  11586. }
  11587. const String StringPairArray::getDescription() const
  11588. {
  11589. String s;
  11590. for (int i = 0; i < keys.size(); ++i)
  11591. {
  11592. s << keys[i] << " = " << values[i];
  11593. if (i < keys.size())
  11594. s << ", ";
  11595. }
  11596. return s;
  11597. }
  11598. void StringPairArray::minimiseStorageOverheads()
  11599. {
  11600. keys.minimiseStorageOverheads();
  11601. values.minimiseStorageOverheads();
  11602. }
  11603. END_JUCE_NAMESPACE
  11604. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11605. /*** Start of inlined file: juce_StringPool.cpp ***/
  11606. BEGIN_JUCE_NAMESPACE
  11607. StringPool::StringPool() throw() {}
  11608. StringPool::~StringPool() {}
  11609. namespace StringPoolHelpers
  11610. {
  11611. template <class StringType>
  11612. const String::CharPointerType getPooledStringFromArray (Array<String>& strings, StringType newString)
  11613. {
  11614. int start = 0;
  11615. int end = strings.size();
  11616. for (;;)
  11617. {
  11618. if (start >= end)
  11619. {
  11620. jassert (start <= end);
  11621. strings.insert (start, newString);
  11622. return strings.getReference (start).getCharPointer();
  11623. }
  11624. else
  11625. {
  11626. const String& startString = strings.getReference (start);
  11627. if (startString == newString)
  11628. return startString.getCharPointer();
  11629. const int halfway = (start + end) >> 1;
  11630. if (halfway == start)
  11631. {
  11632. if (startString.compare (newString) < 0)
  11633. ++start;
  11634. strings.insert (start, newString);
  11635. return strings.getReference (start).getCharPointer();
  11636. }
  11637. const int comp = strings.getReference (halfway).compare (newString);
  11638. if (comp == 0)
  11639. return strings.getReference (halfway).getCharPointer();
  11640. else if (comp < 0)
  11641. start = halfway;
  11642. else
  11643. end = halfway;
  11644. }
  11645. }
  11646. }
  11647. }
  11648. const String::CharPointerType StringPool::getPooledString (const String& s)
  11649. {
  11650. if (s.isEmpty())
  11651. return String::empty.getCharPointer();
  11652. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11653. }
  11654. const String::CharPointerType StringPool::getPooledString (const char* const s)
  11655. {
  11656. if (s == 0 || *s == 0)
  11657. return String::empty.getCharPointer();
  11658. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11659. }
  11660. const String::CharPointerType StringPool::getPooledString (const juce_wchar* const s)
  11661. {
  11662. if (s == 0 || *s == 0)
  11663. return String::empty.getCharPointer();
  11664. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11665. }
  11666. int StringPool::size() const throw()
  11667. {
  11668. return strings.size();
  11669. }
  11670. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11671. {
  11672. return strings [index].getCharPointer();
  11673. }
  11674. END_JUCE_NAMESPACE
  11675. /*** End of inlined file: juce_StringPool.cpp ***/
  11676. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11677. BEGIN_JUCE_NAMESPACE
  11678. XmlDocument::XmlDocument (const String& documentText)
  11679. : originalText (documentText),
  11680. input (0),
  11681. ignoreEmptyTextElements (true)
  11682. {
  11683. }
  11684. XmlDocument::XmlDocument (const File& file)
  11685. : input (0),
  11686. ignoreEmptyTextElements (true),
  11687. inputSource (new FileInputSource (file))
  11688. {
  11689. }
  11690. XmlDocument::~XmlDocument()
  11691. {
  11692. }
  11693. XmlElement* XmlDocument::parse (const File& file)
  11694. {
  11695. XmlDocument doc (file);
  11696. return doc.getDocumentElement();
  11697. }
  11698. XmlElement* XmlDocument::parse (const String& xmlData)
  11699. {
  11700. XmlDocument doc (xmlData);
  11701. return doc.getDocumentElement();
  11702. }
  11703. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11704. {
  11705. inputSource = newSource;
  11706. }
  11707. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11708. {
  11709. ignoreEmptyTextElements = shouldBeIgnored;
  11710. }
  11711. namespace XmlIdentifierChars
  11712. {
  11713. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11714. {
  11715. return CharacterFunctions::isLetterOrDigit (c)
  11716. || c == '_' || c == '-' || c == ':' || c == '.';
  11717. }
  11718. bool isIdentifierChar (const juce_wchar c) throw()
  11719. {
  11720. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11721. return ((int) c < (int) numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11722. : isIdentifierCharSlow (c);
  11723. }
  11724. /*static void generateIdentifierCharConstants()
  11725. {
  11726. uint32 n[8];
  11727. zerostruct (n);
  11728. for (int i = 0; i < 256; ++i)
  11729. if (isIdentifierCharSlow (i))
  11730. n[i >> 5] |= (1 << (i & 31));
  11731. String s;
  11732. for (int i = 0; i < 8; ++i)
  11733. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11734. DBG (s);
  11735. }*/
  11736. }
  11737. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11738. {
  11739. String textToParse (originalText);
  11740. if (textToParse.isEmpty() && inputSource != 0)
  11741. {
  11742. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11743. if (in != 0)
  11744. {
  11745. MemoryOutputStream data;
  11746. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11747. textToParse = data.toString();
  11748. if (! onlyReadOuterDocumentElement)
  11749. originalText = textToParse;
  11750. }
  11751. }
  11752. input = textToParse.getCharPointer();
  11753. lastError = String::empty;
  11754. errorOccurred = false;
  11755. outOfData = false;
  11756. needToLoadDTD = true;
  11757. if (textToParse.isEmpty())
  11758. {
  11759. lastError = "not enough input";
  11760. }
  11761. else
  11762. {
  11763. skipHeader();
  11764. if (input.getAddress() != 0)
  11765. {
  11766. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11767. if (! errorOccurred)
  11768. return result.release();
  11769. }
  11770. else
  11771. {
  11772. lastError = "incorrect xml header";
  11773. }
  11774. }
  11775. return 0;
  11776. }
  11777. const String& XmlDocument::getLastParseError() const throw()
  11778. {
  11779. return lastError;
  11780. }
  11781. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11782. {
  11783. lastError = desc;
  11784. errorOccurred = ! carryOn;
  11785. }
  11786. const String XmlDocument::getFileContents (const String& filename) const
  11787. {
  11788. if (inputSource != 0)
  11789. {
  11790. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11791. if (in != 0)
  11792. return in->readEntireStreamAsString();
  11793. }
  11794. return String::empty;
  11795. }
  11796. juce_wchar XmlDocument::readNextChar() throw()
  11797. {
  11798. if (*input != 0)
  11799. return *input++;
  11800. outOfData = true;
  11801. return 0;
  11802. }
  11803. int XmlDocument::findNextTokenLength() throw()
  11804. {
  11805. int len = 0;
  11806. juce_wchar c = *input;
  11807. while (XmlIdentifierChars::isIdentifierChar (c))
  11808. c = input [++len];
  11809. return len;
  11810. }
  11811. void XmlDocument::skipHeader()
  11812. {
  11813. const int headerStart = input.indexOf (CharPointer_UTF8 ("<?xml"));
  11814. if (headerStart >= 0)
  11815. {
  11816. const int headerEnd = (input + headerStart).indexOf (CharPointer_UTF8 ("?>"));
  11817. if (headerEnd < 0)
  11818. return;
  11819. #if JUCE_DEBUG
  11820. const String header ((input + headerStart).getAddress(), headerEnd - headerStart);
  11821. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11822. .fromFirstOccurrenceOf ("=", false, false)
  11823. .fromFirstOccurrenceOf ("\"", false, false)
  11824. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11825. /* If you load an XML document with a non-UTF encoding type, it may have been
  11826. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11827. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11828. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11829. read, use your own code to convert them to a unicode String, and pass that to the
  11830. XML parser.
  11831. */
  11832. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  11833. #endif
  11834. input += headerEnd + 2;
  11835. }
  11836. skipNextWhiteSpace();
  11837. const int docTypeIndex = input.indexOf (CharPointer_UTF8 ("<!DOCTYPE"));
  11838. if (docTypeIndex < 0)
  11839. return;
  11840. input += docTypeIndex + 9;
  11841. const String::CharPointerType docType (input);
  11842. int n = 1;
  11843. while (n > 0)
  11844. {
  11845. const juce_wchar c = readNextChar();
  11846. if (outOfData)
  11847. return;
  11848. if (c == '<')
  11849. ++n;
  11850. else if (c == '>')
  11851. --n;
  11852. }
  11853. dtdText = String (docType.getAddress(), (int) (input.getAddress() - (docType.getAddress() + 1))).trim();
  11854. }
  11855. void XmlDocument::skipNextWhiteSpace()
  11856. {
  11857. for (;;)
  11858. {
  11859. juce_wchar c = *input;
  11860. while (CharacterFunctions::isWhitespace (c))
  11861. c = *++input;
  11862. if (c == 0)
  11863. {
  11864. outOfData = true;
  11865. break;
  11866. }
  11867. else if (c == '<')
  11868. {
  11869. if (input[1] == '!'
  11870. && input[2] == '-'
  11871. && input[3] == '-')
  11872. {
  11873. const int closeComment = input.indexOf (CharPointer_UTF8 ("-->"));
  11874. if (closeComment < 0)
  11875. {
  11876. outOfData = true;
  11877. break;
  11878. }
  11879. input += closeComment + 3;
  11880. continue;
  11881. }
  11882. else if (input[1] == '?')
  11883. {
  11884. const int closeBracket = input.indexOf (CharPointer_UTF8 ("?>"));
  11885. if (closeBracket < 0)
  11886. {
  11887. outOfData = true;
  11888. break;
  11889. }
  11890. input += closeBracket + 2;
  11891. continue;
  11892. }
  11893. }
  11894. break;
  11895. }
  11896. }
  11897. void XmlDocument::readQuotedString (String& result)
  11898. {
  11899. const juce_wchar quote = readNextChar();
  11900. while (! outOfData)
  11901. {
  11902. const juce_wchar c = readNextChar();
  11903. if (c == quote)
  11904. break;
  11905. if (c == '&')
  11906. {
  11907. --input;
  11908. readEntity (result);
  11909. }
  11910. else
  11911. {
  11912. --input;
  11913. const String::CharPointerType start (input);
  11914. for (;;)
  11915. {
  11916. const juce_wchar character = *input;
  11917. if (character == quote)
  11918. {
  11919. result.appendCharPointer (start, (int) (input.getAddress() - start.getAddress()));
  11920. ++input;
  11921. return;
  11922. }
  11923. else if (character == '&')
  11924. {
  11925. result.appendCharPointer (start, (int) (input.getAddress() - start.getAddress()));
  11926. break;
  11927. }
  11928. else if (character == 0)
  11929. {
  11930. outOfData = true;
  11931. setLastError ("unmatched quotes", false);
  11932. break;
  11933. }
  11934. ++input;
  11935. }
  11936. }
  11937. }
  11938. }
  11939. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  11940. {
  11941. XmlElement* node = 0;
  11942. skipNextWhiteSpace();
  11943. if (outOfData)
  11944. return 0;
  11945. const int openBracket = input.indexOf ((juce_wchar) '<');
  11946. if (openBracket >= 0)
  11947. {
  11948. input += openBracket + 1;
  11949. int tagLen = findNextTokenLength();
  11950. if (tagLen == 0)
  11951. {
  11952. // no tag name - but allow for a gap after the '<' before giving an error
  11953. skipNextWhiteSpace();
  11954. tagLen = findNextTokenLength();
  11955. if (tagLen == 0)
  11956. {
  11957. setLastError ("tag name missing", false);
  11958. return node;
  11959. }
  11960. }
  11961. node = new XmlElement (String (input.getAddress(), tagLen));
  11962. input += tagLen;
  11963. LinkedListPointer<XmlElement::XmlAttributeNode>::Appender attributeAppender (node->attributes);
  11964. // look for attributes
  11965. for (;;)
  11966. {
  11967. skipNextWhiteSpace();
  11968. const juce_wchar c = *input;
  11969. // empty tag..
  11970. if (c == '/' && input[1] == '>')
  11971. {
  11972. input += 2;
  11973. break;
  11974. }
  11975. // parse the guts of the element..
  11976. if (c == '>')
  11977. {
  11978. ++input;
  11979. if (alsoParseSubElements)
  11980. readChildElements (node);
  11981. break;
  11982. }
  11983. // get an attribute..
  11984. if (XmlIdentifierChars::isIdentifierChar (c))
  11985. {
  11986. const int attNameLen = findNextTokenLength();
  11987. if (attNameLen > 0)
  11988. {
  11989. const String::CharPointerType attNameStart (input);
  11990. input += attNameLen;
  11991. skipNextWhiteSpace();
  11992. if (readNextChar() == '=')
  11993. {
  11994. skipNextWhiteSpace();
  11995. const juce_wchar nextChar = *input;
  11996. if (nextChar == '"' || nextChar == '\'')
  11997. {
  11998. XmlElement::XmlAttributeNode* const newAtt
  11999. = new XmlElement::XmlAttributeNode (String (attNameStart.getAddress(), attNameLen),
  12000. String::empty);
  12001. readQuotedString (newAtt->value);
  12002. attributeAppender.append (newAtt);
  12003. continue;
  12004. }
  12005. }
  12006. }
  12007. }
  12008. else
  12009. {
  12010. if (! outOfData)
  12011. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12012. }
  12013. break;
  12014. }
  12015. }
  12016. return node;
  12017. }
  12018. void XmlDocument::readChildElements (XmlElement* parent)
  12019. {
  12020. LinkedListPointer<XmlElement>::Appender childAppender (parent->firstChildElement);
  12021. for (;;)
  12022. {
  12023. const String::CharPointerType preWhitespaceInput (input);
  12024. skipNextWhiteSpace();
  12025. if (outOfData)
  12026. {
  12027. setLastError ("unmatched tags", false);
  12028. break;
  12029. }
  12030. if (*input == '<')
  12031. {
  12032. if (input[1] == '/')
  12033. {
  12034. // our close tag..
  12035. const int closeTag = input.indexOf ((juce_wchar) '>');
  12036. if (closeTag >= 0)
  12037. input += closeTag + 1;
  12038. break;
  12039. }
  12040. else if (input[1] == '!'
  12041. && input[2] == '['
  12042. && input[3] == 'C'
  12043. && input[4] == 'D'
  12044. && input[5] == 'A'
  12045. && input[6] == 'T'
  12046. && input[7] == 'A'
  12047. && input[8] == '[')
  12048. {
  12049. input += 9;
  12050. const String::CharPointerType inputStart (input);
  12051. int len = 0;
  12052. for (;;)
  12053. {
  12054. if (*input == 0)
  12055. {
  12056. setLastError ("unterminated CDATA section", false);
  12057. outOfData = true;
  12058. break;
  12059. }
  12060. else if (input[0] == ']'
  12061. && input[1] == ']'
  12062. && input[2] == '>')
  12063. {
  12064. input += 3;
  12065. break;
  12066. }
  12067. ++input;
  12068. ++len;
  12069. }
  12070. childAppender.append (XmlElement::createTextElement (String (inputStart.getAddress(), len)));
  12071. }
  12072. else
  12073. {
  12074. // this is some other element, so parse and add it..
  12075. XmlElement* const n = readNextElement (true);
  12076. if (n != 0)
  12077. childAppender.append (n);
  12078. else
  12079. return;
  12080. }
  12081. }
  12082. else // must be a character block
  12083. {
  12084. input = preWhitespaceInput; // roll back to include the leading whitespace
  12085. String textElementContent;
  12086. for (;;)
  12087. {
  12088. const juce_wchar c = *input;
  12089. if (c == '<')
  12090. break;
  12091. if (c == 0)
  12092. {
  12093. setLastError ("unmatched tags", false);
  12094. outOfData = true;
  12095. return;
  12096. }
  12097. if (c == '&')
  12098. {
  12099. String entity;
  12100. readEntity (entity);
  12101. if (entity.startsWithChar ('<') && entity [1] != 0)
  12102. {
  12103. const String::CharPointerType oldInput (input);
  12104. const bool oldOutOfData = outOfData;
  12105. input = entity.getCharPointer();
  12106. outOfData = false;
  12107. for (;;)
  12108. {
  12109. XmlElement* const n = readNextElement (true);
  12110. if (n == 0)
  12111. break;
  12112. childAppender.append (n);
  12113. }
  12114. input = oldInput;
  12115. outOfData = oldOutOfData;
  12116. }
  12117. else
  12118. {
  12119. textElementContent += entity;
  12120. }
  12121. }
  12122. else
  12123. {
  12124. const String::CharPointerType start (input);
  12125. int len = 0;
  12126. for (;;)
  12127. {
  12128. const juce_wchar nextChar = *input;
  12129. if (nextChar == '<' || nextChar == '&')
  12130. {
  12131. break;
  12132. }
  12133. else if (nextChar == 0)
  12134. {
  12135. setLastError ("unmatched tags", false);
  12136. outOfData = true;
  12137. return;
  12138. }
  12139. ++input;
  12140. ++len;
  12141. }
  12142. textElementContent.appendCharPointer (start, len);
  12143. }
  12144. }
  12145. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12146. {
  12147. childAppender.append (XmlElement::createTextElement (textElementContent));
  12148. }
  12149. }
  12150. }
  12151. }
  12152. void XmlDocument::readEntity (String& result)
  12153. {
  12154. // skip over the ampersand
  12155. ++input;
  12156. if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("amp;"), 4) == 0)
  12157. {
  12158. input += 4;
  12159. result += '&';
  12160. }
  12161. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("quot;"), 5) == 0)
  12162. {
  12163. input += 5;
  12164. result += '"';
  12165. }
  12166. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("apos;"), 5) == 0)
  12167. {
  12168. input += 5;
  12169. result += '\'';
  12170. }
  12171. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("lt;"), 3) == 0)
  12172. {
  12173. input += 3;
  12174. result += '<';
  12175. }
  12176. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("gt;"), 3) == 0)
  12177. {
  12178. input += 3;
  12179. result += '>';
  12180. }
  12181. else if (*input == '#')
  12182. {
  12183. int charCode = 0;
  12184. ++input;
  12185. if (*input == 'x' || *input == 'X')
  12186. {
  12187. ++input;
  12188. int numChars = 0;
  12189. while (input[0] != ';')
  12190. {
  12191. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12192. if (hexValue < 0 || ++numChars > 8)
  12193. {
  12194. setLastError ("illegal escape sequence", true);
  12195. break;
  12196. }
  12197. charCode = (charCode << 4) | hexValue;
  12198. ++input;
  12199. }
  12200. ++input;
  12201. }
  12202. else if (input[0] >= '0' && input[0] <= '9')
  12203. {
  12204. int numChars = 0;
  12205. while (input[0] != ';')
  12206. {
  12207. if (++numChars > 12)
  12208. {
  12209. setLastError ("illegal escape sequence", true);
  12210. break;
  12211. }
  12212. charCode = charCode * 10 + (input[0] - '0');
  12213. ++input;
  12214. }
  12215. ++input;
  12216. }
  12217. else
  12218. {
  12219. setLastError ("illegal escape sequence", true);
  12220. result += '&';
  12221. return;
  12222. }
  12223. result << (juce_wchar) charCode;
  12224. }
  12225. else
  12226. {
  12227. const String::CharPointerType entityNameStart (input);
  12228. const int closingSemiColon = input.indexOf ((juce_wchar) ';');
  12229. if (closingSemiColon < 0)
  12230. {
  12231. outOfData = true;
  12232. result += '&';
  12233. }
  12234. else
  12235. {
  12236. input += closingSemiColon + 1;
  12237. result += expandExternalEntity (String (entityNameStart.getAddress(), closingSemiColon));
  12238. }
  12239. }
  12240. }
  12241. const String XmlDocument::expandEntity (const String& ent)
  12242. {
  12243. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12244. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12245. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12246. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12247. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12248. if (ent[0] == '#')
  12249. {
  12250. if (ent[1] == 'x' || ent[1] == 'X')
  12251. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12252. if (ent[1] >= '0' && ent[1] <= '9')
  12253. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12254. setLastError ("illegal escape sequence", false);
  12255. return String::charToString ('&');
  12256. }
  12257. return expandExternalEntity (ent);
  12258. }
  12259. const String XmlDocument::expandExternalEntity (const String& entity)
  12260. {
  12261. if (needToLoadDTD)
  12262. {
  12263. if (dtdText.isNotEmpty())
  12264. {
  12265. dtdText = dtdText.trimCharactersAtEnd (">");
  12266. tokenisedDTD.addTokens (dtdText, true);
  12267. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12268. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12269. {
  12270. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12271. tokenisedDTD.clear();
  12272. tokenisedDTD.addTokens (getFileContents (fn), true);
  12273. }
  12274. else
  12275. {
  12276. tokenisedDTD.clear();
  12277. const int openBracket = dtdText.indexOfChar ('[');
  12278. if (openBracket > 0)
  12279. {
  12280. const int closeBracket = dtdText.lastIndexOfChar (']');
  12281. if (closeBracket > openBracket)
  12282. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12283. closeBracket), true);
  12284. }
  12285. }
  12286. for (int i = tokenisedDTD.size(); --i >= 0;)
  12287. {
  12288. if (tokenisedDTD[i].startsWithChar ('%')
  12289. && tokenisedDTD[i].endsWithChar (';'))
  12290. {
  12291. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12292. StringArray newToks;
  12293. newToks.addTokens (parsed, true);
  12294. tokenisedDTD.remove (i);
  12295. for (int j = newToks.size(); --j >= 0;)
  12296. tokenisedDTD.insert (i, newToks[j]);
  12297. }
  12298. }
  12299. }
  12300. needToLoadDTD = false;
  12301. }
  12302. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12303. {
  12304. if (tokenisedDTD[i] == entity)
  12305. {
  12306. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12307. {
  12308. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12309. // check for sub-entities..
  12310. int ampersand = ent.indexOfChar ('&');
  12311. while (ampersand >= 0)
  12312. {
  12313. const int semiColon = ent.indexOf (i + 1, ";");
  12314. if (semiColon < 0)
  12315. {
  12316. setLastError ("entity without terminating semi-colon", false);
  12317. break;
  12318. }
  12319. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12320. ent = ent.substring (0, ampersand)
  12321. + resolved
  12322. + ent.substring (semiColon + 1);
  12323. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12324. }
  12325. return ent;
  12326. }
  12327. }
  12328. }
  12329. setLastError ("unknown entity", true);
  12330. return entity;
  12331. }
  12332. const String XmlDocument::getParameterEntity (const String& entity)
  12333. {
  12334. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12335. {
  12336. if (tokenisedDTD[i] == entity
  12337. && tokenisedDTD [i - 1] == "%"
  12338. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12339. {
  12340. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12341. if (ent.equalsIgnoreCase ("system"))
  12342. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12343. else
  12344. return ent.trim().unquoted();
  12345. }
  12346. }
  12347. return entity;
  12348. }
  12349. END_JUCE_NAMESPACE
  12350. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12351. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12352. BEGIN_JUCE_NAMESPACE
  12353. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12354. : name (other.name),
  12355. value (other.value)
  12356. {
  12357. }
  12358. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12359. : name (name_),
  12360. value (value_)
  12361. {
  12362. #if JUCE_DEBUG
  12363. // this checks whether the attribute name string contains any illegal characters..
  12364. for (String::CharPointerType t (name.getCharPointer()); ! t.isEmpty(); ++t)
  12365. jassert (t.isLetterOrDigit() || *t == '_' || *t == '-' || *t == ':');
  12366. #endif
  12367. }
  12368. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12369. {
  12370. return name.equalsIgnoreCase (nameToMatch);
  12371. }
  12372. XmlElement::XmlElement (const String& tagName_) throw()
  12373. : tagName (tagName_)
  12374. {
  12375. // the tag name mustn't be empty, or it'll look like a text element!
  12376. jassert (tagName_.containsNonWhitespaceChars())
  12377. // The tag can't contain spaces or other characters that would create invalid XML!
  12378. jassert (! tagName_.containsAnyOf (" <>/&"));
  12379. }
  12380. XmlElement::XmlElement (int /*dummy*/) throw()
  12381. {
  12382. }
  12383. XmlElement::XmlElement (const XmlElement& other)
  12384. : tagName (other.tagName)
  12385. {
  12386. copyChildrenAndAttributesFrom (other);
  12387. }
  12388. XmlElement& XmlElement::operator= (const XmlElement& other)
  12389. {
  12390. if (this != &other)
  12391. {
  12392. removeAllAttributes();
  12393. deleteAllChildElements();
  12394. tagName = other.tagName;
  12395. copyChildrenAndAttributesFrom (other);
  12396. }
  12397. return *this;
  12398. }
  12399. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12400. {
  12401. jassert (firstChildElement.get() == 0);
  12402. firstChildElement.addCopyOfList (other.firstChildElement);
  12403. jassert (attributes.get() == 0);
  12404. attributes.addCopyOfList (other.attributes);
  12405. }
  12406. XmlElement::~XmlElement() throw()
  12407. {
  12408. firstChildElement.deleteAll();
  12409. attributes.deleteAll();
  12410. }
  12411. namespace XmlOutputFunctions
  12412. {
  12413. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12414. {
  12415. if ((character >= 'a' && character <= 'z')
  12416. || (character >= 'A' && character <= 'Z')
  12417. || (character >= '0' && character <= '9'))
  12418. return true;
  12419. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12420. do
  12421. {
  12422. if (((juce_wchar) (uint8) *t) == character)
  12423. return true;
  12424. }
  12425. while (*++t != 0);
  12426. return false;
  12427. }
  12428. void generateLegalCharConstants()
  12429. {
  12430. uint8 n[32];
  12431. zerostruct (n);
  12432. for (int i = 0; i < 256; ++i)
  12433. if (isLegalXmlCharSlow (i))
  12434. n[i >> 3] |= (1 << (i & 7));
  12435. String s;
  12436. for (int i = 0; i < 32; ++i)
  12437. s << (int) n[i] << ", ";
  12438. DBG (s);
  12439. }*/
  12440. bool isLegalXmlChar (const uint32 c) throw()
  12441. {
  12442. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12443. return c < sizeof (legalChars) * 8
  12444. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12445. }
  12446. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12447. {
  12448. String::CharPointerType t (text.getCharPointer());
  12449. for (;;)
  12450. {
  12451. const uint32 character = (uint32) t.getAndAdvance();
  12452. if (character == 0)
  12453. break;
  12454. if (isLegalXmlChar (character))
  12455. {
  12456. outputStream << (char) character;
  12457. }
  12458. else
  12459. {
  12460. switch (character)
  12461. {
  12462. case '&': outputStream << "&amp;"; break;
  12463. case '"': outputStream << "&quot;"; break;
  12464. case '>': outputStream << "&gt;"; break;
  12465. case '<': outputStream << "&lt;"; break;
  12466. case '\n':
  12467. case '\r':
  12468. if (! changeNewLines)
  12469. {
  12470. outputStream << (char) character;
  12471. break;
  12472. }
  12473. // Note: deliberate fall-through here!
  12474. default:
  12475. outputStream << "&#" << ((int) character) << ';';
  12476. break;
  12477. }
  12478. }
  12479. }
  12480. }
  12481. void writeSpaces (OutputStream& out, int numSpaces)
  12482. {
  12483. if (numSpaces > 0)
  12484. {
  12485. const char blanks[] = " ";
  12486. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12487. while (numSpaces > blankSize)
  12488. {
  12489. out.write (blanks, blankSize);
  12490. numSpaces -= blankSize;
  12491. }
  12492. out.write (blanks, numSpaces);
  12493. }
  12494. }
  12495. }
  12496. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12497. const int indentationLevel,
  12498. const int lineWrapLength) const
  12499. {
  12500. using namespace XmlOutputFunctions;
  12501. writeSpaces (outputStream, indentationLevel);
  12502. if (! isTextElement())
  12503. {
  12504. outputStream.writeByte ('<');
  12505. outputStream << tagName;
  12506. {
  12507. const int attIndent = indentationLevel + tagName.length() + 1;
  12508. int lineLen = 0;
  12509. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12510. {
  12511. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12512. {
  12513. outputStream << newLine;
  12514. writeSpaces (outputStream, attIndent);
  12515. lineLen = 0;
  12516. }
  12517. const int64 startPos = outputStream.getPosition();
  12518. outputStream.writeByte (' ');
  12519. outputStream << att->name;
  12520. outputStream.write ("=\"", 2);
  12521. escapeIllegalXmlChars (outputStream, att->value, true);
  12522. outputStream.writeByte ('"');
  12523. lineLen += (int) (outputStream.getPosition() - startPos);
  12524. }
  12525. }
  12526. if (firstChildElement != 0)
  12527. {
  12528. outputStream.writeByte ('>');
  12529. XmlElement* child = firstChildElement;
  12530. bool lastWasTextNode = false;
  12531. while (child != 0)
  12532. {
  12533. if (child->isTextElement())
  12534. {
  12535. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12536. lastWasTextNode = true;
  12537. }
  12538. else
  12539. {
  12540. if (indentationLevel >= 0 && ! lastWasTextNode)
  12541. outputStream << newLine;
  12542. child->writeElementAsText (outputStream,
  12543. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12544. lastWasTextNode = false;
  12545. }
  12546. child = child->getNextElement();
  12547. }
  12548. if (indentationLevel >= 0 && ! lastWasTextNode)
  12549. {
  12550. outputStream << newLine;
  12551. writeSpaces (outputStream, indentationLevel);
  12552. }
  12553. outputStream.write ("</", 2);
  12554. outputStream << tagName;
  12555. outputStream.writeByte ('>');
  12556. }
  12557. else
  12558. {
  12559. outputStream.write ("/>", 2);
  12560. }
  12561. }
  12562. else
  12563. {
  12564. escapeIllegalXmlChars (outputStream, getText(), false);
  12565. }
  12566. }
  12567. const String XmlElement::createDocument (const String& dtdToUse,
  12568. const bool allOnOneLine,
  12569. const bool includeXmlHeader,
  12570. const String& encodingType,
  12571. const int lineWrapLength) const
  12572. {
  12573. MemoryOutputStream mem (2048);
  12574. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12575. return mem.toUTF8();
  12576. }
  12577. void XmlElement::writeToStream (OutputStream& output,
  12578. const String& dtdToUse,
  12579. const bool allOnOneLine,
  12580. const bool includeXmlHeader,
  12581. const String& encodingType,
  12582. const int lineWrapLength) const
  12583. {
  12584. using namespace XmlOutputFunctions;
  12585. if (includeXmlHeader)
  12586. {
  12587. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12588. if (allOnOneLine)
  12589. output.writeByte (' ');
  12590. else
  12591. output << newLine << newLine;
  12592. }
  12593. if (dtdToUse.isNotEmpty())
  12594. {
  12595. output << dtdToUse;
  12596. if (allOnOneLine)
  12597. output.writeByte (' ');
  12598. else
  12599. output << newLine;
  12600. }
  12601. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12602. if (! allOnOneLine)
  12603. output << newLine;
  12604. }
  12605. bool XmlElement::writeToFile (const File& file,
  12606. const String& dtdToUse,
  12607. const String& encodingType,
  12608. const int lineWrapLength) const
  12609. {
  12610. if (file.hasWriteAccess())
  12611. {
  12612. TemporaryFile tempFile (file);
  12613. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12614. if (out != 0)
  12615. {
  12616. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12617. out = 0;
  12618. return tempFile.overwriteTargetFileWithTemporary();
  12619. }
  12620. }
  12621. return false;
  12622. }
  12623. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12624. {
  12625. #if JUCE_DEBUG
  12626. // if debugging, check that the case is actually the same, because
  12627. // valid xml is case-sensitive, and although this lets it pass, it's
  12628. // better not to..
  12629. if (tagName.equalsIgnoreCase (tagNameWanted))
  12630. {
  12631. jassert (tagName == tagNameWanted);
  12632. return true;
  12633. }
  12634. else
  12635. {
  12636. return false;
  12637. }
  12638. #else
  12639. return tagName.equalsIgnoreCase (tagNameWanted);
  12640. #endif
  12641. }
  12642. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12643. {
  12644. XmlElement* e = nextListItem;
  12645. while (e != 0 && ! e->hasTagName (requiredTagName))
  12646. e = e->nextListItem;
  12647. return e;
  12648. }
  12649. int XmlElement::getNumAttributes() const throw()
  12650. {
  12651. return attributes.size();
  12652. }
  12653. const String& XmlElement::getAttributeName (const int index) const throw()
  12654. {
  12655. const XmlAttributeNode* const att = attributes [index];
  12656. return att != 0 ? att->name : String::empty;
  12657. }
  12658. const String& XmlElement::getAttributeValue (const int index) const throw()
  12659. {
  12660. const XmlAttributeNode* const att = attributes [index];
  12661. return att != 0 ? att->value : String::empty;
  12662. }
  12663. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12664. {
  12665. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12666. if (att->hasName (attributeName))
  12667. return true;
  12668. return false;
  12669. }
  12670. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12671. {
  12672. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12673. if (att->hasName (attributeName))
  12674. return att->value;
  12675. return String::empty;
  12676. }
  12677. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12678. {
  12679. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12680. if (att->hasName (attributeName))
  12681. return att->value;
  12682. return defaultReturnValue;
  12683. }
  12684. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12685. {
  12686. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12687. if (att->hasName (attributeName))
  12688. return att->value.getIntValue();
  12689. return defaultReturnValue;
  12690. }
  12691. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12692. {
  12693. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12694. if (att->hasName (attributeName))
  12695. return att->value.getDoubleValue();
  12696. return defaultReturnValue;
  12697. }
  12698. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12699. {
  12700. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12701. {
  12702. if (att->hasName (attributeName))
  12703. {
  12704. juce_wchar firstChar = att->value[0];
  12705. if (CharacterFunctions::isWhitespace (firstChar))
  12706. firstChar = att->value.trimStart() [0];
  12707. return firstChar == '1'
  12708. || firstChar == 't'
  12709. || firstChar == 'y'
  12710. || firstChar == 'T'
  12711. || firstChar == 'Y';
  12712. }
  12713. }
  12714. return defaultReturnValue;
  12715. }
  12716. bool XmlElement::compareAttribute (const String& attributeName,
  12717. const String& stringToCompareAgainst,
  12718. const bool ignoreCase) const throw()
  12719. {
  12720. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12721. if (att->hasName (attributeName))
  12722. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12723. : att->value == stringToCompareAgainst;
  12724. return false;
  12725. }
  12726. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12727. {
  12728. if (attributes == 0)
  12729. {
  12730. attributes = new XmlAttributeNode (attributeName, value);
  12731. }
  12732. else
  12733. {
  12734. XmlAttributeNode* att = attributes;
  12735. for (;;)
  12736. {
  12737. if (att->hasName (attributeName))
  12738. {
  12739. att->value = value;
  12740. break;
  12741. }
  12742. else if (att->nextListItem == 0)
  12743. {
  12744. att->nextListItem = new XmlAttributeNode (attributeName, value);
  12745. break;
  12746. }
  12747. att = att->nextListItem;
  12748. }
  12749. }
  12750. }
  12751. void XmlElement::setAttribute (const String& attributeName, const int number)
  12752. {
  12753. setAttribute (attributeName, String (number));
  12754. }
  12755. void XmlElement::setAttribute (const String& attributeName, const double number)
  12756. {
  12757. setAttribute (attributeName, String (number));
  12758. }
  12759. void XmlElement::removeAttribute (const String& attributeName) throw()
  12760. {
  12761. LinkedListPointer<XmlAttributeNode>* att = &attributes;
  12762. while (att->get() != 0)
  12763. {
  12764. if (att->get()->hasName (attributeName))
  12765. {
  12766. delete att->removeNext();
  12767. break;
  12768. }
  12769. att = &(att->get()->nextListItem);
  12770. }
  12771. }
  12772. void XmlElement::removeAllAttributes() throw()
  12773. {
  12774. attributes.deleteAll();
  12775. }
  12776. int XmlElement::getNumChildElements() const throw()
  12777. {
  12778. return firstChildElement.size();
  12779. }
  12780. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12781. {
  12782. return firstChildElement [index].get();
  12783. }
  12784. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12785. {
  12786. XmlElement* child = firstChildElement;
  12787. while (child != 0)
  12788. {
  12789. if (child->hasTagName (childName))
  12790. break;
  12791. child = child->nextListItem;
  12792. }
  12793. return child;
  12794. }
  12795. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12796. {
  12797. if (newNode != 0)
  12798. firstChildElement.append (newNode);
  12799. }
  12800. void XmlElement::insertChildElement (XmlElement* const newNode,
  12801. int indexToInsertAt) throw()
  12802. {
  12803. if (newNode != 0)
  12804. {
  12805. removeChildElement (newNode, false);
  12806. firstChildElement.insertAtIndex (indexToInsertAt, newNode);
  12807. }
  12808. }
  12809. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12810. {
  12811. XmlElement* const newElement = new XmlElement (childTagName);
  12812. addChildElement (newElement);
  12813. return newElement;
  12814. }
  12815. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12816. XmlElement* const newNode) throw()
  12817. {
  12818. if (newNode != 0)
  12819. {
  12820. LinkedListPointer<XmlElement>* const p = firstChildElement.findPointerTo (currentChildElement);
  12821. if (p != 0)
  12822. {
  12823. if (currentChildElement != newNode)
  12824. delete p->replaceNext (newNode);
  12825. return true;
  12826. }
  12827. }
  12828. return false;
  12829. }
  12830. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12831. const bool shouldDeleteTheChild) throw()
  12832. {
  12833. if (childToRemove != 0)
  12834. {
  12835. firstChildElement.remove (childToRemove);
  12836. if (shouldDeleteTheChild)
  12837. delete childToRemove;
  12838. }
  12839. }
  12840. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12841. const bool ignoreOrderOfAttributes) const throw()
  12842. {
  12843. if (this != other)
  12844. {
  12845. if (other == 0 || tagName != other->tagName)
  12846. return false;
  12847. if (ignoreOrderOfAttributes)
  12848. {
  12849. int totalAtts = 0;
  12850. const XmlAttributeNode* att = attributes;
  12851. while (att != 0)
  12852. {
  12853. if (! other->compareAttribute (att->name, att->value))
  12854. return false;
  12855. att = att->nextListItem;
  12856. ++totalAtts;
  12857. }
  12858. if (totalAtts != other->getNumAttributes())
  12859. return false;
  12860. }
  12861. else
  12862. {
  12863. const XmlAttributeNode* thisAtt = attributes;
  12864. const XmlAttributeNode* otherAtt = other->attributes;
  12865. for (;;)
  12866. {
  12867. if (thisAtt == 0 || otherAtt == 0)
  12868. {
  12869. if (thisAtt == otherAtt) // both 0, so it's a match
  12870. break;
  12871. return false;
  12872. }
  12873. if (thisAtt->name != otherAtt->name
  12874. || thisAtt->value != otherAtt->value)
  12875. {
  12876. return false;
  12877. }
  12878. thisAtt = thisAtt->nextListItem;
  12879. otherAtt = otherAtt->nextListItem;
  12880. }
  12881. }
  12882. const XmlElement* thisChild = firstChildElement;
  12883. const XmlElement* otherChild = other->firstChildElement;
  12884. for (;;)
  12885. {
  12886. if (thisChild == 0 || otherChild == 0)
  12887. {
  12888. if (thisChild == otherChild) // both 0, so it's a match
  12889. break;
  12890. return false;
  12891. }
  12892. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12893. return false;
  12894. thisChild = thisChild->nextListItem;
  12895. otherChild = otherChild->nextListItem;
  12896. }
  12897. }
  12898. return true;
  12899. }
  12900. void XmlElement::deleteAllChildElements() throw()
  12901. {
  12902. firstChildElement.deleteAll();
  12903. }
  12904. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12905. {
  12906. XmlElement* child = firstChildElement;
  12907. while (child != 0)
  12908. {
  12909. XmlElement* const nextChild = child->nextListItem;
  12910. if (child->hasTagName (name))
  12911. removeChildElement (child, true);
  12912. child = nextChild;
  12913. }
  12914. }
  12915. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12916. {
  12917. return firstChildElement.contains (possibleChild);
  12918. }
  12919. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12920. {
  12921. if (this == elementToLookFor || elementToLookFor == 0)
  12922. return 0;
  12923. XmlElement* child = firstChildElement;
  12924. while (child != 0)
  12925. {
  12926. if (elementToLookFor == child)
  12927. return this;
  12928. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12929. if (found != 0)
  12930. return found;
  12931. child = child->nextListItem;
  12932. }
  12933. return 0;
  12934. }
  12935. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12936. {
  12937. firstChildElement.copyToArray (elems);
  12938. }
  12939. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12940. {
  12941. XmlElement* e = firstChildElement = elems[0];
  12942. for (int i = 1; i < num; ++i)
  12943. {
  12944. e->nextListItem = elems[i];
  12945. e = e->nextListItem;
  12946. }
  12947. e->nextListItem = 0;
  12948. }
  12949. bool XmlElement::isTextElement() const throw()
  12950. {
  12951. return tagName.isEmpty();
  12952. }
  12953. static const String juce_xmltextContentAttributeName ("text");
  12954. const String& XmlElement::getText() const throw()
  12955. {
  12956. jassert (isTextElement()); // you're trying to get the text from an element that
  12957. // isn't actually a text element.. If this contains text sub-nodes, you
  12958. // probably want to use getAllSubText instead.
  12959. return getStringAttribute (juce_xmltextContentAttributeName);
  12960. }
  12961. void XmlElement::setText (const String& newText)
  12962. {
  12963. if (isTextElement())
  12964. setAttribute (juce_xmltextContentAttributeName, newText);
  12965. else
  12966. jassertfalse; // you can only change the text in a text element, not a normal one.
  12967. }
  12968. const String XmlElement::getAllSubText() const
  12969. {
  12970. if (isTextElement())
  12971. return getText();
  12972. String result;
  12973. String::Concatenator concatenator (result);
  12974. const XmlElement* child = firstChildElement;
  12975. while (child != 0)
  12976. {
  12977. concatenator.append (child->getAllSubText());
  12978. child = child->nextListItem;
  12979. }
  12980. return result;
  12981. }
  12982. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12983. const String& defaultReturnValue) const
  12984. {
  12985. const XmlElement* const child = getChildByName (childTagName);
  12986. if (child != 0)
  12987. return child->getAllSubText();
  12988. return defaultReturnValue;
  12989. }
  12990. XmlElement* XmlElement::createTextElement (const String& text)
  12991. {
  12992. XmlElement* const e = new XmlElement ((int) 0);
  12993. e->setAttribute (juce_xmltextContentAttributeName, text);
  12994. return e;
  12995. }
  12996. void XmlElement::addTextElement (const String& text)
  12997. {
  12998. addChildElement (createTextElement (text));
  12999. }
  13000. void XmlElement::deleteAllTextElements() throw()
  13001. {
  13002. XmlElement* child = firstChildElement;
  13003. while (child != 0)
  13004. {
  13005. XmlElement* const next = child->nextListItem;
  13006. if (child->isTextElement())
  13007. removeChildElement (child, true);
  13008. child = next;
  13009. }
  13010. }
  13011. END_JUCE_NAMESPACE
  13012. /*** End of inlined file: juce_XmlElement.cpp ***/
  13013. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13014. BEGIN_JUCE_NAMESPACE
  13015. ReadWriteLock::ReadWriteLock() throw()
  13016. : numWaitingWriters (0),
  13017. numWriters (0),
  13018. writerThreadId (0)
  13019. {
  13020. }
  13021. ReadWriteLock::~ReadWriteLock() throw()
  13022. {
  13023. jassert (readerThreads.size() == 0);
  13024. jassert (numWriters == 0);
  13025. }
  13026. void ReadWriteLock::enterRead() const throw()
  13027. {
  13028. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13029. const ScopedLock sl (accessLock);
  13030. for (;;)
  13031. {
  13032. jassert (readerThreads.size() % 2 == 0);
  13033. int i;
  13034. for (i = 0; i < readerThreads.size(); i += 2)
  13035. if (readerThreads.getUnchecked(i) == threadId)
  13036. break;
  13037. if (i < readerThreads.size()
  13038. || numWriters + numWaitingWriters == 0
  13039. || (threadId == writerThreadId && numWriters > 0))
  13040. {
  13041. if (i < readerThreads.size())
  13042. {
  13043. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13044. }
  13045. else
  13046. {
  13047. readerThreads.add (threadId);
  13048. readerThreads.add ((Thread::ThreadID) 1);
  13049. }
  13050. return;
  13051. }
  13052. const ScopedUnlock ul (accessLock);
  13053. waitEvent.wait (100);
  13054. }
  13055. }
  13056. void ReadWriteLock::exitRead() const throw()
  13057. {
  13058. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13059. const ScopedLock sl (accessLock);
  13060. for (int i = 0; i < readerThreads.size(); i += 2)
  13061. {
  13062. if (readerThreads.getUnchecked(i) == threadId)
  13063. {
  13064. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13065. if (newCount == 0)
  13066. {
  13067. readerThreads.removeRange (i, 2);
  13068. waitEvent.signal();
  13069. }
  13070. else
  13071. {
  13072. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13073. }
  13074. return;
  13075. }
  13076. }
  13077. jassertfalse; // unlocking a lock that wasn't locked..
  13078. }
  13079. void ReadWriteLock::enterWrite() const throw()
  13080. {
  13081. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13082. const ScopedLock sl (accessLock);
  13083. for (;;)
  13084. {
  13085. if (readerThreads.size() + numWriters == 0
  13086. || threadId == writerThreadId
  13087. || (readerThreads.size() == 2
  13088. && readerThreads.getUnchecked(0) == threadId))
  13089. {
  13090. writerThreadId = threadId;
  13091. ++numWriters;
  13092. break;
  13093. }
  13094. ++numWaitingWriters;
  13095. accessLock.exit();
  13096. waitEvent.wait (100);
  13097. accessLock.enter();
  13098. --numWaitingWriters;
  13099. }
  13100. }
  13101. bool ReadWriteLock::tryEnterWrite() const throw()
  13102. {
  13103. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13104. const ScopedLock sl (accessLock);
  13105. if (readerThreads.size() + numWriters == 0
  13106. || threadId == writerThreadId
  13107. || (readerThreads.size() == 2
  13108. && readerThreads.getUnchecked(0) == threadId))
  13109. {
  13110. writerThreadId = threadId;
  13111. ++numWriters;
  13112. return true;
  13113. }
  13114. return false;
  13115. }
  13116. void ReadWriteLock::exitWrite() const throw()
  13117. {
  13118. const ScopedLock sl (accessLock);
  13119. // check this thread actually had the lock..
  13120. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13121. if (--numWriters == 0)
  13122. {
  13123. writerThreadId = 0;
  13124. waitEvent.signal();
  13125. }
  13126. }
  13127. END_JUCE_NAMESPACE
  13128. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13129. /*** Start of inlined file: juce_Thread.cpp ***/
  13130. BEGIN_JUCE_NAMESPACE
  13131. class RunningThreadsList
  13132. {
  13133. public:
  13134. RunningThreadsList()
  13135. {
  13136. }
  13137. void add (Thread* const thread)
  13138. {
  13139. const ScopedLock sl (lock);
  13140. jassert (! threads.contains (thread));
  13141. threads.add (thread);
  13142. }
  13143. void remove (Thread* const thread)
  13144. {
  13145. const ScopedLock sl (lock);
  13146. jassert (threads.contains (thread));
  13147. threads.removeValue (thread);
  13148. }
  13149. int size() const throw()
  13150. {
  13151. return threads.size();
  13152. }
  13153. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13154. {
  13155. const ScopedLock sl (lock);
  13156. for (int i = threads.size(); --i >= 0;)
  13157. {
  13158. Thread* const t = threads.getUnchecked(i);
  13159. if (t->getThreadId() == targetID)
  13160. return t;
  13161. }
  13162. return 0;
  13163. }
  13164. void stopAll (const int timeOutMilliseconds)
  13165. {
  13166. signalAllThreadsToStop();
  13167. for (;;)
  13168. {
  13169. Thread* firstThread = getFirstThread();
  13170. if (firstThread != 0)
  13171. firstThread->stopThread (timeOutMilliseconds);
  13172. else
  13173. break;
  13174. }
  13175. }
  13176. static RunningThreadsList& getInstance()
  13177. {
  13178. static RunningThreadsList runningThreads;
  13179. return runningThreads;
  13180. }
  13181. private:
  13182. Array<Thread*> threads;
  13183. CriticalSection lock;
  13184. void signalAllThreadsToStop()
  13185. {
  13186. const ScopedLock sl (lock);
  13187. for (int i = threads.size(); --i >= 0;)
  13188. threads.getUnchecked(i)->signalThreadShouldExit();
  13189. }
  13190. Thread* getFirstThread() const
  13191. {
  13192. const ScopedLock sl (lock);
  13193. return threads.getFirst();
  13194. }
  13195. };
  13196. void Thread::threadEntryPoint()
  13197. {
  13198. RunningThreadsList::getInstance().add (this);
  13199. JUCE_TRY
  13200. {
  13201. if (threadName_.isNotEmpty())
  13202. setCurrentThreadName (threadName_);
  13203. if (startSuspensionEvent_.wait (10000))
  13204. {
  13205. jassert (getCurrentThreadId() == threadId_);
  13206. if (affinityMask_ != 0)
  13207. setCurrentThreadAffinityMask (affinityMask_);
  13208. run();
  13209. }
  13210. }
  13211. JUCE_CATCH_ALL_ASSERT
  13212. RunningThreadsList::getInstance().remove (this);
  13213. closeThreadHandle();
  13214. }
  13215. // used to wrap the incoming call from the platform-specific code
  13216. void JUCE_API juce_threadEntryPoint (void* userData)
  13217. {
  13218. static_cast <Thread*> (userData)->threadEntryPoint();
  13219. }
  13220. Thread::Thread (const String& threadName)
  13221. : threadName_ (threadName),
  13222. threadHandle_ (0),
  13223. threadId_ (0),
  13224. threadPriority_ (5),
  13225. affinityMask_ (0),
  13226. threadShouldExit_ (false)
  13227. {
  13228. }
  13229. Thread::~Thread()
  13230. {
  13231. /* If your thread class's destructor has been called without first stopping the thread, that
  13232. means that this partially destructed object is still performing some work - and that's
  13233. probably a Bad Thing!
  13234. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13235. your subclass's destructor.
  13236. */
  13237. jassert (! isThreadRunning());
  13238. stopThread (100);
  13239. }
  13240. void Thread::startThread()
  13241. {
  13242. const ScopedLock sl (startStopLock);
  13243. threadShouldExit_ = false;
  13244. if (threadHandle_ == 0)
  13245. {
  13246. launchThread();
  13247. setThreadPriority (threadHandle_, threadPriority_);
  13248. startSuspensionEvent_.signal();
  13249. }
  13250. }
  13251. void Thread::startThread (const int priority)
  13252. {
  13253. const ScopedLock sl (startStopLock);
  13254. if (threadHandle_ == 0)
  13255. {
  13256. threadPriority_ = priority;
  13257. startThread();
  13258. }
  13259. else
  13260. {
  13261. setPriority (priority);
  13262. }
  13263. }
  13264. bool Thread::isThreadRunning() const
  13265. {
  13266. return threadHandle_ != 0;
  13267. }
  13268. void Thread::signalThreadShouldExit()
  13269. {
  13270. threadShouldExit_ = true;
  13271. }
  13272. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13273. {
  13274. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13275. jassert (getThreadId() != getCurrentThreadId());
  13276. const int sleepMsPerIteration = 5;
  13277. int count = timeOutMilliseconds / sleepMsPerIteration;
  13278. while (isThreadRunning())
  13279. {
  13280. if (timeOutMilliseconds > 0 && --count < 0)
  13281. return false;
  13282. sleep (sleepMsPerIteration);
  13283. }
  13284. return true;
  13285. }
  13286. void Thread::stopThread (const int timeOutMilliseconds)
  13287. {
  13288. // agh! You can't stop the thread that's calling this method! How on earth
  13289. // would that work??
  13290. jassert (getCurrentThreadId() != getThreadId());
  13291. const ScopedLock sl (startStopLock);
  13292. if (isThreadRunning())
  13293. {
  13294. signalThreadShouldExit();
  13295. notify();
  13296. if (timeOutMilliseconds != 0)
  13297. waitForThreadToExit (timeOutMilliseconds);
  13298. if (isThreadRunning())
  13299. {
  13300. // very bad karma if this point is reached, as there are bound to be
  13301. // locks and events left in silly states when a thread is killed by force..
  13302. jassertfalse;
  13303. Logger::writeToLog ("!! killing thread by force !!");
  13304. killThread();
  13305. RunningThreadsList::getInstance().remove (this);
  13306. threadHandle_ = 0;
  13307. threadId_ = 0;
  13308. }
  13309. }
  13310. }
  13311. bool Thread::setPriority (const int priority)
  13312. {
  13313. const ScopedLock sl (startStopLock);
  13314. if (setThreadPriority (threadHandle_, priority))
  13315. {
  13316. threadPriority_ = priority;
  13317. return true;
  13318. }
  13319. return false;
  13320. }
  13321. bool Thread::setCurrentThreadPriority (const int priority)
  13322. {
  13323. return setThreadPriority (0, priority);
  13324. }
  13325. void Thread::setAffinityMask (const uint32 affinityMask)
  13326. {
  13327. affinityMask_ = affinityMask;
  13328. }
  13329. bool Thread::wait (const int timeOutMilliseconds) const
  13330. {
  13331. return defaultEvent_.wait (timeOutMilliseconds);
  13332. }
  13333. void Thread::notify() const
  13334. {
  13335. defaultEvent_.signal();
  13336. }
  13337. int Thread::getNumRunningThreads()
  13338. {
  13339. return RunningThreadsList::getInstance().size();
  13340. }
  13341. Thread* Thread::getCurrentThread()
  13342. {
  13343. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13344. }
  13345. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13346. {
  13347. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13348. }
  13349. END_JUCE_NAMESPACE
  13350. /*** End of inlined file: juce_Thread.cpp ***/
  13351. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13352. BEGIN_JUCE_NAMESPACE
  13353. ThreadPoolJob::ThreadPoolJob (const String& name)
  13354. : jobName (name),
  13355. pool (0),
  13356. shouldStop (false),
  13357. isActive (false),
  13358. shouldBeDeleted (false)
  13359. {
  13360. }
  13361. ThreadPoolJob::~ThreadPoolJob()
  13362. {
  13363. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13364. // to remove it first!
  13365. jassert (pool == 0 || ! pool->contains (this));
  13366. }
  13367. const String ThreadPoolJob::getJobName() const
  13368. {
  13369. return jobName;
  13370. }
  13371. void ThreadPoolJob::setJobName (const String& newName)
  13372. {
  13373. jobName = newName;
  13374. }
  13375. void ThreadPoolJob::signalJobShouldExit()
  13376. {
  13377. shouldStop = true;
  13378. }
  13379. class ThreadPool::ThreadPoolThread : public Thread
  13380. {
  13381. public:
  13382. ThreadPoolThread (ThreadPool& pool_)
  13383. : Thread ("Pool"),
  13384. pool (pool_),
  13385. busy (false)
  13386. {
  13387. }
  13388. void run()
  13389. {
  13390. while (! threadShouldExit())
  13391. {
  13392. if (! pool.runNextJob())
  13393. wait (500);
  13394. }
  13395. }
  13396. private:
  13397. ThreadPool& pool;
  13398. bool volatile busy;
  13399. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13400. };
  13401. ThreadPool::ThreadPool (const int numThreads,
  13402. const bool startThreadsOnlyWhenNeeded,
  13403. const int stopThreadsWhenNotUsedTimeoutMs)
  13404. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13405. priority (5)
  13406. {
  13407. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13408. for (int i = jmax (1, numThreads); --i >= 0;)
  13409. threads.add (new ThreadPoolThread (*this));
  13410. if (! startThreadsOnlyWhenNeeded)
  13411. for (int i = threads.size(); --i >= 0;)
  13412. threads.getUnchecked(i)->startThread (priority);
  13413. }
  13414. ThreadPool::~ThreadPool()
  13415. {
  13416. removeAllJobs (true, 4000);
  13417. int i;
  13418. for (i = threads.size(); --i >= 0;)
  13419. threads.getUnchecked(i)->signalThreadShouldExit();
  13420. for (i = threads.size(); --i >= 0;)
  13421. threads.getUnchecked(i)->stopThread (500);
  13422. }
  13423. void ThreadPool::addJob (ThreadPoolJob* const job)
  13424. {
  13425. jassert (job != 0);
  13426. jassert (job->pool == 0);
  13427. if (job->pool == 0)
  13428. {
  13429. job->pool = this;
  13430. job->shouldStop = false;
  13431. job->isActive = false;
  13432. {
  13433. const ScopedLock sl (lock);
  13434. jobs.add (job);
  13435. int numRunning = 0;
  13436. for (int i = threads.size(); --i >= 0;)
  13437. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13438. ++numRunning;
  13439. if (numRunning < threads.size())
  13440. {
  13441. bool startedOne = false;
  13442. int n = 1000;
  13443. while (--n >= 0 && ! startedOne)
  13444. {
  13445. for (int i = threads.size(); --i >= 0;)
  13446. {
  13447. if (! threads.getUnchecked(i)->isThreadRunning())
  13448. {
  13449. threads.getUnchecked(i)->startThread (priority);
  13450. startedOne = true;
  13451. break;
  13452. }
  13453. }
  13454. if (! startedOne)
  13455. Thread::sleep (2);
  13456. }
  13457. }
  13458. }
  13459. for (int i = threads.size(); --i >= 0;)
  13460. threads.getUnchecked(i)->notify();
  13461. }
  13462. }
  13463. int ThreadPool::getNumJobs() const
  13464. {
  13465. return jobs.size();
  13466. }
  13467. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13468. {
  13469. const ScopedLock sl (lock);
  13470. return jobs [index];
  13471. }
  13472. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13473. {
  13474. const ScopedLock sl (lock);
  13475. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13476. }
  13477. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13478. {
  13479. const ScopedLock sl (lock);
  13480. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13481. }
  13482. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13483. const int timeOutMs) const
  13484. {
  13485. if (job != 0)
  13486. {
  13487. const uint32 start = Time::getMillisecondCounter();
  13488. while (contains (job))
  13489. {
  13490. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13491. return false;
  13492. jobFinishedSignal.wait (2);
  13493. }
  13494. }
  13495. return true;
  13496. }
  13497. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13498. const bool interruptIfRunning,
  13499. const int timeOutMs)
  13500. {
  13501. bool dontWait = true;
  13502. if (job != 0)
  13503. {
  13504. const ScopedLock sl (lock);
  13505. if (jobs.contains (job))
  13506. {
  13507. if (job->isActive)
  13508. {
  13509. if (interruptIfRunning)
  13510. job->signalJobShouldExit();
  13511. dontWait = false;
  13512. }
  13513. else
  13514. {
  13515. jobs.removeValue (job);
  13516. job->pool = 0;
  13517. }
  13518. }
  13519. }
  13520. return dontWait || waitForJobToFinish (job, timeOutMs);
  13521. }
  13522. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13523. const int timeOutMs,
  13524. const bool deleteInactiveJobs,
  13525. ThreadPool::JobSelector* selectedJobsToRemove)
  13526. {
  13527. Array <ThreadPoolJob*> jobsToWaitFor;
  13528. {
  13529. const ScopedLock sl (lock);
  13530. for (int i = jobs.size(); --i >= 0;)
  13531. {
  13532. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13533. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13534. {
  13535. if (job->isActive)
  13536. {
  13537. jobsToWaitFor.add (job);
  13538. if (interruptRunningJobs)
  13539. job->signalJobShouldExit();
  13540. }
  13541. else
  13542. {
  13543. jobs.remove (i);
  13544. if (deleteInactiveJobs)
  13545. delete job;
  13546. else
  13547. job->pool = 0;
  13548. }
  13549. }
  13550. }
  13551. }
  13552. const uint32 start = Time::getMillisecondCounter();
  13553. for (;;)
  13554. {
  13555. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13556. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13557. jobsToWaitFor.remove (i);
  13558. if (jobsToWaitFor.size() == 0)
  13559. break;
  13560. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13561. return false;
  13562. jobFinishedSignal.wait (20);
  13563. }
  13564. return true;
  13565. }
  13566. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13567. {
  13568. StringArray s;
  13569. const ScopedLock sl (lock);
  13570. for (int i = 0; i < jobs.size(); ++i)
  13571. {
  13572. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13573. if (job->isActive || ! onlyReturnActiveJobs)
  13574. s.add (job->getJobName());
  13575. }
  13576. return s;
  13577. }
  13578. bool ThreadPool::setThreadPriorities (const int newPriority)
  13579. {
  13580. bool ok = true;
  13581. if (priority != newPriority)
  13582. {
  13583. priority = newPriority;
  13584. for (int i = threads.size(); --i >= 0;)
  13585. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13586. ok = false;
  13587. }
  13588. return ok;
  13589. }
  13590. bool ThreadPool::runNextJob()
  13591. {
  13592. ThreadPoolJob* job = 0;
  13593. {
  13594. const ScopedLock sl (lock);
  13595. for (int i = 0; i < jobs.size(); ++i)
  13596. {
  13597. job = jobs[i];
  13598. if (job != 0 && ! (job->isActive || job->shouldStop))
  13599. break;
  13600. job = 0;
  13601. }
  13602. if (job != 0)
  13603. job->isActive = true;
  13604. }
  13605. if (job != 0)
  13606. {
  13607. JUCE_TRY
  13608. {
  13609. ThreadPoolJob::JobStatus result = job->runJob();
  13610. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13611. const ScopedLock sl (lock);
  13612. if (jobs.contains (job))
  13613. {
  13614. job->isActive = false;
  13615. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13616. {
  13617. job->pool = 0;
  13618. job->shouldStop = true;
  13619. jobs.removeValue (job);
  13620. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13621. delete job;
  13622. jobFinishedSignal.signal();
  13623. }
  13624. else
  13625. {
  13626. // move the job to the end of the queue if it wants another go
  13627. jobs.move (jobs.indexOf (job), -1);
  13628. }
  13629. }
  13630. }
  13631. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13632. catch (...)
  13633. {
  13634. const ScopedLock sl (lock);
  13635. jobs.removeValue (job);
  13636. }
  13637. #endif
  13638. }
  13639. else
  13640. {
  13641. if (threadStopTimeout > 0
  13642. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13643. {
  13644. const ScopedLock sl (lock);
  13645. if (jobs.size() == 0)
  13646. for (int i = threads.size(); --i >= 0;)
  13647. threads.getUnchecked(i)->signalThreadShouldExit();
  13648. }
  13649. else
  13650. {
  13651. return false;
  13652. }
  13653. }
  13654. return true;
  13655. }
  13656. END_JUCE_NAMESPACE
  13657. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13658. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13659. BEGIN_JUCE_NAMESPACE
  13660. TimeSliceThread::TimeSliceThread (const String& threadName)
  13661. : Thread (threadName),
  13662. clientBeingCalled (0)
  13663. {
  13664. }
  13665. TimeSliceThread::~TimeSliceThread()
  13666. {
  13667. stopThread (2000);
  13668. }
  13669. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client, int millisecondsBeforeStarting)
  13670. {
  13671. if (client != 0)
  13672. {
  13673. const ScopedLock sl (listLock);
  13674. client->nextCallTime = Time::getCurrentTime() + RelativeTime::milliseconds (millisecondsBeforeStarting);
  13675. clients.addIfNotAlreadyThere (client);
  13676. notify();
  13677. }
  13678. }
  13679. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13680. {
  13681. const ScopedLock sl1 (listLock);
  13682. // if there's a chance we're in the middle of calling this client, we need to
  13683. // also lock the outer lock..
  13684. if (clientBeingCalled == client)
  13685. {
  13686. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13687. const ScopedLock sl2 (callbackLock);
  13688. const ScopedLock sl3 (listLock);
  13689. clients.removeValue (client);
  13690. }
  13691. else
  13692. {
  13693. clients.removeValue (client);
  13694. }
  13695. }
  13696. int TimeSliceThread::getNumClients() const
  13697. {
  13698. return clients.size();
  13699. }
  13700. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13701. {
  13702. const ScopedLock sl (listLock);
  13703. return clients [i];
  13704. }
  13705. TimeSliceClient* TimeSliceThread::getNextClient (int index) const
  13706. {
  13707. Time soonest;
  13708. TimeSliceClient* client = 0;
  13709. for (int i = clients.size(); --i >= 0;)
  13710. {
  13711. TimeSliceClient* const c = clients.getUnchecked ((i + index) % clients.size());
  13712. if (client == 0 || c->nextCallTime < soonest)
  13713. {
  13714. client = c;
  13715. soonest = c->nextCallTime;
  13716. }
  13717. }
  13718. return client;
  13719. }
  13720. void TimeSliceThread::run()
  13721. {
  13722. int index = 0;
  13723. while (! threadShouldExit())
  13724. {
  13725. int timeToWait = 500;
  13726. {
  13727. Time nextClientTime;
  13728. {
  13729. const ScopedLock sl2 (listLock);
  13730. index = clients.size() > 0 ? ((index + 1) % clients.size()) : 0;
  13731. TimeSliceClient* const firstClient = getNextClient (index);
  13732. if (firstClient != 0)
  13733. nextClientTime = firstClient->nextCallTime;
  13734. }
  13735. const Time now (Time::getCurrentTime());
  13736. if (nextClientTime > now)
  13737. {
  13738. timeToWait = (int) jmin ((int64) 500, (nextClientTime - now).inMilliseconds());
  13739. }
  13740. else
  13741. {
  13742. timeToWait = index == 0 ? 1 : 0;
  13743. const ScopedLock sl (callbackLock);
  13744. {
  13745. const ScopedLock sl2 (listLock);
  13746. clientBeingCalled = getNextClient (index);
  13747. }
  13748. if (clientBeingCalled != 0)
  13749. {
  13750. const int msUntilNextCall = clientBeingCalled->useTimeSlice();
  13751. const ScopedLock sl2 (listLock);
  13752. if (msUntilNextCall >= 0)
  13753. clientBeingCalled->nextCallTime += RelativeTime::milliseconds (msUntilNextCall);
  13754. else
  13755. clients.removeValue (clientBeingCalled);
  13756. clientBeingCalled = 0;
  13757. }
  13758. }
  13759. }
  13760. if (timeToWait > 0)
  13761. wait (timeToWait);
  13762. }
  13763. }
  13764. END_JUCE_NAMESPACE
  13765. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13766. #endif
  13767. #if JUCE_BUILD_MISC
  13768. /*** Start of inlined file: juce_ValueTree.cpp ***/
  13769. BEGIN_JUCE_NAMESPACE
  13770. class ValueTree::SetPropertyAction : public UndoableAction
  13771. {
  13772. public:
  13773. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13774. const var& newValue_, const var& oldValue_,
  13775. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13776. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13777. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13778. {
  13779. }
  13780. bool perform()
  13781. {
  13782. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13783. if (isDeletingProperty)
  13784. target->removeProperty (name, 0);
  13785. else
  13786. target->setProperty (name, newValue, 0);
  13787. return true;
  13788. }
  13789. bool undo()
  13790. {
  13791. if (isAddingNewProperty)
  13792. target->removeProperty (name, 0);
  13793. else
  13794. target->setProperty (name, oldValue, 0);
  13795. return true;
  13796. }
  13797. int getSizeInUnits()
  13798. {
  13799. return (int) sizeof (*this); //xxx should be more accurate
  13800. }
  13801. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13802. {
  13803. if (! (isAddingNewProperty || isDeletingProperty))
  13804. {
  13805. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13806. if (next != 0 && next->target == target && next->name == name
  13807. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13808. {
  13809. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13810. }
  13811. }
  13812. return 0;
  13813. }
  13814. private:
  13815. const SharedObjectPtr target;
  13816. const Identifier name;
  13817. const var newValue;
  13818. var oldValue;
  13819. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13820. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  13821. };
  13822. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13823. {
  13824. public:
  13825. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13826. const SharedObjectPtr& newChild_)
  13827. : target (target_),
  13828. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13829. childIndex (childIndex_),
  13830. isDeleting (newChild_ == 0)
  13831. {
  13832. jassert (child != 0);
  13833. }
  13834. bool perform()
  13835. {
  13836. if (isDeleting)
  13837. target->removeChild (childIndex, 0);
  13838. else
  13839. target->addChild (child, childIndex, 0);
  13840. return true;
  13841. }
  13842. bool undo()
  13843. {
  13844. if (isDeleting)
  13845. {
  13846. target->addChild (child, childIndex, 0);
  13847. }
  13848. else
  13849. {
  13850. // If you hit this, it seems that your object's state is getting confused - probably
  13851. // because you've interleaved some undoable and non-undoable operations?
  13852. jassert (childIndex < target->children.size());
  13853. target->removeChild (childIndex, 0);
  13854. }
  13855. return true;
  13856. }
  13857. int getSizeInUnits()
  13858. {
  13859. return (int) sizeof (*this); //xxx should be more accurate
  13860. }
  13861. private:
  13862. const SharedObjectPtr target, child;
  13863. const int childIndex;
  13864. const bool isDeleting;
  13865. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  13866. };
  13867. class ValueTree::MoveChildAction : public UndoableAction
  13868. {
  13869. public:
  13870. MoveChildAction (const SharedObjectPtr& parent_,
  13871. const int startIndex_, const int endIndex_)
  13872. : parent (parent_),
  13873. startIndex (startIndex_),
  13874. endIndex (endIndex_)
  13875. {
  13876. }
  13877. bool perform()
  13878. {
  13879. parent->moveChild (startIndex, endIndex, 0);
  13880. return true;
  13881. }
  13882. bool undo()
  13883. {
  13884. parent->moveChild (endIndex, startIndex, 0);
  13885. return true;
  13886. }
  13887. int getSizeInUnits()
  13888. {
  13889. return (int) sizeof (*this); //xxx should be more accurate
  13890. }
  13891. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13892. {
  13893. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13894. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13895. return new MoveChildAction (parent, startIndex, next->endIndex);
  13896. return 0;
  13897. }
  13898. private:
  13899. const SharedObjectPtr parent;
  13900. const int startIndex, endIndex;
  13901. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  13902. };
  13903. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13904. : type (type_), parent (0)
  13905. {
  13906. }
  13907. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13908. : type (other.type), properties (other.properties), parent (0)
  13909. {
  13910. for (int i = 0; i < other.children.size(); ++i)
  13911. {
  13912. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13913. child->parent = this;
  13914. children.add (child);
  13915. }
  13916. }
  13917. ValueTree::SharedObject::~SharedObject()
  13918. {
  13919. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13920. for (int i = children.size(); --i >= 0;)
  13921. {
  13922. const SharedObjectPtr c (children.getUnchecked(i));
  13923. c->parent = 0;
  13924. children.remove (i);
  13925. c->sendParentChangeMessage();
  13926. }
  13927. }
  13928. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13929. {
  13930. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13931. {
  13932. ValueTree* const v = valueTreesWithListeners[i];
  13933. if (v != 0)
  13934. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13935. }
  13936. }
  13937. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13938. {
  13939. ValueTree tree (this);
  13940. ValueTree::SharedObject* t = this;
  13941. while (t != 0)
  13942. {
  13943. t->sendPropertyChangeMessage (tree, property);
  13944. t = t->parent;
  13945. }
  13946. }
  13947. void ValueTree::SharedObject::sendChildAddedMessage (ValueTree& tree, ValueTree& child)
  13948. {
  13949. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13950. {
  13951. ValueTree* const v = valueTreesWithListeners[i];
  13952. if (v != 0)
  13953. v->listeners.call (&ValueTree::Listener::valueTreeChildAdded, tree, child);
  13954. }
  13955. }
  13956. void ValueTree::SharedObject::sendChildAddedMessage (ValueTree child)
  13957. {
  13958. ValueTree tree (this);
  13959. ValueTree::SharedObject* t = this;
  13960. while (t != 0)
  13961. {
  13962. t->sendChildAddedMessage (tree, child);
  13963. t = t->parent;
  13964. }
  13965. }
  13966. void ValueTree::SharedObject::sendChildRemovedMessage (ValueTree& tree, ValueTree& child)
  13967. {
  13968. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13969. {
  13970. ValueTree* const v = valueTreesWithListeners[i];
  13971. if (v != 0)
  13972. v->listeners.call (&ValueTree::Listener::valueTreeChildRemoved, tree, child);
  13973. }
  13974. }
  13975. void ValueTree::SharedObject::sendChildRemovedMessage (ValueTree child)
  13976. {
  13977. ValueTree tree (this);
  13978. ValueTree::SharedObject* t = this;
  13979. while (t != 0)
  13980. {
  13981. t->sendChildRemovedMessage (tree, child);
  13982. t = t->parent;
  13983. }
  13984. }
  13985. void ValueTree::SharedObject::sendChildOrderChangedMessage (ValueTree& tree)
  13986. {
  13987. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13988. {
  13989. ValueTree* const v = valueTreesWithListeners[i];
  13990. if (v != 0)
  13991. v->listeners.call (&ValueTree::Listener::valueTreeChildOrderChanged, tree);
  13992. }
  13993. }
  13994. void ValueTree::SharedObject::sendChildOrderChangedMessage()
  13995. {
  13996. ValueTree tree (this);
  13997. ValueTree::SharedObject* t = this;
  13998. while (t != 0)
  13999. {
  14000. t->sendChildOrderChangedMessage (tree);
  14001. t = t->parent;
  14002. }
  14003. }
  14004. void ValueTree::SharedObject::sendParentChangeMessage()
  14005. {
  14006. ValueTree tree (this);
  14007. int i;
  14008. for (i = children.size(); --i >= 0;)
  14009. {
  14010. SharedObject* const t = children[i];
  14011. if (t != 0)
  14012. t->sendParentChangeMessage();
  14013. }
  14014. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14015. {
  14016. ValueTree* const v = valueTreesWithListeners[i];
  14017. if (v != 0)
  14018. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14019. }
  14020. }
  14021. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14022. {
  14023. return properties [name];
  14024. }
  14025. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14026. {
  14027. return properties.getWithDefault (name, defaultReturnValue);
  14028. }
  14029. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14030. {
  14031. if (undoManager == 0)
  14032. {
  14033. if (properties.set (name, newValue))
  14034. sendPropertyChangeMessage (name);
  14035. }
  14036. else
  14037. {
  14038. var* const existingValue = properties.getVarPointer (name);
  14039. if (existingValue != 0)
  14040. {
  14041. if (*existingValue != newValue)
  14042. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14043. }
  14044. else
  14045. {
  14046. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14047. }
  14048. }
  14049. }
  14050. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14051. {
  14052. return properties.contains (name);
  14053. }
  14054. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14055. {
  14056. if (undoManager == 0)
  14057. {
  14058. if (properties.remove (name))
  14059. sendPropertyChangeMessage (name);
  14060. }
  14061. else
  14062. {
  14063. if (properties.contains (name))
  14064. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14065. }
  14066. }
  14067. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14068. {
  14069. if (undoManager == 0)
  14070. {
  14071. while (properties.size() > 0)
  14072. {
  14073. const Identifier name (properties.getName (properties.size() - 1));
  14074. properties.remove (name);
  14075. sendPropertyChangeMessage (name);
  14076. }
  14077. }
  14078. else
  14079. {
  14080. for (int i = properties.size(); --i >= 0;)
  14081. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14082. }
  14083. }
  14084. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14085. {
  14086. for (int i = 0; i < children.size(); ++i)
  14087. if (children.getUnchecked(i)->type == typeToMatch)
  14088. return ValueTree (children.getUnchecked(i).getObject());
  14089. return ValueTree::invalid;
  14090. }
  14091. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14092. {
  14093. for (int i = 0; i < children.size(); ++i)
  14094. if (children.getUnchecked(i)->type == typeToMatch)
  14095. return ValueTree (children.getUnchecked(i).getObject());
  14096. SharedObject* const newObject = new SharedObject (typeToMatch);
  14097. addChild (newObject, -1, undoManager);
  14098. return ValueTree (newObject);
  14099. }
  14100. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14101. {
  14102. for (int i = 0; i < children.size(); ++i)
  14103. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14104. return ValueTree (children.getUnchecked(i).getObject());
  14105. return ValueTree::invalid;
  14106. }
  14107. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14108. {
  14109. const SharedObject* p = parent;
  14110. while (p != 0)
  14111. {
  14112. if (p == possibleParent)
  14113. return true;
  14114. p = p->parent;
  14115. }
  14116. return false;
  14117. }
  14118. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14119. {
  14120. return children.indexOf (child.object);
  14121. }
  14122. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14123. {
  14124. if (child != 0 && child->parent != this)
  14125. {
  14126. if (child != this && ! isAChildOf (child))
  14127. {
  14128. // You should always make sure that a child is removed from its previous parent before
  14129. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14130. // undomanager should be used when removing it from its current parent..
  14131. jassert (child->parent == 0);
  14132. if (child->parent != 0)
  14133. {
  14134. jassert (child->parent->children.indexOf (child) >= 0);
  14135. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14136. }
  14137. if (undoManager == 0)
  14138. {
  14139. children.insert (index, child);
  14140. child->parent = this;
  14141. sendChildAddedMessage (ValueTree (child));
  14142. child->sendParentChangeMessage();
  14143. }
  14144. else
  14145. {
  14146. if (index < 0)
  14147. index = children.size();
  14148. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14149. }
  14150. }
  14151. else
  14152. {
  14153. // You're attempting to create a recursive loop! A node
  14154. // can't be a child of one of its own children!
  14155. jassertfalse;
  14156. }
  14157. }
  14158. }
  14159. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14160. {
  14161. const SharedObjectPtr child (children [childIndex]);
  14162. if (child != 0)
  14163. {
  14164. if (undoManager == 0)
  14165. {
  14166. children.remove (childIndex);
  14167. child->parent = 0;
  14168. sendChildRemovedMessage (ValueTree (child));
  14169. child->sendParentChangeMessage();
  14170. }
  14171. else
  14172. {
  14173. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14174. }
  14175. }
  14176. }
  14177. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14178. {
  14179. while (children.size() > 0)
  14180. removeChild (children.size() - 1, undoManager);
  14181. }
  14182. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14183. {
  14184. // The source index must be a valid index!
  14185. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14186. if (currentIndex != newIndex
  14187. && isPositiveAndBelow (currentIndex, children.size()))
  14188. {
  14189. if (undoManager == 0)
  14190. {
  14191. children.move (currentIndex, newIndex);
  14192. sendChildOrderChangedMessage();
  14193. }
  14194. else
  14195. {
  14196. if (! isPositiveAndBelow (newIndex, children.size()))
  14197. newIndex = children.size() - 1;
  14198. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14199. }
  14200. }
  14201. }
  14202. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14203. {
  14204. jassert (newOrder.size() == children.size());
  14205. if (undoManager == 0)
  14206. {
  14207. children = newOrder;
  14208. sendChildOrderChangedMessage();
  14209. }
  14210. else
  14211. {
  14212. for (int i = 0; i < children.size(); ++i)
  14213. {
  14214. const SharedObjectPtr child (newOrder.getUnchecked(i));
  14215. if (children.getUnchecked(i) != child)
  14216. {
  14217. const int oldIndex = children.indexOf (child);
  14218. jassert (oldIndex >= 0);
  14219. moveChild (oldIndex, i, undoManager);
  14220. }
  14221. }
  14222. }
  14223. }
  14224. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14225. {
  14226. if (type != other.type
  14227. || properties.size() != other.properties.size()
  14228. || children.size() != other.children.size()
  14229. || properties != other.properties)
  14230. return false;
  14231. for (int i = 0; i < children.size(); ++i)
  14232. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14233. return false;
  14234. return true;
  14235. }
  14236. ValueTree::ValueTree() throw()
  14237. : object (0)
  14238. {
  14239. }
  14240. const ValueTree ValueTree::invalid;
  14241. ValueTree::ValueTree (const Identifier& type_)
  14242. : object (new ValueTree::SharedObject (type_))
  14243. {
  14244. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14245. }
  14246. ValueTree::ValueTree (SharedObject* const object_)
  14247. : object (object_)
  14248. {
  14249. }
  14250. ValueTree::ValueTree (const ValueTree& other)
  14251. : object (other.object)
  14252. {
  14253. }
  14254. ValueTree& ValueTree::operator= (const ValueTree& other)
  14255. {
  14256. if (listeners.size() > 0)
  14257. {
  14258. if (object != 0)
  14259. object->valueTreesWithListeners.removeValue (this);
  14260. if (other.object != 0)
  14261. other.object->valueTreesWithListeners.add (this);
  14262. }
  14263. object = other.object;
  14264. return *this;
  14265. }
  14266. ValueTree::~ValueTree()
  14267. {
  14268. if (listeners.size() > 0 && object != 0)
  14269. object->valueTreesWithListeners.removeValue (this);
  14270. }
  14271. bool ValueTree::operator== (const ValueTree& other) const throw()
  14272. {
  14273. return object == other.object;
  14274. }
  14275. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14276. {
  14277. return object != other.object;
  14278. }
  14279. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14280. {
  14281. return object == other.object
  14282. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14283. }
  14284. ValueTree ValueTree::createCopy() const
  14285. {
  14286. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14287. }
  14288. bool ValueTree::hasType (const Identifier& typeName) const
  14289. {
  14290. return object != 0 && object->type == typeName;
  14291. }
  14292. const Identifier ValueTree::getType() const
  14293. {
  14294. return object != 0 ? object->type : Identifier();
  14295. }
  14296. ValueTree ValueTree::getParent() const
  14297. {
  14298. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14299. }
  14300. ValueTree ValueTree::getSibling (const int delta) const
  14301. {
  14302. if (object == 0 || object->parent == 0)
  14303. return invalid;
  14304. const int index = object->parent->indexOf (*this) + delta;
  14305. return ValueTree (object->parent->children [index].getObject());
  14306. }
  14307. const var& ValueTree::operator[] (const Identifier& name) const
  14308. {
  14309. return object == 0 ? var::null : object->getProperty (name);
  14310. }
  14311. const var& ValueTree::getProperty (const Identifier& name) const
  14312. {
  14313. return object == 0 ? var::null : object->getProperty (name);
  14314. }
  14315. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14316. {
  14317. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14318. }
  14319. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14320. {
  14321. jassert (name.toString().isNotEmpty());
  14322. if (object != 0 && name.toString().isNotEmpty())
  14323. object->setProperty (name, newValue, undoManager);
  14324. }
  14325. bool ValueTree::hasProperty (const Identifier& name) const
  14326. {
  14327. return object != 0 && object->hasProperty (name);
  14328. }
  14329. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14330. {
  14331. if (object != 0)
  14332. object->removeProperty (name, undoManager);
  14333. }
  14334. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14335. {
  14336. if (object != 0)
  14337. object->removeAllProperties (undoManager);
  14338. }
  14339. int ValueTree::getNumProperties() const
  14340. {
  14341. return object == 0 ? 0 : object->properties.size();
  14342. }
  14343. const Identifier ValueTree::getPropertyName (const int index) const
  14344. {
  14345. return object == 0 ? Identifier()
  14346. : object->properties.getName (index);
  14347. }
  14348. class ValueTreePropertyValueSource : public Value::ValueSource,
  14349. public ValueTree::Listener
  14350. {
  14351. public:
  14352. ValueTreePropertyValueSource (const ValueTree& tree_,
  14353. const Identifier& property_,
  14354. UndoManager* const undoManager_)
  14355. : tree (tree_),
  14356. property (property_),
  14357. undoManager (undoManager_)
  14358. {
  14359. tree.addListener (this);
  14360. }
  14361. ~ValueTreePropertyValueSource()
  14362. {
  14363. tree.removeListener (this);
  14364. }
  14365. const var getValue() const
  14366. {
  14367. return tree [property];
  14368. }
  14369. void setValue (const var& newValue)
  14370. {
  14371. tree.setProperty (property, newValue, undoManager);
  14372. }
  14373. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14374. {
  14375. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14376. sendChangeMessage (false);
  14377. }
  14378. void valueTreeChildAdded (ValueTree&, ValueTree&) {}
  14379. void valueTreeChildRemoved (ValueTree&, ValueTree&) {}
  14380. void valueTreeChildOrderChanged (ValueTree&) {}
  14381. void valueTreeParentChanged (ValueTree&) {}
  14382. private:
  14383. ValueTree tree;
  14384. const Identifier property;
  14385. UndoManager* const undoManager;
  14386. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14387. };
  14388. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14389. {
  14390. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14391. }
  14392. int ValueTree::getNumChildren() const
  14393. {
  14394. return object == 0 ? 0 : object->children.size();
  14395. }
  14396. ValueTree ValueTree::getChild (int index) const
  14397. {
  14398. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14399. }
  14400. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14401. {
  14402. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14403. }
  14404. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14405. {
  14406. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14407. }
  14408. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14409. {
  14410. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14411. }
  14412. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14413. {
  14414. return object != 0 && object->isAChildOf (possibleParent.object);
  14415. }
  14416. int ValueTree::indexOf (const ValueTree& child) const
  14417. {
  14418. return object != 0 ? object->indexOf (child) : -1;
  14419. }
  14420. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14421. {
  14422. if (object != 0)
  14423. object->addChild (child.object, index, undoManager);
  14424. }
  14425. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14426. {
  14427. if (object != 0)
  14428. object->removeChild (childIndex, undoManager);
  14429. }
  14430. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14431. {
  14432. if (object != 0)
  14433. object->removeChild (object->children.indexOf (child.object), undoManager);
  14434. }
  14435. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14436. {
  14437. if (object != 0)
  14438. object->removeAllChildren (undoManager);
  14439. }
  14440. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14441. {
  14442. if (object != 0)
  14443. object->moveChild (currentIndex, newIndex, undoManager);
  14444. }
  14445. void ValueTree::addListener (Listener* listener)
  14446. {
  14447. if (listener != 0)
  14448. {
  14449. if (listeners.size() == 0 && object != 0)
  14450. object->valueTreesWithListeners.add (this);
  14451. listeners.add (listener);
  14452. }
  14453. }
  14454. void ValueTree::removeListener (Listener* listener)
  14455. {
  14456. listeners.remove (listener);
  14457. if (listeners.size() == 0 && object != 0)
  14458. object->valueTreesWithListeners.removeValue (this);
  14459. }
  14460. XmlElement* ValueTree::SharedObject::createXml() const
  14461. {
  14462. XmlElement* const xml = new XmlElement (type.toString());
  14463. properties.copyToXmlAttributes (*xml);
  14464. for (int i = 0; i < children.size(); ++i)
  14465. xml->addChildElement (children.getUnchecked(i)->createXml());
  14466. return xml;
  14467. }
  14468. XmlElement* ValueTree::createXml() const
  14469. {
  14470. return object != 0 ? object->createXml() : 0;
  14471. }
  14472. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14473. {
  14474. ValueTree v (xml.getTagName());
  14475. v.object->properties.setFromXmlAttributes (xml);
  14476. forEachXmlChildElement (xml, e)
  14477. v.addChild (fromXml (*e), -1, 0);
  14478. return v;
  14479. }
  14480. void ValueTree::writeToStream (OutputStream& output)
  14481. {
  14482. output.writeString (getType().toString());
  14483. const int numProps = getNumProperties();
  14484. output.writeCompressedInt (numProps);
  14485. int i;
  14486. for (i = 0; i < numProps; ++i)
  14487. {
  14488. const Identifier name (getPropertyName(i));
  14489. output.writeString (name.toString());
  14490. getProperty(name).writeToStream (output);
  14491. }
  14492. const int numChildren = getNumChildren();
  14493. output.writeCompressedInt (numChildren);
  14494. for (i = 0; i < numChildren; ++i)
  14495. getChild (i).writeToStream (output);
  14496. }
  14497. ValueTree ValueTree::readFromStream (InputStream& input)
  14498. {
  14499. const String type (input.readString());
  14500. if (type.isEmpty())
  14501. return ValueTree::invalid;
  14502. ValueTree v (type);
  14503. const int numProps = input.readCompressedInt();
  14504. if (numProps < 0)
  14505. {
  14506. jassertfalse; // trying to read corrupted data!
  14507. return v;
  14508. }
  14509. int i;
  14510. for (i = 0; i < numProps; ++i)
  14511. {
  14512. const String name (input.readString());
  14513. jassert (name.isNotEmpty());
  14514. const var value (var::readFromStream (input));
  14515. v.object->properties.set (name, value);
  14516. }
  14517. const int numChildren = input.readCompressedInt();
  14518. for (i = 0; i < numChildren; ++i)
  14519. {
  14520. ValueTree child (readFromStream (input));
  14521. v.object->children.add (child.object);
  14522. child.object->parent = v.object;
  14523. }
  14524. return v;
  14525. }
  14526. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14527. {
  14528. MemoryInputStream in (data, numBytes, false);
  14529. return readFromStream (in);
  14530. }
  14531. END_JUCE_NAMESPACE
  14532. /*** End of inlined file: juce_ValueTree.cpp ***/
  14533. /*** Start of inlined file: juce_Value.cpp ***/
  14534. BEGIN_JUCE_NAMESPACE
  14535. Value::ValueSource::ValueSource()
  14536. {
  14537. }
  14538. Value::ValueSource::~ValueSource()
  14539. {
  14540. }
  14541. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14542. {
  14543. if (synchronous)
  14544. {
  14545. for (int i = valuesWithListeners.size(); --i >= 0;)
  14546. {
  14547. Value* const v = valuesWithListeners[i];
  14548. if (v != 0)
  14549. v->callListeners();
  14550. }
  14551. }
  14552. else
  14553. {
  14554. triggerAsyncUpdate();
  14555. }
  14556. }
  14557. void Value::ValueSource::handleAsyncUpdate()
  14558. {
  14559. sendChangeMessage (true);
  14560. }
  14561. class SimpleValueSource : public Value::ValueSource
  14562. {
  14563. public:
  14564. SimpleValueSource()
  14565. {
  14566. }
  14567. SimpleValueSource (const var& initialValue)
  14568. : value (initialValue)
  14569. {
  14570. }
  14571. const var getValue() const
  14572. {
  14573. return value;
  14574. }
  14575. void setValue (const var& newValue)
  14576. {
  14577. if (! newValue.equalsWithSameType (value))
  14578. {
  14579. value = newValue;
  14580. sendChangeMessage (false);
  14581. }
  14582. }
  14583. private:
  14584. var value;
  14585. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  14586. };
  14587. Value::Value()
  14588. : value (new SimpleValueSource())
  14589. {
  14590. }
  14591. Value::Value (ValueSource* const value_)
  14592. : value (value_)
  14593. {
  14594. jassert (value_ != 0);
  14595. }
  14596. Value::Value (const var& initialValue)
  14597. : value (new SimpleValueSource (initialValue))
  14598. {
  14599. }
  14600. Value::Value (const Value& other)
  14601. : value (other.value)
  14602. {
  14603. }
  14604. Value& Value::operator= (const Value& other)
  14605. {
  14606. value = other.value;
  14607. return *this;
  14608. }
  14609. Value::~Value()
  14610. {
  14611. if (listeners.size() > 0)
  14612. value->valuesWithListeners.removeValue (this);
  14613. }
  14614. const var Value::getValue() const
  14615. {
  14616. return value->getValue();
  14617. }
  14618. Value::operator const var() const
  14619. {
  14620. return getValue();
  14621. }
  14622. void Value::setValue (const var& newValue)
  14623. {
  14624. value->setValue (newValue);
  14625. }
  14626. const String Value::toString() const
  14627. {
  14628. return value->getValue().toString();
  14629. }
  14630. Value& Value::operator= (const var& newValue)
  14631. {
  14632. value->setValue (newValue);
  14633. return *this;
  14634. }
  14635. void Value::referTo (const Value& valueToReferTo)
  14636. {
  14637. if (valueToReferTo.value != value)
  14638. {
  14639. if (listeners.size() > 0)
  14640. {
  14641. value->valuesWithListeners.removeValue (this);
  14642. valueToReferTo.value->valuesWithListeners.add (this);
  14643. }
  14644. value = valueToReferTo.value;
  14645. callListeners();
  14646. }
  14647. }
  14648. bool Value::refersToSameSourceAs (const Value& other) const
  14649. {
  14650. return value == other.value;
  14651. }
  14652. bool Value::operator== (const Value& other) const
  14653. {
  14654. return value == other.value || value->getValue() == other.getValue();
  14655. }
  14656. bool Value::operator!= (const Value& other) const
  14657. {
  14658. return value != other.value && value->getValue() != other.getValue();
  14659. }
  14660. void Value::addListener (ValueListener* const listener)
  14661. {
  14662. if (listener != 0)
  14663. {
  14664. if (listeners.size() == 0)
  14665. value->valuesWithListeners.add (this);
  14666. listeners.add (listener);
  14667. }
  14668. }
  14669. void Value::removeListener (ValueListener* const listener)
  14670. {
  14671. listeners.remove (listener);
  14672. if (listeners.size() == 0)
  14673. value->valuesWithListeners.removeValue (this);
  14674. }
  14675. void Value::callListeners()
  14676. {
  14677. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14678. listeners.call (&ValueListener::valueChanged, v);
  14679. }
  14680. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14681. {
  14682. return stream << value.toString();
  14683. }
  14684. END_JUCE_NAMESPACE
  14685. /*** End of inlined file: juce_Value.cpp ***/
  14686. /*** Start of inlined file: juce_Application.cpp ***/
  14687. BEGIN_JUCE_NAMESPACE
  14688. #if JUCE_MAC
  14689. extern void juce_initialiseMacMainMenu();
  14690. #endif
  14691. JUCEApplication::JUCEApplication()
  14692. : appReturnValue (0),
  14693. stillInitialising (true)
  14694. {
  14695. jassert (isStandaloneApp() && appInstance == 0);
  14696. appInstance = this;
  14697. }
  14698. JUCEApplication::~JUCEApplication()
  14699. {
  14700. if (appLock != 0)
  14701. {
  14702. appLock->exit();
  14703. appLock = 0;
  14704. }
  14705. jassert (appInstance == this);
  14706. appInstance = 0;
  14707. }
  14708. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  14709. JUCEApplication* JUCEApplication::appInstance = 0;
  14710. bool JUCEApplication::moreThanOneInstanceAllowed()
  14711. {
  14712. return true;
  14713. }
  14714. void JUCEApplication::anotherInstanceStarted (const String&)
  14715. {
  14716. }
  14717. void JUCEApplication::systemRequestedQuit()
  14718. {
  14719. quit();
  14720. }
  14721. void JUCEApplication::quit()
  14722. {
  14723. MessageManager::getInstance()->stopDispatchLoop();
  14724. }
  14725. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  14726. {
  14727. appReturnValue = newReturnValue;
  14728. }
  14729. void JUCEApplication::actionListenerCallback (const String& message)
  14730. {
  14731. if (message.startsWith (getApplicationName() + "/"))
  14732. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  14733. }
  14734. void JUCEApplication::unhandledException (const std::exception*,
  14735. const String&,
  14736. const int)
  14737. {
  14738. jassertfalse;
  14739. }
  14740. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  14741. const char* const sourceFile,
  14742. const int lineNumber)
  14743. {
  14744. if (appInstance != 0)
  14745. appInstance->unhandledException (e, sourceFile, lineNumber);
  14746. }
  14747. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  14748. {
  14749. return 0;
  14750. }
  14751. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  14752. {
  14753. commands.add (StandardApplicationCommandIDs::quit);
  14754. }
  14755. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  14756. {
  14757. if (commandID == StandardApplicationCommandIDs::quit)
  14758. {
  14759. result.setInfo (TRANS("Quit"),
  14760. TRANS("Quits the application"),
  14761. "Application",
  14762. 0);
  14763. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  14764. }
  14765. }
  14766. bool JUCEApplication::perform (const InvocationInfo& info)
  14767. {
  14768. if (info.commandID == StandardApplicationCommandIDs::quit)
  14769. {
  14770. systemRequestedQuit();
  14771. return true;
  14772. }
  14773. return false;
  14774. }
  14775. bool JUCEApplication::initialiseApp (const String& commandLine)
  14776. {
  14777. commandLineParameters = commandLine.trim();
  14778. #if ! JUCE_IOS
  14779. jassert (appLock == 0); // initialiseApp must only be called once!
  14780. if (! moreThanOneInstanceAllowed())
  14781. {
  14782. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  14783. if (! appLock->enter(0))
  14784. {
  14785. appLock = 0;
  14786. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  14787. DBG ("Another instance is running - quitting...");
  14788. return false;
  14789. }
  14790. }
  14791. #endif
  14792. // let the app do its setting-up..
  14793. initialise (commandLineParameters);
  14794. #if JUCE_MAC
  14795. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  14796. #endif
  14797. // register for broadcast new app messages
  14798. MessageManager::getInstance()->registerBroadcastListener (this);
  14799. stillInitialising = false;
  14800. return true;
  14801. }
  14802. int JUCEApplication::shutdownApp()
  14803. {
  14804. jassert (appInstance == this);
  14805. MessageManager::getInstance()->deregisterBroadcastListener (this);
  14806. JUCE_TRY
  14807. {
  14808. // give the app a chance to clean up..
  14809. shutdown();
  14810. }
  14811. JUCE_CATCH_EXCEPTION
  14812. return getApplicationReturnValue();
  14813. }
  14814. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  14815. void JUCEApplication::appWillTerminateByForce()
  14816. {
  14817. {
  14818. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  14819. if (app != 0)
  14820. app->shutdownApp();
  14821. }
  14822. shutdownJuce_GUI();
  14823. }
  14824. #if ! JUCE_ANDROID
  14825. int JUCEApplication::main (const String& commandLine)
  14826. {
  14827. ScopedJuceInitialiser_GUI libraryInitialiser;
  14828. jassert (createInstance != 0);
  14829. int returnCode = 0;
  14830. {
  14831. const ScopedPointer<JUCEApplication> app (createInstance());
  14832. if (! app->initialiseApp (commandLine))
  14833. return 0;
  14834. JUCE_TRY
  14835. {
  14836. // loop until a quit message is received..
  14837. MessageManager::getInstance()->runDispatchLoop();
  14838. }
  14839. JUCE_CATCH_EXCEPTION
  14840. returnCode = app->shutdownApp();
  14841. }
  14842. return returnCode;
  14843. }
  14844. #if JUCE_IOS
  14845. extern int juce_iOSMain (int argc, const char* argv[]);
  14846. #endif
  14847. #if ! JUCE_WINDOWS
  14848. extern const char* juce_Argv0;
  14849. #endif
  14850. int JUCEApplication::main (int argc, const char* argv[])
  14851. {
  14852. JUCE_AUTORELEASEPOOL
  14853. #if ! JUCE_WINDOWS
  14854. jassert (createInstance != 0);
  14855. juce_Argv0 = argv[0];
  14856. #endif
  14857. #if JUCE_IOS
  14858. return juce_iOSMain (argc, argv);
  14859. #else
  14860. String cmd;
  14861. for (int i = 1; i < argc; ++i)
  14862. cmd << argv[i] << ' ';
  14863. return JUCEApplication::main (cmd);
  14864. #endif
  14865. }
  14866. #endif
  14867. END_JUCE_NAMESPACE
  14868. /*** End of inlined file: juce_Application.cpp ***/
  14869. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14870. BEGIN_JUCE_NAMESPACE
  14871. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14872. : commandID (commandID_),
  14873. flags (0)
  14874. {
  14875. }
  14876. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14877. const String& description_,
  14878. const String& categoryName_,
  14879. const int flags_) throw()
  14880. {
  14881. shortName = shortName_;
  14882. description = description_;
  14883. categoryName = categoryName_;
  14884. flags = flags_;
  14885. }
  14886. void ApplicationCommandInfo::setActive (const bool b) throw()
  14887. {
  14888. if (b)
  14889. flags &= ~isDisabled;
  14890. else
  14891. flags |= isDisabled;
  14892. }
  14893. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14894. {
  14895. if (b)
  14896. flags |= isTicked;
  14897. else
  14898. flags &= ~isTicked;
  14899. }
  14900. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14901. {
  14902. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14903. }
  14904. END_JUCE_NAMESPACE
  14905. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14906. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14907. BEGIN_JUCE_NAMESPACE
  14908. ApplicationCommandManager::ApplicationCommandManager()
  14909. : firstTarget (0)
  14910. {
  14911. keyMappings = new KeyPressMappingSet (this);
  14912. Desktop::getInstance().addFocusChangeListener (this);
  14913. }
  14914. ApplicationCommandManager::~ApplicationCommandManager()
  14915. {
  14916. Desktop::getInstance().removeFocusChangeListener (this);
  14917. keyMappings = 0;
  14918. }
  14919. void ApplicationCommandManager::clearCommands()
  14920. {
  14921. commands.clear();
  14922. keyMappings->clearAllKeyPresses();
  14923. triggerAsyncUpdate();
  14924. }
  14925. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14926. {
  14927. // zero isn't a valid command ID!
  14928. jassert (newCommand.commandID != 0);
  14929. // the name isn't optional!
  14930. jassert (newCommand.shortName.isNotEmpty());
  14931. if (getCommandForID (newCommand.commandID) == 0)
  14932. {
  14933. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14934. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14935. commands.add (newInfo);
  14936. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14937. triggerAsyncUpdate();
  14938. }
  14939. else
  14940. {
  14941. // trying to re-register the same command with different parameters?
  14942. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14943. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14944. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14945. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14946. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14947. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14948. }
  14949. }
  14950. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14951. {
  14952. if (target != 0)
  14953. {
  14954. Array <CommandID> commandIDs;
  14955. target->getAllCommands (commandIDs);
  14956. for (int i = 0; i < commandIDs.size(); ++i)
  14957. {
  14958. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14959. target->getCommandInfo (info.commandID, info);
  14960. registerCommand (info);
  14961. }
  14962. }
  14963. }
  14964. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14965. {
  14966. for (int i = commands.size(); --i >= 0;)
  14967. {
  14968. if (commands.getUnchecked (i)->commandID == commandID)
  14969. {
  14970. commands.remove (i);
  14971. triggerAsyncUpdate();
  14972. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14973. for (int j = keys.size(); --j >= 0;)
  14974. keyMappings->removeKeyPress (keys.getReference (j));
  14975. }
  14976. }
  14977. }
  14978. void ApplicationCommandManager::commandStatusChanged()
  14979. {
  14980. triggerAsyncUpdate();
  14981. }
  14982. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14983. {
  14984. for (int i = commands.size(); --i >= 0;)
  14985. if (commands.getUnchecked(i)->commandID == commandID)
  14986. return commands.getUnchecked(i);
  14987. return 0;
  14988. }
  14989. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14990. {
  14991. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14992. return (ci != 0) ? ci->shortName : String::empty;
  14993. }
  14994. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14995. {
  14996. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14997. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14998. : String::empty;
  14999. }
  15000. const StringArray ApplicationCommandManager::getCommandCategories() const
  15001. {
  15002. StringArray s;
  15003. for (int i = 0; i < commands.size(); ++i)
  15004. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15005. return s;
  15006. }
  15007. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15008. {
  15009. Array <CommandID> results;
  15010. for (int i = 0; i < commands.size(); ++i)
  15011. if (commands.getUnchecked(i)->categoryName == categoryName)
  15012. results.add (commands.getUnchecked(i)->commandID);
  15013. return results;
  15014. }
  15015. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15016. {
  15017. ApplicationCommandTarget::InvocationInfo info (commandID);
  15018. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15019. return invoke (info, asynchronously);
  15020. }
  15021. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15022. {
  15023. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15024. // manager first..
  15025. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15026. ApplicationCommandInfo commandInfo (0);
  15027. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15028. if (target == 0)
  15029. return false;
  15030. ApplicationCommandTarget::InvocationInfo info (info_);
  15031. info.commandFlags = commandInfo.flags;
  15032. sendListenerInvokeCallback (info);
  15033. const bool ok = target->invoke (info, asynchronously);
  15034. commandStatusChanged();
  15035. return ok;
  15036. }
  15037. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15038. {
  15039. return firstTarget != 0 ? firstTarget
  15040. : findDefaultComponentTarget();
  15041. }
  15042. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15043. {
  15044. firstTarget = newTarget;
  15045. }
  15046. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15047. ApplicationCommandInfo& upToDateInfo)
  15048. {
  15049. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15050. if (target == 0)
  15051. target = JUCEApplication::getInstance();
  15052. if (target != 0)
  15053. target = target->getTargetForCommand (commandID);
  15054. if (target != 0)
  15055. target->getCommandInfo (commandID, upToDateInfo);
  15056. return target;
  15057. }
  15058. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15059. {
  15060. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15061. if (target == 0 && c != 0)
  15062. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15063. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15064. return target;
  15065. }
  15066. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15067. {
  15068. Component* c = Component::getCurrentlyFocusedComponent();
  15069. if (c == 0)
  15070. {
  15071. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15072. if (activeWindow != 0)
  15073. {
  15074. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15075. if (c == 0)
  15076. c = activeWindow;
  15077. }
  15078. }
  15079. if (c == 0 && Process::isForegroundProcess())
  15080. {
  15081. // getting a bit desperate now - try all desktop comps..
  15082. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15083. {
  15084. ApplicationCommandTarget* const target
  15085. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15086. ->getPeer()->getLastFocusedSubcomponent());
  15087. if (target != 0)
  15088. return target;
  15089. }
  15090. }
  15091. if (c != 0)
  15092. {
  15093. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15094. // if we're focused on a ResizableWindow, chances are that it's the content
  15095. // component that really should get the event. And if not, the event will
  15096. // still be passed up to the top level window anyway, so let's send it to the
  15097. // content comp.
  15098. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15099. c = resizableWindow->getContentComponent();
  15100. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15101. if (target != 0)
  15102. return target;
  15103. }
  15104. return JUCEApplication::getInstance();
  15105. }
  15106. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15107. {
  15108. listeners.add (listener);
  15109. }
  15110. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15111. {
  15112. listeners.remove (listener);
  15113. }
  15114. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15115. {
  15116. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15117. }
  15118. void ApplicationCommandManager::handleAsyncUpdate()
  15119. {
  15120. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15121. }
  15122. void ApplicationCommandManager::globalFocusChanged (Component*)
  15123. {
  15124. commandStatusChanged();
  15125. }
  15126. END_JUCE_NAMESPACE
  15127. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15128. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15129. BEGIN_JUCE_NAMESPACE
  15130. ApplicationCommandTarget::ApplicationCommandTarget()
  15131. {
  15132. }
  15133. ApplicationCommandTarget::~ApplicationCommandTarget()
  15134. {
  15135. messageInvoker = 0;
  15136. }
  15137. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15138. {
  15139. if (isCommandActive (info.commandID))
  15140. {
  15141. if (async)
  15142. {
  15143. if (messageInvoker == 0)
  15144. messageInvoker = new CommandTargetMessageInvoker (this);
  15145. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15146. return true;
  15147. }
  15148. else
  15149. {
  15150. const bool success = perform (info);
  15151. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15152. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15153. // returns the command's info.
  15154. return success;
  15155. }
  15156. }
  15157. return false;
  15158. }
  15159. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15160. {
  15161. Component* c = dynamic_cast <Component*> (this);
  15162. if (c != 0)
  15163. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15164. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15165. return 0;
  15166. }
  15167. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15168. {
  15169. ApplicationCommandTarget* target = this;
  15170. int depth = 0;
  15171. while (target != 0)
  15172. {
  15173. Array <CommandID> commandIDs;
  15174. target->getAllCommands (commandIDs);
  15175. if (commandIDs.contains (commandID))
  15176. return target;
  15177. target = target->getNextCommandTarget();
  15178. ++depth;
  15179. jassert (depth < 100); // could be a recursive command chain??
  15180. jassert (target != this); // definitely a recursive command chain!
  15181. if (depth > 100 || target == this)
  15182. break;
  15183. }
  15184. if (target == 0)
  15185. {
  15186. target = JUCEApplication::getInstance();
  15187. if (target != 0)
  15188. {
  15189. Array <CommandID> commandIDs;
  15190. target->getAllCommands (commandIDs);
  15191. if (commandIDs.contains (commandID))
  15192. return target;
  15193. }
  15194. }
  15195. return 0;
  15196. }
  15197. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15198. {
  15199. ApplicationCommandInfo info (commandID);
  15200. info.flags = ApplicationCommandInfo::isDisabled;
  15201. getCommandInfo (commandID, info);
  15202. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15203. }
  15204. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15205. {
  15206. ApplicationCommandTarget* target = this;
  15207. int depth = 0;
  15208. while (target != 0)
  15209. {
  15210. if (target->tryToInvoke (info, async))
  15211. return true;
  15212. target = target->getNextCommandTarget();
  15213. ++depth;
  15214. jassert (depth < 100); // could be a recursive command chain??
  15215. jassert (target != this); // definitely a recursive command chain!
  15216. if (depth > 100 || target == this)
  15217. break;
  15218. }
  15219. if (target == 0)
  15220. {
  15221. target = JUCEApplication::getInstance();
  15222. if (target != 0)
  15223. return target->tryToInvoke (info, async);
  15224. }
  15225. return false;
  15226. }
  15227. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15228. {
  15229. ApplicationCommandTarget::InvocationInfo info (commandID);
  15230. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15231. return invoke (info, asynchronously);
  15232. }
  15233. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15234. : commandID (commandID_),
  15235. commandFlags (0),
  15236. invocationMethod (direct),
  15237. originatingComponent (0),
  15238. isKeyDown (false),
  15239. millisecsSinceKeyPressed (0)
  15240. {
  15241. }
  15242. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15243. : owner (owner_)
  15244. {
  15245. }
  15246. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15247. {
  15248. }
  15249. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15250. {
  15251. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15252. owner->tryToInvoke (*info, false);
  15253. }
  15254. END_JUCE_NAMESPACE
  15255. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15256. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15257. BEGIN_JUCE_NAMESPACE
  15258. juce_ImplementSingleton (ApplicationProperties)
  15259. ApplicationProperties::ApplicationProperties()
  15260. : msBeforeSaving (3000),
  15261. options (PropertiesFile::storeAsBinary),
  15262. commonSettingsAreReadOnly (0),
  15263. processLock (0)
  15264. {
  15265. }
  15266. ApplicationProperties::~ApplicationProperties()
  15267. {
  15268. closeFiles();
  15269. clearSingletonInstance();
  15270. }
  15271. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15272. const String& fileNameSuffix,
  15273. const String& folderName_,
  15274. const int millisecondsBeforeSaving,
  15275. const int propertiesFileOptions,
  15276. InterProcessLock* processLock_)
  15277. {
  15278. appName = applicationName;
  15279. fileSuffix = fileNameSuffix;
  15280. folderName = folderName_;
  15281. msBeforeSaving = millisecondsBeforeSaving;
  15282. options = propertiesFileOptions;
  15283. processLock = processLock_;
  15284. }
  15285. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15286. const bool testCommonSettings,
  15287. const bool showWarningDialogOnFailure)
  15288. {
  15289. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15290. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15291. if (! (userOk && commonOk))
  15292. {
  15293. if (showWarningDialogOnFailure)
  15294. {
  15295. String filenames;
  15296. if (userProps != 0 && ! userOk)
  15297. filenames << '\n' << userProps->getFile().getFullPathName();
  15298. if (commonProps != 0 && ! commonOk)
  15299. filenames << '\n' << commonProps->getFile().getFullPathName();
  15300. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  15301. appName + TRANS(" - Unable to save settings"),
  15302. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15303. + appName + TRANS(" needs to be able to write to the following files:\n")
  15304. + filenames
  15305. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15306. }
  15307. return false;
  15308. }
  15309. return true;
  15310. }
  15311. void ApplicationProperties::openFiles()
  15312. {
  15313. // You need to call setStorageParameters() before trying to get hold of the
  15314. // properties!
  15315. jassert (appName.isNotEmpty());
  15316. if (appName.isNotEmpty())
  15317. {
  15318. if (userProps == 0)
  15319. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15320. false, msBeforeSaving, options, processLock);
  15321. if (commonProps == 0)
  15322. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15323. true, msBeforeSaving, options, processLock);
  15324. userProps->setFallbackPropertySet (commonProps);
  15325. }
  15326. }
  15327. PropertiesFile* ApplicationProperties::getUserSettings()
  15328. {
  15329. if (userProps == 0)
  15330. openFiles();
  15331. return userProps;
  15332. }
  15333. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15334. {
  15335. if (commonProps == 0)
  15336. openFiles();
  15337. if (returnUserPropsIfReadOnly)
  15338. {
  15339. if (commonSettingsAreReadOnly == 0)
  15340. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15341. if (commonSettingsAreReadOnly > 0)
  15342. return userProps;
  15343. }
  15344. return commonProps;
  15345. }
  15346. bool ApplicationProperties::saveIfNeeded()
  15347. {
  15348. return (userProps == 0 || userProps->saveIfNeeded())
  15349. && (commonProps == 0 || commonProps->saveIfNeeded());
  15350. }
  15351. void ApplicationProperties::closeFiles()
  15352. {
  15353. userProps = 0;
  15354. commonProps = 0;
  15355. }
  15356. END_JUCE_NAMESPACE
  15357. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15358. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15359. BEGIN_JUCE_NAMESPACE
  15360. namespace PropertyFileConstants
  15361. {
  15362. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15363. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15364. static const char* const fileTag = "PROPERTIES";
  15365. static const char* const valueTag = "VALUE";
  15366. static const char* const nameAttribute = "name";
  15367. static const char* const valueAttribute = "val";
  15368. }
  15369. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15370. const int options_, InterProcessLock* const processLock_)
  15371. : PropertySet (ignoreCaseOfKeyNames),
  15372. file (f),
  15373. timerInterval (millisecondsBeforeSaving),
  15374. options (options_),
  15375. loadedOk (false),
  15376. needsWriting (false),
  15377. processLock (processLock_)
  15378. {
  15379. // You need to correctly specify just one storage format for the file
  15380. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15381. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15382. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15383. ProcessScopedLock pl (createProcessLock());
  15384. if (pl != 0 && ! pl->isLocked())
  15385. return; // locking failure..
  15386. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15387. if (fileStream != 0)
  15388. {
  15389. int magicNumber = fileStream->readInt();
  15390. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15391. {
  15392. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15393. magicNumber = PropertyFileConstants::magicNumber;
  15394. }
  15395. if (magicNumber == PropertyFileConstants::magicNumber)
  15396. {
  15397. loadedOk = true;
  15398. BufferedInputStream in (fileStream.release(), 2048, true);
  15399. int numValues = in.readInt();
  15400. while (--numValues >= 0 && ! in.isExhausted())
  15401. {
  15402. const String key (in.readString());
  15403. const String value (in.readString());
  15404. jassert (key.isNotEmpty());
  15405. if (key.isNotEmpty())
  15406. getAllProperties().set (key, value);
  15407. }
  15408. }
  15409. else
  15410. {
  15411. // Not a binary props file - let's see if it's XML..
  15412. fileStream = 0;
  15413. XmlDocument parser (f);
  15414. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15415. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15416. {
  15417. doc = parser.getDocumentElement();
  15418. if (doc != 0)
  15419. {
  15420. loadedOk = true;
  15421. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15422. {
  15423. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15424. if (name.isNotEmpty())
  15425. {
  15426. getAllProperties().set (name,
  15427. e->getFirstChildElement() != 0
  15428. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15429. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15430. }
  15431. }
  15432. }
  15433. else
  15434. {
  15435. // must be a pretty broken XML file we're trying to parse here,
  15436. // or a sign that this object needs an InterProcessLock,
  15437. // or just a failure reading the file. This last reason is why
  15438. // we don't jassertfalse here.
  15439. }
  15440. }
  15441. }
  15442. }
  15443. else
  15444. {
  15445. loadedOk = ! f.exists();
  15446. }
  15447. }
  15448. PropertiesFile::~PropertiesFile()
  15449. {
  15450. if (! saveIfNeeded())
  15451. jassertfalse;
  15452. }
  15453. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15454. {
  15455. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15456. }
  15457. bool PropertiesFile::saveIfNeeded()
  15458. {
  15459. const ScopedLock sl (getLock());
  15460. return (! needsWriting) || save();
  15461. }
  15462. bool PropertiesFile::needsToBeSaved() const
  15463. {
  15464. const ScopedLock sl (getLock());
  15465. return needsWriting;
  15466. }
  15467. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15468. {
  15469. const ScopedLock sl (getLock());
  15470. needsWriting = needsToBeSaved_;
  15471. }
  15472. bool PropertiesFile::save()
  15473. {
  15474. const ScopedLock sl (getLock());
  15475. stopTimer();
  15476. if (file == File::nonexistent
  15477. || file.isDirectory()
  15478. || ! file.getParentDirectory().createDirectory())
  15479. return false;
  15480. if ((options & storeAsXML) != 0)
  15481. {
  15482. XmlElement doc (PropertyFileConstants::fileTag);
  15483. for (int i = 0; i < getAllProperties().size(); ++i)
  15484. {
  15485. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15486. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15487. // if the value seems to contain xml, store it as such..
  15488. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  15489. if (childElement != 0)
  15490. e->addChildElement (childElement);
  15491. else
  15492. e->setAttribute (PropertyFileConstants::valueAttribute,
  15493. getAllProperties().getAllValues() [i]);
  15494. }
  15495. ProcessScopedLock pl (createProcessLock());
  15496. if (pl != 0 && ! pl->isLocked())
  15497. return false; // locking failure..
  15498. if (doc.writeToFile (file, String::empty))
  15499. {
  15500. needsWriting = false;
  15501. return true;
  15502. }
  15503. }
  15504. else
  15505. {
  15506. ProcessScopedLock pl (createProcessLock());
  15507. if (pl != 0 && ! pl->isLocked())
  15508. return false; // locking failure..
  15509. TemporaryFile tempFile (file);
  15510. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15511. if (out != 0)
  15512. {
  15513. if ((options & storeAsCompressedBinary) != 0)
  15514. {
  15515. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15516. out->flush();
  15517. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15518. }
  15519. else
  15520. {
  15521. // have you set up the storage option flags correctly?
  15522. jassert ((options & storeAsBinary) != 0);
  15523. out->writeInt (PropertyFileConstants::magicNumber);
  15524. }
  15525. const int numProperties = getAllProperties().size();
  15526. out->writeInt (numProperties);
  15527. for (int i = 0; i < numProperties; ++i)
  15528. {
  15529. out->writeString (getAllProperties().getAllKeys() [i]);
  15530. out->writeString (getAllProperties().getAllValues() [i]);
  15531. }
  15532. out = 0;
  15533. if (tempFile.overwriteTargetFileWithTemporary())
  15534. {
  15535. needsWriting = false;
  15536. return true;
  15537. }
  15538. }
  15539. }
  15540. return false;
  15541. }
  15542. void PropertiesFile::timerCallback()
  15543. {
  15544. saveIfNeeded();
  15545. }
  15546. void PropertiesFile::propertyChanged()
  15547. {
  15548. sendChangeMessage();
  15549. needsWriting = true;
  15550. if (timerInterval > 0)
  15551. startTimer (timerInterval);
  15552. else if (timerInterval == 0)
  15553. saveIfNeeded();
  15554. }
  15555. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15556. const String& fileNameSuffix,
  15557. const String& folderName,
  15558. const bool commonToAllUsers)
  15559. {
  15560. // mustn't have illegal characters in this name..
  15561. jassert (applicationName == File::createLegalFileName (applicationName));
  15562. #if JUCE_MAC || JUCE_IOS
  15563. File dir (commonToAllUsers ? "/Library/Preferences"
  15564. : "~/Library/Preferences");
  15565. if (folderName.isNotEmpty())
  15566. dir = dir.getChildFile (folderName);
  15567. #elif JUCE_LINUX || JUCE_ANDROID
  15568. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15569. + (folderName.isNotEmpty() ? folderName
  15570. : ("." + applicationName)));
  15571. #elif JUCE_WINDOWS
  15572. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15573. : File::userApplicationDataDirectory));
  15574. if (dir == File::nonexistent)
  15575. return File::nonexistent;
  15576. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15577. : applicationName);
  15578. #endif
  15579. return dir.getChildFile (applicationName)
  15580. .withFileExtension (fileNameSuffix);
  15581. }
  15582. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15583. const String& fileNameSuffix,
  15584. const String& folderName,
  15585. const bool commonToAllUsers,
  15586. const int millisecondsBeforeSaving,
  15587. const int propertiesFileOptions,
  15588. InterProcessLock* processLock_)
  15589. {
  15590. const File file (getDefaultAppSettingsFile (applicationName,
  15591. fileNameSuffix,
  15592. folderName,
  15593. commonToAllUsers));
  15594. jassert (file != File::nonexistent);
  15595. if (file == File::nonexistent)
  15596. return 0;
  15597. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15598. }
  15599. END_JUCE_NAMESPACE
  15600. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15601. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15602. BEGIN_JUCE_NAMESPACE
  15603. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15604. const String& fileWildcard_,
  15605. const String& openFileDialogTitle_,
  15606. const String& saveFileDialogTitle_)
  15607. : changedSinceSave (false),
  15608. fileExtension (fileExtension_),
  15609. fileWildcard (fileWildcard_),
  15610. openFileDialogTitle (openFileDialogTitle_),
  15611. saveFileDialogTitle (saveFileDialogTitle_)
  15612. {
  15613. }
  15614. FileBasedDocument::~FileBasedDocument()
  15615. {
  15616. }
  15617. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15618. {
  15619. if (changedSinceSave != hasChanged)
  15620. {
  15621. changedSinceSave = hasChanged;
  15622. sendChangeMessage();
  15623. }
  15624. }
  15625. void FileBasedDocument::changed()
  15626. {
  15627. changedSinceSave = true;
  15628. sendChangeMessage();
  15629. }
  15630. void FileBasedDocument::setFile (const File& newFile)
  15631. {
  15632. if (documentFile != newFile)
  15633. {
  15634. documentFile = newFile;
  15635. changed();
  15636. }
  15637. }
  15638. #if JUCE_MODAL_LOOPS_PERMITTED
  15639. bool FileBasedDocument::loadFrom (const File& newFile,
  15640. const bool showMessageOnFailure)
  15641. {
  15642. MouseCursor::showWaitCursor();
  15643. const File oldFile (documentFile);
  15644. documentFile = newFile;
  15645. String error;
  15646. if (newFile.existsAsFile())
  15647. {
  15648. error = loadDocument (newFile);
  15649. if (error.isEmpty())
  15650. {
  15651. setChangedFlag (false);
  15652. MouseCursor::hideWaitCursor();
  15653. setLastDocumentOpened (newFile);
  15654. return true;
  15655. }
  15656. }
  15657. else
  15658. {
  15659. error = "The file doesn't exist";
  15660. }
  15661. documentFile = oldFile;
  15662. MouseCursor::hideWaitCursor();
  15663. if (showMessageOnFailure)
  15664. {
  15665. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15666. TRANS("Failed to open file..."),
  15667. TRANS("There was an error while trying to load the file:\n\n")
  15668. + newFile.getFullPathName()
  15669. + "\n\n"
  15670. + error);
  15671. }
  15672. return false;
  15673. }
  15674. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15675. {
  15676. FileChooser fc (openFileDialogTitle,
  15677. getLastDocumentOpened(),
  15678. fileWildcard);
  15679. if (fc.browseForFileToOpen())
  15680. return loadFrom (fc.getResult(), showMessageOnFailure);
  15681. return false;
  15682. }
  15683. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15684. const bool showMessageOnFailure)
  15685. {
  15686. return saveAs (documentFile,
  15687. false,
  15688. askUserForFileIfNotSpecified,
  15689. showMessageOnFailure);
  15690. }
  15691. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  15692. const bool warnAboutOverwritingExistingFiles,
  15693. const bool askUserForFileIfNotSpecified,
  15694. const bool showMessageOnFailure)
  15695. {
  15696. if (newFile == File::nonexistent)
  15697. {
  15698. if (askUserForFileIfNotSpecified)
  15699. {
  15700. return saveAsInteractive (true);
  15701. }
  15702. else
  15703. {
  15704. // can't save to an unspecified file
  15705. jassertfalse;
  15706. return failedToWriteToFile;
  15707. }
  15708. }
  15709. if (warnAboutOverwritingExistingFiles && newFile.exists())
  15710. {
  15711. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15712. TRANS("File already exists"),
  15713. TRANS("There's already a file called:\n\n")
  15714. + newFile.getFullPathName()
  15715. + TRANS("\n\nAre you sure you want to overwrite it?"),
  15716. TRANS("overwrite"),
  15717. TRANS("cancel")))
  15718. {
  15719. return userCancelledSave;
  15720. }
  15721. }
  15722. MouseCursor::showWaitCursor();
  15723. const File oldFile (documentFile);
  15724. documentFile = newFile;
  15725. String error (saveDocument (newFile));
  15726. if (error.isEmpty())
  15727. {
  15728. setChangedFlag (false);
  15729. MouseCursor::hideWaitCursor();
  15730. return savedOk;
  15731. }
  15732. documentFile = oldFile;
  15733. MouseCursor::hideWaitCursor();
  15734. if (showMessageOnFailure)
  15735. {
  15736. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15737. TRANS("Error writing to file..."),
  15738. TRANS("An error occurred while trying to save \"")
  15739. + getDocumentTitle()
  15740. + TRANS("\" to the file:\n\n")
  15741. + newFile.getFullPathName()
  15742. + "\n\n"
  15743. + error);
  15744. }
  15745. return failedToWriteToFile;
  15746. }
  15747. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  15748. {
  15749. if (! hasChangedSinceSaved())
  15750. return savedOk;
  15751. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  15752. TRANS("Closing document..."),
  15753. TRANS("Do you want to save the changes to \"")
  15754. + getDocumentTitle() + "\"?",
  15755. TRANS("save"),
  15756. TRANS("discard changes"),
  15757. TRANS("cancel"));
  15758. if (r == 1)
  15759. {
  15760. // save changes
  15761. return save (true, true);
  15762. }
  15763. else if (r == 2)
  15764. {
  15765. // discard changes
  15766. return savedOk;
  15767. }
  15768. return userCancelledSave;
  15769. }
  15770. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  15771. {
  15772. File f;
  15773. if (documentFile.existsAsFile())
  15774. f = documentFile;
  15775. else
  15776. f = getLastDocumentOpened();
  15777. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  15778. if (legalFilename.isEmpty())
  15779. legalFilename = "unnamed";
  15780. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  15781. f = f.getSiblingFile (legalFilename);
  15782. else
  15783. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  15784. f = f.withFileExtension (fileExtension)
  15785. .getNonexistentSibling (true);
  15786. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  15787. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  15788. {
  15789. File chosen (fc.getResult());
  15790. if (chosen.getFileExtension().isEmpty())
  15791. {
  15792. chosen = chosen.withFileExtension (fileExtension);
  15793. if (chosen.exists())
  15794. {
  15795. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15796. TRANS("File already exists"),
  15797. TRANS("There's already a file called:")
  15798. + "\n\n" + chosen.getFullPathName()
  15799. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  15800. TRANS("overwrite"),
  15801. TRANS("cancel")))
  15802. {
  15803. return userCancelledSave;
  15804. }
  15805. }
  15806. }
  15807. setLastDocumentOpened (chosen);
  15808. return saveAs (chosen, false, false, true);
  15809. }
  15810. return userCancelledSave;
  15811. }
  15812. #endif
  15813. END_JUCE_NAMESPACE
  15814. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  15815. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15816. BEGIN_JUCE_NAMESPACE
  15817. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  15818. : maxNumberOfItems (10)
  15819. {
  15820. }
  15821. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  15822. {
  15823. }
  15824. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  15825. {
  15826. maxNumberOfItems = jmax (1, newMaxNumber);
  15827. while (getNumFiles() > maxNumberOfItems)
  15828. files.remove (getNumFiles() - 1);
  15829. }
  15830. int RecentlyOpenedFilesList::getNumFiles() const
  15831. {
  15832. return files.size();
  15833. }
  15834. const File RecentlyOpenedFilesList::getFile (const int index) const
  15835. {
  15836. return File (files [index]);
  15837. }
  15838. void RecentlyOpenedFilesList::clear()
  15839. {
  15840. files.clear();
  15841. }
  15842. void RecentlyOpenedFilesList::addFile (const File& file)
  15843. {
  15844. const String path (file.getFullPathName());
  15845. files.removeString (path, true);
  15846. files.insert (0, path);
  15847. setMaxNumberOfItems (maxNumberOfItems);
  15848. }
  15849. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15850. {
  15851. for (int i = getNumFiles(); --i >= 0;)
  15852. if (! getFile(i).exists())
  15853. files.remove (i);
  15854. }
  15855. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15856. const int baseItemId,
  15857. const bool showFullPaths,
  15858. const bool dontAddNonExistentFiles,
  15859. const File** filesToAvoid)
  15860. {
  15861. int num = 0;
  15862. for (int i = 0; i < getNumFiles(); ++i)
  15863. {
  15864. const File f (getFile(i));
  15865. if ((! dontAddNonExistentFiles) || f.exists())
  15866. {
  15867. bool needsAvoiding = false;
  15868. if (filesToAvoid != 0)
  15869. {
  15870. const File** avoid = filesToAvoid;
  15871. while (*avoid != 0)
  15872. {
  15873. if (f == **avoid)
  15874. {
  15875. needsAvoiding = true;
  15876. break;
  15877. }
  15878. ++avoid;
  15879. }
  15880. }
  15881. if (! needsAvoiding)
  15882. {
  15883. menuToAddTo.addItem (baseItemId + i,
  15884. showFullPaths ? f.getFullPathName()
  15885. : f.getFileName());
  15886. ++num;
  15887. }
  15888. }
  15889. }
  15890. return num;
  15891. }
  15892. const String RecentlyOpenedFilesList::toString() const
  15893. {
  15894. return files.joinIntoString ("\n");
  15895. }
  15896. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15897. {
  15898. clear();
  15899. files.addLines (stringifiedVersion);
  15900. setMaxNumberOfItems (maxNumberOfItems);
  15901. }
  15902. END_JUCE_NAMESPACE
  15903. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15904. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15905. BEGIN_JUCE_NAMESPACE
  15906. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15907. const int minimumTransactions)
  15908. : totalUnitsStored (0),
  15909. nextIndex (0),
  15910. newTransaction (true),
  15911. reentrancyCheck (false)
  15912. {
  15913. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15914. minimumTransactions);
  15915. }
  15916. UndoManager::~UndoManager()
  15917. {
  15918. clearUndoHistory();
  15919. }
  15920. void UndoManager::clearUndoHistory()
  15921. {
  15922. transactions.clear();
  15923. transactionNames.clear();
  15924. totalUnitsStored = 0;
  15925. nextIndex = 0;
  15926. sendChangeMessage();
  15927. }
  15928. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15929. {
  15930. return totalUnitsStored;
  15931. }
  15932. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15933. const int minimumTransactions)
  15934. {
  15935. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15936. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15937. }
  15938. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15939. {
  15940. if (command_ != 0)
  15941. {
  15942. ScopedPointer<UndoableAction> command (command_);
  15943. if (actionName.isNotEmpty())
  15944. currentTransactionName = actionName;
  15945. if (reentrancyCheck)
  15946. {
  15947. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15948. // undo() methods, or else these actions won't actually get done.
  15949. return false;
  15950. }
  15951. else if (command->perform())
  15952. {
  15953. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15954. if (commandSet != 0 && ! newTransaction)
  15955. {
  15956. UndoableAction* lastAction = commandSet->getLast();
  15957. if (lastAction != 0)
  15958. {
  15959. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15960. if (coalescedAction != 0)
  15961. {
  15962. command = coalescedAction;
  15963. totalUnitsStored -= lastAction->getSizeInUnits();
  15964. commandSet->removeLast();
  15965. }
  15966. }
  15967. }
  15968. else
  15969. {
  15970. commandSet = new OwnedArray<UndoableAction>();
  15971. transactions.insert (nextIndex, commandSet);
  15972. transactionNames.insert (nextIndex, currentTransactionName);
  15973. ++nextIndex;
  15974. }
  15975. totalUnitsStored += command->getSizeInUnits();
  15976. commandSet->add (command.release());
  15977. newTransaction = false;
  15978. while (nextIndex < transactions.size())
  15979. {
  15980. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15981. for (int i = lastSet->size(); --i >= 0;)
  15982. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15983. transactions.removeLast();
  15984. transactionNames.remove (transactionNames.size() - 1);
  15985. }
  15986. while (nextIndex > 0
  15987. && totalUnitsStored > maxNumUnitsToKeep
  15988. && transactions.size() > minimumTransactionsToKeep)
  15989. {
  15990. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15991. for (int i = firstSet->size(); --i >= 0;)
  15992. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15993. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15994. transactions.remove (0);
  15995. transactionNames.remove (0);
  15996. --nextIndex;
  15997. }
  15998. sendChangeMessage();
  15999. return true;
  16000. }
  16001. }
  16002. return false;
  16003. }
  16004. void UndoManager::beginNewTransaction (const String& actionName)
  16005. {
  16006. newTransaction = true;
  16007. currentTransactionName = actionName;
  16008. }
  16009. void UndoManager::setCurrentTransactionName (const String& newName)
  16010. {
  16011. currentTransactionName = newName;
  16012. }
  16013. bool UndoManager::canUndo() const
  16014. {
  16015. return nextIndex > 0;
  16016. }
  16017. bool UndoManager::canRedo() const
  16018. {
  16019. return nextIndex < transactions.size();
  16020. }
  16021. const String UndoManager::getUndoDescription() const
  16022. {
  16023. return transactionNames [nextIndex - 1];
  16024. }
  16025. const String UndoManager::getRedoDescription() const
  16026. {
  16027. return transactionNames [nextIndex];
  16028. }
  16029. bool UndoManager::undo()
  16030. {
  16031. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16032. if (commandSet == 0)
  16033. return false;
  16034. bool failed = false;
  16035. {
  16036. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16037. for (int i = commandSet->size(); --i >= 0;)
  16038. {
  16039. if (! commandSet->getUnchecked(i)->undo())
  16040. {
  16041. jassertfalse;
  16042. failed = true;
  16043. break;
  16044. }
  16045. }
  16046. }
  16047. if (failed)
  16048. clearUndoHistory();
  16049. else
  16050. --nextIndex;
  16051. beginNewTransaction();
  16052. sendChangeMessage();
  16053. return true;
  16054. }
  16055. bool UndoManager::redo()
  16056. {
  16057. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16058. if (commandSet == 0)
  16059. return false;
  16060. bool failed = false;
  16061. {
  16062. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16063. for (int i = 0; i < commandSet->size(); ++i)
  16064. {
  16065. if (! commandSet->getUnchecked(i)->perform())
  16066. {
  16067. jassertfalse;
  16068. failed = true;
  16069. break;
  16070. }
  16071. }
  16072. }
  16073. if (failed)
  16074. clearUndoHistory();
  16075. else
  16076. ++nextIndex;
  16077. beginNewTransaction();
  16078. sendChangeMessage();
  16079. return true;
  16080. }
  16081. bool UndoManager::undoCurrentTransactionOnly()
  16082. {
  16083. return newTransaction ? false : undo();
  16084. }
  16085. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16086. {
  16087. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16088. if (commandSet != 0 && ! newTransaction)
  16089. {
  16090. for (int i = 0; i < commandSet->size(); ++i)
  16091. actionsFound.add (commandSet->getUnchecked(i));
  16092. }
  16093. }
  16094. int UndoManager::getNumActionsInCurrentTransaction() const
  16095. {
  16096. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16097. if (commandSet != 0 && ! newTransaction)
  16098. return commandSet->size();
  16099. return 0;
  16100. }
  16101. END_JUCE_NAMESPACE
  16102. /*** End of inlined file: juce_UndoManager.cpp ***/
  16103. /*** Start of inlined file: juce_UnitTest.cpp ***/
  16104. BEGIN_JUCE_NAMESPACE
  16105. UnitTest::UnitTest (const String& name_)
  16106. : name (name_), runner (0)
  16107. {
  16108. getAllTests().add (this);
  16109. }
  16110. UnitTest::~UnitTest()
  16111. {
  16112. getAllTests().removeValue (this);
  16113. }
  16114. Array<UnitTest*>& UnitTest::getAllTests()
  16115. {
  16116. static Array<UnitTest*> tests;
  16117. return tests;
  16118. }
  16119. void UnitTest::initialise() {}
  16120. void UnitTest::shutdown() {}
  16121. void UnitTest::performTest (UnitTestRunner* const runner_)
  16122. {
  16123. jassert (runner_ != 0);
  16124. runner = runner_;
  16125. initialise();
  16126. runTest();
  16127. shutdown();
  16128. }
  16129. void UnitTest::logMessage (const String& message)
  16130. {
  16131. runner->logMessage (message);
  16132. }
  16133. void UnitTest::beginTest (const String& testName)
  16134. {
  16135. runner->beginNewTest (this, testName);
  16136. }
  16137. void UnitTest::expect (const bool result, const String& failureMessage)
  16138. {
  16139. if (result)
  16140. runner->addPass();
  16141. else
  16142. runner->addFail (failureMessage);
  16143. }
  16144. UnitTestRunner::UnitTestRunner()
  16145. : currentTest (0), assertOnFailure (false)
  16146. {
  16147. }
  16148. UnitTestRunner::~UnitTestRunner()
  16149. {
  16150. }
  16151. int UnitTestRunner::getNumResults() const throw()
  16152. {
  16153. return results.size();
  16154. }
  16155. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  16156. {
  16157. return results [index];
  16158. }
  16159. void UnitTestRunner::resultsUpdated()
  16160. {
  16161. }
  16162. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  16163. {
  16164. results.clear();
  16165. assertOnFailure = assertOnFailure_;
  16166. resultsUpdated();
  16167. for (int i = 0; i < tests.size(); ++i)
  16168. {
  16169. try
  16170. {
  16171. tests.getUnchecked(i)->performTest (this);
  16172. }
  16173. catch (...)
  16174. {
  16175. addFail ("An unhandled exception was thrown!");
  16176. }
  16177. }
  16178. endTest();
  16179. }
  16180. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  16181. {
  16182. runTests (UnitTest::getAllTests(), assertOnFailure_);
  16183. }
  16184. void UnitTestRunner::logMessage (const String& message)
  16185. {
  16186. Logger::writeToLog (message);
  16187. }
  16188. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  16189. {
  16190. endTest();
  16191. currentTest = test;
  16192. TestResult* const r = new TestResult();
  16193. r->unitTestName = test->getName();
  16194. r->subcategoryName = subCategory;
  16195. r->passes = 0;
  16196. r->failures = 0;
  16197. results.add (r);
  16198. logMessage ("-----------------------------------------------------------------");
  16199. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  16200. resultsUpdated();
  16201. }
  16202. void UnitTestRunner::endTest()
  16203. {
  16204. if (results.size() > 0)
  16205. {
  16206. TestResult* const r = results.getLast();
  16207. if (r->failures > 0)
  16208. {
  16209. String m ("FAILED!! ");
  16210. m << r->failures << (r->failures == 1 ? " test" : " tests")
  16211. << " failed, out of a total of " << (r->passes + r->failures);
  16212. logMessage (String::empty);
  16213. logMessage (m);
  16214. logMessage (String::empty);
  16215. }
  16216. else
  16217. {
  16218. logMessage ("All tests completed successfully");
  16219. }
  16220. }
  16221. }
  16222. void UnitTestRunner::addPass()
  16223. {
  16224. {
  16225. const ScopedLock sl (results.getLock());
  16226. TestResult* const r = results.getLast();
  16227. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  16228. r->passes++;
  16229. String message ("Test ");
  16230. message << (r->failures + r->passes) << " passed";
  16231. logMessage (message);
  16232. }
  16233. resultsUpdated();
  16234. }
  16235. void UnitTestRunner::addFail (const String& failureMessage)
  16236. {
  16237. {
  16238. const ScopedLock sl (results.getLock());
  16239. TestResult* const r = results.getLast();
  16240. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  16241. r->failures++;
  16242. String message ("!!! Test ");
  16243. message << (r->failures + r->passes) << " failed";
  16244. if (failureMessage.isNotEmpty())
  16245. message << ": " << failureMessage;
  16246. r->messages.add (message);
  16247. logMessage (message);
  16248. }
  16249. resultsUpdated();
  16250. if (assertOnFailure) { jassertfalse }
  16251. }
  16252. END_JUCE_NAMESPACE
  16253. /*** End of inlined file: juce_UnitTest.cpp ***/
  16254. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  16255. BEGIN_JUCE_NAMESPACE
  16256. DeletedAtShutdown::DeletedAtShutdown()
  16257. {
  16258. const ScopedLock sl (getLock());
  16259. getObjects().add (this);
  16260. }
  16261. DeletedAtShutdown::~DeletedAtShutdown()
  16262. {
  16263. const ScopedLock sl (getLock());
  16264. getObjects().removeValue (this);
  16265. }
  16266. void DeletedAtShutdown::deleteAll()
  16267. {
  16268. // make a local copy of the array, so it can't get into a loop if something
  16269. // creates another DeletedAtShutdown object during its destructor.
  16270. Array <DeletedAtShutdown*> localCopy;
  16271. {
  16272. const ScopedLock sl (getLock());
  16273. localCopy = getObjects();
  16274. }
  16275. for (int i = localCopy.size(); --i >= 0;)
  16276. {
  16277. JUCE_TRY
  16278. {
  16279. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  16280. // double-check that it's not already been deleted during another object's destructor.
  16281. {
  16282. const ScopedLock sl (getLock());
  16283. if (! getObjects().contains (deletee))
  16284. deletee = 0;
  16285. }
  16286. delete deletee;
  16287. }
  16288. JUCE_CATCH_EXCEPTION
  16289. }
  16290. // if no objects got re-created during shutdown, this should have been emptied by their
  16291. // destructors
  16292. jassert (getObjects().size() == 0);
  16293. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  16294. }
  16295. CriticalSection& DeletedAtShutdown::getLock()
  16296. {
  16297. static CriticalSection lock;
  16298. return lock;
  16299. }
  16300. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  16301. {
  16302. static Array <DeletedAtShutdown*> objects;
  16303. return objects;
  16304. }
  16305. END_JUCE_NAMESPACE
  16306. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  16307. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16308. BEGIN_JUCE_NAMESPACE
  16309. static const char* const aiffFormatName = "AIFF file";
  16310. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16311. class AiffAudioFormatReader : public AudioFormatReader
  16312. {
  16313. public:
  16314. int bytesPerFrame;
  16315. int64 dataChunkStart;
  16316. bool littleEndian;
  16317. AiffAudioFormatReader (InputStream* in)
  16318. : AudioFormatReader (in, TRANS (aiffFormatName))
  16319. {
  16320. if (input->readInt() == chunkName ("FORM"))
  16321. {
  16322. const int len = input->readIntBigEndian();
  16323. const int64 end = input->getPosition() + len;
  16324. const int nextType = input->readInt();
  16325. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16326. {
  16327. bool hasGotVer = false;
  16328. bool hasGotData = false;
  16329. bool hasGotType = false;
  16330. while (input->getPosition() < end)
  16331. {
  16332. const int type = input->readInt();
  16333. const uint32 length = (uint32) input->readIntBigEndian();
  16334. const int64 chunkEnd = input->getPosition() + length;
  16335. if (type == chunkName ("FVER"))
  16336. {
  16337. hasGotVer = true;
  16338. const int ver = input->readIntBigEndian();
  16339. if (ver != 0 && ver != (int) 0xa2805140)
  16340. break;
  16341. }
  16342. else if (type == chunkName ("COMM"))
  16343. {
  16344. hasGotType = true;
  16345. numChannels = (unsigned int) input->readShortBigEndian();
  16346. lengthInSamples = input->readIntBigEndian();
  16347. bitsPerSample = input->readShortBigEndian();
  16348. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16349. unsigned char sampleRateBytes[10];
  16350. input->read (sampleRateBytes, 10);
  16351. const int byte0 = sampleRateBytes[0];
  16352. if ((byte0 & 0x80) != 0
  16353. || byte0 <= 0x3F || byte0 > 0x40
  16354. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16355. break;
  16356. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16357. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16358. sampleRate = (int) sampRate;
  16359. if (length <= 18)
  16360. {
  16361. // some types don't have a chunk large enough to include a compression
  16362. // type, so assume it's just big-endian pcm
  16363. littleEndian = false;
  16364. }
  16365. else
  16366. {
  16367. const int compType = input->readInt();
  16368. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16369. {
  16370. littleEndian = false;
  16371. }
  16372. else if (compType == chunkName ("sowt"))
  16373. {
  16374. littleEndian = true;
  16375. }
  16376. else
  16377. {
  16378. sampleRate = 0;
  16379. break;
  16380. }
  16381. }
  16382. }
  16383. else if (type == chunkName ("SSND"))
  16384. {
  16385. hasGotData = true;
  16386. const int offset = input->readIntBigEndian();
  16387. dataChunkStart = input->getPosition() + 4 + offset;
  16388. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16389. }
  16390. else if ((hasGotVer && hasGotData && hasGotType)
  16391. || chunkEnd < input->getPosition()
  16392. || input->isExhausted())
  16393. {
  16394. break;
  16395. }
  16396. input->setPosition (chunkEnd);
  16397. }
  16398. }
  16399. }
  16400. }
  16401. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16402. int64 startSampleInFile, int numSamples)
  16403. {
  16404. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16405. if (samplesAvailable < numSamples)
  16406. {
  16407. for (int i = numDestChannels; --i >= 0;)
  16408. if (destSamples[i] != 0)
  16409. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16410. numSamples = (int) samplesAvailable;
  16411. }
  16412. if (numSamples <= 0)
  16413. return true;
  16414. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16415. while (numSamples > 0)
  16416. {
  16417. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16418. char tempBuffer [tempBufSize];
  16419. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16420. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16421. if (bytesRead < numThisTime * bytesPerFrame)
  16422. {
  16423. jassert (bytesRead >= 0);
  16424. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16425. }
  16426. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16427. if (littleEndian)
  16428. {
  16429. switch (bitsPerSample)
  16430. {
  16431. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16432. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16433. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16434. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16435. default: jassertfalse; break;
  16436. }
  16437. }
  16438. else
  16439. {
  16440. switch (bitsPerSample)
  16441. {
  16442. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16443. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16444. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16445. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16446. default: jassertfalse; break;
  16447. }
  16448. }
  16449. startOffsetInDestBuffer += numThisTime;
  16450. numSamples -= numThisTime;
  16451. }
  16452. return true;
  16453. }
  16454. private:
  16455. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16456. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16457. };
  16458. class AiffAudioFormatWriter : public AudioFormatWriter
  16459. {
  16460. public:
  16461. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16462. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16463. lengthInSamples (0),
  16464. bytesWritten (0),
  16465. writeFailed (false)
  16466. {
  16467. headerPosition = out->getPosition();
  16468. writeHeader();
  16469. }
  16470. ~AiffAudioFormatWriter()
  16471. {
  16472. if ((bytesWritten & 1) != 0)
  16473. output->writeByte (0);
  16474. writeHeader();
  16475. }
  16476. bool write (const int** data, int numSamples)
  16477. {
  16478. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16479. if (writeFailed)
  16480. return false;
  16481. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16482. tempBlock.ensureSize (bytes, false);
  16483. switch (bitsPerSample)
  16484. {
  16485. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16486. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16487. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16488. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16489. default: jassertfalse; break;
  16490. }
  16491. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16492. || ! output->write (tempBlock.getData(), bytes))
  16493. {
  16494. // failed to write to disk, so let's try writing the header.
  16495. // If it's just run out of disk space, then if it does manage
  16496. // to write the header, we'll still have a useable file..
  16497. writeHeader();
  16498. writeFailed = true;
  16499. return false;
  16500. }
  16501. else
  16502. {
  16503. bytesWritten += bytes;
  16504. lengthInSamples += numSamples;
  16505. return true;
  16506. }
  16507. }
  16508. private:
  16509. MemoryBlock tempBlock;
  16510. uint32 lengthInSamples, bytesWritten;
  16511. int64 headerPosition;
  16512. bool writeFailed;
  16513. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16514. void writeHeader()
  16515. {
  16516. const bool couldSeekOk = output->setPosition (headerPosition);
  16517. (void) couldSeekOk;
  16518. // if this fails, you've given it an output stream that can't seek! It needs
  16519. // to be able to seek back to write the header
  16520. jassert (couldSeekOk);
  16521. const int headerLen = 54;
  16522. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16523. audioBytes += (audioBytes & 1);
  16524. output->writeInt (chunkName ("FORM"));
  16525. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16526. output->writeInt (chunkName ("AIFF"));
  16527. output->writeInt (chunkName ("COMM"));
  16528. output->writeIntBigEndian (18);
  16529. output->writeShortBigEndian ((short) numChannels);
  16530. output->writeIntBigEndian (lengthInSamples);
  16531. output->writeShortBigEndian ((short) bitsPerSample);
  16532. uint8 sampleRateBytes[10];
  16533. zeromem (sampleRateBytes, 10);
  16534. if (sampleRate <= 1)
  16535. {
  16536. sampleRateBytes[0] = 0x3f;
  16537. sampleRateBytes[1] = 0xff;
  16538. sampleRateBytes[2] = 0x80;
  16539. }
  16540. else
  16541. {
  16542. int mask = 0x40000000;
  16543. sampleRateBytes[0] = 0x40;
  16544. if (sampleRate >= mask)
  16545. {
  16546. jassertfalse;
  16547. sampleRateBytes[1] = 0x1d;
  16548. }
  16549. else
  16550. {
  16551. int n = (int) sampleRate;
  16552. int i;
  16553. for (i = 0; i <= 32 ; ++i)
  16554. {
  16555. if ((n & mask) != 0)
  16556. break;
  16557. mask >>= 1;
  16558. }
  16559. n = n << (i + 1);
  16560. sampleRateBytes[1] = (uint8) (29 - i);
  16561. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16562. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16563. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16564. sampleRateBytes[5] = (uint8) (n & 0xff);
  16565. }
  16566. }
  16567. output->write (sampleRateBytes, 10);
  16568. output->writeInt (chunkName ("SSND"));
  16569. output->writeIntBigEndian (audioBytes + 8);
  16570. output->writeInt (0);
  16571. output->writeInt (0);
  16572. jassert (output->getPosition() == headerLen);
  16573. }
  16574. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16575. };
  16576. AiffAudioFormat::AiffAudioFormat()
  16577. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16578. {
  16579. }
  16580. AiffAudioFormat::~AiffAudioFormat()
  16581. {
  16582. }
  16583. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16584. {
  16585. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16586. return Array <int> (rates);
  16587. }
  16588. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16589. {
  16590. const int depths[] = { 8, 16, 24, 0 };
  16591. return Array <int> (depths);
  16592. }
  16593. bool AiffAudioFormat::canDoStereo() { return true; }
  16594. bool AiffAudioFormat::canDoMono() { return true; }
  16595. #if JUCE_MAC
  16596. bool AiffAudioFormat::canHandleFile (const File& f)
  16597. {
  16598. if (AudioFormat::canHandleFile (f))
  16599. return true;
  16600. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16601. return type == 'AIFF' || type == 'AIFC'
  16602. || type == 'aiff' || type == 'aifc';
  16603. }
  16604. #endif
  16605. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16606. {
  16607. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16608. if (w->sampleRate > 0)
  16609. return w.release();
  16610. if (! deleteStreamIfOpeningFails)
  16611. w->input = 0;
  16612. return 0;
  16613. }
  16614. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16615. double sampleRate,
  16616. unsigned int numberOfChannels,
  16617. int bitsPerSample,
  16618. const StringPairArray& /*metadataValues*/,
  16619. int /*qualityOptionIndex*/)
  16620. {
  16621. if (getPossibleBitDepths().contains (bitsPerSample))
  16622. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16623. return 0;
  16624. }
  16625. END_JUCE_NAMESPACE
  16626. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16627. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16628. BEGIN_JUCE_NAMESPACE
  16629. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16630. : formatName (name),
  16631. fileExtensions (extensions)
  16632. {
  16633. }
  16634. AudioFormat::~AudioFormat()
  16635. {
  16636. }
  16637. bool AudioFormat::canHandleFile (const File& f)
  16638. {
  16639. for (int i = 0; i < fileExtensions.size(); ++i)
  16640. if (f.hasFileExtension (fileExtensions[i]))
  16641. return true;
  16642. return false;
  16643. }
  16644. const String& AudioFormat::getFormatName() const { return formatName; }
  16645. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16646. bool AudioFormat::isCompressed() { return false; }
  16647. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16648. END_JUCE_NAMESPACE
  16649. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16650. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16651. BEGIN_JUCE_NAMESPACE
  16652. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16653. const String& formatName_)
  16654. : sampleRate (0),
  16655. bitsPerSample (0),
  16656. lengthInSamples (0),
  16657. numChannels (0),
  16658. usesFloatingPointData (false),
  16659. input (in),
  16660. formatName (formatName_)
  16661. {
  16662. }
  16663. AudioFormatReader::~AudioFormatReader()
  16664. {
  16665. delete input;
  16666. }
  16667. bool AudioFormatReader::read (int* const* destSamples,
  16668. int numDestChannels,
  16669. int64 startSampleInSource,
  16670. int numSamplesToRead,
  16671. const bool fillLeftoverChannelsWithCopies)
  16672. {
  16673. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16674. int startOffsetInDestBuffer = 0;
  16675. if (startSampleInSource < 0)
  16676. {
  16677. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16678. for (int i = numDestChannels; --i >= 0;)
  16679. if (destSamples[i] != 0)
  16680. zeromem (destSamples[i], sizeof (int) * silence);
  16681. startOffsetInDestBuffer += silence;
  16682. numSamplesToRead -= silence;
  16683. startSampleInSource = 0;
  16684. }
  16685. if (numSamplesToRead <= 0)
  16686. return true;
  16687. if (! readSamples (const_cast<int**> (destSamples),
  16688. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16689. startSampleInSource, numSamplesToRead))
  16690. return false;
  16691. if (numDestChannels > (int) numChannels)
  16692. {
  16693. if (fillLeftoverChannelsWithCopies)
  16694. {
  16695. int* lastFullChannel = destSamples[0];
  16696. for (int i = (int) numChannels; --i > 0;)
  16697. {
  16698. if (destSamples[i] != 0)
  16699. {
  16700. lastFullChannel = destSamples[i];
  16701. break;
  16702. }
  16703. }
  16704. if (lastFullChannel != 0)
  16705. for (int i = numChannels; i < numDestChannels; ++i)
  16706. if (destSamples[i] != 0)
  16707. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16708. }
  16709. else
  16710. {
  16711. for (int i = numChannels; i < numDestChannels; ++i)
  16712. if (destSamples[i] != 0)
  16713. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16714. }
  16715. }
  16716. return true;
  16717. }
  16718. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16719. int64 numSamples,
  16720. float& lowestLeft, float& highestLeft,
  16721. float& lowestRight, float& highestRight)
  16722. {
  16723. if (numSamples <= 0)
  16724. {
  16725. lowestLeft = 0;
  16726. lowestRight = 0;
  16727. highestLeft = 0;
  16728. highestRight = 0;
  16729. return;
  16730. }
  16731. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16732. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16733. int* tempBuffer[3];
  16734. tempBuffer[0] = tempSpace.getData();
  16735. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16736. tempBuffer[2] = 0;
  16737. if (usesFloatingPointData)
  16738. {
  16739. float lmin = 1.0e6f;
  16740. float lmax = -lmin;
  16741. float rmin = lmin;
  16742. float rmax = lmax;
  16743. while (numSamples > 0)
  16744. {
  16745. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16746. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  16747. numSamples -= numToDo;
  16748. startSampleInFile += numToDo;
  16749. float bufMin, bufMax;
  16750. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  16751. lmin = jmin (lmin, bufMin);
  16752. lmax = jmax (lmax, bufMax);
  16753. if (numChannels > 1)
  16754. {
  16755. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  16756. rmin = jmin (rmin, bufMin);
  16757. rmax = jmax (rmax, bufMax);
  16758. }
  16759. }
  16760. if (numChannels <= 1)
  16761. {
  16762. rmax = lmax;
  16763. rmin = lmin;
  16764. }
  16765. lowestLeft = lmin;
  16766. highestLeft = lmax;
  16767. lowestRight = rmin;
  16768. highestRight = rmax;
  16769. }
  16770. else
  16771. {
  16772. int lmax = std::numeric_limits<int>::min();
  16773. int lmin = std::numeric_limits<int>::max();
  16774. int rmax = std::numeric_limits<int>::min();
  16775. int rmin = std::numeric_limits<int>::max();
  16776. while (numSamples > 0)
  16777. {
  16778. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16779. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  16780. break;
  16781. numSamples -= numToDo;
  16782. startSampleInFile += numToDo;
  16783. for (int j = numChannels; --j >= 0;)
  16784. {
  16785. int bufMin, bufMax;
  16786. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  16787. if (j == 0)
  16788. {
  16789. lmax = jmax (lmax, bufMax);
  16790. lmin = jmin (lmin, bufMin);
  16791. }
  16792. else
  16793. {
  16794. rmax = jmax (rmax, bufMax);
  16795. rmin = jmin (rmin, bufMin);
  16796. }
  16797. }
  16798. }
  16799. if (numChannels <= 1)
  16800. {
  16801. rmax = lmax;
  16802. rmin = lmin;
  16803. }
  16804. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16805. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16806. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16807. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16808. }
  16809. }
  16810. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16811. int64 numSamplesToSearch,
  16812. const double magnitudeRangeMinimum,
  16813. const double magnitudeRangeMaximum,
  16814. const int minimumConsecutiveSamples)
  16815. {
  16816. if (numSamplesToSearch == 0)
  16817. return -1;
  16818. const int bufferSize = 4096;
  16819. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16820. int* tempBuffer[3];
  16821. tempBuffer[0] = tempSpace.getData();
  16822. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16823. tempBuffer[2] = 0;
  16824. int consecutive = 0;
  16825. int64 firstMatchPos = -1;
  16826. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16827. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16828. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16829. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16830. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16831. while (numSamplesToSearch != 0)
  16832. {
  16833. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16834. int64 bufferStart = startSample;
  16835. if (numSamplesToSearch < 0)
  16836. bufferStart -= numThisTime;
  16837. if (bufferStart >= (int) lengthInSamples)
  16838. break;
  16839. read (tempBuffer, 2, bufferStart, numThisTime, false);
  16840. int num = numThisTime;
  16841. while (--num >= 0)
  16842. {
  16843. if (numSamplesToSearch < 0)
  16844. --startSample;
  16845. bool matches = false;
  16846. const int index = (int) (startSample - bufferStart);
  16847. if (usesFloatingPointData)
  16848. {
  16849. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16850. if (sample1 >= magnitudeRangeMinimum
  16851. && sample1 <= magnitudeRangeMaximum)
  16852. {
  16853. matches = true;
  16854. }
  16855. else if (numChannels > 1)
  16856. {
  16857. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16858. matches = (sample2 >= magnitudeRangeMinimum
  16859. && sample2 <= magnitudeRangeMaximum);
  16860. }
  16861. }
  16862. else
  16863. {
  16864. const int sample1 = abs (tempBuffer[0] [index]);
  16865. if (sample1 >= intMagnitudeRangeMinimum
  16866. && sample1 <= intMagnitudeRangeMaximum)
  16867. {
  16868. matches = true;
  16869. }
  16870. else if (numChannels > 1)
  16871. {
  16872. const int sample2 = abs (tempBuffer[1][index]);
  16873. matches = (sample2 >= intMagnitudeRangeMinimum
  16874. && sample2 <= intMagnitudeRangeMaximum);
  16875. }
  16876. }
  16877. if (matches)
  16878. {
  16879. if (firstMatchPos < 0)
  16880. firstMatchPos = startSample;
  16881. if (++consecutive >= minimumConsecutiveSamples)
  16882. {
  16883. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16884. return -1;
  16885. return firstMatchPos;
  16886. }
  16887. }
  16888. else
  16889. {
  16890. consecutive = 0;
  16891. firstMatchPos = -1;
  16892. }
  16893. if (numSamplesToSearch > 0)
  16894. ++startSample;
  16895. }
  16896. if (numSamplesToSearch > 0)
  16897. numSamplesToSearch -= numThisTime;
  16898. else
  16899. numSamplesToSearch += numThisTime;
  16900. }
  16901. return -1;
  16902. }
  16903. END_JUCE_NAMESPACE
  16904. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  16905. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  16906. BEGIN_JUCE_NAMESPACE
  16907. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16908. const String& formatName_,
  16909. const double rate,
  16910. const unsigned int numChannels_,
  16911. const unsigned int bitsPerSample_)
  16912. : sampleRate (rate),
  16913. numChannels (numChannels_),
  16914. bitsPerSample (bitsPerSample_),
  16915. usesFloatingPointData (false),
  16916. output (out),
  16917. formatName (formatName_)
  16918. {
  16919. }
  16920. AudioFormatWriter::~AudioFormatWriter()
  16921. {
  16922. delete output;
  16923. }
  16924. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16925. int64 startSample,
  16926. int64 numSamplesToRead)
  16927. {
  16928. const int bufferSize = 16384;
  16929. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16930. int* buffers [128];
  16931. zerostruct (buffers);
  16932. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16933. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  16934. if (numSamplesToRead < 0)
  16935. numSamplesToRead = reader.lengthInSamples;
  16936. while (numSamplesToRead > 0)
  16937. {
  16938. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16939. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16940. return false;
  16941. if (reader.usesFloatingPointData != isFloatingPoint())
  16942. {
  16943. int** bufferChan = buffers;
  16944. while (*bufferChan != 0)
  16945. {
  16946. int* b = *bufferChan++;
  16947. if (isFloatingPoint())
  16948. {
  16949. // int -> float
  16950. const double factor = 1.0 / std::numeric_limits<int>::max();
  16951. for (int i = 0; i < numToDo; ++i)
  16952. ((float*) b)[i] = (float) (factor * b[i]);
  16953. }
  16954. else
  16955. {
  16956. // float -> int
  16957. for (int i = 0; i < numToDo; ++i)
  16958. {
  16959. const double samp = *(const float*) b;
  16960. if (samp <= -1.0)
  16961. *b++ = std::numeric_limits<int>::min();
  16962. else if (samp >= 1.0)
  16963. *b++ = std::numeric_limits<int>::max();
  16964. else
  16965. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16966. }
  16967. }
  16968. }
  16969. }
  16970. if (! write (const_cast<const int**> (buffers), numToDo))
  16971. return false;
  16972. numSamplesToRead -= numToDo;
  16973. startSample += numToDo;
  16974. }
  16975. return true;
  16976. }
  16977. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  16978. {
  16979. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16980. while (numSamplesToRead > 0)
  16981. {
  16982. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16983. AudioSourceChannelInfo info;
  16984. info.buffer = &tempBuffer;
  16985. info.startSample = 0;
  16986. info.numSamples = numToDo;
  16987. info.clearActiveBufferRegion();
  16988. source.getNextAudioBlock (info);
  16989. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  16990. return false;
  16991. numSamplesToRead -= numToDo;
  16992. }
  16993. return true;
  16994. }
  16995. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  16996. {
  16997. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  16998. if (numSamples <= 0)
  16999. return true;
  17000. HeapBlock<int> tempBuffer;
  17001. HeapBlock<int*> chans (numChannels + 1);
  17002. chans [numChannels] = 0;
  17003. if (isFloatingPoint())
  17004. {
  17005. for (int i = numChannels; --i >= 0;)
  17006. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17007. }
  17008. else
  17009. {
  17010. tempBuffer.malloc (numSamples * numChannels);
  17011. for (unsigned int i = 0; i < numChannels; ++i)
  17012. {
  17013. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17014. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17015. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17016. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17017. destData.convertSamples (sourceData, numSamples);
  17018. }
  17019. }
  17020. return write ((const int**) chans.getData(), numSamples);
  17021. }
  17022. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17023. public AbstractFifo
  17024. {
  17025. public:
  17026. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize_)
  17027. : AbstractFifo (bufferSize_),
  17028. buffer (numChannels, bufferSize_),
  17029. timeSliceThread (timeSliceThread_),
  17030. writer (writer_),
  17031. thumbnailToUpdate (0),
  17032. samplesWritten (0),
  17033. isRunning (true)
  17034. {
  17035. timeSliceThread.addTimeSliceClient (this);
  17036. }
  17037. ~Buffer()
  17038. {
  17039. isRunning = false;
  17040. timeSliceThread.removeTimeSliceClient (this);
  17041. while (useTimeSlice() == 0)
  17042. {}
  17043. }
  17044. bool write (const float** data, int numSamples)
  17045. {
  17046. if (numSamples <= 0 || ! isRunning)
  17047. return true;
  17048. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17049. int start1, size1, start2, size2;
  17050. prepareToWrite (numSamples, start1, size1, start2, size2);
  17051. if (size1 + size2 < numSamples)
  17052. return false;
  17053. for (int i = buffer.getNumChannels(); --i >= 0;)
  17054. {
  17055. buffer.copyFrom (i, start1, data[i], size1);
  17056. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17057. }
  17058. finishedWrite (size1 + size2);
  17059. timeSliceThread.notify();
  17060. return true;
  17061. }
  17062. int useTimeSlice()
  17063. {
  17064. const int numToDo = getTotalSize() / 4;
  17065. int start1, size1, start2, size2;
  17066. prepareToRead (numToDo, start1, size1, start2, size2);
  17067. if (size1 <= 0)
  17068. return 10;
  17069. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17070. const ScopedLock sl (thumbnailLock);
  17071. if (thumbnailToUpdate != 0)
  17072. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  17073. samplesWritten += size1;
  17074. if (size2 > 0)
  17075. {
  17076. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17077. if (thumbnailToUpdate != 0)
  17078. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  17079. samplesWritten += size2;
  17080. }
  17081. finishedRead (size1 + size2);
  17082. return 0;
  17083. }
  17084. void setThumbnail (AudioThumbnail* thumb)
  17085. {
  17086. if (thumb != 0)
  17087. thumb->reset (buffer.getNumChannels(), writer->getSampleRate(), 0);
  17088. const ScopedLock sl (thumbnailLock);
  17089. thumbnailToUpdate = thumb;
  17090. samplesWritten = 0;
  17091. }
  17092. private:
  17093. AudioSampleBuffer buffer;
  17094. TimeSliceThread& timeSliceThread;
  17095. ScopedPointer<AudioFormatWriter> writer;
  17096. CriticalSection thumbnailLock;
  17097. AudioThumbnail* thumbnailToUpdate;
  17098. int64 samplesWritten;
  17099. volatile bool isRunning;
  17100. JUCE_DECLARE_NON_COPYABLE (Buffer);
  17101. };
  17102. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17103. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17104. {
  17105. }
  17106. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17107. {
  17108. }
  17109. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17110. {
  17111. return buffer->write (data, numSamples);
  17112. }
  17113. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  17114. {
  17115. buffer->setThumbnail (thumb);
  17116. }
  17117. END_JUCE_NAMESPACE
  17118. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17119. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17120. BEGIN_JUCE_NAMESPACE
  17121. AudioFormatManager::AudioFormatManager()
  17122. : defaultFormatIndex (0)
  17123. {
  17124. }
  17125. AudioFormatManager::~AudioFormatManager()
  17126. {
  17127. }
  17128. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  17129. {
  17130. jassert (newFormat != 0);
  17131. if (newFormat != 0)
  17132. {
  17133. #if JUCE_DEBUG
  17134. for (int i = getNumKnownFormats(); --i >= 0;)
  17135. {
  17136. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17137. {
  17138. jassertfalse; // trying to add the same format twice!
  17139. }
  17140. }
  17141. #endif
  17142. if (makeThisTheDefaultFormat)
  17143. defaultFormatIndex = getNumKnownFormats();
  17144. knownFormats.add (newFormat);
  17145. }
  17146. }
  17147. void AudioFormatManager::registerBasicFormats()
  17148. {
  17149. #if JUCE_MAC
  17150. registerFormat (new AiffAudioFormat(), true);
  17151. registerFormat (new WavAudioFormat(), false);
  17152. #else
  17153. registerFormat (new WavAudioFormat(), true);
  17154. registerFormat (new AiffAudioFormat(), false);
  17155. #endif
  17156. #if JUCE_USE_FLAC
  17157. registerFormat (new FlacAudioFormat(), false);
  17158. #endif
  17159. #if JUCE_USE_OGGVORBIS
  17160. registerFormat (new OggVorbisAudioFormat(), false);
  17161. #endif
  17162. }
  17163. void AudioFormatManager::clearFormats()
  17164. {
  17165. knownFormats.clear();
  17166. defaultFormatIndex = 0;
  17167. }
  17168. int AudioFormatManager::getNumKnownFormats() const
  17169. {
  17170. return knownFormats.size();
  17171. }
  17172. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17173. {
  17174. return knownFormats [index];
  17175. }
  17176. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17177. {
  17178. return getKnownFormat (defaultFormatIndex);
  17179. }
  17180. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17181. {
  17182. String e (fileExtension);
  17183. if (! e.startsWithChar ('.'))
  17184. e = "." + e;
  17185. for (int i = 0; i < getNumKnownFormats(); ++i)
  17186. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17187. return getKnownFormat(i);
  17188. return 0;
  17189. }
  17190. const String AudioFormatManager::getWildcardForAllFormats() const
  17191. {
  17192. StringArray allExtensions;
  17193. int i;
  17194. for (i = 0; i < getNumKnownFormats(); ++i)
  17195. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17196. allExtensions.trim();
  17197. allExtensions.removeEmptyStrings();
  17198. String s;
  17199. for (i = 0; i < allExtensions.size(); ++i)
  17200. {
  17201. s << '*';
  17202. if (! allExtensions[i].startsWithChar ('.'))
  17203. s << '.';
  17204. s << allExtensions[i];
  17205. if (i < allExtensions.size() - 1)
  17206. s << ';';
  17207. }
  17208. return s;
  17209. }
  17210. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17211. {
  17212. // you need to actually register some formats before the manager can
  17213. // use them to open a file!
  17214. jassert (getNumKnownFormats() > 0);
  17215. for (int i = 0; i < getNumKnownFormats(); ++i)
  17216. {
  17217. AudioFormat* const af = getKnownFormat(i);
  17218. if (af->canHandleFile (file))
  17219. {
  17220. InputStream* const in = file.createInputStream();
  17221. if (in != 0)
  17222. {
  17223. AudioFormatReader* const r = af->createReaderFor (in, true);
  17224. if (r != 0)
  17225. return r;
  17226. }
  17227. }
  17228. }
  17229. return 0;
  17230. }
  17231. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17232. {
  17233. // you need to actually register some formats before the manager can
  17234. // use them to open a file!
  17235. jassert (getNumKnownFormats() > 0);
  17236. ScopedPointer <InputStream> in (audioFileStream);
  17237. if (in != 0)
  17238. {
  17239. const int64 originalStreamPos = in->getPosition();
  17240. for (int i = 0; i < getNumKnownFormats(); ++i)
  17241. {
  17242. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17243. if (r != 0)
  17244. {
  17245. in.release();
  17246. return r;
  17247. }
  17248. in->setPosition (originalStreamPos);
  17249. // the stream that is passed-in must be capable of being repositioned so
  17250. // that all the formats can have a go at opening it.
  17251. jassert (in->getPosition() == originalStreamPos);
  17252. }
  17253. }
  17254. return 0;
  17255. }
  17256. END_JUCE_NAMESPACE
  17257. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17258. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17259. BEGIN_JUCE_NAMESPACE
  17260. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17261. const int64 startSample_,
  17262. const int64 length_,
  17263. const bool deleteSourceWhenDeleted_)
  17264. : AudioFormatReader (0, source_->getFormatName()),
  17265. source (source_),
  17266. startSample (startSample_),
  17267. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17268. {
  17269. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17270. sampleRate = source->sampleRate;
  17271. bitsPerSample = source->bitsPerSample;
  17272. lengthInSamples = length;
  17273. numChannels = source->numChannels;
  17274. usesFloatingPointData = source->usesFloatingPointData;
  17275. }
  17276. AudioSubsectionReader::~AudioSubsectionReader()
  17277. {
  17278. if (deleteSourceWhenDeleted)
  17279. delete source;
  17280. }
  17281. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17282. int64 startSampleInFile, int numSamples)
  17283. {
  17284. if (startSampleInFile + numSamples > length)
  17285. {
  17286. for (int i = numDestChannels; --i >= 0;)
  17287. if (destSamples[i] != 0)
  17288. zeromem (destSamples[i], sizeof (int) * numSamples);
  17289. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17290. if (numSamples <= 0)
  17291. return true;
  17292. }
  17293. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17294. startSampleInFile + startSample, numSamples);
  17295. }
  17296. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17297. int64 numSamples,
  17298. float& lowestLeft,
  17299. float& highestLeft,
  17300. float& lowestRight,
  17301. float& highestRight)
  17302. {
  17303. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17304. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17305. source->readMaxLevels (startSampleInFile + startSample,
  17306. numSamples,
  17307. lowestLeft,
  17308. highestLeft,
  17309. lowestRight,
  17310. highestRight);
  17311. }
  17312. END_JUCE_NAMESPACE
  17313. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17314. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17315. BEGIN_JUCE_NAMESPACE
  17316. struct AudioThumbnail::MinMaxValue
  17317. {
  17318. char minValue;
  17319. char maxValue;
  17320. MinMaxValue() : minValue (0), maxValue (0)
  17321. {
  17322. }
  17323. inline void set (const char newMin, const char newMax) throw()
  17324. {
  17325. minValue = newMin;
  17326. maxValue = newMax;
  17327. }
  17328. inline void setFloat (const float newMin, const float newMax) throw()
  17329. {
  17330. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17331. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17332. if (maxValue == minValue)
  17333. maxValue = (char) jmin (127, maxValue + 1);
  17334. }
  17335. inline bool isNonZero() const throw()
  17336. {
  17337. return maxValue > minValue;
  17338. }
  17339. inline int getPeak() const throw()
  17340. {
  17341. return jmax (std::abs ((int) minValue),
  17342. std::abs ((int) maxValue));
  17343. }
  17344. inline void read (InputStream& input)
  17345. {
  17346. minValue = input.readByte();
  17347. maxValue = input.readByte();
  17348. }
  17349. inline void write (OutputStream& output)
  17350. {
  17351. output.writeByte (minValue);
  17352. output.writeByte (maxValue);
  17353. }
  17354. };
  17355. class AudioThumbnail::LevelDataSource : public TimeSliceClient
  17356. {
  17357. public:
  17358. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17359. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17360. hashCode (hash), owner (owner_), reader (newReader)
  17361. {
  17362. }
  17363. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17364. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17365. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17366. {
  17367. }
  17368. ~LevelDataSource()
  17369. {
  17370. owner.cache.removeTimeSliceClient (this);
  17371. }
  17372. enum { timeBeforeDeletingReader = 1000 };
  17373. void initialise (int64 numSamplesFinished_)
  17374. {
  17375. const ScopedLock sl (readerLock);
  17376. numSamplesFinished = numSamplesFinished_;
  17377. createReader();
  17378. if (reader != 0)
  17379. {
  17380. lengthInSamples = reader->lengthInSamples;
  17381. numChannels = reader->numChannels;
  17382. sampleRate = reader->sampleRate;
  17383. if (lengthInSamples <= 0 || isFullyLoaded())
  17384. reader = 0;
  17385. else
  17386. owner.cache.addTimeSliceClient (this);
  17387. }
  17388. }
  17389. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17390. {
  17391. const ScopedLock sl (readerLock);
  17392. if (reader == 0)
  17393. {
  17394. createReader();
  17395. if (reader != 0)
  17396. owner.cache.addTimeSliceClient (this);
  17397. }
  17398. if (reader != 0)
  17399. {
  17400. float l[4] = { 0 };
  17401. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17402. levels.clearQuick();
  17403. levels.addArray ((const float*) l, 4);
  17404. }
  17405. }
  17406. void releaseResources()
  17407. {
  17408. const ScopedLock sl (readerLock);
  17409. reader = 0;
  17410. }
  17411. int useTimeSlice()
  17412. {
  17413. if (isFullyLoaded())
  17414. {
  17415. if (reader != 0 && source != 0)
  17416. releaseResources();
  17417. return -1;
  17418. }
  17419. bool justFinished = false;
  17420. {
  17421. const ScopedLock sl (readerLock);
  17422. createReader();
  17423. if (reader != 0)
  17424. {
  17425. if (! readNextBlock())
  17426. return 0;
  17427. justFinished = true;
  17428. }
  17429. }
  17430. if (justFinished)
  17431. owner.cache.storeThumb (owner, hashCode);
  17432. return timeBeforeDeletingReader;
  17433. }
  17434. bool isFullyLoaded() const throw()
  17435. {
  17436. return numSamplesFinished >= lengthInSamples;
  17437. }
  17438. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17439. {
  17440. return (int) (originalSample / owner.samplesPerThumbSample);
  17441. }
  17442. int64 lengthInSamples, numSamplesFinished;
  17443. double sampleRate;
  17444. int numChannels;
  17445. int64 hashCode;
  17446. private:
  17447. AudioThumbnail& owner;
  17448. ScopedPointer <InputSource> source;
  17449. ScopedPointer <AudioFormatReader> reader;
  17450. CriticalSection readerLock;
  17451. void createReader()
  17452. {
  17453. if (reader == 0 && source != 0)
  17454. {
  17455. InputStream* audioFileStream = source->createInputStream();
  17456. if (audioFileStream != 0)
  17457. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17458. }
  17459. }
  17460. bool readNextBlock()
  17461. {
  17462. jassert (reader != 0);
  17463. if (! isFullyLoaded())
  17464. {
  17465. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17466. if (numToDo > 0)
  17467. {
  17468. int64 startSample = numSamplesFinished;
  17469. const int firstThumbIndex = sampleToThumbSample (startSample);
  17470. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17471. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17472. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17473. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17474. for (int i = 0; i < numThumbSamps; ++i)
  17475. {
  17476. float lowestLeft, highestLeft, lowestRight, highestRight;
  17477. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17478. lowestLeft, highestLeft, lowestRight, highestRight);
  17479. levels[0][i].setFloat (lowestLeft, highestLeft);
  17480. levels[1][i].setFloat (lowestRight, highestRight);
  17481. }
  17482. {
  17483. const ScopedUnlock su (readerLock);
  17484. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17485. }
  17486. numSamplesFinished += numToDo;
  17487. }
  17488. }
  17489. return isFullyLoaded();
  17490. }
  17491. };
  17492. class AudioThumbnail::ThumbData
  17493. {
  17494. public:
  17495. ThumbData (const int numThumbSamples)
  17496. : peakLevel (-1)
  17497. {
  17498. ensureSize (numThumbSamples);
  17499. }
  17500. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17501. {
  17502. jassert (thumbSampleIndex < data.size());
  17503. return data.getRawDataPointer() + thumbSampleIndex;
  17504. }
  17505. int getSize() const throw()
  17506. {
  17507. return data.size();
  17508. }
  17509. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17510. {
  17511. if (startSample >= 0)
  17512. {
  17513. endSample = jmin (endSample, data.size() - 1);
  17514. char mx = -128;
  17515. char mn = 127;
  17516. while (startSample <= endSample)
  17517. {
  17518. const MinMaxValue& v = data.getReference (startSample);
  17519. if (v.minValue < mn) mn = v.minValue;
  17520. if (v.maxValue > mx) mx = v.maxValue;
  17521. ++startSample;
  17522. }
  17523. if (mn <= mx)
  17524. {
  17525. result.set (mn, mx);
  17526. return;
  17527. }
  17528. }
  17529. result.set (1, 0);
  17530. }
  17531. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17532. {
  17533. resetPeak();
  17534. if (startIndex + numValues > data.size())
  17535. ensureSize (startIndex + numValues);
  17536. MinMaxValue* const dest = getData (startIndex);
  17537. for (int i = 0; i < numValues; ++i)
  17538. dest[i] = source[i];
  17539. }
  17540. void resetPeak()
  17541. {
  17542. peakLevel = -1;
  17543. }
  17544. int getPeak()
  17545. {
  17546. if (peakLevel < 0)
  17547. {
  17548. for (int i = 0; i < data.size(); ++i)
  17549. {
  17550. const int peak = data[i].getPeak();
  17551. if (peak > peakLevel)
  17552. peakLevel = peak;
  17553. }
  17554. }
  17555. return peakLevel;
  17556. }
  17557. private:
  17558. Array <MinMaxValue> data;
  17559. int peakLevel;
  17560. void ensureSize (const int thumbSamples)
  17561. {
  17562. const int extraNeeded = thumbSamples - data.size();
  17563. if (extraNeeded > 0)
  17564. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17565. }
  17566. };
  17567. class AudioThumbnail::CachedWindow
  17568. {
  17569. public:
  17570. CachedWindow()
  17571. : cachedStart (0), cachedTimePerPixel (0),
  17572. numChannelsCached (0), numSamplesCached (0),
  17573. cacheNeedsRefilling (true)
  17574. {
  17575. }
  17576. void invalidate()
  17577. {
  17578. cacheNeedsRefilling = true;
  17579. }
  17580. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17581. const double startTime, const double endTime,
  17582. const int channelNum, const float verticalZoomFactor,
  17583. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17584. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17585. {
  17586. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17587. numChannels, samplesPerThumbSample, levelData, channels);
  17588. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17589. {
  17590. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17591. if (! clip.isEmpty())
  17592. {
  17593. const float topY = (float) area.getY();
  17594. const float bottomY = (float) area.getBottom();
  17595. const float midY = (topY + bottomY) * 0.5f;
  17596. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17597. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17598. int x = clip.getX();
  17599. for (int w = clip.getWidth(); --w >= 0;)
  17600. {
  17601. if (cacheData->isNonZero())
  17602. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17603. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17604. ++x;
  17605. ++cacheData;
  17606. }
  17607. }
  17608. }
  17609. }
  17610. private:
  17611. Array <MinMaxValue> data;
  17612. double cachedStart, cachedTimePerPixel;
  17613. int numChannelsCached, numSamplesCached;
  17614. bool cacheNeedsRefilling;
  17615. void refillCache (const int numSamples, double startTime, const double endTime,
  17616. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17617. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17618. {
  17619. const double timePerPixel = (endTime - startTime) / numSamples;
  17620. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17621. {
  17622. invalidate();
  17623. return;
  17624. }
  17625. if (numSamples == numSamplesCached
  17626. && numChannelsCached == numChannels
  17627. && startTime == cachedStart
  17628. && timePerPixel == cachedTimePerPixel
  17629. && ! cacheNeedsRefilling)
  17630. {
  17631. return;
  17632. }
  17633. numSamplesCached = numSamples;
  17634. numChannelsCached = numChannels;
  17635. cachedStart = startTime;
  17636. cachedTimePerPixel = timePerPixel;
  17637. cacheNeedsRefilling = false;
  17638. ensureSize (numSamples);
  17639. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17640. {
  17641. int sample = roundToInt (startTime * sampleRate);
  17642. Array<float> levels;
  17643. int i;
  17644. for (i = 0; i < numSamples; ++i)
  17645. {
  17646. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17647. if (sample >= 0)
  17648. {
  17649. if (sample >= levelData->lengthInSamples)
  17650. break;
  17651. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17652. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17653. for (int chan = 0; chan < numChans; ++chan)
  17654. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17655. levels.getUnchecked (chan * 2 + 1));
  17656. }
  17657. startTime += timePerPixel;
  17658. sample = nextSample;
  17659. }
  17660. numSamplesCached = i;
  17661. }
  17662. else
  17663. {
  17664. jassert (channels.size() == numChannelsCached);
  17665. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17666. {
  17667. ThumbData* channelData = channels.getUnchecked (channelNum);
  17668. MinMaxValue* cacheData = getData (channelNum, 0);
  17669. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17670. startTime = cachedStart;
  17671. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17672. for (int i = numSamples; --i >= 0;)
  17673. {
  17674. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17675. channelData->getMinMax (sample, nextSample, *cacheData);
  17676. ++cacheData;
  17677. startTime += timePerPixel;
  17678. sample = nextSample;
  17679. }
  17680. }
  17681. }
  17682. }
  17683. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17684. {
  17685. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17686. return data.getRawDataPointer() + channelNum * numSamplesCached
  17687. + cacheIndex;
  17688. }
  17689. void ensureSize (const int numSamples)
  17690. {
  17691. const int itemsRequired = numSamples * numChannelsCached;
  17692. if (data.size() < itemsRequired)
  17693. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  17694. }
  17695. };
  17696. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  17697. AudioFormatManager& formatManagerToUse_,
  17698. AudioThumbnailCache& cacheToUse)
  17699. : formatManagerToUse (formatManagerToUse_),
  17700. cache (cacheToUse),
  17701. window (new CachedWindow()),
  17702. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  17703. totalSamples (0),
  17704. numChannels (0),
  17705. sampleRate (0)
  17706. {
  17707. }
  17708. AudioThumbnail::~AudioThumbnail()
  17709. {
  17710. clear();
  17711. }
  17712. void AudioThumbnail::clear()
  17713. {
  17714. source = 0;
  17715. const ScopedLock sl (lock);
  17716. window->invalidate();
  17717. channels.clear();
  17718. totalSamples = numSamplesFinished = 0;
  17719. numChannels = 0;
  17720. sampleRate = 0;
  17721. sendChangeMessage();
  17722. }
  17723. void AudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  17724. {
  17725. clear();
  17726. numChannels = newNumChannels;
  17727. sampleRate = newSampleRate;
  17728. totalSamples = totalSamplesInSource;
  17729. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  17730. }
  17731. void AudioThumbnail::createChannels (const int length)
  17732. {
  17733. while (channels.size() < numChannels)
  17734. channels.add (new ThumbData (length));
  17735. }
  17736. void AudioThumbnail::loadFrom (InputStream& input)
  17737. {
  17738. clear();
  17739. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  17740. return;
  17741. samplesPerThumbSample = input.readInt();
  17742. totalSamples = input.readInt64(); // Total number of source samples.
  17743. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  17744. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  17745. numChannels = input.readInt(); // Number of audio channels.
  17746. sampleRate = input.readInt(); // Source sample rate.
  17747. input.skipNextBytes (16); // reserved area
  17748. createChannels (numThumbnailSamples);
  17749. for (int i = 0; i < numThumbnailSamples; ++i)
  17750. for (int chan = 0; chan < numChannels; ++chan)
  17751. channels.getUnchecked(chan)->getData(i)->read (input);
  17752. }
  17753. void AudioThumbnail::saveTo (OutputStream& output) const
  17754. {
  17755. const ScopedLock sl (lock);
  17756. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  17757. output.write ("jatm", 4);
  17758. output.writeInt (samplesPerThumbSample);
  17759. output.writeInt64 (totalSamples);
  17760. output.writeInt64 (numSamplesFinished);
  17761. output.writeInt (numThumbnailSamples);
  17762. output.writeInt (numChannels);
  17763. output.writeInt ((int) sampleRate);
  17764. output.writeInt64 (0);
  17765. output.writeInt64 (0);
  17766. for (int i = 0; i < numThumbnailSamples; ++i)
  17767. for (int chan = 0; chan < numChannels; ++chan)
  17768. channels.getUnchecked(chan)->getData(i)->write (output);
  17769. }
  17770. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  17771. {
  17772. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  17773. numSamplesFinished = 0;
  17774. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  17775. {
  17776. source = newSource; // (make sure this isn't done before loadThumb is called)
  17777. source->lengthInSamples = totalSamples;
  17778. source->sampleRate = sampleRate;
  17779. source->numChannels = numChannels;
  17780. source->numSamplesFinished = numSamplesFinished;
  17781. }
  17782. else
  17783. {
  17784. source = newSource; // (make sure this isn't done before loadThumb is called)
  17785. const ScopedLock sl (lock);
  17786. source->initialise (numSamplesFinished);
  17787. totalSamples = source->lengthInSamples;
  17788. sampleRate = source->sampleRate;
  17789. numChannels = source->numChannels;
  17790. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  17791. }
  17792. return sampleRate > 0 && totalSamples > 0;
  17793. }
  17794. bool AudioThumbnail::setSource (InputSource* const newSource)
  17795. {
  17796. clear();
  17797. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  17798. }
  17799. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  17800. {
  17801. clear();
  17802. if (newReader != 0)
  17803. setDataSource (new LevelDataSource (*this, newReader, hash));
  17804. }
  17805. int64 AudioThumbnail::getHashCode() const
  17806. {
  17807. return source == 0 ? 0 : source->hashCode;
  17808. }
  17809. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  17810. int startOffsetInBuffer, int numSamples)
  17811. {
  17812. jassert (startSample >= 0);
  17813. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  17814. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  17815. const int numToDo = lastThumbIndex - firstThumbIndex;
  17816. if (numToDo > 0)
  17817. {
  17818. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  17819. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  17820. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  17821. for (int chan = 0; chan < numChans; ++chan)
  17822. {
  17823. const float* const sourceData = incoming.getSampleData (chan, startOffsetInBuffer);
  17824. MinMaxValue* const dest = thumbData + numToDo * chan;
  17825. thumbChannels [chan] = dest;
  17826. for (int i = 0; i < numToDo; ++i)
  17827. {
  17828. float low, high;
  17829. const int start = i * samplesPerThumbSample;
  17830. findMinAndMax (sourceData + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  17831. dest[i].setFloat (low, high);
  17832. }
  17833. }
  17834. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  17835. }
  17836. }
  17837. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  17838. {
  17839. const ScopedLock sl (lock);
  17840. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  17841. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  17842. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  17843. totalSamples = jmax (numSamplesFinished, totalSamples);
  17844. window->invalidate();
  17845. sendChangeMessage();
  17846. }
  17847. int AudioThumbnail::getNumChannels() const throw()
  17848. {
  17849. return numChannels;
  17850. }
  17851. double AudioThumbnail::getTotalLength() const throw()
  17852. {
  17853. return totalSamples / sampleRate;
  17854. }
  17855. bool AudioThumbnail::isFullyLoaded() const throw()
  17856. {
  17857. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  17858. }
  17859. int64 AudioThumbnail::getNumSamplesFinished() const throw()
  17860. {
  17861. return numSamplesFinished;
  17862. }
  17863. float AudioThumbnail::getApproximatePeak() const
  17864. {
  17865. int peak = 0;
  17866. for (int i = channels.size(); --i >= 0;)
  17867. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  17868. return jlimit (0, 127, peak) / 127.0f;
  17869. }
  17870. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  17871. double endTime, int channelNum, float verticalZoomFactor)
  17872. {
  17873. const ScopedLock sl (lock);
  17874. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  17875. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  17876. }
  17877. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  17878. double endTimeSeconds, float verticalZoomFactor)
  17879. {
  17880. for (int i = 0; i < numChannels; ++i)
  17881. {
  17882. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  17883. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  17884. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  17885. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  17886. }
  17887. }
  17888. END_JUCE_NAMESPACE
  17889. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17890. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17891. BEGIN_JUCE_NAMESPACE
  17892. struct ThumbnailCacheEntry
  17893. {
  17894. int64 hash;
  17895. uint32 lastUsed;
  17896. MemoryBlock data;
  17897. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  17898. };
  17899. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  17900. : TimeSliceThread ("thumb cache"),
  17901. maxNumThumbsToStore (maxNumThumbsToStore_)
  17902. {
  17903. startThread (2);
  17904. }
  17905. AudioThumbnailCache::~AudioThumbnailCache()
  17906. {
  17907. }
  17908. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  17909. {
  17910. for (int i = thumbs.size(); --i >= 0;)
  17911. if (thumbs.getUnchecked(i)->hash == hash)
  17912. return thumbs.getUnchecked(i);
  17913. return 0;
  17914. }
  17915. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  17916. {
  17917. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17918. if (te != 0)
  17919. {
  17920. te->lastUsed = Time::getMillisecondCounter();
  17921. MemoryInputStream in (te->data, false);
  17922. thumb.loadFrom (in);
  17923. return true;
  17924. }
  17925. return false;
  17926. }
  17927. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17928. const int64 hashCode)
  17929. {
  17930. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17931. if (te == 0)
  17932. {
  17933. te = new ThumbnailCacheEntry();
  17934. te->hash = hashCode;
  17935. if (thumbs.size() < maxNumThumbsToStore)
  17936. {
  17937. thumbs.add (te);
  17938. }
  17939. else
  17940. {
  17941. int oldest = 0;
  17942. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  17943. for (int i = thumbs.size(); --i >= 0;)
  17944. {
  17945. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  17946. {
  17947. oldest = i;
  17948. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  17949. }
  17950. }
  17951. thumbs.set (oldest, te);
  17952. }
  17953. }
  17954. te->lastUsed = Time::getMillisecondCounter();
  17955. MemoryOutputStream out (te->data, false);
  17956. thumb.saveTo (out);
  17957. }
  17958. void AudioThumbnailCache::clear()
  17959. {
  17960. thumbs.clear();
  17961. }
  17962. END_JUCE_NAMESPACE
  17963. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17964. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17965. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17966. #if ! JUCE_WINDOWS
  17967. #include <QuickTime/Movies.h>
  17968. #include <QuickTime/QTML.h>
  17969. #include <QuickTime/QuickTimeComponents.h>
  17970. #include <QuickTime/MediaHandlers.h>
  17971. #include <QuickTime/ImageCodec.h>
  17972. #else
  17973. #if JUCE_MSVC
  17974. #pragma warning (push)
  17975. #pragma warning (disable : 4100)
  17976. #endif
  17977. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17978. add its header directory to your include path.
  17979. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  17980. flag in juce_Config.h
  17981. */
  17982. #include <Movies.h>
  17983. #include <QTML.h>
  17984. #include <QuickTimeComponents.h>
  17985. #include <MediaHandlers.h>
  17986. #include <ImageCodec.h>
  17987. #if JUCE_MSVC
  17988. #pragma warning (pop)
  17989. #endif
  17990. #endif
  17991. BEGIN_JUCE_NAMESPACE
  17992. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17993. static const char* const quickTimeFormatName = "QuickTime file";
  17994. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  17995. class QTAudioReader : public AudioFormatReader
  17996. {
  17997. public:
  17998. QTAudioReader (InputStream* const input_, const int trackNum_)
  17999. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18000. ok (false),
  18001. movie (0),
  18002. trackNum (trackNum_),
  18003. lastSampleRead (0),
  18004. lastThreadId (0),
  18005. extractor (0),
  18006. dataHandle (0)
  18007. {
  18008. JUCE_AUTORELEASEPOOL
  18009. bufferList.calloc (256, 1);
  18010. #if JUCE_WINDOWS
  18011. if (InitializeQTML (0) != noErr)
  18012. return;
  18013. #endif
  18014. if (EnterMovies() != noErr)
  18015. return;
  18016. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18017. if (! opened)
  18018. return;
  18019. {
  18020. const int numTracks = GetMovieTrackCount (movie);
  18021. int trackCount = 0;
  18022. for (int i = 1; i <= numTracks; ++i)
  18023. {
  18024. track = GetMovieIndTrack (movie, i);
  18025. media = GetTrackMedia (track);
  18026. OSType mediaType;
  18027. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18028. if (mediaType == SoundMediaType
  18029. && trackCount++ == trackNum_)
  18030. {
  18031. ok = true;
  18032. break;
  18033. }
  18034. }
  18035. }
  18036. if (! ok)
  18037. return;
  18038. ok = false;
  18039. lengthInSamples = GetMediaDecodeDuration (media);
  18040. usesFloatingPointData = false;
  18041. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18042. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18043. / GetMediaTimeScale (media);
  18044. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18045. unsigned long output_layout_size;
  18046. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18047. kQTPropertyClass_MovieAudioExtraction_Audio,
  18048. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18049. 0, &output_layout_size, 0);
  18050. if (err != noErr)
  18051. return;
  18052. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18053. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18054. err = MovieAudioExtractionGetProperty (extractor,
  18055. kQTPropertyClass_MovieAudioExtraction_Audio,
  18056. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18057. output_layout_size, qt_audio_channel_layout, 0);
  18058. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18059. err = MovieAudioExtractionSetProperty (extractor,
  18060. kQTPropertyClass_MovieAudioExtraction_Audio,
  18061. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18062. output_layout_size,
  18063. qt_audio_channel_layout);
  18064. err = MovieAudioExtractionGetProperty (extractor,
  18065. kQTPropertyClass_MovieAudioExtraction_Audio,
  18066. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18067. sizeof (inputStreamDesc),
  18068. &inputStreamDesc, 0);
  18069. if (err != noErr)
  18070. return;
  18071. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18072. | kAudioFormatFlagIsPacked
  18073. | kAudioFormatFlagsNativeEndian;
  18074. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18075. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18076. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18077. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18078. err = MovieAudioExtractionSetProperty (extractor,
  18079. kQTPropertyClass_MovieAudioExtraction_Audio,
  18080. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18081. sizeof (inputStreamDesc),
  18082. &inputStreamDesc);
  18083. if (err != noErr)
  18084. return;
  18085. Boolean allChannelsDiscrete = false;
  18086. err = MovieAudioExtractionSetProperty (extractor,
  18087. kQTPropertyClass_MovieAudioExtraction_Movie,
  18088. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18089. sizeof (allChannelsDiscrete),
  18090. &allChannelsDiscrete);
  18091. if (err != noErr)
  18092. return;
  18093. bufferList->mNumberBuffers = 1;
  18094. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18095. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18096. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18097. bufferList->mBuffers[0].mData = dataBuffer;
  18098. sampleRate = inputStreamDesc.mSampleRate;
  18099. bitsPerSample = 16;
  18100. numChannels = inputStreamDesc.mChannelsPerFrame;
  18101. detachThread();
  18102. ok = true;
  18103. }
  18104. ~QTAudioReader()
  18105. {
  18106. JUCE_AUTORELEASEPOOL
  18107. checkThreadIsAttached();
  18108. if (dataHandle != 0)
  18109. DisposeHandle (dataHandle);
  18110. if (extractor != 0)
  18111. {
  18112. MovieAudioExtractionEnd (extractor);
  18113. extractor = 0;
  18114. }
  18115. DisposeMovie (movie);
  18116. #if JUCE_MAC
  18117. ExitMoviesOnThread ();
  18118. #endif
  18119. }
  18120. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18121. int64 startSampleInFile, int numSamples)
  18122. {
  18123. JUCE_AUTORELEASEPOOL
  18124. checkThreadIsAttached();
  18125. bool ok = true;
  18126. while (numSamples > 0)
  18127. {
  18128. if (lastSampleRead != startSampleInFile)
  18129. {
  18130. TimeRecord time;
  18131. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18132. time.base = 0;
  18133. time.value.hi = 0;
  18134. time.value.lo = (UInt32) startSampleInFile;
  18135. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18136. kQTPropertyClass_MovieAudioExtraction_Movie,
  18137. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18138. sizeof (time), &time);
  18139. if (err != noErr)
  18140. {
  18141. ok = false;
  18142. break;
  18143. }
  18144. }
  18145. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18146. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18147. UInt32 outFlags = 0;
  18148. UInt32 actualNumFrames = framesToDo;
  18149. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18150. if (err != noErr)
  18151. {
  18152. ok = false;
  18153. break;
  18154. }
  18155. lastSampleRead = startSampleInFile + actualNumFrames;
  18156. const int samplesReceived = actualNumFrames;
  18157. for (int j = numDestChannels; --j >= 0;)
  18158. {
  18159. if (destSamples[j] != 0)
  18160. {
  18161. const short* src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18162. for (int i = 0; i < samplesReceived; ++i)
  18163. {
  18164. destSamples[j][startOffsetInDestBuffer + i] = (*src << 16);
  18165. src += numChannels;
  18166. }
  18167. }
  18168. }
  18169. startOffsetInDestBuffer += samplesReceived;
  18170. startSampleInFile += samplesReceived;
  18171. numSamples -= samplesReceived;
  18172. if (((outFlags & kQTMovieAudioExtractionComplete) != 0 || samplesReceived == 0) && numSamples > 0)
  18173. {
  18174. for (int j = numDestChannels; --j >= 0;)
  18175. if (destSamples[j] != 0)
  18176. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18177. break;
  18178. }
  18179. }
  18180. detachThread();
  18181. return ok;
  18182. }
  18183. bool ok;
  18184. private:
  18185. Movie movie;
  18186. Media media;
  18187. Track track;
  18188. const int trackNum;
  18189. double trackUnitsPerFrame;
  18190. int samplesPerFrame;
  18191. int64 lastSampleRead;
  18192. Thread::ThreadID lastThreadId;
  18193. MovieAudioExtractionRef extractor;
  18194. AudioStreamBasicDescription inputStreamDesc;
  18195. HeapBlock <AudioBufferList> bufferList;
  18196. HeapBlock <char> dataBuffer;
  18197. Handle dataHandle;
  18198. void checkThreadIsAttached()
  18199. {
  18200. #if JUCE_MAC
  18201. if (Thread::getCurrentThreadId() != lastThreadId)
  18202. EnterMoviesOnThread (0);
  18203. AttachMovieToCurrentThread (movie);
  18204. #endif
  18205. }
  18206. void detachThread()
  18207. {
  18208. #if JUCE_MAC
  18209. DetachMovieFromCurrentThread (movie);
  18210. #endif
  18211. }
  18212. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18213. };
  18214. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18215. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18216. {
  18217. }
  18218. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18219. {
  18220. }
  18221. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18222. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18223. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18224. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18225. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18226. const bool deleteStreamIfOpeningFails)
  18227. {
  18228. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18229. if (r->ok)
  18230. return r.release();
  18231. if (! deleteStreamIfOpeningFails)
  18232. r->input = 0;
  18233. return 0;
  18234. }
  18235. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18236. double /*sampleRateToUse*/,
  18237. unsigned int /*numberOfChannels*/,
  18238. int /*bitsPerSample*/,
  18239. const StringPairArray& /*metadataValues*/,
  18240. int /*qualityOptionIndex*/)
  18241. {
  18242. jassertfalse; // not yet implemented!
  18243. return 0;
  18244. }
  18245. END_JUCE_NAMESPACE
  18246. #endif
  18247. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18248. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18249. BEGIN_JUCE_NAMESPACE
  18250. static const char* const wavFormatName = "WAV file";
  18251. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18252. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18253. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18254. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18255. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18256. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18257. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18258. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18259. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18260. const String& originator,
  18261. const String& originatorRef,
  18262. const Time& date,
  18263. const int64 timeReferenceSamples,
  18264. const String& codingHistory)
  18265. {
  18266. StringPairArray m;
  18267. m.set (bwavDescription, description);
  18268. m.set (bwavOriginator, originator);
  18269. m.set (bwavOriginatorRef, originatorRef);
  18270. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18271. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18272. m.set (bwavTimeReference, String (timeReferenceSamples));
  18273. m.set (bwavCodingHistory, codingHistory);
  18274. return m;
  18275. }
  18276. namespace WavFileHelpers
  18277. {
  18278. #if JUCE_MSVC
  18279. #pragma pack (push, 1)
  18280. #define PACKED
  18281. #elif JUCE_GCC
  18282. #define PACKED __attribute__((packed))
  18283. #else
  18284. #define PACKED
  18285. #endif
  18286. struct BWAVChunk
  18287. {
  18288. char description [256];
  18289. char originator [32];
  18290. char originatorRef [32];
  18291. char originationDate [10];
  18292. char originationTime [8];
  18293. uint32 timeRefLow;
  18294. uint32 timeRefHigh;
  18295. uint16 version;
  18296. uint8 umid[64];
  18297. uint8 reserved[190];
  18298. char codingHistory[1];
  18299. void copyTo (StringPairArray& values) const
  18300. {
  18301. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18302. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18303. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18304. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18305. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18306. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18307. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18308. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18309. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18310. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18311. }
  18312. static MemoryBlock createFrom (const StringPairArray& values)
  18313. {
  18314. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18315. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18316. data.fillWith (0);
  18317. BWAVChunk* b = (BWAVChunk*) data.getData();
  18318. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18319. // as they get called in the right order..
  18320. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18321. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18322. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18323. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18324. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18325. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18326. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18327. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18328. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18329. if (b->description[0] != 0
  18330. || b->originator[0] != 0
  18331. || b->originationDate[0] != 0
  18332. || b->originationTime[0] != 0
  18333. || b->codingHistory[0] != 0
  18334. || time != 0)
  18335. {
  18336. return data;
  18337. }
  18338. return MemoryBlock();
  18339. }
  18340. } PACKED;
  18341. struct SMPLChunk
  18342. {
  18343. struct SampleLoop
  18344. {
  18345. uint32 identifier;
  18346. uint32 type;
  18347. uint32 start;
  18348. uint32 end;
  18349. uint32 fraction;
  18350. uint32 playCount;
  18351. } PACKED;
  18352. uint32 manufacturer;
  18353. uint32 product;
  18354. uint32 samplePeriod;
  18355. uint32 midiUnityNote;
  18356. uint32 midiPitchFraction;
  18357. uint32 smpteFormat;
  18358. uint32 smpteOffset;
  18359. uint32 numSampleLoops;
  18360. uint32 samplerData;
  18361. SampleLoop loops[1];
  18362. void copyTo (StringPairArray& values, const int totalSize) const
  18363. {
  18364. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18365. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18366. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18367. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18368. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18369. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18370. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18371. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18372. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18373. for (uint32 i = 0; i < numSampleLoops; ++i)
  18374. {
  18375. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18376. break;
  18377. const String prefix ("Loop" + String(i));
  18378. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18379. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18380. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18381. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18382. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18383. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18384. }
  18385. }
  18386. static MemoryBlock createFrom (const StringPairArray& values)
  18387. {
  18388. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18389. if (numLoops <= 0)
  18390. return MemoryBlock();
  18391. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18392. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18393. data.fillWith (0);
  18394. SMPLChunk* s = (SMPLChunk*) data.getData();
  18395. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18396. // as they get called in the right order..
  18397. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18398. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18399. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18400. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18401. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18402. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18403. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18404. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18405. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18406. for (int i = 0; i < numLoops; ++i)
  18407. {
  18408. const String prefix ("Loop" + String(i));
  18409. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18410. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18411. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18412. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18413. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18414. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18415. }
  18416. return data;
  18417. }
  18418. } PACKED;
  18419. struct ExtensibleWavSubFormat
  18420. {
  18421. uint32 data1;
  18422. uint16 data2;
  18423. uint16 data3;
  18424. uint8 data4[8];
  18425. } PACKED;
  18426. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  18427. {
  18428. uint32 riffSizeLow; // low 4 byte size of RF64 block
  18429. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  18430. uint32 dataSizeLow; // low 4 byte size of data chunk
  18431. uint32 dataSizeHigh; // high 4 byte size of data chunk
  18432. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  18433. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  18434. uint32 tableLength; // number of valid entries in array 'table'
  18435. } PACKED;
  18436. #if JUCE_MSVC
  18437. #pragma pack (pop)
  18438. #endif
  18439. #undef PACKED
  18440. inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18441. }
  18442. class WavAudioFormatReader : public AudioFormatReader
  18443. {
  18444. public:
  18445. WavAudioFormatReader (InputStream* const in)
  18446. : AudioFormatReader (in, TRANS (wavFormatName)),
  18447. bwavChunkStart (0),
  18448. bwavSize (0),
  18449. dataLength (0),
  18450. isRF64 (false)
  18451. {
  18452. using namespace WavFileHelpers;
  18453. uint64 len = 0;
  18454. int64 end = 0;
  18455. bool hasGotType = false;
  18456. bool hasGotData = false;
  18457. const int firstChunkType = input->readInt();
  18458. if (firstChunkType == chunkName ("RF64"))
  18459. {
  18460. input->skipNextBytes (4); // size is -1 for RF64
  18461. isRF64 = true;
  18462. }
  18463. else if (firstChunkType == chunkName ("RIFF"))
  18464. {
  18465. len = (uint64) input->readInt();
  18466. end = input->getPosition() + len;
  18467. }
  18468. else
  18469. {
  18470. return;
  18471. }
  18472. const int64 startOfRIFFChunk = input->getPosition();
  18473. if (input->readInt() == chunkName ("WAVE"))
  18474. {
  18475. if (isRF64 && input->readInt() == chunkName ("ds64"))
  18476. {
  18477. uint32 length = (uint32) input->readInt();
  18478. if (length < 28)
  18479. {
  18480. return;
  18481. }
  18482. else
  18483. {
  18484. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18485. len = input->readInt64();
  18486. end = startOfRIFFChunk + len;
  18487. dataLength = input->readInt64();
  18488. input->setPosition (chunkEnd);
  18489. }
  18490. }
  18491. while (input->getPosition() < end && ! input->isExhausted())
  18492. {
  18493. const int chunkType = input->readInt();
  18494. uint32 length = (uint32) input->readInt();
  18495. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18496. if (chunkType == chunkName ("fmt "))
  18497. {
  18498. // read the format chunk
  18499. const unsigned short format = input->readShort();
  18500. const short numChans = input->readShort();
  18501. sampleRate = input->readInt();
  18502. const int bytesPerSec = input->readInt();
  18503. numChannels = numChans;
  18504. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18505. bitsPerSample = 8 * bytesPerFrame / numChans;
  18506. if (format == 3)
  18507. {
  18508. usesFloatingPointData = true;
  18509. }
  18510. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18511. {
  18512. if (length < 40) // too short
  18513. {
  18514. bytesPerFrame = 0;
  18515. }
  18516. else
  18517. {
  18518. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18519. ExtensibleWavSubFormat subFormat;
  18520. subFormat.data1 = input->readInt();
  18521. subFormat.data2 = input->readShort();
  18522. subFormat.data3 = input->readShort();
  18523. input->read (subFormat.data4, sizeof (subFormat.data4));
  18524. const ExtensibleWavSubFormat pcmFormat
  18525. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18526. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18527. {
  18528. const ExtensibleWavSubFormat ambisonicFormat
  18529. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18530. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18531. bytesPerFrame = 0;
  18532. }
  18533. }
  18534. }
  18535. else if (format != 1)
  18536. {
  18537. bytesPerFrame = 0;
  18538. }
  18539. hasGotType = true;
  18540. }
  18541. else if (chunkType == chunkName ("data"))
  18542. {
  18543. // get the data chunk's position
  18544. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  18545. dataLength = length;
  18546. dataChunkStart = input->getPosition();
  18547. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18548. hasGotData = true;
  18549. }
  18550. else if (chunkType == chunkName ("bext"))
  18551. {
  18552. bwavChunkStart = input->getPosition();
  18553. bwavSize = length;
  18554. // Broadcast-wav extension chunk..
  18555. HeapBlock <BWAVChunk> bwav;
  18556. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18557. input->read (bwav, length);
  18558. bwav->copyTo (metadataValues);
  18559. }
  18560. else if (chunkType == chunkName ("smpl"))
  18561. {
  18562. HeapBlock <SMPLChunk> smpl;
  18563. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18564. input->read (smpl, length);
  18565. smpl->copyTo (metadataValues, length);
  18566. }
  18567. else if (chunkEnd <= input->getPosition())
  18568. {
  18569. break;
  18570. }
  18571. input->setPosition (chunkEnd);
  18572. }
  18573. }
  18574. }
  18575. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18576. int64 startSampleInFile, int numSamples)
  18577. {
  18578. jassert (destSamples != 0);
  18579. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18580. if (samplesAvailable < numSamples)
  18581. {
  18582. for (int i = numDestChannels; --i >= 0;)
  18583. if (destSamples[i] != 0)
  18584. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18585. numSamples = (int) samplesAvailable;
  18586. }
  18587. if (numSamples <= 0)
  18588. return true;
  18589. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18590. while (numSamples > 0)
  18591. {
  18592. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18593. char tempBuffer [tempBufSize];
  18594. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18595. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18596. if (bytesRead < numThisTime * bytesPerFrame)
  18597. {
  18598. jassert (bytesRead >= 0);
  18599. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18600. }
  18601. switch (bitsPerSample)
  18602. {
  18603. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18604. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18605. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18606. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18607. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18608. default: jassertfalse; break;
  18609. }
  18610. startOffsetInDestBuffer += numThisTime;
  18611. numSamples -= numThisTime;
  18612. }
  18613. return true;
  18614. }
  18615. int64 bwavChunkStart, bwavSize;
  18616. private:
  18617. ScopedPointer<AudioData::Converter> converter;
  18618. int bytesPerFrame;
  18619. int64 dataChunkStart, dataLength;
  18620. bool isRF64;
  18621. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18622. };
  18623. class WavAudioFormatWriter : public AudioFormatWriter
  18624. {
  18625. public:
  18626. WavAudioFormatWriter (OutputStream* const out, const double sampleRate_,
  18627. const unsigned int numChannels_, const int bits,
  18628. const StringPairArray& metadataValues)
  18629. : AudioFormatWriter (out, TRANS (wavFormatName), sampleRate_, numChannels_, bits),
  18630. lengthInSamples (0),
  18631. bytesWritten (0),
  18632. writeFailed (false)
  18633. {
  18634. using namespace WavFileHelpers;
  18635. if (metadataValues.size() > 0)
  18636. {
  18637. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18638. smplChunk = SMPLChunk::createFrom (metadataValues);
  18639. }
  18640. headerPosition = out->getPosition();
  18641. writeHeader();
  18642. }
  18643. ~WavAudioFormatWriter()
  18644. {
  18645. if ((bytesWritten & 1) != 0) // pad to an even length
  18646. {
  18647. ++bytesWritten;
  18648. output->writeByte (0);
  18649. }
  18650. writeHeader();
  18651. }
  18652. bool write (const int** data, int numSamples)
  18653. {
  18654. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18655. if (writeFailed)
  18656. return false;
  18657. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18658. tempBlock.ensureSize (bytes, false);
  18659. switch (bitsPerSample)
  18660. {
  18661. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18662. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18663. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18664. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18665. default: jassertfalse; break;
  18666. }
  18667. if (! output->write (tempBlock.getData(), bytes))
  18668. {
  18669. // failed to write to disk, so let's try writing the header.
  18670. // If it's just run out of disk space, then if it does manage
  18671. // to write the header, we'll still have a useable file..
  18672. writeHeader();
  18673. writeFailed = true;
  18674. return false;
  18675. }
  18676. else
  18677. {
  18678. bytesWritten += bytes;
  18679. lengthInSamples += numSamples;
  18680. return true;
  18681. }
  18682. }
  18683. private:
  18684. ScopedPointer<AudioData::Converter> converter;
  18685. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18686. uint64 lengthInSamples, bytesWritten;
  18687. int64 headerPosition;
  18688. bool writeFailed;
  18689. static int getChannelMask (const int numChannels) throw()
  18690. {
  18691. switch (numChannels)
  18692. {
  18693. case 1: return 0;
  18694. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  18695. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  18696. 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
  18697. default: break;
  18698. }
  18699. return 0;
  18700. }
  18701. void writeHeader()
  18702. {
  18703. using namespace WavFileHelpers;
  18704. const bool seekedOk = output->setPosition (headerPosition);
  18705. (void) seekedOk;
  18706. // if this fails, you've given it an output stream that can't seek! It needs
  18707. // to be able to seek back to write the header
  18708. jassert (seekedOk);
  18709. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18710. int64 audioDataSize = bytesPerFrame * lengthInSamples;
  18711. const bool isRF64 = (bytesWritten >= literal64bit (0x100000000));
  18712. int64 riffChunkSize = 4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  18713. + 8 + audioDataSize + (audioDataSize & 1)
  18714. + (bwavChunk.getSize() > 0 ? (8 + bwavChunk.getSize()) : 0)
  18715. + (smplChunk.getSize() > 0 ? (8 + smplChunk.getSize()) : 0)
  18716. + (8 + 28); // (ds64 chunk)
  18717. riffChunkSize += (riffChunkSize & 0x1);
  18718. output->writeInt (chunkName (isRF64 ? "RF64" : "RIFF"));
  18719. output->writeInt (isRF64 ? -1 : (int) riffChunkSize);
  18720. output->writeInt (chunkName ("WAVE"));
  18721. if (! isRF64)
  18722. {
  18723. output->writeInt (chunkName ("JUNK"));
  18724. output->writeInt (28 + 24);
  18725. output->writeRepeatedByte (0, 28 /* ds64 */ + 24 /* extra waveformatex */);
  18726. }
  18727. else
  18728. {
  18729. // write ds64 chunk
  18730. output->writeInt (chunkName ("ds64"));
  18731. output->writeInt (28); // chunk size for uncompressed data (no table)
  18732. output->writeInt64 (riffChunkSize);
  18733. output->writeInt64 (audioDataSize);
  18734. output->writeRepeatedByte (0, 12);
  18735. }
  18736. output->writeInt (chunkName ("fmt "));
  18737. if (isRF64)
  18738. {
  18739. output->writeInt (40); // chunk size
  18740. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  18741. }
  18742. else
  18743. {
  18744. output->writeInt (16); // chunk size
  18745. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  18746. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18747. }
  18748. output->writeShort ((short) numChannels);
  18749. output->writeInt ((int) sampleRate);
  18750. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  18751. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  18752. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  18753. if (isRF64)
  18754. {
  18755. output->writeShort (22); // cbSize (size of the extension)
  18756. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  18757. output->writeInt (getChannelMask (numChannels));
  18758. const ExtensibleWavSubFormat pcmFormat
  18759. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18760. const ExtensibleWavSubFormat IEEEFloatFormat
  18761. = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18762. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  18763. output->writeInt ((int) subFormat.data1);
  18764. output->writeShort ((short) subFormat.data2);
  18765. output->writeShort ((short) subFormat.data3);
  18766. output->write (subFormat.data4, sizeof (subFormat.data4));
  18767. }
  18768. if (bwavChunk.getSize() > 0)
  18769. {
  18770. output->writeInt (chunkName ("bext"));
  18771. output->writeInt ((int) bwavChunk.getSize());
  18772. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18773. }
  18774. if (smplChunk.getSize() > 0)
  18775. {
  18776. output->writeInt (chunkName ("smpl"));
  18777. output->writeInt ((int) smplChunk.getSize());
  18778. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18779. }
  18780. output->writeInt (chunkName ("data"));
  18781. output->writeInt (isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  18782. usesFloatingPointData = (bitsPerSample == 32);
  18783. }
  18784. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18785. };
  18786. WavAudioFormat::WavAudioFormat()
  18787. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18788. {
  18789. }
  18790. WavAudioFormat::~WavAudioFormat()
  18791. {
  18792. }
  18793. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18794. {
  18795. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18796. return Array <int> (rates);
  18797. }
  18798. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18799. {
  18800. const int depths[] = { 8, 16, 24, 32, 0 };
  18801. return Array <int> (depths);
  18802. }
  18803. bool WavAudioFormat::canDoStereo() { return true; }
  18804. bool WavAudioFormat::canDoMono() { return true; }
  18805. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18806. const bool deleteStreamIfOpeningFails)
  18807. {
  18808. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18809. if (r->sampleRate > 0)
  18810. return r.release();
  18811. if (! deleteStreamIfOpeningFails)
  18812. r->input = 0;
  18813. return 0;
  18814. }
  18815. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  18816. unsigned int numChannels, int bitsPerSample,
  18817. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  18818. {
  18819. if (getPossibleBitDepths().contains (bitsPerSample))
  18820. return new WavAudioFormatWriter (out, sampleRate, numChannels, bitsPerSample, metadataValues);
  18821. return 0;
  18822. }
  18823. namespace WavFileHelpers
  18824. {
  18825. bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18826. {
  18827. TemporaryFile tempFile (file);
  18828. WavAudioFormat wav;
  18829. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18830. if (reader != 0)
  18831. {
  18832. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18833. if (outStream != 0)
  18834. {
  18835. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18836. reader->numChannels, reader->bitsPerSample,
  18837. metadata, 0));
  18838. if (writer != 0)
  18839. {
  18840. outStream.release();
  18841. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18842. writer = 0;
  18843. reader = 0;
  18844. return ok && tempFile.overwriteTargetFileWithTemporary();
  18845. }
  18846. }
  18847. }
  18848. return false;
  18849. }
  18850. }
  18851. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18852. {
  18853. using namespace WavFileHelpers;
  18854. ScopedPointer <WavAudioFormatReader> reader (static_cast <WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  18855. if (reader != 0)
  18856. {
  18857. const int64 bwavPos = reader->bwavChunkStart;
  18858. const int64 bwavSize = reader->bwavSize;
  18859. reader = 0;
  18860. if (bwavSize > 0)
  18861. {
  18862. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18863. if (chunk.getSize() <= (size_t) bwavSize)
  18864. {
  18865. // the new one will fit in the space available, so write it directly..
  18866. const int64 oldSize = wavFile.getSize();
  18867. {
  18868. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18869. out->setPosition (bwavPos);
  18870. out->write (chunk.getData(), (int) chunk.getSize());
  18871. out->setPosition (oldSize);
  18872. }
  18873. jassert (wavFile.getSize() == oldSize);
  18874. return true;
  18875. }
  18876. }
  18877. }
  18878. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  18879. }
  18880. END_JUCE_NAMESPACE
  18881. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18882. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18883. #if JUCE_USE_CDREADER
  18884. BEGIN_JUCE_NAMESPACE
  18885. int AudioCDReader::getNumTracks() const
  18886. {
  18887. return trackStartSamples.size() - 1;
  18888. }
  18889. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18890. {
  18891. return trackStartSamples [trackNum];
  18892. }
  18893. const Array<int>& AudioCDReader::getTrackOffsets() const
  18894. {
  18895. return trackStartSamples;
  18896. }
  18897. int AudioCDReader::getCDDBId()
  18898. {
  18899. int checksum = 0;
  18900. const int numTracks = getNumTracks();
  18901. for (int i = 0; i < numTracks; ++i)
  18902. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18903. checksum += offset % 10;
  18904. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18905. // CCLLLLTT: checksum, length, tracks
  18906. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18907. }
  18908. END_JUCE_NAMESPACE
  18909. #endif
  18910. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18911. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18912. BEGIN_JUCE_NAMESPACE
  18913. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18914. const bool deleteReaderWhenThisIsDeleted)
  18915. : reader (reader_),
  18916. deleteReader (deleteReaderWhenThisIsDeleted),
  18917. nextPlayPos (0),
  18918. looping (false)
  18919. {
  18920. jassert (reader != 0);
  18921. }
  18922. AudioFormatReaderSource::~AudioFormatReaderSource()
  18923. {
  18924. releaseResources();
  18925. if (deleteReader)
  18926. delete reader;
  18927. }
  18928. void AudioFormatReaderSource::setNextReadPosition (int64 newPosition)
  18929. {
  18930. nextPlayPos = newPosition;
  18931. }
  18932. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18933. {
  18934. looping = shouldLoop;
  18935. }
  18936. int64 AudioFormatReaderSource::getNextReadPosition() const
  18937. {
  18938. return looping ? nextPlayPos % reader->lengthInSamples
  18939. : nextPlayPos;
  18940. }
  18941. int64 AudioFormatReaderSource::getTotalLength() const
  18942. {
  18943. return reader->lengthInSamples;
  18944. }
  18945. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18946. double /*sampleRate*/)
  18947. {
  18948. }
  18949. void AudioFormatReaderSource::releaseResources()
  18950. {
  18951. }
  18952. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18953. {
  18954. if (info.numSamples > 0)
  18955. {
  18956. const int64 start = nextPlayPos;
  18957. if (looping)
  18958. {
  18959. const int newStart = start % (int) reader->lengthInSamples;
  18960. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18961. if (newEnd > newStart)
  18962. {
  18963. info.buffer->readFromAudioReader (reader,
  18964. info.startSample,
  18965. newEnd - newStart,
  18966. newStart,
  18967. true, true);
  18968. }
  18969. else
  18970. {
  18971. const int endSamps = (int) reader->lengthInSamples - newStart;
  18972. info.buffer->readFromAudioReader (reader,
  18973. info.startSample,
  18974. endSamps,
  18975. newStart,
  18976. true, true);
  18977. info.buffer->readFromAudioReader (reader,
  18978. info.startSample + endSamps,
  18979. newEnd,
  18980. 0,
  18981. true, true);
  18982. }
  18983. nextPlayPos = newEnd;
  18984. }
  18985. else
  18986. {
  18987. info.buffer->readFromAudioReader (reader,
  18988. info.startSample,
  18989. info.numSamples,
  18990. start,
  18991. true, true);
  18992. nextPlayPos += info.numSamples;
  18993. }
  18994. }
  18995. }
  18996. END_JUCE_NAMESPACE
  18997. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18998. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18999. BEGIN_JUCE_NAMESPACE
  19000. AudioSourcePlayer::AudioSourcePlayer()
  19001. : source (0),
  19002. sampleRate (0),
  19003. bufferSize (0),
  19004. tempBuffer (2, 8),
  19005. lastGain (1.0f),
  19006. gain (1.0f)
  19007. {
  19008. }
  19009. AudioSourcePlayer::~AudioSourcePlayer()
  19010. {
  19011. setSource (0);
  19012. }
  19013. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19014. {
  19015. if (source != newSource)
  19016. {
  19017. AudioSource* const oldSource = source;
  19018. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19019. newSource->prepareToPlay (bufferSize, sampleRate);
  19020. {
  19021. const ScopedLock sl (readLock);
  19022. source = newSource;
  19023. }
  19024. if (oldSource != 0)
  19025. oldSource->releaseResources();
  19026. }
  19027. }
  19028. void AudioSourcePlayer::setGain (const float newGain) throw()
  19029. {
  19030. gain = newGain;
  19031. }
  19032. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19033. int totalNumInputChannels,
  19034. float** outputChannelData,
  19035. int totalNumOutputChannels,
  19036. int numSamples)
  19037. {
  19038. // these should have been prepared by audioDeviceAboutToStart()...
  19039. jassert (sampleRate > 0 && bufferSize > 0);
  19040. const ScopedLock sl (readLock);
  19041. if (source != 0)
  19042. {
  19043. AudioSourceChannelInfo info;
  19044. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19045. // messy stuff needed to compact the channels down into an array
  19046. // of non-zero pointers..
  19047. for (i = 0; i < totalNumInputChannels; ++i)
  19048. {
  19049. if (inputChannelData[i] != 0)
  19050. {
  19051. inputChans [numInputs++] = inputChannelData[i];
  19052. if (numInputs >= numElementsInArray (inputChans))
  19053. break;
  19054. }
  19055. }
  19056. for (i = 0; i < totalNumOutputChannels; ++i)
  19057. {
  19058. if (outputChannelData[i] != 0)
  19059. {
  19060. outputChans [numOutputs++] = outputChannelData[i];
  19061. if (numOutputs >= numElementsInArray (outputChans))
  19062. break;
  19063. }
  19064. }
  19065. if (numInputs > numOutputs)
  19066. {
  19067. // if there aren't enough output channels for the number of
  19068. // inputs, we need to create some temporary extra ones (can't
  19069. // use the input data in case it gets written to)
  19070. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19071. false, false, true);
  19072. for (i = 0; i < numOutputs; ++i)
  19073. {
  19074. channels[numActiveChans] = outputChans[i];
  19075. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19076. ++numActiveChans;
  19077. }
  19078. for (i = numOutputs; i < numInputs; ++i)
  19079. {
  19080. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19081. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19082. ++numActiveChans;
  19083. }
  19084. }
  19085. else
  19086. {
  19087. for (i = 0; i < numInputs; ++i)
  19088. {
  19089. channels[numActiveChans] = outputChans[i];
  19090. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19091. ++numActiveChans;
  19092. }
  19093. for (i = numInputs; i < numOutputs; ++i)
  19094. {
  19095. channels[numActiveChans] = outputChans[i];
  19096. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19097. ++numActiveChans;
  19098. }
  19099. }
  19100. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19101. info.buffer = &buffer;
  19102. info.startSample = 0;
  19103. info.numSamples = numSamples;
  19104. source->getNextAudioBlock (info);
  19105. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19106. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19107. lastGain = gain;
  19108. }
  19109. else
  19110. {
  19111. for (int i = 0; i < totalNumOutputChannels; ++i)
  19112. if (outputChannelData[i] != 0)
  19113. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19114. }
  19115. }
  19116. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19117. {
  19118. sampleRate = device->getCurrentSampleRate();
  19119. bufferSize = device->getCurrentBufferSizeSamples();
  19120. zeromem (channels, sizeof (channels));
  19121. if (source != 0)
  19122. source->prepareToPlay (bufferSize, sampleRate);
  19123. }
  19124. void AudioSourcePlayer::audioDeviceStopped()
  19125. {
  19126. if (source != 0)
  19127. source->releaseResources();
  19128. sampleRate = 0.0;
  19129. bufferSize = 0;
  19130. tempBuffer.setSize (2, 8);
  19131. }
  19132. END_JUCE_NAMESPACE
  19133. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19134. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19135. BEGIN_JUCE_NAMESPACE
  19136. AudioTransportSource::AudioTransportSource()
  19137. : source (0),
  19138. resamplerSource (0),
  19139. bufferingSource (0),
  19140. positionableSource (0),
  19141. masterSource (0),
  19142. gain (1.0f),
  19143. lastGain (1.0f),
  19144. playing (false),
  19145. stopped (true),
  19146. sampleRate (44100.0),
  19147. sourceSampleRate (0.0),
  19148. blockSize (128),
  19149. readAheadBufferSize (0),
  19150. isPrepared (false),
  19151. inputStreamEOF (false)
  19152. {
  19153. }
  19154. AudioTransportSource::~AudioTransportSource()
  19155. {
  19156. setSource (0);
  19157. releaseResources();
  19158. }
  19159. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19160. int readAheadBufferSize_,
  19161. double sourceSampleRateToCorrectFor,
  19162. int maxNumChannels)
  19163. {
  19164. if (source == newSource)
  19165. {
  19166. if (source == 0)
  19167. return;
  19168. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19169. }
  19170. readAheadBufferSize = readAheadBufferSize_;
  19171. sourceSampleRate = sourceSampleRateToCorrectFor;
  19172. ResamplingAudioSource* newResamplerSource = 0;
  19173. BufferingAudioSource* newBufferingSource = 0;
  19174. PositionableAudioSource* newPositionableSource = 0;
  19175. AudioSource* newMasterSource = 0;
  19176. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19177. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19178. AudioSource* oldMasterSource = masterSource;
  19179. if (newSource != 0)
  19180. {
  19181. newPositionableSource = newSource;
  19182. if (readAheadBufferSize_ > 0)
  19183. newPositionableSource = newBufferingSource
  19184. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19185. newPositionableSource->setNextReadPosition (0);
  19186. if (sourceSampleRateToCorrectFor > 0)
  19187. newMasterSource = newResamplerSource
  19188. = new ResamplingAudioSource (newPositionableSource, false, maxNumChannels);
  19189. else
  19190. newMasterSource = newPositionableSource;
  19191. if (isPrepared)
  19192. {
  19193. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19194. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19195. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19196. }
  19197. }
  19198. {
  19199. const ScopedLock sl (callbackLock);
  19200. source = newSource;
  19201. resamplerSource = newResamplerSource;
  19202. bufferingSource = newBufferingSource;
  19203. masterSource = newMasterSource;
  19204. positionableSource = newPositionableSource;
  19205. playing = false;
  19206. }
  19207. if (oldMasterSource != 0)
  19208. oldMasterSource->releaseResources();
  19209. }
  19210. void AudioTransportSource::start()
  19211. {
  19212. if ((! playing) && masterSource != 0)
  19213. {
  19214. {
  19215. const ScopedLock sl (callbackLock);
  19216. playing = true;
  19217. stopped = false;
  19218. inputStreamEOF = false;
  19219. }
  19220. sendChangeMessage();
  19221. }
  19222. }
  19223. void AudioTransportSource::stop()
  19224. {
  19225. if (playing)
  19226. {
  19227. {
  19228. const ScopedLock sl (callbackLock);
  19229. playing = false;
  19230. }
  19231. int n = 500;
  19232. while (--n >= 0 && ! stopped)
  19233. Thread::sleep (2);
  19234. sendChangeMessage();
  19235. }
  19236. }
  19237. void AudioTransportSource::setPosition (double newPosition)
  19238. {
  19239. if (sampleRate > 0.0)
  19240. setNextReadPosition ((int64) (newPosition * sampleRate));
  19241. }
  19242. double AudioTransportSource::getCurrentPosition() const
  19243. {
  19244. if (sampleRate > 0.0)
  19245. return getNextReadPosition() / sampleRate;
  19246. else
  19247. return 0.0;
  19248. }
  19249. double AudioTransportSource::getLengthInSeconds() const
  19250. {
  19251. return getTotalLength() / sampleRate;
  19252. }
  19253. void AudioTransportSource::setNextReadPosition (int64 newPosition)
  19254. {
  19255. if (positionableSource != 0)
  19256. {
  19257. if (sampleRate > 0 && sourceSampleRate > 0)
  19258. newPosition = (int64) (newPosition * sourceSampleRate / sampleRate);
  19259. positionableSource->setNextReadPosition (newPosition);
  19260. }
  19261. }
  19262. int64 AudioTransportSource::getNextReadPosition() const
  19263. {
  19264. if (positionableSource != 0)
  19265. {
  19266. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19267. return (int64) (positionableSource->getNextReadPosition() * ratio);
  19268. }
  19269. return 0;
  19270. }
  19271. int64 AudioTransportSource::getTotalLength() const
  19272. {
  19273. const ScopedLock sl (callbackLock);
  19274. if (positionableSource != 0)
  19275. {
  19276. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19277. return (int64) (positionableSource->getTotalLength() * ratio);
  19278. }
  19279. return 0;
  19280. }
  19281. bool AudioTransportSource::isLooping() const
  19282. {
  19283. const ScopedLock sl (callbackLock);
  19284. return positionableSource != 0
  19285. && positionableSource->isLooping();
  19286. }
  19287. void AudioTransportSource::setGain (const float newGain) throw()
  19288. {
  19289. gain = newGain;
  19290. }
  19291. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19292. double sampleRate_)
  19293. {
  19294. const ScopedLock sl (callbackLock);
  19295. sampleRate = sampleRate_;
  19296. blockSize = samplesPerBlockExpected;
  19297. if (masterSource != 0)
  19298. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19299. if (resamplerSource != 0 && sourceSampleRate > 0)
  19300. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19301. isPrepared = true;
  19302. }
  19303. void AudioTransportSource::releaseResources()
  19304. {
  19305. const ScopedLock sl (callbackLock);
  19306. if (masterSource != 0)
  19307. masterSource->releaseResources();
  19308. isPrepared = false;
  19309. }
  19310. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19311. {
  19312. const ScopedLock sl (callbackLock);
  19313. inputStreamEOF = false;
  19314. if (masterSource != 0 && ! stopped)
  19315. {
  19316. masterSource->getNextAudioBlock (info);
  19317. if (! playing)
  19318. {
  19319. // just stopped playing, so fade out the last block..
  19320. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19321. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19322. if (info.numSamples > 256)
  19323. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19324. }
  19325. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19326. && ! positionableSource->isLooping())
  19327. {
  19328. playing = false;
  19329. inputStreamEOF = true;
  19330. sendChangeMessage();
  19331. }
  19332. stopped = ! playing;
  19333. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19334. {
  19335. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19336. lastGain, gain);
  19337. }
  19338. }
  19339. else
  19340. {
  19341. info.clearActiveBufferRegion();
  19342. stopped = true;
  19343. }
  19344. lastGain = gain;
  19345. }
  19346. END_JUCE_NAMESPACE
  19347. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19348. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19349. BEGIN_JUCE_NAMESPACE
  19350. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19351. public Thread,
  19352. private Timer
  19353. {
  19354. public:
  19355. SharedBufferingAudioSourceThread()
  19356. : Thread ("Audio Buffer")
  19357. {
  19358. }
  19359. ~SharedBufferingAudioSourceThread()
  19360. {
  19361. stopThread (10000);
  19362. clearSingletonInstance();
  19363. }
  19364. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19365. void addSource (BufferingAudioSource* source)
  19366. {
  19367. const ScopedLock sl (lock);
  19368. if (! sources.contains (source))
  19369. {
  19370. sources.add (source);
  19371. startThread();
  19372. stopTimer();
  19373. }
  19374. notify();
  19375. }
  19376. void removeSource (BufferingAudioSource* source)
  19377. {
  19378. const ScopedLock sl (lock);
  19379. sources.removeValue (source);
  19380. if (sources.size() == 0)
  19381. startTimer (5000);
  19382. }
  19383. private:
  19384. Array <BufferingAudioSource*> sources;
  19385. CriticalSection lock;
  19386. void run()
  19387. {
  19388. while (! threadShouldExit())
  19389. {
  19390. bool busy = false;
  19391. for (int i = sources.size(); --i >= 0;)
  19392. {
  19393. if (threadShouldExit())
  19394. return;
  19395. const ScopedLock sl (lock);
  19396. BufferingAudioSource* const b = sources[i];
  19397. if (b != 0 && b->readNextBufferChunk())
  19398. busy = true;
  19399. }
  19400. if (! busy)
  19401. wait (500);
  19402. }
  19403. }
  19404. void timerCallback()
  19405. {
  19406. stopTimer();
  19407. if (sources.size() == 0)
  19408. deleteInstance();
  19409. }
  19410. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19411. };
  19412. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19413. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19414. const bool deleteSourceWhenDeleted_,
  19415. int numberOfSamplesToBuffer_)
  19416. : source (source_),
  19417. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19418. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19419. buffer (2, 0),
  19420. bufferValidStart (0),
  19421. bufferValidEnd (0),
  19422. nextPlayPos (0),
  19423. wasSourceLooping (false)
  19424. {
  19425. jassert (source_ != 0);
  19426. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19427. // not using a larger buffer..
  19428. }
  19429. BufferingAudioSource::~BufferingAudioSource()
  19430. {
  19431. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19432. if (thread != 0)
  19433. thread->removeSource (this);
  19434. if (deleteSourceWhenDeleted)
  19435. delete source;
  19436. }
  19437. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19438. {
  19439. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19440. sampleRate = sampleRate_;
  19441. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19442. buffer.clear();
  19443. bufferValidStart = 0;
  19444. bufferValidEnd = 0;
  19445. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19446. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19447. buffer.getNumSamples() / 2))
  19448. {
  19449. SharedBufferingAudioSourceThread::getInstance()->notify();
  19450. Thread::sleep (5);
  19451. }
  19452. }
  19453. void BufferingAudioSource::releaseResources()
  19454. {
  19455. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19456. if (thread != 0)
  19457. thread->removeSource (this);
  19458. buffer.setSize (2, 0);
  19459. source->releaseResources();
  19460. }
  19461. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19462. {
  19463. const ScopedLock sl (bufferStartPosLock);
  19464. const int validStart = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos);
  19465. const int validEnd = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos);
  19466. if (validStart == validEnd)
  19467. {
  19468. // total cache miss
  19469. info.clearActiveBufferRegion();
  19470. }
  19471. else
  19472. {
  19473. if (validStart > 0)
  19474. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19475. if (validEnd < info.numSamples)
  19476. info.buffer->clear (info.startSample + validEnd,
  19477. info.numSamples - validEnd); // partial cache miss at end
  19478. if (validStart < validEnd)
  19479. {
  19480. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19481. {
  19482. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19483. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19484. if (startBufferIndex < endBufferIndex)
  19485. {
  19486. info.buffer->copyFrom (chan, info.startSample + validStart,
  19487. buffer,
  19488. chan, startBufferIndex,
  19489. validEnd - validStart);
  19490. }
  19491. else
  19492. {
  19493. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19494. info.buffer->copyFrom (chan, info.startSample + validStart,
  19495. buffer,
  19496. chan, startBufferIndex,
  19497. initialSize);
  19498. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19499. buffer,
  19500. chan, 0,
  19501. (validEnd - validStart) - initialSize);
  19502. }
  19503. }
  19504. }
  19505. nextPlayPos += info.numSamples;
  19506. if (source->isLooping() && nextPlayPos > 0)
  19507. nextPlayPos %= source->getTotalLength();
  19508. }
  19509. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19510. if (thread != 0)
  19511. thread->notify();
  19512. }
  19513. int64 BufferingAudioSource::getNextReadPosition() const
  19514. {
  19515. return (source->isLooping() && nextPlayPos > 0)
  19516. ? nextPlayPos % source->getTotalLength()
  19517. : nextPlayPos;
  19518. }
  19519. void BufferingAudioSource::setNextReadPosition (int64 newPosition)
  19520. {
  19521. const ScopedLock sl (bufferStartPosLock);
  19522. nextPlayPos = newPosition;
  19523. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19524. if (thread != 0)
  19525. thread->notify();
  19526. }
  19527. bool BufferingAudioSource::readNextBufferChunk()
  19528. {
  19529. int64 newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19530. {
  19531. const ScopedLock sl (bufferStartPosLock);
  19532. if (wasSourceLooping != isLooping())
  19533. {
  19534. wasSourceLooping = isLooping();
  19535. bufferValidStart = 0;
  19536. bufferValidEnd = 0;
  19537. }
  19538. newBVS = jmax ((int64) 0, nextPlayPos);
  19539. newBVE = newBVS + buffer.getNumSamples() - 4;
  19540. sectionToReadStart = 0;
  19541. sectionToReadEnd = 0;
  19542. const int maxChunkSize = 2048;
  19543. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19544. {
  19545. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19546. sectionToReadStart = newBVS;
  19547. sectionToReadEnd = newBVE;
  19548. bufferValidStart = 0;
  19549. bufferValidEnd = 0;
  19550. }
  19551. else if (std::abs ((int) (newBVS - bufferValidStart)) > 512
  19552. || std::abs ((int) (newBVE - bufferValidEnd)) > 512)
  19553. {
  19554. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19555. sectionToReadStart = bufferValidEnd;
  19556. sectionToReadEnd = newBVE;
  19557. bufferValidStart = newBVS;
  19558. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19559. }
  19560. }
  19561. if (sectionToReadStart != sectionToReadEnd)
  19562. {
  19563. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19564. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19565. if (bufferIndexStart < bufferIndexEnd)
  19566. {
  19567. readBufferSection (sectionToReadStart,
  19568. (int) (sectionToReadEnd - sectionToReadStart),
  19569. bufferIndexStart);
  19570. }
  19571. else
  19572. {
  19573. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19574. readBufferSection (sectionToReadStart,
  19575. initialSize,
  19576. bufferIndexStart);
  19577. readBufferSection (sectionToReadStart + initialSize,
  19578. (int) (sectionToReadEnd - sectionToReadStart) - initialSize,
  19579. 0);
  19580. }
  19581. const ScopedLock sl2 (bufferStartPosLock);
  19582. bufferValidStart = newBVS;
  19583. bufferValidEnd = newBVE;
  19584. return true;
  19585. }
  19586. else
  19587. {
  19588. return false;
  19589. }
  19590. }
  19591. void BufferingAudioSource::readBufferSection (const int64 start, const int length, const int bufferOffset)
  19592. {
  19593. if (source->getNextReadPosition() != start)
  19594. source->setNextReadPosition (start);
  19595. AudioSourceChannelInfo info;
  19596. info.buffer = &buffer;
  19597. info.startSample = bufferOffset;
  19598. info.numSamples = length;
  19599. source->getNextAudioBlock (info);
  19600. }
  19601. END_JUCE_NAMESPACE
  19602. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19603. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19604. BEGIN_JUCE_NAMESPACE
  19605. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19606. const bool deleteSourceWhenDeleted_)
  19607. : requiredNumberOfChannels (2),
  19608. source (source_),
  19609. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19610. buffer (2, 16)
  19611. {
  19612. remappedInfo.buffer = &buffer;
  19613. remappedInfo.startSample = 0;
  19614. }
  19615. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19616. {
  19617. if (deleteSourceWhenDeleted)
  19618. delete source;
  19619. }
  19620. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19621. {
  19622. const ScopedLock sl (lock);
  19623. requiredNumberOfChannels = requiredNumberOfChannels_;
  19624. }
  19625. void ChannelRemappingAudioSource::clearAllMappings()
  19626. {
  19627. const ScopedLock sl (lock);
  19628. remappedInputs.clear();
  19629. remappedOutputs.clear();
  19630. }
  19631. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19632. {
  19633. const ScopedLock sl (lock);
  19634. while (remappedInputs.size() < destIndex)
  19635. remappedInputs.add (-1);
  19636. remappedInputs.set (destIndex, sourceIndex);
  19637. }
  19638. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19639. {
  19640. const ScopedLock sl (lock);
  19641. while (remappedOutputs.size() < sourceIndex)
  19642. remappedOutputs.add (-1);
  19643. remappedOutputs.set (sourceIndex, destIndex);
  19644. }
  19645. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19646. {
  19647. const ScopedLock sl (lock);
  19648. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19649. return remappedInputs.getUnchecked (inputChannelIndex);
  19650. return -1;
  19651. }
  19652. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19653. {
  19654. const ScopedLock sl (lock);
  19655. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19656. return remappedOutputs .getUnchecked (outputChannelIndex);
  19657. return -1;
  19658. }
  19659. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19660. {
  19661. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19662. }
  19663. void ChannelRemappingAudioSource::releaseResources()
  19664. {
  19665. source->releaseResources();
  19666. }
  19667. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19668. {
  19669. const ScopedLock sl (lock);
  19670. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19671. const int numChans = bufferToFill.buffer->getNumChannels();
  19672. int i;
  19673. for (i = 0; i < buffer.getNumChannels(); ++i)
  19674. {
  19675. const int remappedChan = getRemappedInputChannel (i);
  19676. if (remappedChan >= 0 && remappedChan < numChans)
  19677. {
  19678. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19679. remappedChan,
  19680. bufferToFill.startSample,
  19681. bufferToFill.numSamples);
  19682. }
  19683. else
  19684. {
  19685. buffer.clear (i, 0, bufferToFill.numSamples);
  19686. }
  19687. }
  19688. remappedInfo.numSamples = bufferToFill.numSamples;
  19689. source->getNextAudioBlock (remappedInfo);
  19690. bufferToFill.clearActiveBufferRegion();
  19691. for (i = 0; i < requiredNumberOfChannels; ++i)
  19692. {
  19693. const int remappedChan = getRemappedOutputChannel (i);
  19694. if (remappedChan >= 0 && remappedChan < numChans)
  19695. {
  19696. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19697. buffer, i, 0, bufferToFill.numSamples);
  19698. }
  19699. }
  19700. }
  19701. XmlElement* ChannelRemappingAudioSource::createXml() const
  19702. {
  19703. XmlElement* e = new XmlElement ("MAPPINGS");
  19704. String ins, outs;
  19705. int i;
  19706. const ScopedLock sl (lock);
  19707. for (i = 0; i < remappedInputs.size(); ++i)
  19708. ins << remappedInputs.getUnchecked(i) << ' ';
  19709. for (i = 0; i < remappedOutputs.size(); ++i)
  19710. outs << remappedOutputs.getUnchecked(i) << ' ';
  19711. e->setAttribute ("inputs", ins.trimEnd());
  19712. e->setAttribute ("outputs", outs.trimEnd());
  19713. return e;
  19714. }
  19715. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19716. {
  19717. if (e.hasTagName ("MAPPINGS"))
  19718. {
  19719. const ScopedLock sl (lock);
  19720. clearAllMappings();
  19721. StringArray ins, outs;
  19722. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19723. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19724. int i;
  19725. for (i = 0; i < ins.size(); ++i)
  19726. remappedInputs.add (ins[i].getIntValue());
  19727. for (i = 0; i < outs.size(); ++i)
  19728. remappedOutputs.add (outs[i].getIntValue());
  19729. }
  19730. }
  19731. END_JUCE_NAMESPACE
  19732. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19733. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19734. BEGIN_JUCE_NAMESPACE
  19735. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19736. const bool deleteInputWhenDeleted_)
  19737. : input (inputSource),
  19738. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19739. {
  19740. jassert (inputSource != 0);
  19741. for (int i = 2; --i >= 0;)
  19742. iirFilters.add (new IIRFilter());
  19743. }
  19744. IIRFilterAudioSource::~IIRFilterAudioSource()
  19745. {
  19746. if (deleteInputWhenDeleted)
  19747. delete input;
  19748. }
  19749. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19750. {
  19751. for (int i = iirFilters.size(); --i >= 0;)
  19752. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19753. }
  19754. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19755. {
  19756. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19757. for (int i = iirFilters.size(); --i >= 0;)
  19758. iirFilters.getUnchecked(i)->reset();
  19759. }
  19760. void IIRFilterAudioSource::releaseResources()
  19761. {
  19762. input->releaseResources();
  19763. }
  19764. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19765. {
  19766. input->getNextAudioBlock (bufferToFill);
  19767. const int numChannels = bufferToFill.buffer->getNumChannels();
  19768. while (numChannels > iirFilters.size())
  19769. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19770. for (int i = 0; i < numChannels; ++i)
  19771. iirFilters.getUnchecked(i)
  19772. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19773. bufferToFill.numSamples);
  19774. }
  19775. END_JUCE_NAMESPACE
  19776. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19777. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19778. BEGIN_JUCE_NAMESPACE
  19779. MixerAudioSource::MixerAudioSource()
  19780. : tempBuffer (2, 0),
  19781. currentSampleRate (0.0),
  19782. bufferSizeExpected (0)
  19783. {
  19784. }
  19785. MixerAudioSource::~MixerAudioSource()
  19786. {
  19787. removeAllInputs();
  19788. }
  19789. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19790. {
  19791. if (input != 0 && ! inputs.contains (input))
  19792. {
  19793. double localRate;
  19794. int localBufferSize;
  19795. {
  19796. const ScopedLock sl (lock);
  19797. localRate = currentSampleRate;
  19798. localBufferSize = bufferSizeExpected;
  19799. }
  19800. if (localRate > 0.0)
  19801. input->prepareToPlay (localBufferSize, localRate);
  19802. const ScopedLock sl (lock);
  19803. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19804. inputs.add (input);
  19805. }
  19806. }
  19807. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19808. {
  19809. if (input != 0)
  19810. {
  19811. int index;
  19812. {
  19813. const ScopedLock sl (lock);
  19814. index = inputs.indexOf (input);
  19815. if (index >= 0)
  19816. {
  19817. inputsToDelete.shiftBits (index, 1);
  19818. inputs.remove (index);
  19819. }
  19820. }
  19821. if (index >= 0)
  19822. {
  19823. input->releaseResources();
  19824. if (deleteInput)
  19825. delete input;
  19826. }
  19827. }
  19828. }
  19829. void MixerAudioSource::removeAllInputs()
  19830. {
  19831. OwnedArray<AudioSource> toDelete;
  19832. {
  19833. const ScopedLock sl (lock);
  19834. for (int i = inputs.size(); --i >= 0;)
  19835. if (inputsToDelete[i])
  19836. toDelete.add (inputs.getUnchecked(i));
  19837. }
  19838. }
  19839. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19840. {
  19841. tempBuffer.setSize (2, samplesPerBlockExpected);
  19842. const ScopedLock sl (lock);
  19843. currentSampleRate = sampleRate;
  19844. bufferSizeExpected = samplesPerBlockExpected;
  19845. for (int i = inputs.size(); --i >= 0;)
  19846. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19847. }
  19848. void MixerAudioSource::releaseResources()
  19849. {
  19850. const ScopedLock sl (lock);
  19851. for (int i = inputs.size(); --i >= 0;)
  19852. inputs.getUnchecked(i)->releaseResources();
  19853. tempBuffer.setSize (2, 0);
  19854. currentSampleRate = 0;
  19855. bufferSizeExpected = 0;
  19856. }
  19857. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19858. {
  19859. const ScopedLock sl (lock);
  19860. if (inputs.size() > 0)
  19861. {
  19862. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19863. if (inputs.size() > 1)
  19864. {
  19865. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19866. info.buffer->getNumSamples());
  19867. AudioSourceChannelInfo info2;
  19868. info2.buffer = &tempBuffer;
  19869. info2.numSamples = info.numSamples;
  19870. info2.startSample = 0;
  19871. for (int i = 1; i < inputs.size(); ++i)
  19872. {
  19873. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19874. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19875. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19876. }
  19877. }
  19878. }
  19879. else
  19880. {
  19881. info.clearActiveBufferRegion();
  19882. }
  19883. }
  19884. END_JUCE_NAMESPACE
  19885. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19886. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19887. BEGIN_JUCE_NAMESPACE
  19888. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19889. const bool deleteInputWhenDeleted_,
  19890. const int numChannels_)
  19891. : input (inputSource),
  19892. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19893. ratio (1.0),
  19894. lastRatio (1.0),
  19895. buffer (numChannels_, 0),
  19896. sampsInBuffer (0),
  19897. numChannels (numChannels_)
  19898. {
  19899. jassert (input != 0);
  19900. }
  19901. ResamplingAudioSource::~ResamplingAudioSource()
  19902. {
  19903. if (deleteInputWhenDeleted)
  19904. delete input;
  19905. }
  19906. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19907. {
  19908. jassert (samplesInPerOutputSample > 0);
  19909. const ScopedLock sl (ratioLock);
  19910. ratio = jmax (0.0, samplesInPerOutputSample);
  19911. }
  19912. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19913. double sampleRate)
  19914. {
  19915. const ScopedLock sl (ratioLock);
  19916. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19917. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19918. buffer.clear();
  19919. sampsInBuffer = 0;
  19920. bufferPos = 0;
  19921. subSampleOffset = 0.0;
  19922. filterStates.calloc (numChannels);
  19923. srcBuffers.calloc (numChannels);
  19924. destBuffers.calloc (numChannels);
  19925. createLowPass (ratio);
  19926. resetFilters();
  19927. }
  19928. void ResamplingAudioSource::releaseResources()
  19929. {
  19930. input->releaseResources();
  19931. buffer.setSize (numChannels, 0);
  19932. }
  19933. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19934. {
  19935. double localRatio;
  19936. {
  19937. const ScopedLock sl (ratioLock);
  19938. localRatio = ratio;
  19939. }
  19940. if (lastRatio != localRatio)
  19941. {
  19942. createLowPass (localRatio);
  19943. lastRatio = localRatio;
  19944. }
  19945. const int sampsNeeded = roundToInt (info.numSamples * localRatio) + 2;
  19946. int bufferSize = buffer.getNumSamples();
  19947. if (bufferSize < sampsNeeded + 8)
  19948. {
  19949. bufferPos %= bufferSize;
  19950. bufferSize = sampsNeeded + 32;
  19951. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19952. }
  19953. bufferPos %= bufferSize;
  19954. int endOfBufferPos = bufferPos + sampsInBuffer;
  19955. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19956. while (sampsNeeded > sampsInBuffer)
  19957. {
  19958. endOfBufferPos %= bufferSize;
  19959. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19960. bufferSize - endOfBufferPos);
  19961. AudioSourceChannelInfo readInfo;
  19962. readInfo.buffer = &buffer;
  19963. readInfo.numSamples = numToDo;
  19964. readInfo.startSample = endOfBufferPos;
  19965. input->getNextAudioBlock (readInfo);
  19966. if (localRatio > 1.0001)
  19967. {
  19968. // for down-sampling, pre-apply the filter..
  19969. for (int i = channelsToProcess; --i >= 0;)
  19970. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19971. }
  19972. sampsInBuffer += numToDo;
  19973. endOfBufferPos += numToDo;
  19974. }
  19975. for (int channel = 0; channel < channelsToProcess; ++channel)
  19976. {
  19977. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19978. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19979. }
  19980. int nextPos = (bufferPos + 1) % bufferSize;
  19981. for (int m = info.numSamples; --m >= 0;)
  19982. {
  19983. const float alpha = (float) subSampleOffset;
  19984. const float invAlpha = 1.0f - alpha;
  19985. for (int channel = 0; channel < channelsToProcess; ++channel)
  19986. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19987. subSampleOffset += localRatio;
  19988. jassert (sampsInBuffer > 0);
  19989. while (subSampleOffset >= 1.0)
  19990. {
  19991. if (++bufferPos >= bufferSize)
  19992. bufferPos = 0;
  19993. --sampsInBuffer;
  19994. nextPos = (bufferPos + 1) % bufferSize;
  19995. subSampleOffset -= 1.0;
  19996. }
  19997. }
  19998. if (localRatio < 0.9999)
  19999. {
  20000. // for up-sampling, apply the filter after transposing..
  20001. for (int i = channelsToProcess; --i >= 0;)
  20002. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20003. }
  20004. else if (localRatio <= 1.0001)
  20005. {
  20006. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20007. for (int i = channelsToProcess; --i >= 0;)
  20008. {
  20009. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20010. FilterState& fs = filterStates[i];
  20011. if (info.numSamples > 1)
  20012. {
  20013. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20014. }
  20015. else
  20016. {
  20017. fs.y2 = fs.y1;
  20018. fs.x2 = fs.x1;
  20019. }
  20020. fs.y1 = fs.x1 = *endOfBuffer;
  20021. }
  20022. }
  20023. jassert (sampsInBuffer >= 0);
  20024. }
  20025. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20026. {
  20027. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20028. : 0.5 * frequencyRatio;
  20029. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  20030. const double nSquared = n * n;
  20031. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20032. setFilterCoefficients (c1,
  20033. c1 * 2.0f,
  20034. c1,
  20035. 1.0,
  20036. c1 * 2.0 * (1.0 - nSquared),
  20037. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20038. }
  20039. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20040. {
  20041. const double a = 1.0 / c4;
  20042. c1 *= a;
  20043. c2 *= a;
  20044. c3 *= a;
  20045. c5 *= a;
  20046. c6 *= a;
  20047. coefficients[0] = c1;
  20048. coefficients[1] = c2;
  20049. coefficients[2] = c3;
  20050. coefficients[3] = c4;
  20051. coefficients[4] = c5;
  20052. coefficients[5] = c6;
  20053. }
  20054. void ResamplingAudioSource::resetFilters()
  20055. {
  20056. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20057. }
  20058. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20059. {
  20060. while (--num >= 0)
  20061. {
  20062. const double in = *samples;
  20063. double out = coefficients[0] * in
  20064. + coefficients[1] * fs.x1
  20065. + coefficients[2] * fs.x2
  20066. - coefficients[4] * fs.y1
  20067. - coefficients[5] * fs.y2;
  20068. #if JUCE_INTEL
  20069. if (! (out < -1.0e-8 || out > 1.0e-8))
  20070. out = 0;
  20071. #endif
  20072. fs.x2 = fs.x1;
  20073. fs.x1 = in;
  20074. fs.y2 = fs.y1;
  20075. fs.y1 = out;
  20076. *samples++ = (float) out;
  20077. }
  20078. }
  20079. END_JUCE_NAMESPACE
  20080. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20081. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20082. BEGIN_JUCE_NAMESPACE
  20083. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20084. : frequency (1000.0),
  20085. sampleRate (44100.0),
  20086. currentPhase (0.0),
  20087. phasePerSample (0.0),
  20088. amplitude (0.5f)
  20089. {
  20090. }
  20091. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20092. {
  20093. }
  20094. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20095. {
  20096. amplitude = newAmplitude;
  20097. }
  20098. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20099. {
  20100. frequency = newFrequencyHz;
  20101. phasePerSample = 0.0;
  20102. }
  20103. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20104. double sampleRate_)
  20105. {
  20106. currentPhase = 0.0;
  20107. phasePerSample = 0.0;
  20108. sampleRate = sampleRate_;
  20109. }
  20110. void ToneGeneratorAudioSource::releaseResources()
  20111. {
  20112. }
  20113. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20114. {
  20115. if (phasePerSample == 0.0)
  20116. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20117. for (int i = 0; i < info.numSamples; ++i)
  20118. {
  20119. const float sample = amplitude * (float) std::sin (currentPhase);
  20120. currentPhase += phasePerSample;
  20121. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20122. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20123. }
  20124. }
  20125. END_JUCE_NAMESPACE
  20126. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20127. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20128. BEGIN_JUCE_NAMESPACE
  20129. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20130. : sampleRate (0),
  20131. bufferSize (0),
  20132. useDefaultInputChannels (true),
  20133. useDefaultOutputChannels (true)
  20134. {
  20135. }
  20136. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20137. {
  20138. return outputDeviceName == other.outputDeviceName
  20139. && inputDeviceName == other.inputDeviceName
  20140. && sampleRate == other.sampleRate
  20141. && bufferSize == other.bufferSize
  20142. && inputChannels == other.inputChannels
  20143. && useDefaultInputChannels == other.useDefaultInputChannels
  20144. && outputChannels == other.outputChannels
  20145. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20146. }
  20147. AudioDeviceManager::AudioDeviceManager()
  20148. : currentAudioDevice (0),
  20149. numInputChansNeeded (0),
  20150. numOutputChansNeeded (2),
  20151. listNeedsScanning (true),
  20152. useInputNames (false),
  20153. inputLevelMeasurementEnabledCount (0),
  20154. inputLevel (0),
  20155. tempBuffer (2, 2),
  20156. defaultMidiOutput (0),
  20157. cpuUsageMs (0),
  20158. timeToCpuScale (0)
  20159. {
  20160. callbackHandler.owner = this;
  20161. }
  20162. AudioDeviceManager::~AudioDeviceManager()
  20163. {
  20164. currentAudioDevice = 0;
  20165. defaultMidiOutput = 0;
  20166. }
  20167. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20168. {
  20169. if (availableDeviceTypes.size() == 0)
  20170. {
  20171. createAudioDeviceTypes (availableDeviceTypes);
  20172. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20173. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20174. if (availableDeviceTypes.size() > 0)
  20175. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20176. }
  20177. }
  20178. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20179. {
  20180. scanDevicesIfNeeded();
  20181. return availableDeviceTypes;
  20182. }
  20183. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20184. static void addIfNotNull (OwnedArray <AudioIODeviceType>& list, AudioIODeviceType* const device)
  20185. {
  20186. if (device != 0)
  20187. list.add (device);
  20188. }
  20189. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20190. {
  20191. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI());
  20192. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_DirectSound());
  20193. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ASIO());
  20194. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_CoreAudio());
  20195. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_iOSAudio());
  20196. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ALSA());
  20197. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_JACK());
  20198. }
  20199. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20200. const int numOutputChannelsNeeded,
  20201. const XmlElement* const e,
  20202. const bool selectDefaultDeviceOnFailure,
  20203. const String& preferredDefaultDeviceName,
  20204. const AudioDeviceSetup* preferredSetupOptions)
  20205. {
  20206. scanDevicesIfNeeded();
  20207. numInputChansNeeded = numInputChannelsNeeded;
  20208. numOutputChansNeeded = numOutputChannelsNeeded;
  20209. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20210. {
  20211. lastExplicitSettings = new XmlElement (*e);
  20212. String error;
  20213. AudioDeviceSetup setup;
  20214. if (preferredSetupOptions != 0)
  20215. setup = *preferredSetupOptions;
  20216. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20217. {
  20218. setup.inputDeviceName = setup.outputDeviceName
  20219. = e->getStringAttribute ("audioDeviceName");
  20220. }
  20221. else
  20222. {
  20223. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20224. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20225. }
  20226. currentDeviceType = e->getStringAttribute ("deviceType");
  20227. if (currentDeviceType.isEmpty())
  20228. {
  20229. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20230. if (type != 0)
  20231. currentDeviceType = type->getTypeName();
  20232. else if (availableDeviceTypes.size() > 0)
  20233. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20234. }
  20235. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20236. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20237. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20238. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20239. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20240. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20241. error = setAudioDeviceSetup (setup, true);
  20242. midiInsFromXml.clear();
  20243. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20244. midiInsFromXml.add (c->getStringAttribute ("name"));
  20245. const StringArray allMidiIns (MidiInput::getDevices());
  20246. for (int i = allMidiIns.size(); --i >= 0;)
  20247. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20248. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20249. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20250. false, preferredDefaultDeviceName);
  20251. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20252. return error;
  20253. }
  20254. else
  20255. {
  20256. AudioDeviceSetup setup;
  20257. if (preferredSetupOptions != 0)
  20258. {
  20259. setup = *preferredSetupOptions;
  20260. }
  20261. else if (preferredDefaultDeviceName.isNotEmpty())
  20262. {
  20263. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20264. {
  20265. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20266. StringArray outs (type->getDeviceNames (false));
  20267. int i;
  20268. for (i = 0; i < outs.size(); ++i)
  20269. {
  20270. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20271. {
  20272. setup.outputDeviceName = outs[i];
  20273. break;
  20274. }
  20275. }
  20276. StringArray ins (type->getDeviceNames (true));
  20277. for (i = 0; i < ins.size(); ++i)
  20278. {
  20279. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20280. {
  20281. setup.inputDeviceName = ins[i];
  20282. break;
  20283. }
  20284. }
  20285. }
  20286. }
  20287. insertDefaultDeviceNames (setup);
  20288. return setAudioDeviceSetup (setup, false);
  20289. }
  20290. }
  20291. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20292. {
  20293. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20294. if (type != 0)
  20295. {
  20296. if (setup.outputDeviceName.isEmpty())
  20297. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20298. if (setup.inputDeviceName.isEmpty())
  20299. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20300. }
  20301. }
  20302. XmlElement* AudioDeviceManager::createStateXml() const
  20303. {
  20304. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20305. }
  20306. void AudioDeviceManager::scanDevicesIfNeeded()
  20307. {
  20308. if (listNeedsScanning)
  20309. {
  20310. listNeedsScanning = false;
  20311. createDeviceTypesIfNeeded();
  20312. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20313. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20314. }
  20315. }
  20316. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20317. {
  20318. scanDevicesIfNeeded();
  20319. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20320. {
  20321. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20322. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20323. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20324. {
  20325. return type;
  20326. }
  20327. }
  20328. return 0;
  20329. }
  20330. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20331. {
  20332. setup = currentSetup;
  20333. }
  20334. void AudioDeviceManager::deleteCurrentDevice()
  20335. {
  20336. currentAudioDevice = 0;
  20337. currentSetup.inputDeviceName = String::empty;
  20338. currentSetup.outputDeviceName = String::empty;
  20339. }
  20340. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20341. const bool treatAsChosenDevice)
  20342. {
  20343. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20344. {
  20345. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20346. && currentDeviceType != type)
  20347. {
  20348. currentDeviceType = type;
  20349. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20350. insertDefaultDeviceNames (s);
  20351. setAudioDeviceSetup (s, treatAsChosenDevice);
  20352. sendChangeMessage();
  20353. break;
  20354. }
  20355. }
  20356. }
  20357. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20358. {
  20359. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20360. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20361. return availableDeviceTypes[i];
  20362. return availableDeviceTypes[0];
  20363. }
  20364. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20365. const bool treatAsChosenDevice)
  20366. {
  20367. jassert (&newSetup != &currentSetup); // this will have no effect
  20368. if (newSetup == currentSetup && currentAudioDevice != 0)
  20369. return String::empty;
  20370. if (! (newSetup == currentSetup))
  20371. sendChangeMessage();
  20372. stopDevice();
  20373. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20374. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20375. String error;
  20376. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20377. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20378. {
  20379. deleteCurrentDevice();
  20380. if (treatAsChosenDevice)
  20381. updateXml();
  20382. return String::empty;
  20383. }
  20384. if (currentSetup.inputDeviceName != newInputDeviceName
  20385. || currentSetup.outputDeviceName != newOutputDeviceName
  20386. || currentAudioDevice == 0)
  20387. {
  20388. deleteCurrentDevice();
  20389. scanDevicesIfNeeded();
  20390. if (newOutputDeviceName.isNotEmpty()
  20391. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20392. {
  20393. return "No such device: " + newOutputDeviceName;
  20394. }
  20395. if (newInputDeviceName.isNotEmpty()
  20396. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20397. {
  20398. return "No such device: " + newInputDeviceName;
  20399. }
  20400. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20401. if (currentAudioDevice == 0)
  20402. 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!";
  20403. else
  20404. error = currentAudioDevice->getLastError();
  20405. if (error.isNotEmpty())
  20406. {
  20407. deleteCurrentDevice();
  20408. return error;
  20409. }
  20410. if (newSetup.useDefaultInputChannels)
  20411. {
  20412. inputChannels.clear();
  20413. inputChannels.setRange (0, numInputChansNeeded, true);
  20414. }
  20415. if (newSetup.useDefaultOutputChannels)
  20416. {
  20417. outputChannels.clear();
  20418. outputChannels.setRange (0, numOutputChansNeeded, true);
  20419. }
  20420. if (newInputDeviceName.isEmpty())
  20421. inputChannels.clear();
  20422. if (newOutputDeviceName.isEmpty())
  20423. outputChannels.clear();
  20424. }
  20425. if (! newSetup.useDefaultInputChannels)
  20426. inputChannels = newSetup.inputChannels;
  20427. if (! newSetup.useDefaultOutputChannels)
  20428. outputChannels = newSetup.outputChannels;
  20429. currentSetup = newSetup;
  20430. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20431. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20432. error = currentAudioDevice->open (inputChannels,
  20433. outputChannels,
  20434. currentSetup.sampleRate,
  20435. currentSetup.bufferSize);
  20436. if (error.isEmpty())
  20437. {
  20438. currentDeviceType = currentAudioDevice->getTypeName();
  20439. currentAudioDevice->start (&callbackHandler);
  20440. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20441. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20442. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20443. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20444. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20445. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20446. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20447. if (treatAsChosenDevice)
  20448. updateXml();
  20449. }
  20450. else
  20451. {
  20452. deleteCurrentDevice();
  20453. }
  20454. return error;
  20455. }
  20456. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20457. {
  20458. jassert (currentAudioDevice != 0);
  20459. if (rate > 0)
  20460. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20461. if (currentAudioDevice->getSampleRate (i) == rate)
  20462. return rate;
  20463. double lowestAbove44 = 0.0;
  20464. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20465. {
  20466. const double sr = currentAudioDevice->getSampleRate (i);
  20467. if (sr >= 44100.0 && (lowestAbove44 < 1.0 || sr < lowestAbove44))
  20468. lowestAbove44 = sr;
  20469. }
  20470. if (lowestAbove44 > 0.0)
  20471. return lowestAbove44;
  20472. return currentAudioDevice->getSampleRate (0);
  20473. }
  20474. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20475. {
  20476. jassert (currentAudioDevice != 0);
  20477. if (bufferSize > 0)
  20478. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20479. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20480. return bufferSize;
  20481. return currentAudioDevice->getDefaultBufferSize();
  20482. }
  20483. void AudioDeviceManager::stopDevice()
  20484. {
  20485. if (currentAudioDevice != 0)
  20486. currentAudioDevice->stop();
  20487. testSound = 0;
  20488. }
  20489. void AudioDeviceManager::closeAudioDevice()
  20490. {
  20491. stopDevice();
  20492. currentAudioDevice = 0;
  20493. }
  20494. void AudioDeviceManager::restartLastAudioDevice()
  20495. {
  20496. if (currentAudioDevice == 0)
  20497. {
  20498. if (currentSetup.inputDeviceName.isEmpty()
  20499. && currentSetup.outputDeviceName.isEmpty())
  20500. {
  20501. // This method will only reload the last device that was running
  20502. // before closeAudioDevice() was called - you need to actually open
  20503. // one first, with setAudioDevice().
  20504. jassertfalse;
  20505. return;
  20506. }
  20507. AudioDeviceSetup s (currentSetup);
  20508. setAudioDeviceSetup (s, false);
  20509. }
  20510. }
  20511. void AudioDeviceManager::updateXml()
  20512. {
  20513. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20514. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20515. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20516. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20517. if (currentAudioDevice != 0)
  20518. {
  20519. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20520. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20521. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20522. if (! currentSetup.useDefaultInputChannels)
  20523. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20524. if (! currentSetup.useDefaultOutputChannels)
  20525. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20526. }
  20527. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20528. {
  20529. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20530. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20531. }
  20532. if (midiInsFromXml.size() > 0)
  20533. {
  20534. // Add any midi devices that have been enabled before, but which aren't currently
  20535. // open because the device has been disconnected.
  20536. const StringArray availableMidiDevices (MidiInput::getDevices());
  20537. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20538. {
  20539. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20540. {
  20541. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20542. m->setAttribute ("name", midiInsFromXml[i]);
  20543. }
  20544. }
  20545. }
  20546. if (defaultMidiOutputName.isNotEmpty())
  20547. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20548. }
  20549. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20550. {
  20551. {
  20552. const ScopedLock sl (audioCallbackLock);
  20553. if (callbacks.contains (newCallback))
  20554. return;
  20555. }
  20556. if (currentAudioDevice != 0 && newCallback != 0)
  20557. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20558. const ScopedLock sl (audioCallbackLock);
  20559. callbacks.add (newCallback);
  20560. }
  20561. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  20562. {
  20563. if (callbackToRemove != 0)
  20564. {
  20565. bool needsDeinitialising = currentAudioDevice != 0;
  20566. {
  20567. const ScopedLock sl (audioCallbackLock);
  20568. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  20569. callbacks.removeValue (callbackToRemove);
  20570. }
  20571. if (needsDeinitialising)
  20572. callbackToRemove->audioDeviceStopped();
  20573. }
  20574. }
  20575. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20576. int numInputChannels,
  20577. float** outputChannelData,
  20578. int numOutputChannels,
  20579. int numSamples)
  20580. {
  20581. const ScopedLock sl (audioCallbackLock);
  20582. if (inputLevelMeasurementEnabledCount > 0)
  20583. {
  20584. for (int j = 0; j < numSamples; ++j)
  20585. {
  20586. float s = 0;
  20587. for (int i = 0; i < numInputChannels; ++i)
  20588. s += std::abs (inputChannelData[i][j]);
  20589. s /= numInputChannels;
  20590. const double decayFactor = 0.99992;
  20591. if (s > inputLevel)
  20592. inputLevel = s;
  20593. else if (inputLevel > 0.001f)
  20594. inputLevel *= decayFactor;
  20595. else
  20596. inputLevel = 0;
  20597. }
  20598. }
  20599. if (callbacks.size() > 0)
  20600. {
  20601. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20602. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20603. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20604. outputChannelData, numOutputChannels, numSamples);
  20605. float** const tempChans = tempBuffer.getArrayOfChannels();
  20606. for (int i = callbacks.size(); --i > 0;)
  20607. {
  20608. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20609. tempChans, numOutputChannels, numSamples);
  20610. for (int chan = 0; chan < numOutputChannels; ++chan)
  20611. {
  20612. const float* const src = tempChans [chan];
  20613. float* const dst = outputChannelData [chan];
  20614. if (src != 0 && dst != 0)
  20615. for (int j = 0; j < numSamples; ++j)
  20616. dst[j] += src[j];
  20617. }
  20618. }
  20619. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20620. const double filterAmount = 0.2;
  20621. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20622. }
  20623. else
  20624. {
  20625. for (int i = 0; i < numOutputChannels; ++i)
  20626. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20627. }
  20628. if (testSound != 0)
  20629. {
  20630. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20631. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20632. for (int i = 0; i < numOutputChannels; ++i)
  20633. for (int j = 0; j < numSamps; ++j)
  20634. outputChannelData [i][j] += src[j];
  20635. testSoundPosition += numSamps;
  20636. if (testSoundPosition >= testSound->getNumSamples())
  20637. testSound = 0;
  20638. }
  20639. }
  20640. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20641. {
  20642. cpuUsageMs = 0;
  20643. const double sampleRate = device->getCurrentSampleRate();
  20644. const int blockSize = device->getCurrentBufferSizeSamples();
  20645. if (sampleRate > 0.0 && blockSize > 0)
  20646. {
  20647. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20648. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20649. }
  20650. {
  20651. const ScopedLock sl (audioCallbackLock);
  20652. for (int i = callbacks.size(); --i >= 0;)
  20653. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20654. }
  20655. sendChangeMessage();
  20656. }
  20657. void AudioDeviceManager::audioDeviceStoppedInt()
  20658. {
  20659. cpuUsageMs = 0;
  20660. timeToCpuScale = 0;
  20661. sendChangeMessage();
  20662. const ScopedLock sl (audioCallbackLock);
  20663. for (int i = callbacks.size(); --i >= 0;)
  20664. callbacks.getUnchecked(i)->audioDeviceStopped();
  20665. }
  20666. double AudioDeviceManager::getCpuUsage() const
  20667. {
  20668. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20669. }
  20670. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20671. const bool enabled)
  20672. {
  20673. if (enabled != isMidiInputEnabled (name))
  20674. {
  20675. if (enabled)
  20676. {
  20677. const int index = MidiInput::getDevices().indexOf (name);
  20678. if (index >= 0)
  20679. {
  20680. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20681. if (min != 0)
  20682. {
  20683. enabledMidiInputs.add (min);
  20684. min->start();
  20685. }
  20686. }
  20687. }
  20688. else
  20689. {
  20690. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20691. if (enabledMidiInputs[i]->getName() == name)
  20692. enabledMidiInputs.remove (i);
  20693. }
  20694. updateXml();
  20695. sendChangeMessage();
  20696. }
  20697. }
  20698. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20699. {
  20700. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20701. if (enabledMidiInputs[i]->getName() == name)
  20702. return true;
  20703. return false;
  20704. }
  20705. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20706. MidiInputCallback* callbackToAdd)
  20707. {
  20708. removeMidiInputCallback (name, callbackToAdd);
  20709. if (name.isEmpty() || isMidiInputEnabled (name))
  20710. {
  20711. const ScopedLock sl (midiCallbackLock);
  20712. midiCallbacks.add (callbackToAdd);
  20713. midiCallbackDevices.add (name);
  20714. }
  20715. }
  20716. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callback)
  20717. {
  20718. for (int i = midiCallbacks.size(); --i >= 0;)
  20719. {
  20720. if (midiCallbackDevices[i] == name && midiCallbacks.getUnchecked(i) == callback)
  20721. {
  20722. const ScopedLock sl (midiCallbackLock);
  20723. midiCallbacks.remove (i);
  20724. midiCallbackDevices.remove (i);
  20725. }
  20726. }
  20727. }
  20728. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20729. const MidiMessage& message)
  20730. {
  20731. if (! message.isActiveSense())
  20732. {
  20733. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20734. const ScopedLock sl (midiCallbackLock);
  20735. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20736. {
  20737. const String name (midiCallbackDevices[i]);
  20738. if ((isDefaultSource && name.isEmpty()) || (name.isNotEmpty() && name == source->getName()))
  20739. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20740. }
  20741. }
  20742. }
  20743. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20744. {
  20745. if (defaultMidiOutputName != deviceName)
  20746. {
  20747. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20748. {
  20749. const ScopedLock sl (audioCallbackLock);
  20750. oldCallbacks = callbacks;
  20751. callbacks.clear();
  20752. }
  20753. if (currentAudioDevice != 0)
  20754. for (int i = oldCallbacks.size(); --i >= 0;)
  20755. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20756. defaultMidiOutput = 0;
  20757. defaultMidiOutputName = deviceName;
  20758. if (deviceName.isNotEmpty())
  20759. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20760. if (currentAudioDevice != 0)
  20761. for (int i = oldCallbacks.size(); --i >= 0;)
  20762. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20763. {
  20764. const ScopedLock sl (audioCallbackLock);
  20765. callbacks = oldCallbacks;
  20766. }
  20767. updateXml();
  20768. sendChangeMessage();
  20769. }
  20770. }
  20771. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20772. int numInputChannels,
  20773. float** outputChannelData,
  20774. int numOutputChannels,
  20775. int numSamples)
  20776. {
  20777. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20778. }
  20779. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20780. {
  20781. owner->audioDeviceAboutToStartInt (device);
  20782. }
  20783. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20784. {
  20785. owner->audioDeviceStoppedInt();
  20786. }
  20787. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20788. {
  20789. owner->handleIncomingMidiMessageInt (source, message);
  20790. }
  20791. void AudioDeviceManager::playTestSound()
  20792. {
  20793. { // cunningly nested to swap, unlock and delete in that order.
  20794. ScopedPointer <AudioSampleBuffer> oldSound;
  20795. {
  20796. const ScopedLock sl (audioCallbackLock);
  20797. oldSound = testSound;
  20798. }
  20799. }
  20800. testSoundPosition = 0;
  20801. if (currentAudioDevice != 0)
  20802. {
  20803. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20804. const int soundLength = (int) sampleRate;
  20805. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20806. float* samples = newSound->getSampleData (0);
  20807. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20808. const float amplitude = 0.5f;
  20809. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20810. for (int i = 0; i < soundLength; ++i)
  20811. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20812. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20813. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20814. const ScopedLock sl (audioCallbackLock);
  20815. testSound = newSound;
  20816. }
  20817. }
  20818. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20819. {
  20820. const ScopedLock sl (audioCallbackLock);
  20821. if (enableMeasurement)
  20822. ++inputLevelMeasurementEnabledCount;
  20823. else
  20824. --inputLevelMeasurementEnabledCount;
  20825. inputLevel = 0;
  20826. }
  20827. double AudioDeviceManager::getCurrentInputLevel() const
  20828. {
  20829. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20830. return inputLevel;
  20831. }
  20832. END_JUCE_NAMESPACE
  20833. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20834. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20835. BEGIN_JUCE_NAMESPACE
  20836. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20837. : name (deviceName),
  20838. typeName (typeName_)
  20839. {
  20840. }
  20841. AudioIODevice::~AudioIODevice()
  20842. {
  20843. }
  20844. bool AudioIODevice::hasControlPanel() const
  20845. {
  20846. return false;
  20847. }
  20848. bool AudioIODevice::showControlPanel()
  20849. {
  20850. jassertfalse; // this should only be called for devices which return true from
  20851. // their hasControlPanel() method.
  20852. return false;
  20853. }
  20854. END_JUCE_NAMESPACE
  20855. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20856. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20857. BEGIN_JUCE_NAMESPACE
  20858. AudioIODeviceType::AudioIODeviceType (const String& name)
  20859. : typeName (name)
  20860. {
  20861. }
  20862. AudioIODeviceType::~AudioIODeviceType()
  20863. {
  20864. }
  20865. #if ! JUCE_MAC
  20866. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_CoreAudio() { return 0; }
  20867. #endif
  20868. #if ! JUCE_IOS
  20869. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio() { return 0; }
  20870. #endif
  20871. #if ! (JUCE_WINDOWS && JUCE_WASAPI)
  20872. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI() { return 0; }
  20873. #endif
  20874. #if ! (JUCE_WINDOWS && JUCE_DIRECTSOUND)
  20875. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound() { return 0; }
  20876. #endif
  20877. #if ! (JUCE_WINDOWS && JUCE_ASIO)
  20878. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO() { return 0; }
  20879. #endif
  20880. #if ! (JUCE_LINUX && JUCE_ALSA)
  20881. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA() { return 0; }
  20882. #endif
  20883. #if ! (JUCE_LINUX && JUCE_JACK)
  20884. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK() { return 0; }
  20885. #endif
  20886. END_JUCE_NAMESPACE
  20887. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20888. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20889. BEGIN_JUCE_NAMESPACE
  20890. MidiOutput::MidiOutput()
  20891. : Thread ("midi out"),
  20892. internal (0),
  20893. firstMessage (0)
  20894. {
  20895. }
  20896. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20897. const double sampleNumber)
  20898. : message (data, len, sampleNumber)
  20899. {
  20900. }
  20901. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20902. const double millisecondCounterToStartAt,
  20903. double samplesPerSecondForBuffer)
  20904. {
  20905. // You've got to call startBackgroundThread() for this to actually work..
  20906. jassert (isThreadRunning());
  20907. // this needs to be a value in the future - RTFM for this method!
  20908. jassert (millisecondCounterToStartAt > 0);
  20909. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20910. MidiBuffer::Iterator i (buffer);
  20911. const uint8* data;
  20912. int len, time;
  20913. while (i.getNextEvent (data, len, time))
  20914. {
  20915. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20916. PendingMessage* const m
  20917. = new PendingMessage (data, len, eventTime);
  20918. const ScopedLock sl (lock);
  20919. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20920. {
  20921. m->next = firstMessage;
  20922. firstMessage = m;
  20923. }
  20924. else
  20925. {
  20926. PendingMessage* mm = firstMessage;
  20927. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20928. mm = mm->next;
  20929. m->next = mm->next;
  20930. mm->next = m;
  20931. }
  20932. }
  20933. notify();
  20934. }
  20935. void MidiOutput::clearAllPendingMessages()
  20936. {
  20937. const ScopedLock sl (lock);
  20938. while (firstMessage != 0)
  20939. {
  20940. PendingMessage* const m = firstMessage;
  20941. firstMessage = firstMessage->next;
  20942. delete m;
  20943. }
  20944. }
  20945. void MidiOutput::startBackgroundThread()
  20946. {
  20947. startThread (9);
  20948. }
  20949. void MidiOutput::stopBackgroundThread()
  20950. {
  20951. stopThread (5000);
  20952. }
  20953. void MidiOutput::run()
  20954. {
  20955. while (! threadShouldExit())
  20956. {
  20957. uint32 now = Time::getMillisecondCounter();
  20958. uint32 eventTime = 0;
  20959. uint32 timeToWait = 500;
  20960. PendingMessage* message;
  20961. {
  20962. const ScopedLock sl (lock);
  20963. message = firstMessage;
  20964. if (message != 0)
  20965. {
  20966. eventTime = roundToInt (message->message.getTimeStamp());
  20967. if (eventTime > now + 20)
  20968. {
  20969. timeToWait = eventTime - (now + 20);
  20970. message = 0;
  20971. }
  20972. else
  20973. {
  20974. firstMessage = message->next;
  20975. }
  20976. }
  20977. }
  20978. if (message != 0)
  20979. {
  20980. if (eventTime > now)
  20981. {
  20982. Time::waitForMillisecondCounter (eventTime);
  20983. if (threadShouldExit())
  20984. break;
  20985. }
  20986. if (eventTime > now - 200)
  20987. sendMessageNow (message->message);
  20988. delete message;
  20989. }
  20990. else
  20991. {
  20992. jassert (timeToWait < 1000 * 30);
  20993. wait (timeToWait);
  20994. }
  20995. }
  20996. clearAllPendingMessages();
  20997. }
  20998. END_JUCE_NAMESPACE
  20999. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21000. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21001. BEGIN_JUCE_NAMESPACE
  21002. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21003. {
  21004. const double maxVal = (double) 0x7fff;
  21005. char* intData = static_cast <char*> (dest);
  21006. if (dest != (void*) source || destBytesPerSample <= 4)
  21007. {
  21008. for (int i = 0; i < numSamples; ++i)
  21009. {
  21010. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21011. intData += destBytesPerSample;
  21012. }
  21013. }
  21014. else
  21015. {
  21016. intData += destBytesPerSample * numSamples;
  21017. for (int i = numSamples; --i >= 0;)
  21018. {
  21019. intData -= destBytesPerSample;
  21020. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21021. }
  21022. }
  21023. }
  21024. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21025. {
  21026. const double maxVal = (double) 0x7fff;
  21027. char* intData = static_cast <char*> (dest);
  21028. if (dest != (void*) source || destBytesPerSample <= 4)
  21029. {
  21030. for (int i = 0; i < numSamples; ++i)
  21031. {
  21032. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21033. intData += destBytesPerSample;
  21034. }
  21035. }
  21036. else
  21037. {
  21038. intData += destBytesPerSample * numSamples;
  21039. for (int i = numSamples; --i >= 0;)
  21040. {
  21041. intData -= destBytesPerSample;
  21042. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21043. }
  21044. }
  21045. }
  21046. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21047. {
  21048. const double maxVal = (double) 0x7fffff;
  21049. char* intData = static_cast <char*> (dest);
  21050. if (dest != (void*) source || destBytesPerSample <= 4)
  21051. {
  21052. for (int i = 0; i < numSamples; ++i)
  21053. {
  21054. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21055. intData += destBytesPerSample;
  21056. }
  21057. }
  21058. else
  21059. {
  21060. intData += destBytesPerSample * numSamples;
  21061. for (int i = numSamples; --i >= 0;)
  21062. {
  21063. intData -= destBytesPerSample;
  21064. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21065. }
  21066. }
  21067. }
  21068. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21069. {
  21070. const double maxVal = (double) 0x7fffff;
  21071. char* intData = static_cast <char*> (dest);
  21072. if (dest != (void*) source || destBytesPerSample <= 4)
  21073. {
  21074. for (int i = 0; i < numSamples; ++i)
  21075. {
  21076. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21077. intData += destBytesPerSample;
  21078. }
  21079. }
  21080. else
  21081. {
  21082. intData += destBytesPerSample * numSamples;
  21083. for (int i = numSamples; --i >= 0;)
  21084. {
  21085. intData -= destBytesPerSample;
  21086. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21087. }
  21088. }
  21089. }
  21090. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21091. {
  21092. const double maxVal = (double) 0x7fffffff;
  21093. char* intData = static_cast <char*> (dest);
  21094. if (dest != (void*) source || destBytesPerSample <= 4)
  21095. {
  21096. for (int i = 0; i < numSamples; ++i)
  21097. {
  21098. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21099. intData += destBytesPerSample;
  21100. }
  21101. }
  21102. else
  21103. {
  21104. intData += destBytesPerSample * numSamples;
  21105. for (int i = numSamples; --i >= 0;)
  21106. {
  21107. intData -= destBytesPerSample;
  21108. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21109. }
  21110. }
  21111. }
  21112. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21113. {
  21114. const double maxVal = (double) 0x7fffffff;
  21115. char* intData = static_cast <char*> (dest);
  21116. if (dest != (void*) source || destBytesPerSample <= 4)
  21117. {
  21118. for (int i = 0; i < numSamples; ++i)
  21119. {
  21120. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21121. intData += destBytesPerSample;
  21122. }
  21123. }
  21124. else
  21125. {
  21126. intData += destBytesPerSample * numSamples;
  21127. for (int i = numSamples; --i >= 0;)
  21128. {
  21129. intData -= destBytesPerSample;
  21130. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21131. }
  21132. }
  21133. }
  21134. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21135. {
  21136. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21137. char* d = static_cast <char*> (dest);
  21138. for (int i = 0; i < numSamples; ++i)
  21139. {
  21140. *(float*) d = source[i];
  21141. #if JUCE_BIG_ENDIAN
  21142. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21143. #endif
  21144. d += destBytesPerSample;
  21145. }
  21146. }
  21147. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21148. {
  21149. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21150. char* d = static_cast <char*> (dest);
  21151. for (int i = 0; i < numSamples; ++i)
  21152. {
  21153. *(float*) d = source[i];
  21154. #if JUCE_LITTLE_ENDIAN
  21155. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21156. #endif
  21157. d += destBytesPerSample;
  21158. }
  21159. }
  21160. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21161. {
  21162. const float scale = 1.0f / 0x7fff;
  21163. const char* intData = static_cast <const char*> (source);
  21164. if (source != (void*) dest || srcBytesPerSample >= 4)
  21165. {
  21166. for (int i = 0; i < numSamples; ++i)
  21167. {
  21168. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21169. intData += srcBytesPerSample;
  21170. }
  21171. }
  21172. else
  21173. {
  21174. intData += srcBytesPerSample * numSamples;
  21175. for (int i = numSamples; --i >= 0;)
  21176. {
  21177. intData -= srcBytesPerSample;
  21178. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21179. }
  21180. }
  21181. }
  21182. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21183. {
  21184. const float scale = 1.0f / 0x7fff;
  21185. const char* intData = static_cast <const char*> (source);
  21186. if (source != (void*) dest || srcBytesPerSample >= 4)
  21187. {
  21188. for (int i = 0; i < numSamples; ++i)
  21189. {
  21190. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21191. intData += srcBytesPerSample;
  21192. }
  21193. }
  21194. else
  21195. {
  21196. intData += srcBytesPerSample * numSamples;
  21197. for (int i = numSamples; --i >= 0;)
  21198. {
  21199. intData -= srcBytesPerSample;
  21200. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21201. }
  21202. }
  21203. }
  21204. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21205. {
  21206. const float scale = 1.0f / 0x7fffff;
  21207. const char* intData = static_cast <const char*> (source);
  21208. if (source != (void*) dest || srcBytesPerSample >= 4)
  21209. {
  21210. for (int i = 0; i < numSamples; ++i)
  21211. {
  21212. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21213. intData += srcBytesPerSample;
  21214. }
  21215. }
  21216. else
  21217. {
  21218. intData += srcBytesPerSample * numSamples;
  21219. for (int i = numSamples; --i >= 0;)
  21220. {
  21221. intData -= srcBytesPerSample;
  21222. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21223. }
  21224. }
  21225. }
  21226. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21227. {
  21228. const float scale = 1.0f / 0x7fffff;
  21229. const char* intData = static_cast <const char*> (source);
  21230. if (source != (void*) dest || srcBytesPerSample >= 4)
  21231. {
  21232. for (int i = 0; i < numSamples; ++i)
  21233. {
  21234. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21235. intData += srcBytesPerSample;
  21236. }
  21237. }
  21238. else
  21239. {
  21240. intData += srcBytesPerSample * numSamples;
  21241. for (int i = numSamples; --i >= 0;)
  21242. {
  21243. intData -= srcBytesPerSample;
  21244. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21245. }
  21246. }
  21247. }
  21248. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21249. {
  21250. const float scale = 1.0f / 0x7fffffff;
  21251. const char* intData = static_cast <const char*> (source);
  21252. if (source != (void*) dest || srcBytesPerSample >= 4)
  21253. {
  21254. for (int i = 0; i < numSamples; ++i)
  21255. {
  21256. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21257. intData += srcBytesPerSample;
  21258. }
  21259. }
  21260. else
  21261. {
  21262. intData += srcBytesPerSample * numSamples;
  21263. for (int i = numSamples; --i >= 0;)
  21264. {
  21265. intData -= srcBytesPerSample;
  21266. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21267. }
  21268. }
  21269. }
  21270. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21271. {
  21272. const float scale = 1.0f / 0x7fffffff;
  21273. const char* intData = static_cast <const char*> (source);
  21274. if (source != (void*) dest || srcBytesPerSample >= 4)
  21275. {
  21276. for (int i = 0; i < numSamples; ++i)
  21277. {
  21278. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21279. intData += srcBytesPerSample;
  21280. }
  21281. }
  21282. else
  21283. {
  21284. intData += srcBytesPerSample * numSamples;
  21285. for (int i = numSamples; --i >= 0;)
  21286. {
  21287. intData -= srcBytesPerSample;
  21288. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21289. }
  21290. }
  21291. }
  21292. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21293. {
  21294. const char* s = static_cast <const char*> (source);
  21295. for (int i = 0; i < numSamples; ++i)
  21296. {
  21297. dest[i] = *(float*)s;
  21298. #if JUCE_BIG_ENDIAN
  21299. uint32* const d = (uint32*) (dest + i);
  21300. *d = ByteOrder::swap (*d);
  21301. #endif
  21302. s += srcBytesPerSample;
  21303. }
  21304. }
  21305. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21306. {
  21307. const char* s = static_cast <const char*> (source);
  21308. for (int i = 0; i < numSamples; ++i)
  21309. {
  21310. dest[i] = *(float*)s;
  21311. #if JUCE_LITTLE_ENDIAN
  21312. uint32* const d = (uint32*) (dest + i);
  21313. *d = ByteOrder::swap (*d);
  21314. #endif
  21315. s += srcBytesPerSample;
  21316. }
  21317. }
  21318. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21319. const float* const source,
  21320. void* const dest,
  21321. const int numSamples)
  21322. {
  21323. switch (destFormat)
  21324. {
  21325. case int16LE:
  21326. convertFloatToInt16LE (source, dest, numSamples);
  21327. break;
  21328. case int16BE:
  21329. convertFloatToInt16BE (source, dest, numSamples);
  21330. break;
  21331. case int24LE:
  21332. convertFloatToInt24LE (source, dest, numSamples);
  21333. break;
  21334. case int24BE:
  21335. convertFloatToInt24BE (source, dest, numSamples);
  21336. break;
  21337. case int32LE:
  21338. convertFloatToInt32LE (source, dest, numSamples);
  21339. break;
  21340. case int32BE:
  21341. convertFloatToInt32BE (source, dest, numSamples);
  21342. break;
  21343. case float32LE:
  21344. convertFloatToFloat32LE (source, dest, numSamples);
  21345. break;
  21346. case float32BE:
  21347. convertFloatToFloat32BE (source, dest, numSamples);
  21348. break;
  21349. default:
  21350. jassertfalse;
  21351. break;
  21352. }
  21353. }
  21354. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21355. const void* const source,
  21356. float* const dest,
  21357. const int numSamples)
  21358. {
  21359. switch (sourceFormat)
  21360. {
  21361. case int16LE:
  21362. convertInt16LEToFloat (source, dest, numSamples);
  21363. break;
  21364. case int16BE:
  21365. convertInt16BEToFloat (source, dest, numSamples);
  21366. break;
  21367. case int24LE:
  21368. convertInt24LEToFloat (source, dest, numSamples);
  21369. break;
  21370. case int24BE:
  21371. convertInt24BEToFloat (source, dest, numSamples);
  21372. break;
  21373. case int32LE:
  21374. convertInt32LEToFloat (source, dest, numSamples);
  21375. break;
  21376. case int32BE:
  21377. convertInt32BEToFloat (source, dest, numSamples);
  21378. break;
  21379. case float32LE:
  21380. convertFloat32LEToFloat (source, dest, numSamples);
  21381. break;
  21382. case float32BE:
  21383. convertFloat32BEToFloat (source, dest, numSamples);
  21384. break;
  21385. default:
  21386. jassertfalse;
  21387. break;
  21388. }
  21389. }
  21390. void AudioDataConverters::interleaveSamples (const float** const source,
  21391. float* const dest,
  21392. const int numSamples,
  21393. const int numChannels)
  21394. {
  21395. for (int chan = 0; chan < numChannels; ++chan)
  21396. {
  21397. int i = chan;
  21398. const float* src = source [chan];
  21399. for (int j = 0; j < numSamples; ++j)
  21400. {
  21401. dest [i] = src [j];
  21402. i += numChannels;
  21403. }
  21404. }
  21405. }
  21406. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21407. float** const dest,
  21408. const int numSamples,
  21409. const int numChannels)
  21410. {
  21411. for (int chan = 0; chan < numChannels; ++chan)
  21412. {
  21413. int i = chan;
  21414. float* dst = dest [chan];
  21415. for (int j = 0; j < numSamples; ++j)
  21416. {
  21417. dst [j] = source [i];
  21418. i += numChannels;
  21419. }
  21420. }
  21421. }
  21422. #if JUCE_UNIT_TESTS
  21423. class AudioConversionTests : public UnitTest
  21424. {
  21425. public:
  21426. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21427. template <class F1, class E1, class F2, class E2>
  21428. struct Test5
  21429. {
  21430. static void test (UnitTest& unitTest)
  21431. {
  21432. test (unitTest, false);
  21433. test (unitTest, true);
  21434. }
  21435. static void test (UnitTest& unitTest, bool inPlace)
  21436. {
  21437. const int numSamples = 2048;
  21438. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21439. {
  21440. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21441. bool clippingFailed = false;
  21442. for (int i = 0; i < numSamples / 2; ++i)
  21443. {
  21444. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21445. if (! d.isFloatingPoint())
  21446. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21447. ++d;
  21448. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21449. ++d;
  21450. }
  21451. unitTest.expect (! clippingFailed);
  21452. }
  21453. // convert data from the source to dest format..
  21454. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21455. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21456. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21457. // ..and back again..
  21458. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21459. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21460. if (! inPlace)
  21461. zerostruct (reversed);
  21462. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21463. {
  21464. int biggestDiff = 0;
  21465. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21466. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21467. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21468. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21469. for (int i = 0; i < numSamples; ++i)
  21470. {
  21471. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21472. ++d1;
  21473. ++d2;
  21474. }
  21475. unitTest.expect (biggestDiff <= errorMargin);
  21476. }
  21477. }
  21478. };
  21479. template <class F1, class E1, class FormatType>
  21480. struct Test3
  21481. {
  21482. static void test (UnitTest& unitTest)
  21483. {
  21484. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21485. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21486. }
  21487. };
  21488. template <class FormatType, class Endianness>
  21489. struct Test2
  21490. {
  21491. static void test (UnitTest& unitTest)
  21492. {
  21493. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21494. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21495. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21496. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21497. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21498. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21499. }
  21500. };
  21501. template <class FormatType>
  21502. struct Test1
  21503. {
  21504. static void test (UnitTest& unitTest)
  21505. {
  21506. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21507. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21508. }
  21509. };
  21510. void runTest()
  21511. {
  21512. beginTest ("Round-trip conversion: Int8");
  21513. Test1 <AudioData::Int8>::test (*this);
  21514. beginTest ("Round-trip conversion: Int16");
  21515. Test1 <AudioData::Int16>::test (*this);
  21516. beginTest ("Round-trip conversion: Int24");
  21517. Test1 <AudioData::Int24>::test (*this);
  21518. beginTest ("Round-trip conversion: Int32");
  21519. Test1 <AudioData::Int32>::test (*this);
  21520. beginTest ("Round-trip conversion: Float32");
  21521. Test1 <AudioData::Float32>::test (*this);
  21522. }
  21523. };
  21524. static AudioConversionTests audioConversionUnitTests;
  21525. #endif
  21526. END_JUCE_NAMESPACE
  21527. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21528. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21529. BEGIN_JUCE_NAMESPACE
  21530. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21531. const int numSamples) throw()
  21532. : numChannels (numChannels_),
  21533. size (numSamples)
  21534. {
  21535. jassert (numSamples >= 0);
  21536. jassert (numChannels_ > 0);
  21537. allocateData();
  21538. }
  21539. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21540. : numChannels (other.numChannels),
  21541. size (other.size)
  21542. {
  21543. allocateData();
  21544. const size_t numBytes = size * sizeof (float);
  21545. for (int i = 0; i < numChannels; ++i)
  21546. memcpy (channels[i], other.channels[i], numBytes);
  21547. }
  21548. void AudioSampleBuffer::allocateData()
  21549. {
  21550. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21551. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21552. allocatedData.malloc (allocatedBytes);
  21553. channels = reinterpret_cast <float**> (allocatedData.getData());
  21554. float* chan = (float*) (allocatedData + channelListSize);
  21555. for (int i = 0; i < numChannels; ++i)
  21556. {
  21557. channels[i] = chan;
  21558. chan += size;
  21559. }
  21560. channels [numChannels] = 0;
  21561. }
  21562. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21563. const int numChannels_,
  21564. const int numSamples) throw()
  21565. : numChannels (numChannels_),
  21566. size (numSamples),
  21567. allocatedBytes (0)
  21568. {
  21569. jassert (numChannels_ > 0);
  21570. allocateChannels (dataToReferTo, 0);
  21571. }
  21572. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21573. const int numChannels_,
  21574. const int startSample,
  21575. const int numSamples) throw()
  21576. : numChannels (numChannels_),
  21577. size (numSamples),
  21578. allocatedBytes (0)
  21579. {
  21580. jassert (numChannels_ > 0);
  21581. allocateChannels (dataToReferTo, startSample);
  21582. }
  21583. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21584. const int newNumChannels,
  21585. const int newNumSamples) throw()
  21586. {
  21587. jassert (newNumChannels > 0);
  21588. allocatedBytes = 0;
  21589. allocatedData.free();
  21590. numChannels = newNumChannels;
  21591. size = newNumSamples;
  21592. allocateChannels (dataToReferTo, 0);
  21593. }
  21594. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo, int offset)
  21595. {
  21596. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21597. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21598. {
  21599. channels = static_cast <float**> (preallocatedChannelSpace);
  21600. }
  21601. else
  21602. {
  21603. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21604. channels = reinterpret_cast <float**> (allocatedData.getData());
  21605. }
  21606. for (int i = 0; i < numChannels; ++i)
  21607. {
  21608. // you have to pass in the same number of valid pointers as numChannels
  21609. jassert (dataToReferTo[i] != 0);
  21610. channels[i] = dataToReferTo[i] + offset;
  21611. }
  21612. channels [numChannels] = 0;
  21613. }
  21614. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21615. {
  21616. if (this != &other)
  21617. {
  21618. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21619. const size_t numBytes = size * sizeof (float);
  21620. for (int i = 0; i < numChannels; ++i)
  21621. memcpy (channels[i], other.channels[i], numBytes);
  21622. }
  21623. return *this;
  21624. }
  21625. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21626. {
  21627. }
  21628. void AudioSampleBuffer::setSize (const int newNumChannels,
  21629. const int newNumSamples,
  21630. const bool keepExistingContent,
  21631. const bool clearExtraSpace,
  21632. const bool avoidReallocating) throw()
  21633. {
  21634. jassert (newNumChannels > 0);
  21635. if (newNumSamples != size || newNumChannels != numChannels)
  21636. {
  21637. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21638. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21639. if (keepExistingContent)
  21640. {
  21641. HeapBlock <char> newData;
  21642. newData.allocate (newTotalBytes, clearExtraSpace);
  21643. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21644. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21645. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21646. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21647. for (int i = 0; i < numChansToCopy; ++i)
  21648. {
  21649. memcpy (newChan, channels[i], numBytesToCopy);
  21650. newChannels[i] = newChan;
  21651. newChan += newNumSamples;
  21652. }
  21653. allocatedData.swapWith (newData);
  21654. allocatedBytes = (int) newTotalBytes;
  21655. channels = newChannels;
  21656. }
  21657. else
  21658. {
  21659. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21660. {
  21661. if (clearExtraSpace)
  21662. zeromem (allocatedData, newTotalBytes);
  21663. }
  21664. else
  21665. {
  21666. allocatedBytes = newTotalBytes;
  21667. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21668. channels = reinterpret_cast <float**> (allocatedData.getData());
  21669. }
  21670. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21671. for (int i = 0; i < newNumChannels; ++i)
  21672. {
  21673. channels[i] = chan;
  21674. chan += newNumSamples;
  21675. }
  21676. }
  21677. channels [newNumChannels] = 0;
  21678. size = newNumSamples;
  21679. numChannels = newNumChannels;
  21680. }
  21681. }
  21682. void AudioSampleBuffer::clear() throw()
  21683. {
  21684. for (int i = 0; i < numChannels; ++i)
  21685. zeromem (channels[i], size * sizeof (float));
  21686. }
  21687. void AudioSampleBuffer::clear (const int startSample,
  21688. const int numSamples) throw()
  21689. {
  21690. jassert (startSample >= 0 && startSample + numSamples <= size);
  21691. for (int i = 0; i < numChannels; ++i)
  21692. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21693. }
  21694. void AudioSampleBuffer::clear (const int channel,
  21695. const int startSample,
  21696. const int numSamples) throw()
  21697. {
  21698. jassert (isPositiveAndBelow (channel, numChannels));
  21699. jassert (startSample >= 0 && startSample + numSamples <= size);
  21700. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21701. }
  21702. void AudioSampleBuffer::applyGain (const int channel,
  21703. const int startSample,
  21704. int numSamples,
  21705. const float gain) throw()
  21706. {
  21707. jassert (isPositiveAndBelow (channel, numChannels));
  21708. jassert (startSample >= 0 && startSample + numSamples <= size);
  21709. if (gain != 1.0f)
  21710. {
  21711. float* d = channels [channel] + startSample;
  21712. if (gain == 0.0f)
  21713. {
  21714. zeromem (d, sizeof (float) * numSamples);
  21715. }
  21716. else
  21717. {
  21718. while (--numSamples >= 0)
  21719. *d++ *= gain;
  21720. }
  21721. }
  21722. }
  21723. void AudioSampleBuffer::applyGainRamp (const int channel,
  21724. const int startSample,
  21725. int numSamples,
  21726. float startGain,
  21727. float endGain) throw()
  21728. {
  21729. if (startGain == endGain)
  21730. {
  21731. applyGain (channel, startSample, numSamples, startGain);
  21732. }
  21733. else
  21734. {
  21735. jassert (isPositiveAndBelow (channel, numChannels));
  21736. jassert (startSample >= 0 && startSample + numSamples <= size);
  21737. const float increment = (endGain - startGain) / numSamples;
  21738. float* d = channels [channel] + startSample;
  21739. while (--numSamples >= 0)
  21740. {
  21741. *d++ *= startGain;
  21742. startGain += increment;
  21743. }
  21744. }
  21745. }
  21746. void AudioSampleBuffer::applyGain (const int startSample,
  21747. const int numSamples,
  21748. const float gain) throw()
  21749. {
  21750. for (int i = 0; i < numChannels; ++i)
  21751. applyGain (i, startSample, numSamples, gain);
  21752. }
  21753. void AudioSampleBuffer::addFrom (const int destChannel,
  21754. const int destStartSample,
  21755. const AudioSampleBuffer& source,
  21756. const int sourceChannel,
  21757. const int sourceStartSample,
  21758. int numSamples,
  21759. const float gain) throw()
  21760. {
  21761. jassert (&source != this || sourceChannel != destChannel);
  21762. jassert (isPositiveAndBelow (destChannel, numChannels));
  21763. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21764. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21765. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21766. if (gain != 0.0f && numSamples > 0)
  21767. {
  21768. float* d = channels [destChannel] + destStartSample;
  21769. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21770. if (gain != 1.0f)
  21771. {
  21772. while (--numSamples >= 0)
  21773. *d++ += gain * *s++;
  21774. }
  21775. else
  21776. {
  21777. while (--numSamples >= 0)
  21778. *d++ += *s++;
  21779. }
  21780. }
  21781. }
  21782. void AudioSampleBuffer::addFrom (const int destChannel,
  21783. const int destStartSample,
  21784. const float* source,
  21785. int numSamples,
  21786. const float gain) throw()
  21787. {
  21788. jassert (isPositiveAndBelow (destChannel, numChannels));
  21789. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21790. jassert (source != 0);
  21791. if (gain != 0.0f && numSamples > 0)
  21792. {
  21793. float* d = channels [destChannel] + destStartSample;
  21794. if (gain != 1.0f)
  21795. {
  21796. while (--numSamples >= 0)
  21797. *d++ += gain * *source++;
  21798. }
  21799. else
  21800. {
  21801. while (--numSamples >= 0)
  21802. *d++ += *source++;
  21803. }
  21804. }
  21805. }
  21806. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21807. const int destStartSample,
  21808. const float* source,
  21809. int numSamples,
  21810. float startGain,
  21811. const float endGain) throw()
  21812. {
  21813. jassert (isPositiveAndBelow (destChannel, numChannels));
  21814. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21815. jassert (source != 0);
  21816. if (startGain == endGain)
  21817. {
  21818. addFrom (destChannel,
  21819. destStartSample,
  21820. source,
  21821. numSamples,
  21822. startGain);
  21823. }
  21824. else
  21825. {
  21826. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21827. {
  21828. const float increment = (endGain - startGain) / numSamples;
  21829. float* d = channels [destChannel] + destStartSample;
  21830. while (--numSamples >= 0)
  21831. {
  21832. *d++ += startGain * *source++;
  21833. startGain += increment;
  21834. }
  21835. }
  21836. }
  21837. }
  21838. void AudioSampleBuffer::copyFrom (const int destChannel,
  21839. const int destStartSample,
  21840. const AudioSampleBuffer& source,
  21841. const int sourceChannel,
  21842. const int sourceStartSample,
  21843. int numSamples) throw()
  21844. {
  21845. jassert (&source != this || sourceChannel != destChannel);
  21846. jassert (isPositiveAndBelow (destChannel, numChannels));
  21847. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21848. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21849. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21850. if (numSamples > 0)
  21851. {
  21852. memcpy (channels [destChannel] + destStartSample,
  21853. source.channels [sourceChannel] + sourceStartSample,
  21854. sizeof (float) * numSamples);
  21855. }
  21856. }
  21857. void AudioSampleBuffer::copyFrom (const int destChannel,
  21858. const int destStartSample,
  21859. const float* source,
  21860. int numSamples) throw()
  21861. {
  21862. jassert (isPositiveAndBelow (destChannel, numChannels));
  21863. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21864. jassert (source != 0);
  21865. if (numSamples > 0)
  21866. {
  21867. memcpy (channels [destChannel] + destStartSample,
  21868. source,
  21869. sizeof (float) * numSamples);
  21870. }
  21871. }
  21872. void AudioSampleBuffer::copyFrom (const int destChannel,
  21873. const int destStartSample,
  21874. const float* source,
  21875. int numSamples,
  21876. const float gain) throw()
  21877. {
  21878. jassert (isPositiveAndBelow (destChannel, numChannels));
  21879. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21880. jassert (source != 0);
  21881. if (numSamples > 0)
  21882. {
  21883. float* d = channels [destChannel] + destStartSample;
  21884. if (gain != 1.0f)
  21885. {
  21886. if (gain == 0)
  21887. {
  21888. zeromem (d, sizeof (float) * numSamples);
  21889. }
  21890. else
  21891. {
  21892. while (--numSamples >= 0)
  21893. *d++ = gain * *source++;
  21894. }
  21895. }
  21896. else
  21897. {
  21898. memcpy (d, source, sizeof (float) * numSamples);
  21899. }
  21900. }
  21901. }
  21902. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21903. const int destStartSample,
  21904. const float* source,
  21905. int numSamples,
  21906. float startGain,
  21907. float endGain) throw()
  21908. {
  21909. jassert (isPositiveAndBelow (destChannel, numChannels));
  21910. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21911. jassert (source != 0);
  21912. if (startGain == endGain)
  21913. {
  21914. copyFrom (destChannel,
  21915. destStartSample,
  21916. source,
  21917. numSamples,
  21918. startGain);
  21919. }
  21920. else
  21921. {
  21922. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21923. {
  21924. const float increment = (endGain - startGain) / numSamples;
  21925. float* d = channels [destChannel] + destStartSample;
  21926. while (--numSamples >= 0)
  21927. {
  21928. *d++ = startGain * *source++;
  21929. startGain += increment;
  21930. }
  21931. }
  21932. }
  21933. }
  21934. void AudioSampleBuffer::findMinMax (const int channel,
  21935. const int startSample,
  21936. int numSamples,
  21937. float& minVal,
  21938. float& maxVal) const throw()
  21939. {
  21940. jassert (isPositiveAndBelow (channel, numChannels));
  21941. jassert (startSample >= 0 && startSample + numSamples <= size);
  21942. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  21943. }
  21944. float AudioSampleBuffer::getMagnitude (const int channel,
  21945. const int startSample,
  21946. const int numSamples) const throw()
  21947. {
  21948. jassert (isPositiveAndBelow (channel, numChannels));
  21949. jassert (startSample >= 0 && startSample + numSamples <= size);
  21950. float mn, mx;
  21951. findMinMax (channel, startSample, numSamples, mn, mx);
  21952. return jmax (mn, -mn, mx, -mx);
  21953. }
  21954. float AudioSampleBuffer::getMagnitude (const int startSample,
  21955. const int numSamples) const throw()
  21956. {
  21957. float mag = 0.0f;
  21958. for (int i = 0; i < numChannels; ++i)
  21959. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21960. return mag;
  21961. }
  21962. float AudioSampleBuffer::getRMSLevel (const int channel,
  21963. const int startSample,
  21964. const int numSamples) const throw()
  21965. {
  21966. jassert (isPositiveAndBelow (channel, numChannels));
  21967. jassert (startSample >= 0 && startSample + numSamples <= size);
  21968. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21969. return 0.0f;
  21970. const float* const data = channels [channel] + startSample;
  21971. double sum = 0.0;
  21972. for (int i = 0; i < numSamples; ++i)
  21973. {
  21974. const float sample = data [i];
  21975. sum += sample * sample;
  21976. }
  21977. return (float) std::sqrt (sum / numSamples);
  21978. }
  21979. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21980. const int startSample,
  21981. const int numSamples,
  21982. const int64 readerStartSample,
  21983. const bool useLeftChan,
  21984. const bool useRightChan)
  21985. {
  21986. jassert (reader != 0);
  21987. jassert (startSample >= 0 && startSample + numSamples <= size);
  21988. if (numSamples > 0)
  21989. {
  21990. int* chans[3];
  21991. if (useLeftChan == useRightChan)
  21992. {
  21993. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21994. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  21995. }
  21996. else if (useLeftChan || (reader->numChannels == 1))
  21997. {
  21998. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21999. chans[1] = 0;
  22000. }
  22001. else if (useRightChan)
  22002. {
  22003. chans[0] = 0;
  22004. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22005. }
  22006. chans[2] = 0;
  22007. reader->read (chans, 2, readerStartSample, numSamples, true);
  22008. if (! reader->usesFloatingPointData)
  22009. {
  22010. for (int j = 0; j < 2; ++j)
  22011. {
  22012. float* const d = reinterpret_cast <float*> (chans[j]);
  22013. if (d != 0)
  22014. {
  22015. const float multiplier = 1.0f / 0x7fffffff;
  22016. for (int i = 0; i < numSamples; ++i)
  22017. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22018. }
  22019. }
  22020. }
  22021. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22022. {
  22023. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22024. memcpy (getSampleData (1, startSample),
  22025. getSampleData (0, startSample),
  22026. sizeof (float) * numSamples);
  22027. }
  22028. }
  22029. }
  22030. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22031. const int startSample,
  22032. const int numSamples) const
  22033. {
  22034. jassert (writer != 0);
  22035. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22036. }
  22037. END_JUCE_NAMESPACE
  22038. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22039. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22040. BEGIN_JUCE_NAMESPACE
  22041. IIRFilter::IIRFilter()
  22042. : active (false)
  22043. {
  22044. reset();
  22045. }
  22046. IIRFilter::IIRFilter (const IIRFilter& other)
  22047. : active (other.active)
  22048. {
  22049. const ScopedLock sl (other.processLock);
  22050. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22051. reset();
  22052. }
  22053. IIRFilter::~IIRFilter()
  22054. {
  22055. }
  22056. void IIRFilter::reset() throw()
  22057. {
  22058. const ScopedLock sl (processLock);
  22059. x1 = 0;
  22060. x2 = 0;
  22061. y1 = 0;
  22062. y2 = 0;
  22063. }
  22064. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22065. {
  22066. float out = coefficients[0] * in
  22067. + coefficients[1] * x1
  22068. + coefficients[2] * x2
  22069. - coefficients[4] * y1
  22070. - coefficients[5] * y2;
  22071. #if JUCE_INTEL
  22072. if (! (out < -1.0e-8 || out > 1.0e-8))
  22073. out = 0;
  22074. #endif
  22075. x2 = x1;
  22076. x1 = in;
  22077. y2 = y1;
  22078. y1 = out;
  22079. return out;
  22080. }
  22081. void IIRFilter::processSamples (float* const samples,
  22082. const int numSamples) throw()
  22083. {
  22084. const ScopedLock sl (processLock);
  22085. if (active)
  22086. {
  22087. for (int i = 0; i < numSamples; ++i)
  22088. {
  22089. const float in = samples[i];
  22090. float out = coefficients[0] * in
  22091. + coefficients[1] * x1
  22092. + coefficients[2] * x2
  22093. - coefficients[4] * y1
  22094. - coefficients[5] * y2;
  22095. #if JUCE_INTEL
  22096. if (! (out < -1.0e-8 || out > 1.0e-8))
  22097. out = 0;
  22098. #endif
  22099. x2 = x1;
  22100. x1 = in;
  22101. y2 = y1;
  22102. y1 = out;
  22103. samples[i] = out;
  22104. }
  22105. }
  22106. }
  22107. void IIRFilter::makeLowPass (const double sampleRate,
  22108. const double frequency) throw()
  22109. {
  22110. jassert (sampleRate > 0);
  22111. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22112. const double nSquared = n * n;
  22113. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22114. setCoefficients (c1,
  22115. c1 * 2.0f,
  22116. c1,
  22117. 1.0,
  22118. c1 * 2.0 * (1.0 - nSquared),
  22119. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22120. }
  22121. void IIRFilter::makeHighPass (const double sampleRate,
  22122. const double frequency) throw()
  22123. {
  22124. const double n = tan (double_Pi * frequency / sampleRate);
  22125. const double nSquared = n * n;
  22126. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22127. setCoefficients (c1,
  22128. c1 * -2.0f,
  22129. c1,
  22130. 1.0,
  22131. c1 * 2.0 * (nSquared - 1.0),
  22132. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22133. }
  22134. void IIRFilter::makeLowShelf (const double sampleRate,
  22135. const double cutOffFrequency,
  22136. const double Q,
  22137. const float gainFactor) throw()
  22138. {
  22139. jassert (sampleRate > 0);
  22140. jassert (Q > 0);
  22141. const double A = jmax (0.0f, gainFactor);
  22142. const double aminus1 = A - 1.0;
  22143. const double aplus1 = A + 1.0;
  22144. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22145. const double coso = std::cos (omega);
  22146. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22147. const double aminus1TimesCoso = aminus1 * coso;
  22148. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22149. A * 2.0 * (aminus1 - aplus1 * coso),
  22150. A * (aplus1 - aminus1TimesCoso - beta),
  22151. aplus1 + aminus1TimesCoso + beta,
  22152. -2.0 * (aminus1 + aplus1 * coso),
  22153. aplus1 + aminus1TimesCoso - beta);
  22154. }
  22155. void IIRFilter::makeHighShelf (const double sampleRate,
  22156. const double cutOffFrequency,
  22157. const double Q,
  22158. const float gainFactor) throw()
  22159. {
  22160. jassert (sampleRate > 0);
  22161. jassert (Q > 0);
  22162. const double A = jmax (0.0f, gainFactor);
  22163. const double aminus1 = A - 1.0;
  22164. const double aplus1 = A + 1.0;
  22165. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22166. const double coso = std::cos (omega);
  22167. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22168. const double aminus1TimesCoso = aminus1 * coso;
  22169. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22170. A * -2.0 * (aminus1 + aplus1 * coso),
  22171. A * (aplus1 + aminus1TimesCoso - beta),
  22172. aplus1 - aminus1TimesCoso + beta,
  22173. 2.0 * (aminus1 - aplus1 * coso),
  22174. aplus1 - aminus1TimesCoso - beta);
  22175. }
  22176. void IIRFilter::makeBandPass (const double sampleRate,
  22177. const double centreFrequency,
  22178. const double Q,
  22179. const float gainFactor) throw()
  22180. {
  22181. jassert (sampleRate > 0);
  22182. jassert (Q > 0);
  22183. const double A = jmax (0.0f, gainFactor);
  22184. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22185. const double alpha = 0.5 * std::sin (omega) / Q;
  22186. const double c2 = -2.0 * std::cos (omega);
  22187. const double alphaTimesA = alpha * A;
  22188. const double alphaOverA = alpha / A;
  22189. setCoefficients (1.0 + alphaTimesA,
  22190. c2,
  22191. 1.0 - alphaTimesA,
  22192. 1.0 + alphaOverA,
  22193. c2,
  22194. 1.0 - alphaOverA);
  22195. }
  22196. void IIRFilter::makeInactive() throw()
  22197. {
  22198. const ScopedLock sl (processLock);
  22199. active = false;
  22200. }
  22201. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22202. {
  22203. const ScopedLock sl (processLock);
  22204. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22205. active = other.active;
  22206. }
  22207. void IIRFilter::setCoefficients (double c1,
  22208. double c2,
  22209. double c3,
  22210. double c4,
  22211. double c5,
  22212. double c6) throw()
  22213. {
  22214. const double a = 1.0 / c4;
  22215. c1 *= a;
  22216. c2 *= a;
  22217. c3 *= a;
  22218. c5 *= a;
  22219. c6 *= a;
  22220. const ScopedLock sl (processLock);
  22221. coefficients[0] = (float) c1;
  22222. coefficients[1] = (float) c2;
  22223. coefficients[2] = (float) c3;
  22224. coefficients[3] = (float) c4;
  22225. coefficients[4] = (float) c5;
  22226. coefficients[5] = (float) c6;
  22227. active = true;
  22228. }
  22229. END_JUCE_NAMESPACE
  22230. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22231. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22232. BEGIN_JUCE_NAMESPACE
  22233. MidiBuffer::MidiBuffer() throw()
  22234. : bytesUsed (0)
  22235. {
  22236. }
  22237. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22238. : bytesUsed (0)
  22239. {
  22240. addEvent (message, 0);
  22241. }
  22242. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22243. : data (other.data),
  22244. bytesUsed (other.bytesUsed)
  22245. {
  22246. }
  22247. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22248. {
  22249. bytesUsed = other.bytesUsed;
  22250. data = other.data;
  22251. return *this;
  22252. }
  22253. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22254. {
  22255. data.swapWith (other.data);
  22256. swapVariables <int> (bytesUsed, other.bytesUsed);
  22257. }
  22258. MidiBuffer::~MidiBuffer()
  22259. {
  22260. }
  22261. inline uint8* MidiBuffer::getData() const throw()
  22262. {
  22263. return static_cast <uint8*> (data.getData());
  22264. }
  22265. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22266. {
  22267. return *static_cast <const int*> (d);
  22268. }
  22269. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22270. {
  22271. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22272. }
  22273. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22274. {
  22275. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22276. }
  22277. void MidiBuffer::clear() throw()
  22278. {
  22279. bytesUsed = 0;
  22280. }
  22281. void MidiBuffer::clear (const int startSample, const int numSamples)
  22282. {
  22283. uint8* const start = findEventAfter (getData(), startSample - 1);
  22284. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22285. if (end > start)
  22286. {
  22287. const int bytesToMove = bytesUsed - (int) (end - getData());
  22288. if (bytesToMove > 0)
  22289. memmove (start, end, bytesToMove);
  22290. bytesUsed -= (int) (end - start);
  22291. }
  22292. }
  22293. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22294. {
  22295. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22296. }
  22297. namespace MidiBufferHelpers
  22298. {
  22299. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22300. {
  22301. unsigned int byte = (unsigned int) *data;
  22302. int size = 0;
  22303. if (byte == 0xf0 || byte == 0xf7)
  22304. {
  22305. const uint8* d = data + 1;
  22306. while (d < data + maxBytes)
  22307. if (*d++ == 0xf7)
  22308. break;
  22309. size = (int) (d - data);
  22310. }
  22311. else if (byte == 0xff)
  22312. {
  22313. int n;
  22314. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22315. size = jmin (maxBytes, n + 2 + bytesLeft);
  22316. }
  22317. else if (byte >= 0x80)
  22318. {
  22319. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22320. }
  22321. return size;
  22322. }
  22323. }
  22324. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22325. {
  22326. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22327. if (numBytes > 0)
  22328. {
  22329. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22330. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22331. uint8* d = findEventAfter (getData(), sampleNumber);
  22332. const int bytesToMove = bytesUsed - (int) (d - getData());
  22333. if (bytesToMove > 0)
  22334. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22335. *reinterpret_cast <int*> (d) = sampleNumber;
  22336. d += sizeof (int);
  22337. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22338. d += sizeof (uint16);
  22339. memcpy (d, newData, numBytes);
  22340. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22341. }
  22342. }
  22343. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22344. const int startSample,
  22345. const int numSamples,
  22346. const int sampleDeltaToAdd)
  22347. {
  22348. Iterator i (otherBuffer);
  22349. i.setNextSamplePosition (startSample);
  22350. const uint8* eventData;
  22351. int eventSize, position;
  22352. while (i.getNextEvent (eventData, eventSize, position)
  22353. && (position < startSample + numSamples || numSamples < 0))
  22354. {
  22355. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22356. }
  22357. }
  22358. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22359. {
  22360. data.ensureSize (minimumNumBytes);
  22361. }
  22362. bool MidiBuffer::isEmpty() const throw()
  22363. {
  22364. return bytesUsed == 0;
  22365. }
  22366. int MidiBuffer::getNumEvents() const throw()
  22367. {
  22368. int n = 0;
  22369. const uint8* d = getData();
  22370. const uint8* const end = d + bytesUsed;
  22371. while (d < end)
  22372. {
  22373. d += getEventTotalSize (d);
  22374. ++n;
  22375. }
  22376. return n;
  22377. }
  22378. int MidiBuffer::getFirstEventTime() const throw()
  22379. {
  22380. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22381. }
  22382. int MidiBuffer::getLastEventTime() const throw()
  22383. {
  22384. if (bytesUsed == 0)
  22385. return 0;
  22386. const uint8* d = getData();
  22387. const uint8* const endData = d + bytesUsed;
  22388. for (;;)
  22389. {
  22390. const uint8* const nextOne = d + getEventTotalSize (d);
  22391. if (nextOne >= endData)
  22392. return getEventTime (d);
  22393. d = nextOne;
  22394. }
  22395. }
  22396. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22397. {
  22398. const uint8* const endData = getData() + bytesUsed;
  22399. while (d < endData && getEventTime (d) <= samplePosition)
  22400. d += getEventTotalSize (d);
  22401. return d;
  22402. }
  22403. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22404. : buffer (buffer_),
  22405. data (buffer_.getData())
  22406. {
  22407. }
  22408. MidiBuffer::Iterator::~Iterator() throw()
  22409. {
  22410. }
  22411. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22412. {
  22413. data = buffer.getData();
  22414. const uint8* dataEnd = data + buffer.bytesUsed;
  22415. while (data < dataEnd && getEventTime (data) < samplePosition)
  22416. data += getEventTotalSize (data);
  22417. }
  22418. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22419. {
  22420. if (data >= buffer.getData() + buffer.bytesUsed)
  22421. return false;
  22422. samplePosition = getEventTime (data);
  22423. numBytes = getEventDataSize (data);
  22424. data += sizeof (int) + sizeof (uint16);
  22425. midiData = data;
  22426. data += numBytes;
  22427. return true;
  22428. }
  22429. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22430. {
  22431. if (data >= buffer.getData() + buffer.bytesUsed)
  22432. return false;
  22433. samplePosition = getEventTime (data);
  22434. const int numBytes = getEventDataSize (data);
  22435. data += sizeof (int) + sizeof (uint16);
  22436. result = MidiMessage (data, numBytes, samplePosition);
  22437. data += numBytes;
  22438. return true;
  22439. }
  22440. END_JUCE_NAMESPACE
  22441. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22442. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22443. BEGIN_JUCE_NAMESPACE
  22444. namespace MidiFileHelpers
  22445. {
  22446. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22447. {
  22448. unsigned int buffer = v & 0x7F;
  22449. while ((v >>= 7) != 0)
  22450. {
  22451. buffer <<= 8;
  22452. buffer |= ((v & 0x7F) | 0x80);
  22453. }
  22454. for (;;)
  22455. {
  22456. out.writeByte ((char) buffer);
  22457. if (buffer & 0x80)
  22458. buffer >>= 8;
  22459. else
  22460. break;
  22461. }
  22462. }
  22463. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22464. {
  22465. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22466. data += 4;
  22467. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22468. {
  22469. bool ok = false;
  22470. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22471. {
  22472. for (int i = 0; i < 8; ++i)
  22473. {
  22474. ch = ByteOrder::bigEndianInt (data);
  22475. data += 4;
  22476. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22477. {
  22478. ok = true;
  22479. break;
  22480. }
  22481. }
  22482. }
  22483. if (! ok)
  22484. return false;
  22485. }
  22486. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22487. data += 4;
  22488. fileType = (short) ByteOrder::bigEndianShort (data);
  22489. data += 2;
  22490. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22491. data += 2;
  22492. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22493. data += 2;
  22494. bytesRemaining -= 6;
  22495. data += bytesRemaining;
  22496. return true;
  22497. }
  22498. double convertTicksToSeconds (const double time,
  22499. const MidiMessageSequence& tempoEvents,
  22500. const int timeFormat)
  22501. {
  22502. if (timeFormat > 0)
  22503. {
  22504. int numer = 4, denom = 4;
  22505. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22506. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22507. double secsPerTick = 0.5 * tickLen;
  22508. const int numEvents = tempoEvents.getNumEvents();
  22509. for (int i = 0; i < numEvents; ++i)
  22510. {
  22511. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22512. if (time <= m.getTimeStamp())
  22513. break;
  22514. if (timeFormat > 0)
  22515. {
  22516. correctedTempoTime = correctedTempoTime
  22517. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22518. }
  22519. else
  22520. {
  22521. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22522. }
  22523. tempoTime = m.getTimeStamp();
  22524. if (m.isTempoMetaEvent())
  22525. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22526. else if (m.isTimeSignatureMetaEvent())
  22527. m.getTimeSignatureInfo (numer, denom);
  22528. while (i + 1 < numEvents)
  22529. {
  22530. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22531. if (m2.getTimeStamp() == tempoTime)
  22532. {
  22533. ++i;
  22534. if (m2.isTempoMetaEvent())
  22535. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22536. else if (m2.isTimeSignatureMetaEvent())
  22537. m2.getTimeSignatureInfo (numer, denom);
  22538. }
  22539. else
  22540. {
  22541. break;
  22542. }
  22543. }
  22544. }
  22545. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22546. }
  22547. else
  22548. {
  22549. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22550. }
  22551. }
  22552. // a comparator that puts all the note-offs before note-ons that have the same time
  22553. struct Sorter
  22554. {
  22555. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22556. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22557. {
  22558. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22559. if (diff > 0)
  22560. return 1;
  22561. else if (diff < 0)
  22562. return -1;
  22563. else if (first->message.isNoteOff() && second->message.isNoteOn())
  22564. return -1;
  22565. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22566. return 1;
  22567. return 0;
  22568. }
  22569. };
  22570. }
  22571. MidiFile::MidiFile()
  22572. : timeFormat ((short) (unsigned short) 0xe728)
  22573. {
  22574. }
  22575. MidiFile::~MidiFile()
  22576. {
  22577. clear();
  22578. }
  22579. void MidiFile::clear()
  22580. {
  22581. tracks.clear();
  22582. }
  22583. int MidiFile::getNumTracks() const throw()
  22584. {
  22585. return tracks.size();
  22586. }
  22587. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22588. {
  22589. return tracks [index];
  22590. }
  22591. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22592. {
  22593. tracks.add (new MidiMessageSequence (trackSequence));
  22594. }
  22595. short MidiFile::getTimeFormat() const throw()
  22596. {
  22597. return timeFormat;
  22598. }
  22599. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22600. {
  22601. timeFormat = (short) ticks;
  22602. }
  22603. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22604. const int subframeResolution) throw()
  22605. {
  22606. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22607. }
  22608. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22609. {
  22610. for (int i = tracks.size(); --i >= 0;)
  22611. {
  22612. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22613. for (int j = 0; j < numEvents; ++j)
  22614. {
  22615. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22616. if (m.isTempoMetaEvent())
  22617. tempoChangeEvents.addEvent (m);
  22618. }
  22619. }
  22620. }
  22621. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22622. {
  22623. for (int i = tracks.size(); --i >= 0;)
  22624. {
  22625. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22626. for (int j = 0; j < numEvents; ++j)
  22627. {
  22628. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22629. if (m.isTimeSignatureMetaEvent())
  22630. timeSigEvents.addEvent (m);
  22631. }
  22632. }
  22633. }
  22634. double MidiFile::getLastTimestamp() const
  22635. {
  22636. double t = 0.0;
  22637. for (int i = tracks.size(); --i >= 0;)
  22638. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22639. return t;
  22640. }
  22641. bool MidiFile::readFrom (InputStream& sourceStream)
  22642. {
  22643. clear();
  22644. MemoryBlock data;
  22645. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22646. // (put a sanity-check on the file size, as midi files are generally small)
  22647. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22648. {
  22649. size_t size = data.getSize();
  22650. const uint8* d = static_cast <const uint8*> (data.getData());
  22651. short fileType, expectedTracks;
  22652. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22653. {
  22654. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22655. int track = 0;
  22656. while (size > 0 && track < expectedTracks)
  22657. {
  22658. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22659. d += 4;
  22660. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22661. d += 4;
  22662. if (chunkSize <= 0)
  22663. break;
  22664. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22665. {
  22666. readNextTrack (d, chunkSize);
  22667. }
  22668. size -= chunkSize + 8;
  22669. d += chunkSize;
  22670. ++track;
  22671. }
  22672. return true;
  22673. }
  22674. }
  22675. return false;
  22676. }
  22677. void MidiFile::readNextTrack (const uint8* data, int size)
  22678. {
  22679. double time = 0;
  22680. char lastStatusByte = 0;
  22681. MidiMessageSequence result;
  22682. while (size > 0)
  22683. {
  22684. int bytesUsed;
  22685. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22686. data += bytesUsed;
  22687. size -= bytesUsed;
  22688. time += delay;
  22689. int messSize = 0;
  22690. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22691. if (messSize <= 0)
  22692. break;
  22693. size -= messSize;
  22694. data += messSize;
  22695. result.addEvent (mm);
  22696. const char firstByte = *(mm.getRawData());
  22697. if ((firstByte & 0xf0) != 0xf0)
  22698. lastStatusByte = firstByte;
  22699. }
  22700. // use a sort that puts all the note-offs before note-ons that have the same time
  22701. MidiFileHelpers::Sorter sorter;
  22702. result.list.sort (sorter, true);
  22703. result.updateMatchedPairs();
  22704. addTrack (result);
  22705. }
  22706. void MidiFile::convertTimestampTicksToSeconds()
  22707. {
  22708. MidiMessageSequence tempoEvents;
  22709. findAllTempoEvents (tempoEvents);
  22710. findAllTimeSigEvents (tempoEvents);
  22711. for (int i = 0; i < tracks.size(); ++i)
  22712. {
  22713. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22714. for (int j = ms.getNumEvents(); --j >= 0;)
  22715. {
  22716. MidiMessage& m = ms.getEventPointer(j)->message;
  22717. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22718. tempoEvents,
  22719. timeFormat));
  22720. }
  22721. }
  22722. }
  22723. bool MidiFile::writeTo (OutputStream& out)
  22724. {
  22725. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22726. out.writeIntBigEndian (6);
  22727. out.writeShortBigEndian (1); // type
  22728. out.writeShortBigEndian ((short) tracks.size());
  22729. out.writeShortBigEndian (timeFormat);
  22730. for (int i = 0; i < tracks.size(); ++i)
  22731. writeTrack (out, i);
  22732. out.flush();
  22733. return true;
  22734. }
  22735. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22736. {
  22737. MemoryOutputStream out;
  22738. const MidiMessageSequence& ms = *tracks[trackNum];
  22739. int lastTick = 0;
  22740. char lastStatusByte = 0;
  22741. for (int i = 0; i < ms.getNumEvents(); ++i)
  22742. {
  22743. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22744. const int tick = roundToInt (mm.getTimeStamp());
  22745. const int delta = jmax (0, tick - lastTick);
  22746. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22747. lastTick = tick;
  22748. const char statusByte = *(mm.getRawData());
  22749. if ((statusByte == lastStatusByte)
  22750. && ((statusByte & 0xf0) != 0xf0)
  22751. && i > 0
  22752. && mm.getRawDataSize() > 1)
  22753. {
  22754. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22755. }
  22756. else
  22757. {
  22758. out.write (mm.getRawData(), mm.getRawDataSize());
  22759. }
  22760. lastStatusByte = statusByte;
  22761. }
  22762. out.writeByte (0);
  22763. const MidiMessage m (MidiMessage::endOfTrack());
  22764. out.write (m.getRawData(),
  22765. m.getRawDataSize());
  22766. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22767. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22768. mainOut.write (out.getData(), (int) out.getDataSize());
  22769. }
  22770. END_JUCE_NAMESPACE
  22771. /*** End of inlined file: juce_MidiFile.cpp ***/
  22772. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22773. BEGIN_JUCE_NAMESPACE
  22774. MidiKeyboardState::MidiKeyboardState()
  22775. {
  22776. zerostruct (noteStates);
  22777. }
  22778. MidiKeyboardState::~MidiKeyboardState()
  22779. {
  22780. }
  22781. void MidiKeyboardState::reset()
  22782. {
  22783. const ScopedLock sl (lock);
  22784. zerostruct (noteStates);
  22785. eventsToAdd.clear();
  22786. }
  22787. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22788. {
  22789. jassert (midiChannel >= 0 && midiChannel <= 16);
  22790. return isPositiveAndBelow (n, (int) 128)
  22791. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22792. }
  22793. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22794. {
  22795. return isPositiveAndBelow (n, (int) 128)
  22796. && (noteStates[n] & midiChannelMask) != 0;
  22797. }
  22798. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22799. {
  22800. jassert (midiChannel >= 0 && midiChannel <= 16);
  22801. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  22802. const ScopedLock sl (lock);
  22803. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22804. {
  22805. const int timeNow = (int) Time::getMillisecondCounter();
  22806. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22807. eventsToAdd.clear (0, timeNow - 500);
  22808. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22809. }
  22810. }
  22811. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22812. {
  22813. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22814. {
  22815. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22816. for (int i = listeners.size(); --i >= 0;)
  22817. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22818. }
  22819. }
  22820. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22821. {
  22822. const ScopedLock sl (lock);
  22823. if (isNoteOn (midiChannel, midiNoteNumber))
  22824. {
  22825. const int timeNow = (int) Time::getMillisecondCounter();
  22826. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22827. eventsToAdd.clear (0, timeNow - 500);
  22828. noteOffInternal (midiChannel, midiNoteNumber);
  22829. }
  22830. }
  22831. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22832. {
  22833. if (isNoteOn (midiChannel, midiNoteNumber))
  22834. {
  22835. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22836. for (int i = listeners.size(); --i >= 0;)
  22837. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22838. }
  22839. }
  22840. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22841. {
  22842. const ScopedLock sl (lock);
  22843. if (midiChannel <= 0)
  22844. {
  22845. for (int i = 1; i <= 16; ++i)
  22846. allNotesOff (i);
  22847. }
  22848. else
  22849. {
  22850. for (int i = 0; i < 128; ++i)
  22851. noteOff (midiChannel, i);
  22852. }
  22853. }
  22854. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22855. {
  22856. if (message.isNoteOn())
  22857. {
  22858. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22859. }
  22860. else if (message.isNoteOff())
  22861. {
  22862. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22863. }
  22864. else if (message.isAllNotesOff())
  22865. {
  22866. for (int i = 0; i < 128; ++i)
  22867. noteOffInternal (message.getChannel(), i);
  22868. }
  22869. }
  22870. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22871. const int startSample,
  22872. const int numSamples,
  22873. const bool injectIndirectEvents)
  22874. {
  22875. MidiBuffer::Iterator i (buffer);
  22876. MidiMessage message (0xf4, 0.0);
  22877. int time;
  22878. const ScopedLock sl (lock);
  22879. while (i.getNextEvent (message, time))
  22880. processNextMidiEvent (message);
  22881. if (injectIndirectEvents)
  22882. {
  22883. MidiBuffer::Iterator i2 (eventsToAdd);
  22884. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22885. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22886. while (i2.getNextEvent (message, time))
  22887. {
  22888. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22889. buffer.addEvent (message, startSample + pos);
  22890. }
  22891. }
  22892. eventsToAdd.clear();
  22893. }
  22894. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22895. {
  22896. const ScopedLock sl (lock);
  22897. listeners.addIfNotAlreadyThere (listener);
  22898. }
  22899. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22900. {
  22901. const ScopedLock sl (lock);
  22902. listeners.removeValue (listener);
  22903. }
  22904. END_JUCE_NAMESPACE
  22905. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22906. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22907. BEGIN_JUCE_NAMESPACE
  22908. namespace MidiHelpers
  22909. {
  22910. inline uint8 initialByte (const int type, const int channel) throw()
  22911. {
  22912. return (uint8) (type | jlimit (0, 15, channel - 1));
  22913. }
  22914. inline uint8 validVelocity (const int v) throw()
  22915. {
  22916. return (uint8) jlimit (0, 127, v);
  22917. }
  22918. }
  22919. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22920. {
  22921. numBytesUsed = 0;
  22922. int v = 0;
  22923. int i;
  22924. do
  22925. {
  22926. i = (int) *data++;
  22927. if (++numBytesUsed > 6)
  22928. break;
  22929. v = (v << 7) + (i & 0x7f);
  22930. } while (i & 0x80);
  22931. return v;
  22932. }
  22933. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22934. {
  22935. // this method only works for valid starting bytes of a short midi message
  22936. jassert (firstByte >= 0x80 && firstByte != 0xf0 && firstByte != 0xf7);
  22937. static const char messageLengths[] =
  22938. {
  22939. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22940. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22941. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22942. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22943. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22944. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22945. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22946. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22947. };
  22948. return messageLengths [firstByte & 0x7f];
  22949. }
  22950. MidiMessage::MidiMessage() throw()
  22951. : timeStamp (0),
  22952. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22953. size (2)
  22954. {
  22955. data[0] = 0xf0;
  22956. data[1] = 0xf7;
  22957. }
  22958. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22959. : timeStamp (t),
  22960. size (dataSize)
  22961. {
  22962. jassert (dataSize > 0);
  22963. if (dataSize <= 4)
  22964. data = static_cast<uint8*> (preallocatedData.asBytes);
  22965. else
  22966. data = new uint8 [dataSize];
  22967. memcpy (data, d, dataSize);
  22968. // check that the length matches the data..
  22969. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22970. }
  22971. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22972. : timeStamp (t),
  22973. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22974. size (1)
  22975. {
  22976. data[0] = (uint8) byte1;
  22977. // check that the length matches the data..
  22978. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22979. }
  22980. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22981. : timeStamp (t),
  22982. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22983. size (2)
  22984. {
  22985. data[0] = (uint8) byte1;
  22986. data[1] = (uint8) byte2;
  22987. // check that the length matches the data..
  22988. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22989. }
  22990. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22991. : timeStamp (t),
  22992. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22993. size (3)
  22994. {
  22995. data[0] = (uint8) byte1;
  22996. data[1] = (uint8) byte2;
  22997. data[2] = (uint8) byte3;
  22998. // check that the length matches the data..
  22999. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23000. }
  23001. MidiMessage::MidiMessage (const MidiMessage& other)
  23002. : timeStamp (other.timeStamp),
  23003. size (other.size)
  23004. {
  23005. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23006. {
  23007. data = new uint8 [size];
  23008. memcpy (data, other.data, size);
  23009. }
  23010. else
  23011. {
  23012. data = static_cast<uint8*> (preallocatedData.asBytes);
  23013. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23014. }
  23015. }
  23016. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23017. : timeStamp (newTimeStamp),
  23018. size (other.size)
  23019. {
  23020. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23021. {
  23022. data = new uint8 [size];
  23023. memcpy (data, other.data, size);
  23024. }
  23025. else
  23026. {
  23027. data = static_cast<uint8*> (preallocatedData.asBytes);
  23028. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23029. }
  23030. }
  23031. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23032. : timeStamp (t),
  23033. data (static_cast<uint8*> (preallocatedData.asBytes))
  23034. {
  23035. const uint8* src = static_cast <const uint8*> (src_);
  23036. unsigned int byte = (unsigned int) *src;
  23037. if (byte < 0x80)
  23038. {
  23039. byte = (unsigned int) (uint8) lastStatusByte;
  23040. numBytesUsed = -1;
  23041. }
  23042. else
  23043. {
  23044. numBytesUsed = 0;
  23045. --sz;
  23046. ++src;
  23047. }
  23048. if (byte >= 0x80)
  23049. {
  23050. if (byte == 0xf0)
  23051. {
  23052. const uint8* d = src;
  23053. bool haveReadAllLengthBytes = false;
  23054. while (d < src + sz)
  23055. {
  23056. if (*d >= 0x80)
  23057. {
  23058. if (*d == 0xf7)
  23059. {
  23060. ++d; // include the trailing 0xf7 when we hit it
  23061. break;
  23062. }
  23063. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  23064. break; // bytes, assume it's the end of the sysex
  23065. ++d;
  23066. continue;
  23067. }
  23068. haveReadAllLengthBytes = true;
  23069. ++d;
  23070. }
  23071. size = 1 + (int) (d - src);
  23072. data = new uint8 [size];
  23073. *data = (uint8) byte;
  23074. memcpy (data + 1, src, size - 1);
  23075. }
  23076. else if (byte == 0xff)
  23077. {
  23078. int n;
  23079. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23080. size = jmin (sz + 1, n + 2 + bytesLeft);
  23081. data = new uint8 [size];
  23082. *data = (uint8) byte;
  23083. memcpy (data + 1, src, size - 1);
  23084. }
  23085. else
  23086. {
  23087. preallocatedData.asInt32 = 0;
  23088. size = getMessageLengthFromFirstByte ((uint8) byte);
  23089. data[0] = (uint8) byte;
  23090. if (size > 1)
  23091. {
  23092. data[1] = src[0];
  23093. if (size > 2)
  23094. data[2] = src[1];
  23095. }
  23096. }
  23097. numBytesUsed += size;
  23098. }
  23099. else
  23100. {
  23101. preallocatedData.asInt32 = 0;
  23102. size = 0;
  23103. }
  23104. }
  23105. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23106. {
  23107. if (this != &other)
  23108. {
  23109. timeStamp = other.timeStamp;
  23110. size = other.size;
  23111. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23112. delete[] data;
  23113. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23114. {
  23115. data = new uint8 [size];
  23116. memcpy (data, other.data, size);
  23117. }
  23118. else
  23119. {
  23120. data = static_cast<uint8*> (preallocatedData.asBytes);
  23121. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23122. }
  23123. }
  23124. return *this;
  23125. }
  23126. MidiMessage::~MidiMessage()
  23127. {
  23128. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23129. delete[] data;
  23130. }
  23131. int MidiMessage::getChannel() const throw()
  23132. {
  23133. if ((data[0] & 0xf0) != 0xf0)
  23134. return (data[0] & 0xf) + 1;
  23135. else
  23136. return 0;
  23137. }
  23138. bool MidiMessage::isForChannel (const int channel) const throw()
  23139. {
  23140. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23141. return ((data[0] & 0xf) == channel - 1)
  23142. && ((data[0] & 0xf0) != 0xf0);
  23143. }
  23144. void MidiMessage::setChannel (const int channel) throw()
  23145. {
  23146. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23147. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23148. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23149. | (uint8)(channel - 1));
  23150. }
  23151. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23152. {
  23153. return ((data[0] & 0xf0) == 0x90)
  23154. && (returnTrueForVelocity0 || data[2] != 0);
  23155. }
  23156. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23157. {
  23158. return ((data[0] & 0xf0) == 0x80)
  23159. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23160. }
  23161. bool MidiMessage::isNoteOnOrOff() const throw()
  23162. {
  23163. const int d = data[0] & 0xf0;
  23164. return (d == 0x90) || (d == 0x80);
  23165. }
  23166. int MidiMessage::getNoteNumber() const throw()
  23167. {
  23168. return data[1];
  23169. }
  23170. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23171. {
  23172. if (isNoteOnOrOff())
  23173. data[1] = newNoteNumber & 127;
  23174. }
  23175. uint8 MidiMessage::getVelocity() const throw()
  23176. {
  23177. if (isNoteOnOrOff())
  23178. return data[2];
  23179. else
  23180. return 0;
  23181. }
  23182. float MidiMessage::getFloatVelocity() const throw()
  23183. {
  23184. return getVelocity() * (1.0f / 127.0f);
  23185. }
  23186. void MidiMessage::setVelocity (const float newVelocity) throw()
  23187. {
  23188. if (isNoteOnOrOff())
  23189. data[2] = MidiHelpers::validVelocity (roundToInt (newVelocity * 127.0f));
  23190. }
  23191. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23192. {
  23193. if (isNoteOnOrOff())
  23194. data[2] = MidiHelpers::validVelocity (roundToInt (scaleFactor * data[2]));
  23195. }
  23196. bool MidiMessage::isAftertouch() const throw()
  23197. {
  23198. return (data[0] & 0xf0) == 0xa0;
  23199. }
  23200. int MidiMessage::getAfterTouchValue() const throw()
  23201. {
  23202. return data[2];
  23203. }
  23204. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23205. const int noteNum,
  23206. const int aftertouchValue) throw()
  23207. {
  23208. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23209. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23210. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23211. return MidiMessage (MidiHelpers::initialByte (0xa0, channel),
  23212. noteNum & 0x7f,
  23213. aftertouchValue & 0x7f);
  23214. }
  23215. bool MidiMessage::isChannelPressure() const throw()
  23216. {
  23217. return (data[0] & 0xf0) == 0xd0;
  23218. }
  23219. int MidiMessage::getChannelPressureValue() const throw()
  23220. {
  23221. jassert (isChannelPressure());
  23222. return data[1];
  23223. }
  23224. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23225. const int pressure) throw()
  23226. {
  23227. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23228. jassert (isPositiveAndBelow (pressure, (int) 128));
  23229. return MidiMessage (MidiHelpers::initialByte (0xd0, channel), pressure & 0x7f);
  23230. }
  23231. bool MidiMessage::isProgramChange() const throw()
  23232. {
  23233. return (data[0] & 0xf0) == 0xc0;
  23234. }
  23235. int MidiMessage::getProgramChangeNumber() const throw()
  23236. {
  23237. return data[1];
  23238. }
  23239. const MidiMessage MidiMessage::programChange (const int channel,
  23240. const int programNumber) throw()
  23241. {
  23242. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23243. return MidiMessage (MidiHelpers::initialByte (0xc0, channel), programNumber & 0x7f);
  23244. }
  23245. bool MidiMessage::isPitchWheel() const throw()
  23246. {
  23247. return (data[0] & 0xf0) == 0xe0;
  23248. }
  23249. int MidiMessage::getPitchWheelValue() const throw()
  23250. {
  23251. return data[1] | (data[2] << 7);
  23252. }
  23253. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23254. const int position) throw()
  23255. {
  23256. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23257. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23258. return MidiMessage (MidiHelpers::initialByte (0xe0, channel), position & 127, (position >> 7) & 127);
  23259. }
  23260. bool MidiMessage::isController() const throw()
  23261. {
  23262. return (data[0] & 0xf0) == 0xb0;
  23263. }
  23264. int MidiMessage::getControllerNumber() const throw()
  23265. {
  23266. jassert (isController());
  23267. return data[1];
  23268. }
  23269. int MidiMessage::getControllerValue() const throw()
  23270. {
  23271. jassert (isController());
  23272. return data[2];
  23273. }
  23274. const MidiMessage MidiMessage::controllerEvent (const int channel, const int controllerType, const int value) throw()
  23275. {
  23276. // the channel must be between 1 and 16 inclusive
  23277. jassert (channel > 0 && channel <= 16);
  23278. return MidiMessage (MidiHelpers::initialByte (0xb0, channel), controllerType & 127, value & 127);
  23279. }
  23280. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const float velocity) throw()
  23281. {
  23282. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23283. }
  23284. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const uint8 velocity) throw()
  23285. {
  23286. jassert (channel > 0 && channel <= 16);
  23287. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23288. return MidiMessage (MidiHelpers::initialByte (0x90, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23289. }
  23290. const MidiMessage MidiMessage::noteOff (const int channel, const int noteNumber, uint8 velocity) throw()
  23291. {
  23292. jassert (channel > 0 && channel <= 16);
  23293. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23294. return MidiMessage (MidiHelpers::initialByte (0x80, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23295. }
  23296. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23297. {
  23298. return controllerEvent (channel, 123, 0);
  23299. }
  23300. bool MidiMessage::isAllNotesOff() const throw()
  23301. {
  23302. return (data[0] & 0xf0) == 0xb0 && data[1] == 123;
  23303. }
  23304. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23305. {
  23306. return controllerEvent (channel, 120, 0);
  23307. }
  23308. bool MidiMessage::isAllSoundOff() const throw()
  23309. {
  23310. return (data[0] & 0xf0) == 0xb0 && data[1] == 120;
  23311. }
  23312. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23313. {
  23314. return controllerEvent (channel, 121, 0);
  23315. }
  23316. const MidiMessage MidiMessage::masterVolume (const float volume)
  23317. {
  23318. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23319. uint8 buf[8];
  23320. buf[0] = 0xf0;
  23321. buf[1] = 0x7f;
  23322. buf[2] = 0x7f;
  23323. buf[3] = 0x04;
  23324. buf[4] = 0x01;
  23325. buf[5] = (uint8) (vol & 0x7f);
  23326. buf[6] = (uint8) (vol >> 7);
  23327. buf[7] = 0xf7;
  23328. return MidiMessage (buf, 8);
  23329. }
  23330. bool MidiMessage::isSysEx() const throw()
  23331. {
  23332. return *data == 0xf0;
  23333. }
  23334. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23335. {
  23336. HeapBlock<uint8> m (dataSize + 2);
  23337. m[0] = 0xf0;
  23338. memcpy (m + 1, sysexData, dataSize);
  23339. m[dataSize + 1] = 0xf7;
  23340. return MidiMessage (m, dataSize + 2);
  23341. }
  23342. const uint8* MidiMessage::getSysExData() const throw()
  23343. {
  23344. return isSysEx() ? getRawData() + 1 : 0;
  23345. }
  23346. int MidiMessage::getSysExDataSize() const throw()
  23347. {
  23348. return isSysEx() ? size - 2 : 0;
  23349. }
  23350. bool MidiMessage::isMetaEvent() const throw()
  23351. {
  23352. return *data == 0xff;
  23353. }
  23354. bool MidiMessage::isActiveSense() const throw()
  23355. {
  23356. return *data == 0xfe;
  23357. }
  23358. int MidiMessage::getMetaEventType() const throw()
  23359. {
  23360. return *data != 0xff ? -1 : data[1];
  23361. }
  23362. int MidiMessage::getMetaEventLength() const throw()
  23363. {
  23364. if (*data == 0xff)
  23365. {
  23366. int n;
  23367. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23368. }
  23369. return 0;
  23370. }
  23371. const uint8* MidiMessage::getMetaEventData() const throw()
  23372. {
  23373. int n;
  23374. const uint8* d = data + 2;
  23375. readVariableLengthVal (d, n);
  23376. return d + n;
  23377. }
  23378. bool MidiMessage::isTrackMetaEvent() const throw()
  23379. {
  23380. return getMetaEventType() == 0;
  23381. }
  23382. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23383. {
  23384. return getMetaEventType() == 47;
  23385. }
  23386. bool MidiMessage::isTextMetaEvent() const throw()
  23387. {
  23388. const int t = getMetaEventType();
  23389. return t > 0 && t < 16;
  23390. }
  23391. const String MidiMessage::getTextFromTextMetaEvent() const
  23392. {
  23393. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23394. }
  23395. bool MidiMessage::isTrackNameEvent() const throw()
  23396. {
  23397. return (data[1] == 3) && (*data == 0xff);
  23398. }
  23399. bool MidiMessage::isTempoMetaEvent() const throw()
  23400. {
  23401. return (data[1] == 81) && (*data == 0xff);
  23402. }
  23403. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23404. {
  23405. return (data[1] == 0x20) && (*data == 0xff) && (data[2] == 1);
  23406. }
  23407. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23408. {
  23409. return data[3] + 1;
  23410. }
  23411. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23412. {
  23413. if (! isTempoMetaEvent())
  23414. return 0.0;
  23415. const uint8* const d = getMetaEventData();
  23416. return (((unsigned int) d[0] << 16)
  23417. | ((unsigned int) d[1] << 8)
  23418. | d[2])
  23419. / 1000000.0;
  23420. }
  23421. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23422. {
  23423. if (timeFormat > 0)
  23424. {
  23425. if (! isTempoMetaEvent())
  23426. return 0.5 / timeFormat;
  23427. return getTempoSecondsPerQuarterNote() / timeFormat;
  23428. }
  23429. else
  23430. {
  23431. const int frameCode = (-timeFormat) >> 8;
  23432. double framesPerSecond;
  23433. switch (frameCode)
  23434. {
  23435. case 24: framesPerSecond = 24.0; break;
  23436. case 25: framesPerSecond = 25.0; break;
  23437. case 29: framesPerSecond = 29.97; break;
  23438. case 30: framesPerSecond = 30.0; break;
  23439. default: framesPerSecond = 30.0; break;
  23440. }
  23441. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23442. }
  23443. }
  23444. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23445. {
  23446. uint8 d[8];
  23447. d[0] = 0xff;
  23448. d[1] = 81;
  23449. d[2] = 3;
  23450. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23451. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23452. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23453. return MidiMessage (d, 6, 0.0);
  23454. }
  23455. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23456. {
  23457. return (data[1] == 0x58) && (*data == (uint8) 0xff);
  23458. }
  23459. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23460. {
  23461. if (isTimeSignatureMetaEvent())
  23462. {
  23463. const uint8* const d = getMetaEventData();
  23464. numerator = d[0];
  23465. denominator = 1 << d[1];
  23466. }
  23467. else
  23468. {
  23469. numerator = 4;
  23470. denominator = 4;
  23471. }
  23472. }
  23473. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23474. {
  23475. uint8 d[8];
  23476. d[0] = 0xff;
  23477. d[1] = 0x58;
  23478. d[2] = 0x04;
  23479. d[3] = (uint8) numerator;
  23480. int n = 1;
  23481. int powerOfTwo = 0;
  23482. while (n < denominator)
  23483. {
  23484. n <<= 1;
  23485. ++powerOfTwo;
  23486. }
  23487. d[4] = (uint8) powerOfTwo;
  23488. d[5] = 0x01;
  23489. d[6] = 96;
  23490. return MidiMessage (d, 7, 0.0);
  23491. }
  23492. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23493. {
  23494. uint8 d[8];
  23495. d[0] = 0xff;
  23496. d[1] = 0x20;
  23497. d[2] = 0x01;
  23498. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23499. return MidiMessage (d, 4, 0.0);
  23500. }
  23501. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23502. {
  23503. return getMetaEventType() == 89;
  23504. }
  23505. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23506. {
  23507. return (int) *getMetaEventData();
  23508. }
  23509. const MidiMessage MidiMessage::endOfTrack() throw()
  23510. {
  23511. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23512. }
  23513. bool MidiMessage::isSongPositionPointer() const throw()
  23514. {
  23515. return *data == 0xf2;
  23516. }
  23517. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23518. {
  23519. return data[1] | (data[2] << 7);
  23520. }
  23521. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23522. {
  23523. return MidiMessage (0xf2,
  23524. positionInMidiBeats & 127,
  23525. (positionInMidiBeats >> 7) & 127);
  23526. }
  23527. bool MidiMessage::isMidiStart() const throw()
  23528. {
  23529. return *data == 0xfa;
  23530. }
  23531. const MidiMessage MidiMessage::midiStart() throw()
  23532. {
  23533. return MidiMessage (0xfa);
  23534. }
  23535. bool MidiMessage::isMidiContinue() const throw()
  23536. {
  23537. return *data == 0xfb;
  23538. }
  23539. const MidiMessage MidiMessage::midiContinue() throw()
  23540. {
  23541. return MidiMessage (0xfb);
  23542. }
  23543. bool MidiMessage::isMidiStop() const throw()
  23544. {
  23545. return *data == 0xfc;
  23546. }
  23547. const MidiMessage MidiMessage::midiStop() throw()
  23548. {
  23549. return MidiMessage (0xfc);
  23550. }
  23551. bool MidiMessage::isMidiClock() const throw()
  23552. {
  23553. return *data == 0xf8;
  23554. }
  23555. const MidiMessage MidiMessage::midiClock() throw()
  23556. {
  23557. return MidiMessage (0xf8);
  23558. }
  23559. bool MidiMessage::isQuarterFrame() const throw()
  23560. {
  23561. return *data == 0xf1;
  23562. }
  23563. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23564. {
  23565. return ((int) data[1]) >> 4;
  23566. }
  23567. int MidiMessage::getQuarterFrameValue() const throw()
  23568. {
  23569. return ((int) data[1]) & 0x0f;
  23570. }
  23571. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23572. const int value) throw()
  23573. {
  23574. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23575. }
  23576. bool MidiMessage::isFullFrame() const throw()
  23577. {
  23578. return data[0] == 0xf0
  23579. && data[1] == 0x7f
  23580. && size >= 10
  23581. && data[3] == 0x01
  23582. && data[4] == 0x01;
  23583. }
  23584. void MidiMessage::getFullFrameParameters (int& hours,
  23585. int& minutes,
  23586. int& seconds,
  23587. int& frames,
  23588. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23589. {
  23590. jassert (isFullFrame());
  23591. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23592. hours = data[5] & 0x1f;
  23593. minutes = data[6];
  23594. seconds = data[7];
  23595. frames = data[8];
  23596. }
  23597. const MidiMessage MidiMessage::fullFrame (const int hours,
  23598. const int minutes,
  23599. const int seconds,
  23600. const int frames,
  23601. MidiMessage::SmpteTimecodeType timecodeType)
  23602. {
  23603. uint8 d[10];
  23604. d[0] = 0xf0;
  23605. d[1] = 0x7f;
  23606. d[2] = 0x7f;
  23607. d[3] = 0x01;
  23608. d[4] = 0x01;
  23609. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23610. d[6] = (uint8) minutes;
  23611. d[7] = (uint8) seconds;
  23612. d[8] = (uint8) frames;
  23613. d[9] = 0xf7;
  23614. return MidiMessage (d, 10, 0.0);
  23615. }
  23616. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23617. {
  23618. return data[0] == 0xf0
  23619. && data[1] == 0x7f
  23620. && data[3] == 0x06
  23621. && size > 5;
  23622. }
  23623. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23624. {
  23625. jassert (isMidiMachineControlMessage());
  23626. return (MidiMachineControlCommand) data[4];
  23627. }
  23628. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23629. {
  23630. uint8 d[6];
  23631. d[0] = 0xf0;
  23632. d[1] = 0x7f;
  23633. d[2] = 0x00;
  23634. d[3] = 0x06;
  23635. d[4] = (uint8) command;
  23636. d[5] = 0xf7;
  23637. return MidiMessage (d, 6, 0.0);
  23638. }
  23639. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23640. int& minutes,
  23641. int& seconds,
  23642. int& frames) const throw()
  23643. {
  23644. if (size >= 12
  23645. && data[0] == 0xf0
  23646. && data[1] == 0x7f
  23647. && data[3] == 0x06
  23648. && data[4] == 0x44
  23649. && data[5] == 0x06
  23650. && data[6] == 0x01)
  23651. {
  23652. hours = data[7] % 24; // (that some machines send out hours > 24)
  23653. minutes = data[8];
  23654. seconds = data[9];
  23655. frames = data[10];
  23656. return true;
  23657. }
  23658. return false;
  23659. }
  23660. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23661. int minutes,
  23662. int seconds,
  23663. int frames)
  23664. {
  23665. uint8 d[12];
  23666. d[0] = 0xf0;
  23667. d[1] = 0x7f;
  23668. d[2] = 0x00;
  23669. d[3] = 0x06;
  23670. d[4] = 0x44;
  23671. d[5] = 0x06;
  23672. d[6] = 0x01;
  23673. d[7] = (uint8) hours;
  23674. d[8] = (uint8) minutes;
  23675. d[9] = (uint8) seconds;
  23676. d[10] = (uint8) frames;
  23677. d[11] = 0xf7;
  23678. return MidiMessage (d, 12, 0.0);
  23679. }
  23680. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23681. {
  23682. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23683. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23684. if (isPositiveAndBelow (note, (int) 128))
  23685. {
  23686. String s (useSharps ? sharpNoteNames [note % 12]
  23687. : flatNoteNames [note % 12]);
  23688. if (includeOctaveNumber)
  23689. s << (note / 12 + (octaveNumForMiddleC - 5));
  23690. return s;
  23691. }
  23692. return String::empty;
  23693. }
  23694. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23695. {
  23696. noteNumber -= 12 * 6 + 9; // now 0 = A
  23697. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23698. }
  23699. const String MidiMessage::getGMInstrumentName (const int n)
  23700. {
  23701. const char* names[] =
  23702. {
  23703. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23704. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23705. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23706. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23707. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23708. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23709. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23710. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23711. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23712. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23713. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23714. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23715. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23716. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23717. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23718. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23719. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23720. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23721. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23722. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23723. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23724. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23725. "Applause", "Gunshot"
  23726. };
  23727. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23728. }
  23729. const String MidiMessage::getGMInstrumentBankName (const int n)
  23730. {
  23731. const char* names[] =
  23732. {
  23733. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23734. "Bass", "Strings", "Ensemble", "Brass",
  23735. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23736. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23737. };
  23738. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23739. }
  23740. const String MidiMessage::getRhythmInstrumentName (const int n)
  23741. {
  23742. const char* names[] =
  23743. {
  23744. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23745. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23746. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23747. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23748. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23749. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23750. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23751. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23752. "Mute Triangle", "Open Triangle"
  23753. };
  23754. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23755. }
  23756. const String MidiMessage::getControllerName (const int n)
  23757. {
  23758. const char* names[] =
  23759. {
  23760. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23761. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23762. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23763. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23764. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23765. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23766. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23767. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23768. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23769. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23770. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23771. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23772. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23773. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23774. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23775. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23776. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23777. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23778. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23780. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23781. "Poly Operation"
  23782. };
  23783. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23784. }
  23785. END_JUCE_NAMESPACE
  23786. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23787. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23788. BEGIN_JUCE_NAMESPACE
  23789. MidiMessageCollector::MidiMessageCollector()
  23790. : lastCallbackTime (0),
  23791. sampleRate (44100.0001)
  23792. {
  23793. }
  23794. MidiMessageCollector::~MidiMessageCollector()
  23795. {
  23796. }
  23797. void MidiMessageCollector::reset (const double sampleRate_)
  23798. {
  23799. jassert (sampleRate_ > 0);
  23800. const ScopedLock sl (midiCallbackLock);
  23801. sampleRate = sampleRate_;
  23802. incomingMessages.clear();
  23803. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23804. }
  23805. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23806. {
  23807. // you need to call reset() to set the correct sample rate before using this object
  23808. jassert (sampleRate != 44100.0001);
  23809. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23810. // for details of what the number should be.
  23811. jassert (message.getTimeStamp() != 0);
  23812. const ScopedLock sl (midiCallbackLock);
  23813. const int sampleNumber
  23814. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23815. incomingMessages.addEvent (message, sampleNumber);
  23816. // if the messages don't get used for over a second, we'd better
  23817. // get rid of any old ones to avoid the queue getting too big
  23818. if (sampleNumber > sampleRate)
  23819. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23820. }
  23821. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23822. const int numSamples)
  23823. {
  23824. // you need to call reset() to set the correct sample rate before using this object
  23825. jassert (sampleRate != 44100.0001);
  23826. const double timeNow = Time::getMillisecondCounterHiRes();
  23827. const double msElapsed = timeNow - lastCallbackTime;
  23828. const ScopedLock sl (midiCallbackLock);
  23829. lastCallbackTime = timeNow;
  23830. if (! incomingMessages.isEmpty())
  23831. {
  23832. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23833. int startSample = 0;
  23834. int scale = 1 << 16;
  23835. const uint8* midiData;
  23836. int numBytes, samplePosition;
  23837. MidiBuffer::Iterator iter (incomingMessages);
  23838. if (numSourceSamples > numSamples)
  23839. {
  23840. // if our list of events is longer than the buffer we're being
  23841. // asked for, scale them down to squeeze them all in..
  23842. const int maxBlockLengthToUse = numSamples << 5;
  23843. if (numSourceSamples > maxBlockLengthToUse)
  23844. {
  23845. startSample = numSourceSamples - maxBlockLengthToUse;
  23846. numSourceSamples = maxBlockLengthToUse;
  23847. iter.setNextSamplePosition (startSample);
  23848. }
  23849. scale = (numSamples << 10) / numSourceSamples;
  23850. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23851. {
  23852. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23853. destBuffer.addEvent (midiData, numBytes,
  23854. jlimit (0, numSamples - 1, samplePosition));
  23855. }
  23856. }
  23857. else
  23858. {
  23859. // if our event list is shorter than the number we need, put them
  23860. // towards the end of the buffer
  23861. startSample = numSamples - numSourceSamples;
  23862. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23863. {
  23864. destBuffer.addEvent (midiData, numBytes,
  23865. jlimit (0, numSamples - 1, samplePosition + startSample));
  23866. }
  23867. }
  23868. incomingMessages.clear();
  23869. }
  23870. }
  23871. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23872. {
  23873. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23874. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23875. addMessageToQueue (m);
  23876. }
  23877. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23878. {
  23879. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23880. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23881. addMessageToQueue (m);
  23882. }
  23883. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23884. {
  23885. addMessageToQueue (message);
  23886. }
  23887. END_JUCE_NAMESPACE
  23888. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23889. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23890. BEGIN_JUCE_NAMESPACE
  23891. MidiMessageSequence::MidiMessageSequence()
  23892. {
  23893. }
  23894. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23895. {
  23896. list.ensureStorageAllocated (other.list.size());
  23897. for (int i = 0; i < other.list.size(); ++i)
  23898. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23899. }
  23900. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23901. {
  23902. MidiMessageSequence otherCopy (other);
  23903. swapWith (otherCopy);
  23904. return *this;
  23905. }
  23906. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23907. {
  23908. list.swapWithArray (other.list);
  23909. }
  23910. MidiMessageSequence::~MidiMessageSequence()
  23911. {
  23912. }
  23913. void MidiMessageSequence::clear()
  23914. {
  23915. list.clear();
  23916. }
  23917. int MidiMessageSequence::getNumEvents() const
  23918. {
  23919. return list.size();
  23920. }
  23921. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23922. {
  23923. return list [index];
  23924. }
  23925. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23926. {
  23927. const MidiEventHolder* const meh = list [index];
  23928. if (meh != 0 && meh->noteOffObject != 0)
  23929. return meh->noteOffObject->message.getTimeStamp();
  23930. else
  23931. return 0.0;
  23932. }
  23933. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23934. {
  23935. const MidiEventHolder* const meh = list [index];
  23936. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23937. }
  23938. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23939. {
  23940. return list.indexOf (event);
  23941. }
  23942. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23943. {
  23944. const int numEvents = list.size();
  23945. int i;
  23946. for (i = 0; i < numEvents; ++i)
  23947. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23948. break;
  23949. return i;
  23950. }
  23951. double MidiMessageSequence::getStartTime() const
  23952. {
  23953. if (list.size() > 0)
  23954. return list.getUnchecked(0)->message.getTimeStamp();
  23955. else
  23956. return 0;
  23957. }
  23958. double MidiMessageSequence::getEndTime() const
  23959. {
  23960. if (list.size() > 0)
  23961. return list.getLast()->message.getTimeStamp();
  23962. else
  23963. return 0;
  23964. }
  23965. double MidiMessageSequence::getEventTime (const int index) const
  23966. {
  23967. if (isPositiveAndBelow (index, list.size()))
  23968. return list.getUnchecked (index)->message.getTimeStamp();
  23969. return 0.0;
  23970. }
  23971. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23972. double timeAdjustment)
  23973. {
  23974. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23975. timeAdjustment += newMessage.getTimeStamp();
  23976. newOne->message.setTimeStamp (timeAdjustment);
  23977. int i;
  23978. for (i = list.size(); --i >= 0;)
  23979. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23980. break;
  23981. list.insert (i + 1, newOne);
  23982. }
  23983. void MidiMessageSequence::deleteEvent (const int index,
  23984. const bool deleteMatchingNoteUp)
  23985. {
  23986. if (isPositiveAndBelow (index, list.size()))
  23987. {
  23988. if (deleteMatchingNoteUp)
  23989. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23990. list.remove (index);
  23991. }
  23992. }
  23993. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23994. double timeAdjustment,
  23995. double firstAllowableTime,
  23996. double endOfAllowableDestTimes)
  23997. {
  23998. firstAllowableTime -= timeAdjustment;
  23999. endOfAllowableDestTimes -= timeAdjustment;
  24000. for (int i = 0; i < other.list.size(); ++i)
  24001. {
  24002. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24003. const double t = m.getTimeStamp();
  24004. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24005. {
  24006. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24007. newOne->message.setTimeStamp (timeAdjustment + t);
  24008. list.add (newOne);
  24009. }
  24010. }
  24011. sort();
  24012. }
  24013. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24014. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24015. {
  24016. const double diff = first->message.getTimeStamp()
  24017. - second->message.getTimeStamp();
  24018. return (diff > 0) - (diff < 0);
  24019. }
  24020. void MidiMessageSequence::sort()
  24021. {
  24022. list.sort (*this, true);
  24023. }
  24024. void MidiMessageSequence::updateMatchedPairs()
  24025. {
  24026. for (int i = 0; i < list.size(); ++i)
  24027. {
  24028. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24029. if (m1.isNoteOn())
  24030. {
  24031. list.getUnchecked(i)->noteOffObject = 0;
  24032. const int note = m1.getNoteNumber();
  24033. const int chan = m1.getChannel();
  24034. const int len = list.size();
  24035. for (int j = i + 1; j < len; ++j)
  24036. {
  24037. const MidiMessage& m = list.getUnchecked(j)->message;
  24038. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24039. {
  24040. if (m.isNoteOff())
  24041. {
  24042. list.getUnchecked(i)->noteOffObject = list[j];
  24043. break;
  24044. }
  24045. else if (m.isNoteOn())
  24046. {
  24047. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24048. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24049. list.getUnchecked(i)->noteOffObject = list[j];
  24050. break;
  24051. }
  24052. }
  24053. }
  24054. }
  24055. }
  24056. }
  24057. void MidiMessageSequence::addTimeToMessages (const double delta)
  24058. {
  24059. for (int i = list.size(); --i >= 0;)
  24060. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24061. + delta);
  24062. }
  24063. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24064. MidiMessageSequence& destSequence,
  24065. const bool alsoIncludeMetaEvents) const
  24066. {
  24067. for (int i = 0; i < list.size(); ++i)
  24068. {
  24069. const MidiMessage& mm = list.getUnchecked(i)->message;
  24070. if (mm.isForChannel (channelNumberToExtract)
  24071. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24072. {
  24073. destSequence.addEvent (mm);
  24074. }
  24075. }
  24076. }
  24077. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24078. {
  24079. for (int i = 0; i < list.size(); ++i)
  24080. {
  24081. const MidiMessage& mm = list.getUnchecked(i)->message;
  24082. if (mm.isSysEx())
  24083. destSequence.addEvent (mm);
  24084. }
  24085. }
  24086. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24087. {
  24088. for (int i = list.size(); --i >= 0;)
  24089. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24090. list.remove(i);
  24091. }
  24092. void MidiMessageSequence::deleteSysExMessages()
  24093. {
  24094. for (int i = list.size(); --i >= 0;)
  24095. if (list.getUnchecked(i)->message.isSysEx())
  24096. list.remove(i);
  24097. }
  24098. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24099. const double time,
  24100. OwnedArray<MidiMessage>& dest)
  24101. {
  24102. bool doneProg = false;
  24103. bool donePitchWheel = false;
  24104. Array <int> doneControllers;
  24105. doneControllers.ensureStorageAllocated (32);
  24106. for (int i = list.size(); --i >= 0;)
  24107. {
  24108. const MidiMessage& mm = list.getUnchecked(i)->message;
  24109. if (mm.isForChannel (channelNumber)
  24110. && mm.getTimeStamp() <= time)
  24111. {
  24112. if (mm.isProgramChange())
  24113. {
  24114. if (! doneProg)
  24115. {
  24116. dest.add (new MidiMessage (mm, 0.0));
  24117. doneProg = true;
  24118. }
  24119. }
  24120. else if (mm.isController())
  24121. {
  24122. if (! doneControllers.contains (mm.getControllerNumber()))
  24123. {
  24124. dest.add (new MidiMessage (mm, 0.0));
  24125. doneControllers.add (mm.getControllerNumber());
  24126. }
  24127. }
  24128. else if (mm.isPitchWheel())
  24129. {
  24130. if (! donePitchWheel)
  24131. {
  24132. dest.add (new MidiMessage (mm, 0.0));
  24133. donePitchWheel = true;
  24134. }
  24135. }
  24136. }
  24137. }
  24138. }
  24139. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24140. : message (message_),
  24141. noteOffObject (0)
  24142. {
  24143. }
  24144. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24145. {
  24146. }
  24147. END_JUCE_NAMESPACE
  24148. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24149. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24150. BEGIN_JUCE_NAMESPACE
  24151. AudioPluginFormat::AudioPluginFormat() throw()
  24152. {
  24153. }
  24154. AudioPluginFormat::~AudioPluginFormat()
  24155. {
  24156. }
  24157. END_JUCE_NAMESPACE
  24158. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24159. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24160. BEGIN_JUCE_NAMESPACE
  24161. AudioPluginFormatManager::AudioPluginFormatManager()
  24162. {
  24163. }
  24164. AudioPluginFormatManager::~AudioPluginFormatManager()
  24165. {
  24166. clearSingletonInstance();
  24167. }
  24168. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24169. void AudioPluginFormatManager::addDefaultFormats()
  24170. {
  24171. #if JUCE_DEBUG
  24172. // you should only call this method once!
  24173. for (int i = formats.size(); --i >= 0;)
  24174. {
  24175. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24176. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24177. #endif
  24178. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24179. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24180. #endif
  24181. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24182. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24183. #endif
  24184. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24185. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24186. #endif
  24187. }
  24188. #endif
  24189. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24190. formats.add (new AudioUnitPluginFormat());
  24191. #endif
  24192. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24193. formats.add (new VSTPluginFormat());
  24194. #endif
  24195. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24196. formats.add (new DirectXPluginFormat());
  24197. #endif
  24198. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24199. formats.add (new LADSPAPluginFormat());
  24200. #endif
  24201. }
  24202. int AudioPluginFormatManager::getNumFormats()
  24203. {
  24204. return formats.size();
  24205. }
  24206. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24207. {
  24208. return formats [index];
  24209. }
  24210. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24211. {
  24212. formats.add (format);
  24213. }
  24214. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24215. String& errorMessage) const
  24216. {
  24217. AudioPluginInstance* result = 0;
  24218. for (int i = 0; i < formats.size(); ++i)
  24219. {
  24220. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24221. if (result != 0)
  24222. break;
  24223. }
  24224. if (result == 0)
  24225. {
  24226. if (! doesPluginStillExist (description))
  24227. errorMessage = TRANS ("This plug-in file no longer exists");
  24228. else
  24229. errorMessage = TRANS ("This plug-in failed to load correctly");
  24230. }
  24231. return result;
  24232. }
  24233. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24234. {
  24235. for (int i = 0; i < formats.size(); ++i)
  24236. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24237. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24238. return false;
  24239. }
  24240. END_JUCE_NAMESPACE
  24241. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24242. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24243. #define JUCE_PLUGIN_HOST 1
  24244. BEGIN_JUCE_NAMESPACE
  24245. AudioPluginInstance::AudioPluginInstance()
  24246. {
  24247. }
  24248. AudioPluginInstance::~AudioPluginInstance()
  24249. {
  24250. }
  24251. void* AudioPluginInstance::getPlatformSpecificData()
  24252. {
  24253. return 0;
  24254. }
  24255. END_JUCE_NAMESPACE
  24256. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24257. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24258. BEGIN_JUCE_NAMESPACE
  24259. KnownPluginList::KnownPluginList()
  24260. {
  24261. }
  24262. KnownPluginList::~KnownPluginList()
  24263. {
  24264. }
  24265. void KnownPluginList::clear()
  24266. {
  24267. if (types.size() > 0)
  24268. {
  24269. types.clear();
  24270. sendChangeMessage();
  24271. }
  24272. }
  24273. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24274. {
  24275. for (int i = 0; i < types.size(); ++i)
  24276. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24277. return types.getUnchecked(i);
  24278. return 0;
  24279. }
  24280. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24281. {
  24282. for (int i = 0; i < types.size(); ++i)
  24283. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24284. return types.getUnchecked(i);
  24285. return 0;
  24286. }
  24287. bool KnownPluginList::addType (const PluginDescription& type)
  24288. {
  24289. for (int i = types.size(); --i >= 0;)
  24290. {
  24291. if (types.getUnchecked(i)->isDuplicateOf (type))
  24292. {
  24293. // strange - found a duplicate plugin with different info..
  24294. jassert (types.getUnchecked(i)->name == type.name);
  24295. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24296. *types.getUnchecked(i) = type;
  24297. return false;
  24298. }
  24299. }
  24300. types.add (new PluginDescription (type));
  24301. sendChangeMessage();
  24302. return true;
  24303. }
  24304. void KnownPluginList::removeType (const int index)
  24305. {
  24306. types.remove (index);
  24307. sendChangeMessage();
  24308. }
  24309. namespace
  24310. {
  24311. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24312. {
  24313. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24314. return File (fileOrIdentifier).getLastModificationTime();
  24315. return Time();
  24316. }
  24317. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24318. {
  24319. return t1 != t2 || t1 == Time();
  24320. }
  24321. }
  24322. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24323. {
  24324. if (getTypeForFile (fileOrIdentifier) == 0)
  24325. return false;
  24326. for (int i = types.size(); --i >= 0;)
  24327. {
  24328. const PluginDescription* const d = types.getUnchecked(i);
  24329. if (d->fileOrIdentifier == fileOrIdentifier
  24330. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24331. {
  24332. return false;
  24333. }
  24334. }
  24335. return true;
  24336. }
  24337. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24338. const bool dontRescanIfAlreadyInList,
  24339. OwnedArray <PluginDescription>& typesFound,
  24340. AudioPluginFormat& format)
  24341. {
  24342. bool addedOne = false;
  24343. if (dontRescanIfAlreadyInList
  24344. && getTypeForFile (fileOrIdentifier) != 0)
  24345. {
  24346. bool needsRescanning = false;
  24347. for (int i = types.size(); --i >= 0;)
  24348. {
  24349. const PluginDescription* const d = types.getUnchecked(i);
  24350. if (d->fileOrIdentifier == fileOrIdentifier)
  24351. {
  24352. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24353. needsRescanning = true;
  24354. else
  24355. typesFound.add (new PluginDescription (*d));
  24356. }
  24357. }
  24358. if (! needsRescanning)
  24359. return false;
  24360. }
  24361. OwnedArray <PluginDescription> found;
  24362. format.findAllTypesForFile (found, fileOrIdentifier);
  24363. for (int i = 0; i < found.size(); ++i)
  24364. {
  24365. PluginDescription* const desc = found.getUnchecked(i);
  24366. jassert (desc != 0);
  24367. if (addType (*desc))
  24368. addedOne = true;
  24369. typesFound.add (new PluginDescription (*desc));
  24370. }
  24371. return addedOne;
  24372. }
  24373. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24374. OwnedArray <PluginDescription>& typesFound)
  24375. {
  24376. for (int i = 0; i < files.size(); ++i)
  24377. {
  24378. bool loaded = false;
  24379. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24380. {
  24381. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24382. if (scanAndAddFile (files[i], true, typesFound, *format))
  24383. loaded = true;
  24384. }
  24385. if (! loaded)
  24386. {
  24387. const File f (files[i]);
  24388. if (f.isDirectory())
  24389. {
  24390. StringArray s;
  24391. {
  24392. Array<File> subFiles;
  24393. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24394. for (int j = 0; j < subFiles.size(); ++j)
  24395. s.add (subFiles.getReference(j).getFullPathName());
  24396. }
  24397. scanAndAddDragAndDroppedFiles (s, typesFound);
  24398. }
  24399. }
  24400. }
  24401. }
  24402. class PluginSorter
  24403. {
  24404. public:
  24405. KnownPluginList::SortMethod method;
  24406. PluginSorter() throw() {}
  24407. int compareElements (const PluginDescription* const first,
  24408. const PluginDescription* const second) const
  24409. {
  24410. int diff = 0;
  24411. if (method == KnownPluginList::sortByCategory)
  24412. diff = first->category.compareLexicographically (second->category);
  24413. else if (method == KnownPluginList::sortByManufacturer)
  24414. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24415. else if (method == KnownPluginList::sortByFileSystemLocation)
  24416. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24417. .upToLastOccurrenceOf ("/", false, false)
  24418. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24419. .upToLastOccurrenceOf ("/", false, false));
  24420. if (diff == 0)
  24421. diff = first->name.compareLexicographically (second->name);
  24422. return diff;
  24423. }
  24424. };
  24425. void KnownPluginList::sort (const SortMethod method)
  24426. {
  24427. if (method != defaultOrder)
  24428. {
  24429. PluginSorter sorter;
  24430. sorter.method = method;
  24431. types.sort (sorter, true);
  24432. sendChangeMessage();
  24433. }
  24434. }
  24435. XmlElement* KnownPluginList::createXml() const
  24436. {
  24437. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24438. for (int i = 0; i < types.size(); ++i)
  24439. e->addChildElement (types.getUnchecked(i)->createXml());
  24440. return e;
  24441. }
  24442. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24443. {
  24444. clear();
  24445. if (xml.hasTagName ("KNOWNPLUGINS"))
  24446. {
  24447. forEachXmlChildElement (xml, e)
  24448. {
  24449. PluginDescription info;
  24450. if (info.loadFromXml (*e))
  24451. addType (info);
  24452. }
  24453. }
  24454. }
  24455. const int menuIdBase = 0x324503f4;
  24456. // This is used to turn a bunch of paths into a nested menu structure.
  24457. struct PluginFilesystemTree
  24458. {
  24459. private:
  24460. String folder;
  24461. OwnedArray <PluginFilesystemTree> subFolders;
  24462. Array <PluginDescription*> plugins;
  24463. void addPlugin (PluginDescription* const pd, const String& path)
  24464. {
  24465. if (path.isEmpty())
  24466. {
  24467. plugins.add (pd);
  24468. }
  24469. else
  24470. {
  24471. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24472. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24473. for (int i = subFolders.size(); --i >= 0;)
  24474. {
  24475. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24476. {
  24477. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24478. return;
  24479. }
  24480. }
  24481. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24482. newFolder->folder = firstSubFolder;
  24483. subFolders.add (newFolder);
  24484. newFolder->addPlugin (pd, remainingPath);
  24485. }
  24486. }
  24487. // removes any deeply nested folders that don't contain any actual plugins
  24488. void optimise()
  24489. {
  24490. for (int i = subFolders.size(); --i >= 0;)
  24491. {
  24492. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24493. sub->optimise();
  24494. if (sub->plugins.size() == 0)
  24495. {
  24496. for (int j = 0; j < sub->subFolders.size(); ++j)
  24497. subFolders.add (sub->subFolders.getUnchecked(j));
  24498. sub->subFolders.clear (false);
  24499. subFolders.remove (i);
  24500. }
  24501. }
  24502. }
  24503. public:
  24504. void buildTree (const Array <PluginDescription*>& allPlugins)
  24505. {
  24506. for (int i = 0; i < allPlugins.size(); ++i)
  24507. {
  24508. String path (allPlugins.getUnchecked(i)
  24509. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24510. .upToLastOccurrenceOf ("/", false, false));
  24511. if (path.substring (1, 2) == ":")
  24512. path = path.substring (2);
  24513. addPlugin (allPlugins.getUnchecked(i), path);
  24514. }
  24515. optimise();
  24516. }
  24517. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24518. {
  24519. int i;
  24520. for (i = 0; i < subFolders.size(); ++i)
  24521. {
  24522. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24523. PopupMenu subMenu;
  24524. sub->addToMenu (subMenu, allPlugins);
  24525. #if JUCE_MAC
  24526. // avoid the special AU formatting nonsense on Mac..
  24527. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24528. #else
  24529. m.addSubMenu (sub->folder, subMenu);
  24530. #endif
  24531. }
  24532. for (i = 0; i < plugins.size(); ++i)
  24533. {
  24534. PluginDescription* const plugin = plugins.getUnchecked(i);
  24535. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24536. plugin->name, true, false);
  24537. }
  24538. }
  24539. };
  24540. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24541. {
  24542. Array <PluginDescription*> sorted;
  24543. {
  24544. PluginSorter sorter;
  24545. sorter.method = sortMethod;
  24546. for (int i = 0; i < types.size(); ++i)
  24547. sorted.addSorted (sorter, types.getUnchecked(i));
  24548. }
  24549. if (sortMethod == sortByCategory
  24550. || sortMethod == sortByManufacturer)
  24551. {
  24552. String lastSubMenuName;
  24553. PopupMenu sub;
  24554. for (int i = 0; i < sorted.size(); ++i)
  24555. {
  24556. const PluginDescription* const pd = sorted.getUnchecked(i);
  24557. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24558. : pd->manufacturerName);
  24559. if (! thisSubMenuName.containsNonWhitespaceChars())
  24560. thisSubMenuName = "Other";
  24561. if (thisSubMenuName != lastSubMenuName)
  24562. {
  24563. if (sub.getNumItems() > 0)
  24564. {
  24565. menu.addSubMenu (lastSubMenuName, sub);
  24566. sub.clear();
  24567. }
  24568. lastSubMenuName = thisSubMenuName;
  24569. }
  24570. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24571. }
  24572. if (sub.getNumItems() > 0)
  24573. menu.addSubMenu (lastSubMenuName, sub);
  24574. }
  24575. else if (sortMethod == sortByFileSystemLocation)
  24576. {
  24577. PluginFilesystemTree root;
  24578. root.buildTree (sorted);
  24579. root.addToMenu (menu, types);
  24580. }
  24581. else
  24582. {
  24583. for (int i = 0; i < sorted.size(); ++i)
  24584. {
  24585. const PluginDescription* const pd = sorted.getUnchecked(i);
  24586. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24587. }
  24588. }
  24589. }
  24590. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24591. {
  24592. const int i = menuResultCode - menuIdBase;
  24593. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24594. }
  24595. END_JUCE_NAMESPACE
  24596. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24597. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24598. BEGIN_JUCE_NAMESPACE
  24599. PluginDescription::PluginDescription()
  24600. : uid (0),
  24601. isInstrument (false),
  24602. numInputChannels (0),
  24603. numOutputChannels (0)
  24604. {
  24605. }
  24606. PluginDescription::~PluginDescription()
  24607. {
  24608. }
  24609. PluginDescription::PluginDescription (const PluginDescription& other)
  24610. : name (other.name),
  24611. descriptiveName (other.descriptiveName),
  24612. pluginFormatName (other.pluginFormatName),
  24613. category (other.category),
  24614. manufacturerName (other.manufacturerName),
  24615. version (other.version),
  24616. fileOrIdentifier (other.fileOrIdentifier),
  24617. lastFileModTime (other.lastFileModTime),
  24618. uid (other.uid),
  24619. isInstrument (other.isInstrument),
  24620. numInputChannels (other.numInputChannels),
  24621. numOutputChannels (other.numOutputChannels)
  24622. {
  24623. }
  24624. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24625. {
  24626. name = other.name;
  24627. descriptiveName = other.descriptiveName;
  24628. pluginFormatName = other.pluginFormatName;
  24629. category = other.category;
  24630. manufacturerName = other.manufacturerName;
  24631. version = other.version;
  24632. fileOrIdentifier = other.fileOrIdentifier;
  24633. uid = other.uid;
  24634. isInstrument = other.isInstrument;
  24635. lastFileModTime = other.lastFileModTime;
  24636. numInputChannels = other.numInputChannels;
  24637. numOutputChannels = other.numOutputChannels;
  24638. return *this;
  24639. }
  24640. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24641. {
  24642. return fileOrIdentifier == other.fileOrIdentifier
  24643. && uid == other.uid;
  24644. }
  24645. const String PluginDescription::createIdentifierString() const
  24646. {
  24647. return pluginFormatName
  24648. + "-" + name
  24649. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24650. + "-" + String::toHexString (uid);
  24651. }
  24652. XmlElement* PluginDescription::createXml() const
  24653. {
  24654. XmlElement* const e = new XmlElement ("PLUGIN");
  24655. e->setAttribute ("name", name);
  24656. if (descriptiveName != name)
  24657. e->setAttribute ("descriptiveName", descriptiveName);
  24658. e->setAttribute ("format", pluginFormatName);
  24659. e->setAttribute ("category", category);
  24660. e->setAttribute ("manufacturer", manufacturerName);
  24661. e->setAttribute ("version", version);
  24662. e->setAttribute ("file", fileOrIdentifier);
  24663. e->setAttribute ("uid", String::toHexString (uid));
  24664. e->setAttribute ("isInstrument", isInstrument);
  24665. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24666. e->setAttribute ("numInputs", numInputChannels);
  24667. e->setAttribute ("numOutputs", numOutputChannels);
  24668. return e;
  24669. }
  24670. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24671. {
  24672. if (xml.hasTagName ("PLUGIN"))
  24673. {
  24674. name = xml.getStringAttribute ("name");
  24675. descriptiveName = xml.getStringAttribute ("name", name);
  24676. pluginFormatName = xml.getStringAttribute ("format");
  24677. category = xml.getStringAttribute ("category");
  24678. manufacturerName = xml.getStringAttribute ("manufacturer");
  24679. version = xml.getStringAttribute ("version");
  24680. fileOrIdentifier = xml.getStringAttribute ("file");
  24681. uid = xml.getStringAttribute ("uid").getHexValue32();
  24682. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24683. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24684. numInputChannels = xml.getIntAttribute ("numInputs");
  24685. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24686. return true;
  24687. }
  24688. return false;
  24689. }
  24690. END_JUCE_NAMESPACE
  24691. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24692. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24693. BEGIN_JUCE_NAMESPACE
  24694. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24695. AudioPluginFormat& formatToLookFor,
  24696. FileSearchPath directoriesToSearch,
  24697. const bool recursive,
  24698. const File& deadMansPedalFile_)
  24699. : list (listToAddTo),
  24700. format (formatToLookFor),
  24701. deadMansPedalFile (deadMansPedalFile_),
  24702. nextIndex (0),
  24703. progress (0)
  24704. {
  24705. directoriesToSearch.removeRedundantPaths();
  24706. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24707. // If any plugins have crashed recently when being loaded, move them to the
  24708. // end of the list to give the others a chance to load correctly..
  24709. const StringArray crashedPlugins (getDeadMansPedalFile());
  24710. for (int i = 0; i < crashedPlugins.size(); ++i)
  24711. {
  24712. const String f = crashedPlugins[i];
  24713. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24714. if (f == filesOrIdentifiersToScan[j])
  24715. filesOrIdentifiersToScan.move (j, -1);
  24716. }
  24717. }
  24718. PluginDirectoryScanner::~PluginDirectoryScanner()
  24719. {
  24720. }
  24721. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24722. {
  24723. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24724. }
  24725. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24726. {
  24727. String file (filesOrIdentifiersToScan [nextIndex]);
  24728. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24729. {
  24730. OwnedArray <PluginDescription> typesFound;
  24731. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24732. StringArray crashedPlugins (getDeadMansPedalFile());
  24733. crashedPlugins.removeString (file);
  24734. crashedPlugins.add (file);
  24735. setDeadMansPedalFile (crashedPlugins);
  24736. list.scanAndAddFile (file,
  24737. dontRescanIfAlreadyInList,
  24738. typesFound,
  24739. format);
  24740. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24741. crashedPlugins.removeString (file);
  24742. setDeadMansPedalFile (crashedPlugins);
  24743. if (typesFound.size() == 0)
  24744. failedFiles.add (file);
  24745. }
  24746. return skipNextFile();
  24747. }
  24748. bool PluginDirectoryScanner::skipNextFile()
  24749. {
  24750. if (nextIndex >= filesOrIdentifiersToScan.size())
  24751. return false;
  24752. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24753. return nextIndex < filesOrIdentifiersToScan.size();
  24754. }
  24755. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24756. {
  24757. StringArray lines;
  24758. if (deadMansPedalFile != File::nonexistent)
  24759. {
  24760. lines.addLines (deadMansPedalFile.loadFileAsString());
  24761. lines.removeEmptyStrings();
  24762. }
  24763. return lines;
  24764. }
  24765. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24766. {
  24767. if (deadMansPedalFile != File::nonexistent)
  24768. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24769. }
  24770. END_JUCE_NAMESPACE
  24771. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24772. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24773. BEGIN_JUCE_NAMESPACE
  24774. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24775. const File& deadMansPedalFile_,
  24776. PropertiesFile* const propertiesToUse_)
  24777. : list (listToEdit),
  24778. deadMansPedalFile (deadMansPedalFile_),
  24779. optionsButton ("Options..."),
  24780. propertiesToUse (propertiesToUse_)
  24781. {
  24782. listBox.setModel (this);
  24783. addAndMakeVisible (&listBox);
  24784. addAndMakeVisible (&optionsButton);
  24785. optionsButton.addListener (this);
  24786. optionsButton.setTriggeredOnMouseDown (true);
  24787. setSize (400, 600);
  24788. list.addChangeListener (this);
  24789. changeListenerCallback (0);
  24790. }
  24791. PluginListComponent::~PluginListComponent()
  24792. {
  24793. list.removeChangeListener (this);
  24794. }
  24795. void PluginListComponent::resized()
  24796. {
  24797. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24798. optionsButton.changeWidthToFitText (24);
  24799. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24800. }
  24801. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24802. {
  24803. listBox.updateContent();
  24804. listBox.repaint();
  24805. }
  24806. int PluginListComponent::getNumRows()
  24807. {
  24808. return list.getNumTypes();
  24809. }
  24810. void PluginListComponent::paintListBoxItem (int row,
  24811. Graphics& g,
  24812. int width, int height,
  24813. bool rowIsSelected)
  24814. {
  24815. if (rowIsSelected)
  24816. g.fillAll (findColour (TextEditor::highlightColourId));
  24817. const PluginDescription* const pd = list.getType (row);
  24818. if (pd != 0)
  24819. {
  24820. GlyphArrangement ga;
  24821. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24822. g.setColour (Colours::black);
  24823. ga.draw (g);
  24824. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24825. String desc;
  24826. desc << pd->pluginFormatName
  24827. << (pd->isInstrument ? " instrument" : " effect")
  24828. << " - "
  24829. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24830. << " / "
  24831. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24832. if (pd->manufacturerName.isNotEmpty())
  24833. desc << " - " << pd->manufacturerName;
  24834. if (pd->version.isNotEmpty())
  24835. desc << " - " << pd->version;
  24836. if (pd->category.isNotEmpty())
  24837. desc << " - category: '" << pd->category << '\'';
  24838. g.setColour (Colours::grey);
  24839. ga.clear();
  24840. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24841. ga.draw (g);
  24842. }
  24843. }
  24844. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24845. {
  24846. list.removeType (lastRowSelected);
  24847. }
  24848. void PluginListComponent::optionsMenuCallback (int result)
  24849. {
  24850. switch (result)
  24851. {
  24852. case 1:
  24853. list.clear();
  24854. break;
  24855. case 2:
  24856. list.sort (KnownPluginList::sortAlphabetically);
  24857. break;
  24858. case 3:
  24859. list.sort (KnownPluginList::sortByCategory);
  24860. break;
  24861. case 4:
  24862. list.sort (KnownPluginList::sortByManufacturer);
  24863. break;
  24864. case 5:
  24865. {
  24866. const SparseSet <int> selected (listBox.getSelectedRows());
  24867. for (int i = list.getNumTypes(); --i >= 0;)
  24868. if (selected.contains (i))
  24869. list.removeType (i);
  24870. break;
  24871. }
  24872. case 6:
  24873. {
  24874. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  24875. if (desc != 0)
  24876. {
  24877. if (File (desc->fileOrIdentifier).existsAsFile())
  24878. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24879. }
  24880. break;
  24881. }
  24882. case 7:
  24883. for (int i = list.getNumTypes(); --i >= 0;)
  24884. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24885. list.removeType (i);
  24886. break;
  24887. default:
  24888. if (result != 0)
  24889. {
  24890. typeToScan = result - 10;
  24891. startTimer (1);
  24892. }
  24893. break;
  24894. }
  24895. }
  24896. void PluginListComponent::optionsMenuStaticCallback (int result, PluginListComponent* pluginList)
  24897. {
  24898. if (pluginList != 0)
  24899. pluginList->optionsMenuCallback (result);
  24900. }
  24901. void PluginListComponent::buttonClicked (Button* button)
  24902. {
  24903. if (button == &optionsButton)
  24904. {
  24905. PopupMenu menu;
  24906. menu.addItem (1, TRANS("Clear list"));
  24907. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24908. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24909. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24910. menu.addSeparator();
  24911. menu.addItem (2, TRANS("Sort alphabetically"));
  24912. menu.addItem (3, TRANS("Sort by category"));
  24913. menu.addItem (4, TRANS("Sort by manufacturer"));
  24914. menu.addSeparator();
  24915. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24916. {
  24917. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24918. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24919. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24920. }
  24921. menu.showMenuAsync (PopupMenu::Options().withTargetComponent (&optionsButton),
  24922. ModalCallbackFunction::forComponent (optionsMenuStaticCallback, this));
  24923. }
  24924. }
  24925. void PluginListComponent::timerCallback()
  24926. {
  24927. stopTimer();
  24928. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24929. }
  24930. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24931. {
  24932. return true;
  24933. }
  24934. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24935. {
  24936. OwnedArray <PluginDescription> typesFound;
  24937. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24938. }
  24939. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24940. {
  24941. #if JUCE_MODAL_LOOPS_PERMITTED
  24942. if (format == 0)
  24943. return;
  24944. FileSearchPath path (format->getDefaultLocationsToSearch());
  24945. if (propertiesToUse != 0)
  24946. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24947. {
  24948. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24949. FileSearchPathListComponent pathList;
  24950. pathList.setSize (500, 300);
  24951. pathList.setPath (path);
  24952. aw.addCustomComponent (&pathList);
  24953. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24954. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24955. if (aw.runModalLoop() == 0)
  24956. return;
  24957. path = pathList.getPath();
  24958. }
  24959. if (propertiesToUse != 0)
  24960. {
  24961. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24962. propertiesToUse->saveIfNeeded();
  24963. }
  24964. double progress = 0.0;
  24965. AlertWindow aw (TRANS("Scanning for plugins..."),
  24966. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24967. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24968. aw.addProgressBarComponent (progress);
  24969. aw.enterModalState();
  24970. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24971. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24972. for (;;)
  24973. {
  24974. aw.setMessage (TRANS("Testing:\n\n")
  24975. + scanner.getNextPluginFileThatWillBeScanned());
  24976. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24977. if (! scanner.scanNextFile (true))
  24978. break;
  24979. if (! aw.isCurrentlyModal())
  24980. break;
  24981. progress = scanner.getProgress();
  24982. }
  24983. if (scanner.getFailedFiles().size() > 0)
  24984. {
  24985. StringArray shortNames;
  24986. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24987. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24988. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24989. TRANS("Scan complete"),
  24990. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24991. + shortNames.joinIntoString (", "));
  24992. }
  24993. #else
  24994. jassertfalse; // this method needs refactoring to work without modal loops..
  24995. #endif
  24996. }
  24997. END_JUCE_NAMESPACE
  24998. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24999. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25000. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25001. #include <AudioUnit/AudioUnit.h>
  25002. #include <AudioUnit/AUCocoaUIView.h>
  25003. #include <CoreAudioKit/AUGenericView.h>
  25004. #if JUCE_SUPPORT_CARBON
  25005. #include <AudioToolbox/AudioUnitUtilities.h>
  25006. #include <AudioUnit/AudioUnitCarbonView.h>
  25007. #endif
  25008. BEGIN_JUCE_NAMESPACE
  25009. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25010. #endif
  25011. #if JUCE_MAC
  25012. // Change this to disable logging of various activities
  25013. #ifndef AU_LOGGING
  25014. #define AU_LOGGING 1
  25015. #endif
  25016. #if AU_LOGGING
  25017. #define log(a) Logger::writeToLog(a);
  25018. #else
  25019. #define log(a)
  25020. #endif
  25021. namespace AudioUnitFormatHelpers
  25022. {
  25023. static int insideCallback = 0;
  25024. const String osTypeToString (OSType type)
  25025. {
  25026. char s[4];
  25027. s[0] = (char) (((uint32) type) >> 24);
  25028. s[1] = (char) (((uint32) type) >> 16);
  25029. s[2] = (char) (((uint32) type) >> 8);
  25030. s[3] = (char) ((uint32) type);
  25031. return String (s, 4);
  25032. }
  25033. OSType stringToOSType (const String& s1)
  25034. {
  25035. const String s (s1 + " ");
  25036. return (((OSType) (unsigned char) s[0]) << 24)
  25037. | (((OSType) (unsigned char) s[1]) << 16)
  25038. | (((OSType) (unsigned char) s[2]) << 8)
  25039. | ((OSType) (unsigned char) s[3]);
  25040. }
  25041. static const char* auIdentifierPrefix = "AudioUnit:";
  25042. const String createAUPluginIdentifier (const ComponentDescription& desc)
  25043. {
  25044. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25045. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25046. String s (auIdentifierPrefix);
  25047. if (desc.componentType == kAudioUnitType_MusicDevice)
  25048. s << "Synths/";
  25049. else if (desc.componentType == kAudioUnitType_MusicEffect
  25050. || desc.componentType == kAudioUnitType_Effect)
  25051. s << "Effects/";
  25052. else if (desc.componentType == kAudioUnitType_Generator)
  25053. s << "Generators/";
  25054. else if (desc.componentType == kAudioUnitType_Panner)
  25055. s << "Panners/";
  25056. s << osTypeToString (desc.componentType) << ","
  25057. << osTypeToString (desc.componentSubType) << ","
  25058. << osTypeToString (desc.componentManufacturer);
  25059. return s;
  25060. }
  25061. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25062. {
  25063. Handle componentNameHandle = NewHandle (sizeof (void*));
  25064. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25065. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25066. {
  25067. ComponentDescription desc;
  25068. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25069. {
  25070. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25071. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25072. if (nameString != 0 && nameString[0] != 0)
  25073. {
  25074. const String all ((const char*) nameString + 1, nameString[0]);
  25075. DBG ("name: "+ all);
  25076. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25077. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25078. }
  25079. if (infoString != 0 && infoString[0] != 0)
  25080. {
  25081. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25082. }
  25083. if (name.isEmpty())
  25084. name = "<Unknown>";
  25085. }
  25086. DisposeHandle (componentNameHandle);
  25087. DisposeHandle (componentInfoHandle);
  25088. }
  25089. }
  25090. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25091. String& name, String& version, String& manufacturer)
  25092. {
  25093. zerostruct (desc);
  25094. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25095. {
  25096. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25097. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25098. StringArray tokens;
  25099. tokens.addTokens (s, ",", String::empty);
  25100. tokens.trim();
  25101. tokens.removeEmptyStrings();
  25102. if (tokens.size() == 3)
  25103. {
  25104. desc.componentType = stringToOSType (tokens[0]);
  25105. desc.componentSubType = stringToOSType (tokens[1]);
  25106. desc.componentManufacturer = stringToOSType (tokens[2]);
  25107. ComponentRecord* comp = FindNextComponent (0, &desc);
  25108. if (comp != 0)
  25109. {
  25110. getAUDetails (comp, name, manufacturer);
  25111. return true;
  25112. }
  25113. }
  25114. }
  25115. return false;
  25116. }
  25117. }
  25118. class AudioUnitPluginWindowCarbon;
  25119. class AudioUnitPluginWindowCocoa;
  25120. class AudioUnitPluginInstance : public AudioPluginInstance
  25121. {
  25122. public:
  25123. ~AudioUnitPluginInstance();
  25124. void initialise();
  25125. // AudioPluginInstance methods:
  25126. void fillInPluginDescription (PluginDescription& desc) const
  25127. {
  25128. desc.name = pluginName;
  25129. desc.descriptiveName = pluginName;
  25130. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25131. desc.uid = ((int) componentDesc.componentType)
  25132. ^ ((int) componentDesc.componentSubType)
  25133. ^ ((int) componentDesc.componentManufacturer);
  25134. desc.lastFileModTime = Time();
  25135. desc.pluginFormatName = "AudioUnit";
  25136. desc.category = getCategory();
  25137. desc.manufacturerName = manufacturer;
  25138. desc.version = version;
  25139. desc.numInputChannels = getNumInputChannels();
  25140. desc.numOutputChannels = getNumOutputChannels();
  25141. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25142. }
  25143. void* getPlatformSpecificData() { return audioUnit; }
  25144. const String getName() const { return pluginName; }
  25145. bool acceptsMidi() const { return wantsMidiMessages; }
  25146. bool producesMidi() const { return false; }
  25147. // AudioProcessor methods:
  25148. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25149. void releaseResources();
  25150. void processBlock (AudioSampleBuffer& buffer,
  25151. MidiBuffer& midiMessages);
  25152. bool hasEditor() const;
  25153. AudioProcessorEditor* createEditor();
  25154. const String getInputChannelName (int index) const;
  25155. bool isInputChannelStereoPair (int index) const;
  25156. const String getOutputChannelName (int index) const;
  25157. bool isOutputChannelStereoPair (int index) const;
  25158. int getNumParameters();
  25159. float getParameter (int index);
  25160. void setParameter (int index, float newValue);
  25161. const String getParameterName (int index);
  25162. const String getParameterText (int index);
  25163. bool isParameterAutomatable (int index) const;
  25164. int getNumPrograms();
  25165. int getCurrentProgram();
  25166. void setCurrentProgram (int index);
  25167. const String getProgramName (int index);
  25168. void changeProgramName (int index, const String& newName);
  25169. void getStateInformation (MemoryBlock& destData);
  25170. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25171. void setStateInformation (const void* data, int sizeInBytes);
  25172. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25173. void refreshParameterListFromPlugin();
  25174. private:
  25175. friend class AudioUnitPluginWindowCarbon;
  25176. friend class AudioUnitPluginWindowCocoa;
  25177. friend class AudioUnitPluginFormat;
  25178. ComponentDescription componentDesc;
  25179. String pluginName, manufacturer, version;
  25180. String fileOrIdentifier;
  25181. CriticalSection lock;
  25182. bool wantsMidiMessages, wasPlaying, prepared;
  25183. HeapBlock <AudioBufferList> outputBufferList;
  25184. AudioTimeStamp timeStamp;
  25185. AudioSampleBuffer* currentBuffer;
  25186. AudioUnit audioUnit;
  25187. Array <int> parameterIds;
  25188. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25189. void setPluginCallbacks();
  25190. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25191. const AudioTimeStamp* inTimeStamp,
  25192. UInt32 inBusNumber,
  25193. UInt32 inNumberFrames,
  25194. AudioBufferList* ioData) const;
  25195. static OSStatus renderGetInputCallback (void* inRefCon,
  25196. AudioUnitRenderActionFlags* ioActionFlags,
  25197. const AudioTimeStamp* inTimeStamp,
  25198. UInt32 inBusNumber,
  25199. UInt32 inNumberFrames,
  25200. AudioBufferList* ioData)
  25201. {
  25202. return ((AudioUnitPluginInstance*) inRefCon)
  25203. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25204. }
  25205. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25206. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25207. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25208. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25209. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25210. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25211. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25212. {
  25213. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25214. }
  25215. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25216. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25217. Float64* outCurrentMeasureDownBeat)
  25218. {
  25219. return ((AudioUnitPluginInstance*) inHostUserData)
  25220. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25221. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25222. }
  25223. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25224. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25225. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25226. {
  25227. return ((AudioUnitPluginInstance*) inHostUserData)
  25228. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25229. outCurrentSampleInTimeLine, outIsCycling,
  25230. outCycleStartBeat, outCycleEndBeat);
  25231. }
  25232. void getNumChannels (int& numIns, int& numOuts)
  25233. {
  25234. numIns = 0;
  25235. numOuts = 0;
  25236. AUChannelInfo supportedChannels [128];
  25237. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25238. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25239. 0, supportedChannels, &supportedChannelsSize) == noErr
  25240. && supportedChannelsSize > 0)
  25241. {
  25242. int explicitNumIns = 0;
  25243. int explicitNumOuts = 0;
  25244. int maximumNumIns = 0;
  25245. int maximumNumOuts = 0;
  25246. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25247. {
  25248. const int inChannels = (int) supportedChannels[i].inChannels;
  25249. const int outChannels = (int) supportedChannels[i].outChannels;
  25250. if (inChannels < 0)
  25251. maximumNumIns = jmin (maximumNumIns, inChannels);
  25252. else
  25253. explicitNumIns = jmax (explicitNumIns, inChannels);
  25254. if (outChannels < 0)
  25255. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25256. else
  25257. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25258. }
  25259. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25260. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25261. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25262. {
  25263. numIns = numOuts = 2;
  25264. }
  25265. else
  25266. {
  25267. numIns = explicitNumIns;
  25268. numOuts = explicitNumOuts;
  25269. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25270. numIns = 2;
  25271. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25272. numOuts = 2;
  25273. }
  25274. }
  25275. else
  25276. {
  25277. // (this really means the plugin will take any number of ins/outs as long
  25278. // as they are the same)
  25279. numIns = numOuts = 2;
  25280. }
  25281. }
  25282. const String getCategory() const;
  25283. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25284. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25285. };
  25286. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25287. : fileOrIdentifier (fileOrIdentifier),
  25288. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25289. currentBuffer (0),
  25290. audioUnit (0)
  25291. {
  25292. using namespace AudioUnitFormatHelpers;
  25293. try
  25294. {
  25295. ++insideCallback;
  25296. log ("Opening AU: " + fileOrIdentifier);
  25297. if (getComponentDescFromFile (fileOrIdentifier))
  25298. {
  25299. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25300. if (comp != 0)
  25301. {
  25302. audioUnit = (AudioUnit) OpenComponent (comp);
  25303. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25304. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25305. }
  25306. }
  25307. --insideCallback;
  25308. }
  25309. catch (...)
  25310. {
  25311. --insideCallback;
  25312. }
  25313. }
  25314. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25315. {
  25316. const ScopedLock sl (lock);
  25317. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25318. if (audioUnit != 0)
  25319. {
  25320. AudioUnitUninitialize (audioUnit);
  25321. CloseComponent (audioUnit);
  25322. audioUnit = 0;
  25323. }
  25324. }
  25325. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25326. {
  25327. zerostruct (componentDesc);
  25328. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25329. return true;
  25330. const File file (fileOrIdentifier);
  25331. if (! file.hasFileExtension (".component"))
  25332. return false;
  25333. const char* const utf8 = fileOrIdentifier.toUTF8();
  25334. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25335. strlen (utf8), file.isDirectory());
  25336. if (url != 0)
  25337. {
  25338. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25339. CFRelease (url);
  25340. if (bundleRef != 0)
  25341. {
  25342. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25343. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25344. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25345. if (pluginName.isEmpty())
  25346. pluginName = file.getFileNameWithoutExtension();
  25347. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25348. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25349. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25350. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25351. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25352. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25353. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25354. UseResFile (resFileId);
  25355. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25356. {
  25357. Handle h = Get1IndResource ('thng', i);
  25358. if (h != 0)
  25359. {
  25360. HLock (h);
  25361. const uint32* const types = (const uint32*) *h;
  25362. if (types[0] == kAudioUnitType_MusicDevice
  25363. || types[0] == kAudioUnitType_MusicEffect
  25364. || types[0] == kAudioUnitType_Effect
  25365. || types[0] == kAudioUnitType_Generator
  25366. || types[0] == kAudioUnitType_Panner)
  25367. {
  25368. componentDesc.componentType = types[0];
  25369. componentDesc.componentSubType = types[1];
  25370. componentDesc.componentManufacturer = types[2];
  25371. break;
  25372. }
  25373. HUnlock (h);
  25374. ReleaseResource (h);
  25375. }
  25376. }
  25377. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25378. CFRelease (bundleRef);
  25379. }
  25380. }
  25381. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25382. }
  25383. void AudioUnitPluginInstance::initialise()
  25384. {
  25385. refreshParameterListFromPlugin();
  25386. setPluginCallbacks();
  25387. int numIns, numOuts;
  25388. getNumChannels (numIns, numOuts);
  25389. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25390. setLatencySamples (0);
  25391. }
  25392. void AudioUnitPluginInstance::refreshParameterListFromPlugin()
  25393. {
  25394. parameterIds.clear();
  25395. if (audioUnit != 0)
  25396. {
  25397. UInt32 paramListSize = 0;
  25398. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25399. 0, 0, &paramListSize);
  25400. if (paramListSize > 0)
  25401. {
  25402. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25403. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25404. 0, parameterIds.getRawDataPointer(), &paramListSize);
  25405. }
  25406. }
  25407. }
  25408. void AudioUnitPluginInstance::setPluginCallbacks()
  25409. {
  25410. if (audioUnit != 0)
  25411. {
  25412. {
  25413. AURenderCallbackStruct info;
  25414. zerostruct (info);
  25415. info.inputProcRefCon = this;
  25416. info.inputProc = renderGetInputCallback;
  25417. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25418. 0, &info, sizeof (info));
  25419. }
  25420. {
  25421. HostCallbackInfo info;
  25422. zerostruct (info);
  25423. info.hostUserData = this;
  25424. info.beatAndTempoProc = getBeatAndTempoCallback;
  25425. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25426. info.transportStateProc = getTransportStateCallback;
  25427. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25428. 0, &info, sizeof (info));
  25429. }
  25430. }
  25431. }
  25432. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25433. int samplesPerBlockExpected)
  25434. {
  25435. if (audioUnit != 0)
  25436. {
  25437. releaseResources();
  25438. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25439. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25440. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25441. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25442. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25443. {
  25444. Float64 sr = sampleRate_;
  25445. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25446. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25447. }
  25448. int numIns, numOuts;
  25449. getNumChannels (numIns, numOuts);
  25450. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25451. Float64 latencySecs = 0.0;
  25452. UInt32 latencySize = sizeof (latencySecs);
  25453. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25454. 0, &latencySecs, &latencySize);
  25455. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25456. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25457. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25458. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25459. {
  25460. AudioStreamBasicDescription stream;
  25461. zerostruct (stream);
  25462. stream.mSampleRate = sampleRate_;
  25463. stream.mFormatID = kAudioFormatLinearPCM;
  25464. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25465. stream.mFramesPerPacket = 1;
  25466. stream.mBytesPerPacket = 4;
  25467. stream.mBytesPerFrame = 4;
  25468. stream.mBitsPerChannel = 32;
  25469. stream.mChannelsPerFrame = numIns;
  25470. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25471. 0, &stream, sizeof (stream));
  25472. stream.mChannelsPerFrame = numOuts;
  25473. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25474. 0, &stream, sizeof (stream));
  25475. }
  25476. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25477. outputBufferList->mNumberBuffers = numOuts;
  25478. for (int i = numOuts; --i >= 0;)
  25479. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25480. zerostruct (timeStamp);
  25481. timeStamp.mSampleTime = 0;
  25482. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25483. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25484. currentBuffer = 0;
  25485. wasPlaying = false;
  25486. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25487. }
  25488. }
  25489. void AudioUnitPluginInstance::releaseResources()
  25490. {
  25491. if (prepared)
  25492. {
  25493. AudioUnitUninitialize (audioUnit);
  25494. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25495. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25496. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25497. outputBufferList.free();
  25498. currentBuffer = 0;
  25499. prepared = false;
  25500. }
  25501. }
  25502. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25503. const AudioTimeStamp* inTimeStamp,
  25504. UInt32 inBusNumber,
  25505. UInt32 inNumberFrames,
  25506. AudioBufferList* ioData) const
  25507. {
  25508. if (inBusNumber == 0
  25509. && currentBuffer != 0)
  25510. {
  25511. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25512. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25513. {
  25514. if (i < currentBuffer->getNumChannels())
  25515. {
  25516. memcpy (ioData->mBuffers[i].mData,
  25517. currentBuffer->getSampleData (i, 0),
  25518. sizeof (float) * inNumberFrames);
  25519. }
  25520. else
  25521. {
  25522. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25523. }
  25524. }
  25525. }
  25526. return noErr;
  25527. }
  25528. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25529. MidiBuffer& midiMessages)
  25530. {
  25531. const int numSamples = buffer.getNumSamples();
  25532. if (prepared)
  25533. {
  25534. AudioUnitRenderActionFlags flags = 0;
  25535. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25536. for (int i = getNumOutputChannels(); --i >= 0;)
  25537. {
  25538. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25539. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25540. }
  25541. currentBuffer = &buffer;
  25542. if (wantsMidiMessages)
  25543. {
  25544. const uint8* midiEventData;
  25545. int midiEventSize, midiEventPosition;
  25546. MidiBuffer::Iterator i (midiMessages);
  25547. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25548. {
  25549. if (midiEventSize <= 3)
  25550. MusicDeviceMIDIEvent (audioUnit,
  25551. midiEventData[0], midiEventData[1], midiEventData[2],
  25552. midiEventPosition);
  25553. else
  25554. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25555. }
  25556. midiMessages.clear();
  25557. }
  25558. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25559. 0, numSamples, outputBufferList);
  25560. timeStamp.mSampleTime += numSamples;
  25561. }
  25562. else
  25563. {
  25564. // Plugin not working correctly, so just bypass..
  25565. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25566. buffer.clear (i, 0, buffer.getNumSamples());
  25567. }
  25568. }
  25569. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25570. {
  25571. AudioPlayHead* const ph = getPlayHead();
  25572. AudioPlayHead::CurrentPositionInfo result;
  25573. if (ph != 0 && ph->getCurrentPosition (result))
  25574. {
  25575. if (outCurrentBeat != 0)
  25576. *outCurrentBeat = result.ppqPosition;
  25577. if (outCurrentTempo != 0)
  25578. *outCurrentTempo = result.bpm;
  25579. }
  25580. else
  25581. {
  25582. if (outCurrentBeat != 0)
  25583. *outCurrentBeat = 0;
  25584. if (outCurrentTempo != 0)
  25585. *outCurrentTempo = 120.0;
  25586. }
  25587. return noErr;
  25588. }
  25589. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25590. Float32* outTimeSig_Numerator,
  25591. UInt32* outTimeSig_Denominator,
  25592. Float64* outCurrentMeasureDownBeat) const
  25593. {
  25594. AudioPlayHead* const ph = getPlayHead();
  25595. AudioPlayHead::CurrentPositionInfo result;
  25596. if (ph != 0 && ph->getCurrentPosition (result))
  25597. {
  25598. if (outTimeSig_Numerator != 0)
  25599. *outTimeSig_Numerator = result.timeSigNumerator;
  25600. if (outTimeSig_Denominator != 0)
  25601. *outTimeSig_Denominator = result.timeSigDenominator;
  25602. if (outDeltaSampleOffsetToNextBeat != 0)
  25603. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25604. if (outCurrentMeasureDownBeat != 0)
  25605. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25606. }
  25607. else
  25608. {
  25609. if (outDeltaSampleOffsetToNextBeat != 0)
  25610. *outDeltaSampleOffsetToNextBeat = 0;
  25611. if (outTimeSig_Numerator != 0)
  25612. *outTimeSig_Numerator = 4;
  25613. if (outTimeSig_Denominator != 0)
  25614. *outTimeSig_Denominator = 4;
  25615. if (outCurrentMeasureDownBeat != 0)
  25616. *outCurrentMeasureDownBeat = 0;
  25617. }
  25618. return noErr;
  25619. }
  25620. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25621. Boolean* outTransportStateChanged,
  25622. Float64* outCurrentSampleInTimeLine,
  25623. Boolean* outIsCycling,
  25624. Float64* outCycleStartBeat,
  25625. Float64* outCycleEndBeat)
  25626. {
  25627. AudioPlayHead* const ph = getPlayHead();
  25628. AudioPlayHead::CurrentPositionInfo result;
  25629. if (ph != 0 && ph->getCurrentPosition (result))
  25630. {
  25631. if (outIsPlaying != 0)
  25632. *outIsPlaying = result.isPlaying;
  25633. if (outTransportStateChanged != 0)
  25634. {
  25635. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25636. wasPlaying = result.isPlaying;
  25637. }
  25638. if (outCurrentSampleInTimeLine != 0)
  25639. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25640. if (outIsCycling != 0)
  25641. *outIsCycling = false;
  25642. if (outCycleStartBeat != 0)
  25643. *outCycleStartBeat = 0;
  25644. if (outCycleEndBeat != 0)
  25645. *outCycleEndBeat = 0;
  25646. }
  25647. else
  25648. {
  25649. if (outIsPlaying != 0)
  25650. *outIsPlaying = false;
  25651. if (outTransportStateChanged != 0)
  25652. *outTransportStateChanged = false;
  25653. if (outCurrentSampleInTimeLine != 0)
  25654. *outCurrentSampleInTimeLine = 0;
  25655. if (outIsCycling != 0)
  25656. *outIsCycling = false;
  25657. if (outCycleStartBeat != 0)
  25658. *outCycleStartBeat = 0;
  25659. if (outCycleEndBeat != 0)
  25660. *outCycleEndBeat = 0;
  25661. }
  25662. return noErr;
  25663. }
  25664. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25665. public Timer
  25666. {
  25667. public:
  25668. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25669. : AudioProcessorEditor (&plugin_),
  25670. plugin (plugin_)
  25671. {
  25672. addAndMakeVisible (&wrapper);
  25673. setOpaque (true);
  25674. setVisible (true);
  25675. setSize (100, 100);
  25676. createView (createGenericViewIfNeeded);
  25677. }
  25678. ~AudioUnitPluginWindowCocoa()
  25679. {
  25680. const bool wasValid = isValid();
  25681. wrapper.setView (0);
  25682. if (wasValid)
  25683. plugin.editorBeingDeleted (this);
  25684. }
  25685. bool isValid() const { return wrapper.getView() != 0; }
  25686. void paint (Graphics& g)
  25687. {
  25688. g.fillAll (Colours::white);
  25689. }
  25690. void resized()
  25691. {
  25692. wrapper.setSize (getWidth(), getHeight());
  25693. }
  25694. void timerCallback()
  25695. {
  25696. wrapper.resizeToFitView();
  25697. startTimer (jmin (713, getTimerInterval() + 51));
  25698. }
  25699. void childBoundsChanged (Component* child)
  25700. {
  25701. setSize (wrapper.getWidth(), wrapper.getHeight());
  25702. startTimer (70);
  25703. }
  25704. private:
  25705. AudioUnitPluginInstance& plugin;
  25706. NSViewComponent wrapper;
  25707. bool createView (const bool createGenericViewIfNeeded)
  25708. {
  25709. NSView* pluginView = 0;
  25710. UInt32 dataSize = 0;
  25711. Boolean isWritable = false;
  25712. AudioUnitInitialize (plugin.audioUnit);
  25713. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25714. 0, &dataSize, &isWritable) == noErr
  25715. && dataSize != 0
  25716. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25717. 0, &dataSize, &isWritable) == noErr)
  25718. {
  25719. HeapBlock <AudioUnitCocoaViewInfo> info;
  25720. info.calloc (dataSize, 1);
  25721. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25722. 0, info, &dataSize) == noErr)
  25723. {
  25724. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25725. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25726. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25727. Class viewClass = [viewBundle classNamed: viewClassName];
  25728. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25729. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25730. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25731. {
  25732. id factory = [[[viewClass alloc] init] autorelease];
  25733. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25734. withSize: NSMakeSize (getWidth(), getHeight())];
  25735. }
  25736. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25737. CFRelease (info->mCocoaAUViewClass[i]);
  25738. CFRelease (info->mCocoaAUViewBundleLocation);
  25739. }
  25740. }
  25741. if (createGenericViewIfNeeded && (pluginView == 0))
  25742. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25743. wrapper.setView (pluginView);
  25744. if (pluginView != 0)
  25745. {
  25746. timerCallback();
  25747. startTimer (70);
  25748. }
  25749. return pluginView != 0;
  25750. }
  25751. };
  25752. #if JUCE_SUPPORT_CARBON
  25753. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25754. {
  25755. public:
  25756. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25757. : AudioProcessorEditor (&plugin_),
  25758. plugin (plugin_),
  25759. viewComponent (0)
  25760. {
  25761. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25762. setOpaque (true);
  25763. setVisible (true);
  25764. setSize (400, 300);
  25765. ComponentDescription viewList [16];
  25766. UInt32 viewListSize = sizeof (viewList);
  25767. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25768. 0, &viewList, &viewListSize);
  25769. componentRecord = FindNextComponent (0, &viewList[0]);
  25770. }
  25771. ~AudioUnitPluginWindowCarbon()
  25772. {
  25773. innerWrapper = 0;
  25774. if (isValid())
  25775. plugin.editorBeingDeleted (this);
  25776. }
  25777. bool isValid() const throw() { return componentRecord != 0; }
  25778. void paint (Graphics& g)
  25779. {
  25780. g.fillAll (Colours::black);
  25781. }
  25782. void resized()
  25783. {
  25784. innerWrapper->setSize (getWidth(), getHeight());
  25785. }
  25786. bool keyStateChanged (bool)
  25787. {
  25788. return false;
  25789. }
  25790. bool keyPressed (const KeyPress&)
  25791. {
  25792. return false;
  25793. }
  25794. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25795. AudioUnitCarbonView getViewComponent()
  25796. {
  25797. if (viewComponent == 0 && componentRecord != 0)
  25798. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25799. return viewComponent;
  25800. }
  25801. void closeViewComponent()
  25802. {
  25803. if (viewComponent != 0)
  25804. {
  25805. log ("Closing AU GUI: " + plugin.getName());
  25806. CloseComponent (viewComponent);
  25807. viewComponent = 0;
  25808. }
  25809. }
  25810. private:
  25811. AudioUnitPluginInstance& plugin;
  25812. ComponentRecord* componentRecord;
  25813. AudioUnitCarbonView viewComponent;
  25814. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25815. {
  25816. public:
  25817. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25818. : owner (owner_)
  25819. {
  25820. }
  25821. ~InnerWrapperComponent()
  25822. {
  25823. deleteWindow();
  25824. }
  25825. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25826. {
  25827. log ("Opening AU GUI: " + owner->plugin.getName());
  25828. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25829. if (viewComponent == 0)
  25830. return 0;
  25831. Float32Point pos = { 0, 0 };
  25832. Float32Point size = { 250, 200 };
  25833. HIViewRef pluginView = 0;
  25834. AudioUnitCarbonViewCreate (viewComponent,
  25835. owner->getAudioUnit(),
  25836. windowRef,
  25837. rootView,
  25838. &pos,
  25839. &size,
  25840. (ControlRef*) &pluginView);
  25841. return pluginView;
  25842. }
  25843. void removeView (HIViewRef)
  25844. {
  25845. owner->closeViewComponent();
  25846. }
  25847. private:
  25848. AudioUnitPluginWindowCarbon* const owner;
  25849. };
  25850. friend class InnerWrapperComponent;
  25851. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25852. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  25853. };
  25854. #endif
  25855. bool AudioUnitPluginInstance::hasEditor() const
  25856. {
  25857. return true;
  25858. }
  25859. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25860. {
  25861. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25862. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25863. w = 0;
  25864. #if JUCE_SUPPORT_CARBON
  25865. if (w == 0)
  25866. {
  25867. w = new AudioUnitPluginWindowCarbon (*this);
  25868. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25869. w = 0;
  25870. }
  25871. #endif
  25872. if (w == 0)
  25873. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25874. return w.release();
  25875. }
  25876. const String AudioUnitPluginInstance::getCategory() const
  25877. {
  25878. const char* result = 0;
  25879. switch (componentDesc.componentType)
  25880. {
  25881. case kAudioUnitType_Effect:
  25882. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  25883. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  25884. case kAudioUnitType_Generator: result = "Generator"; break;
  25885. case kAudioUnitType_Panner: result = "Panner"; break;
  25886. default: break;
  25887. }
  25888. return result;
  25889. }
  25890. int AudioUnitPluginInstance::getNumParameters()
  25891. {
  25892. return parameterIds.size();
  25893. }
  25894. float AudioUnitPluginInstance::getParameter (int index)
  25895. {
  25896. const ScopedLock sl (lock);
  25897. Float32 value = 0.0f;
  25898. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25899. {
  25900. AudioUnitGetParameter (audioUnit,
  25901. (UInt32) parameterIds.getUnchecked (index),
  25902. kAudioUnitScope_Global, 0,
  25903. &value);
  25904. }
  25905. return value;
  25906. }
  25907. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25908. {
  25909. const ScopedLock sl (lock);
  25910. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25911. {
  25912. AudioUnitSetParameter (audioUnit,
  25913. (UInt32) parameterIds.getUnchecked (index),
  25914. kAudioUnitScope_Global, 0,
  25915. newValue, 0);
  25916. }
  25917. }
  25918. const String AudioUnitPluginInstance::getParameterName (int index)
  25919. {
  25920. AudioUnitParameterInfo info;
  25921. zerostruct (info);
  25922. UInt32 sz = sizeof (info);
  25923. String name;
  25924. if (AudioUnitGetProperty (audioUnit,
  25925. kAudioUnitProperty_ParameterInfo,
  25926. kAudioUnitScope_Global,
  25927. parameterIds [index], &info, &sz) == noErr)
  25928. {
  25929. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25930. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25931. else
  25932. name = String (info.name, sizeof (info.name));
  25933. }
  25934. return name;
  25935. }
  25936. const String AudioUnitPluginInstance::getParameterText (int index)
  25937. {
  25938. return String (getParameter (index));
  25939. }
  25940. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25941. {
  25942. AudioUnitParameterInfo info;
  25943. UInt32 sz = sizeof (info);
  25944. if (AudioUnitGetProperty (audioUnit,
  25945. kAudioUnitProperty_ParameterInfo,
  25946. kAudioUnitScope_Global,
  25947. parameterIds [index], &info, &sz) == noErr)
  25948. {
  25949. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25950. }
  25951. return true;
  25952. }
  25953. int AudioUnitPluginInstance::getNumPrograms()
  25954. {
  25955. CFArrayRef presets;
  25956. UInt32 sz = sizeof (CFArrayRef);
  25957. int num = 0;
  25958. if (AudioUnitGetProperty (audioUnit,
  25959. kAudioUnitProperty_FactoryPresets,
  25960. kAudioUnitScope_Global,
  25961. 0, &presets, &sz) == noErr)
  25962. {
  25963. num = (int) CFArrayGetCount (presets);
  25964. CFRelease (presets);
  25965. }
  25966. return num;
  25967. }
  25968. int AudioUnitPluginInstance::getCurrentProgram()
  25969. {
  25970. AUPreset current;
  25971. current.presetNumber = 0;
  25972. UInt32 sz = sizeof (AUPreset);
  25973. AudioUnitGetProperty (audioUnit,
  25974. kAudioUnitProperty_FactoryPresets,
  25975. kAudioUnitScope_Global,
  25976. 0, &current, &sz);
  25977. return current.presetNumber;
  25978. }
  25979. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25980. {
  25981. AUPreset current;
  25982. current.presetNumber = newIndex;
  25983. current.presetName = 0;
  25984. AudioUnitSetProperty (audioUnit,
  25985. kAudioUnitProperty_FactoryPresets,
  25986. kAudioUnitScope_Global,
  25987. 0, &current, sizeof (AUPreset));
  25988. }
  25989. const String AudioUnitPluginInstance::getProgramName (int index)
  25990. {
  25991. String s;
  25992. CFArrayRef presets;
  25993. UInt32 sz = sizeof (CFArrayRef);
  25994. if (AudioUnitGetProperty (audioUnit,
  25995. kAudioUnitProperty_FactoryPresets,
  25996. kAudioUnitScope_Global,
  25997. 0, &presets, &sz) == noErr)
  25998. {
  25999. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26000. {
  26001. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26002. if (p != 0 && p->presetNumber == index)
  26003. {
  26004. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26005. break;
  26006. }
  26007. }
  26008. CFRelease (presets);
  26009. }
  26010. return s;
  26011. }
  26012. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26013. {
  26014. jassertfalse; // xxx not implemented!
  26015. }
  26016. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26017. {
  26018. if (isPositiveAndBelow (index, getNumInputChannels()))
  26019. return "Input " + String (index + 1);
  26020. return String::empty;
  26021. }
  26022. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26023. {
  26024. if (! isPositiveAndBelow (index, getNumInputChannels()))
  26025. return false;
  26026. return true;
  26027. }
  26028. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26029. {
  26030. if (isPositiveAndBelow (index, getNumOutputChannels()))
  26031. return "Output " + String (index + 1);
  26032. return String::empty;
  26033. }
  26034. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26035. {
  26036. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  26037. return false;
  26038. return true;
  26039. }
  26040. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26041. {
  26042. getCurrentProgramStateInformation (destData);
  26043. }
  26044. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26045. {
  26046. CFPropertyListRef propertyList = 0;
  26047. UInt32 sz = sizeof (CFPropertyListRef);
  26048. if (AudioUnitGetProperty (audioUnit,
  26049. kAudioUnitProperty_ClassInfo,
  26050. kAudioUnitScope_Global,
  26051. 0, &propertyList, &sz) == noErr)
  26052. {
  26053. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26054. CFWriteStreamOpen (stream);
  26055. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26056. CFWriteStreamClose (stream);
  26057. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26058. destData.setSize (bytesWritten);
  26059. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26060. CFRelease (data);
  26061. CFRelease (stream);
  26062. CFRelease (propertyList);
  26063. }
  26064. }
  26065. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26066. {
  26067. setCurrentProgramStateInformation (data, sizeInBytes);
  26068. }
  26069. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26070. {
  26071. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26072. (const UInt8*) data,
  26073. sizeInBytes,
  26074. kCFAllocatorNull);
  26075. CFReadStreamOpen (stream);
  26076. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26077. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26078. stream,
  26079. 0,
  26080. kCFPropertyListImmutable,
  26081. &format,
  26082. 0);
  26083. CFRelease (stream);
  26084. if (propertyList != 0)
  26085. AudioUnitSetProperty (audioUnit,
  26086. kAudioUnitProperty_ClassInfo,
  26087. kAudioUnitScope_Global,
  26088. 0, &propertyList, sizeof (propertyList));
  26089. }
  26090. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26091. {
  26092. }
  26093. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26094. {
  26095. }
  26096. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26097. const String& fileOrIdentifier)
  26098. {
  26099. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26100. return;
  26101. PluginDescription desc;
  26102. desc.fileOrIdentifier = fileOrIdentifier;
  26103. desc.uid = 0;
  26104. try
  26105. {
  26106. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26107. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26108. if (auInstance != 0)
  26109. {
  26110. auInstance->fillInPluginDescription (desc);
  26111. results.add (new PluginDescription (desc));
  26112. }
  26113. }
  26114. catch (...)
  26115. {
  26116. // crashed while loading...
  26117. }
  26118. }
  26119. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26120. {
  26121. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26122. {
  26123. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26124. if (result->audioUnit != 0)
  26125. {
  26126. result->initialise();
  26127. return result.release();
  26128. }
  26129. }
  26130. return 0;
  26131. }
  26132. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26133. const bool /*recursive*/)
  26134. {
  26135. StringArray result;
  26136. ComponentRecord* comp = 0;
  26137. ComponentDescription desc;
  26138. zerostruct (desc);
  26139. for (;;)
  26140. {
  26141. zerostruct (desc);
  26142. comp = FindNextComponent (comp, &desc);
  26143. if (comp == 0)
  26144. break;
  26145. GetComponentInfo (comp, &desc, 0, 0, 0);
  26146. if (desc.componentType == kAudioUnitType_MusicDevice
  26147. || desc.componentType == kAudioUnitType_MusicEffect
  26148. || desc.componentType == kAudioUnitType_Effect
  26149. || desc.componentType == kAudioUnitType_Generator
  26150. || desc.componentType == kAudioUnitType_Panner)
  26151. {
  26152. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26153. DBG (s);
  26154. result.add (s);
  26155. }
  26156. }
  26157. return result;
  26158. }
  26159. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26160. {
  26161. ComponentDescription desc;
  26162. String name, version, manufacturer;
  26163. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26164. return FindNextComponent (0, &desc) != 0;
  26165. const File f (fileOrIdentifier);
  26166. return f.hasFileExtension (".component")
  26167. && f.isDirectory();
  26168. }
  26169. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26170. {
  26171. ComponentDescription desc;
  26172. String name, version, manufacturer;
  26173. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26174. if (name.isEmpty())
  26175. name = fileOrIdentifier;
  26176. return name;
  26177. }
  26178. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26179. {
  26180. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26181. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26182. else
  26183. return File (desc.fileOrIdentifier).exists();
  26184. }
  26185. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26186. {
  26187. return FileSearchPath ("/(Default AudioUnit locations)");
  26188. }
  26189. #endif
  26190. END_JUCE_NAMESPACE
  26191. #undef log
  26192. #endif
  26193. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26194. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26195. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26196. #define JUCE_MAC_VST_INCLUDED 1
  26197. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26198. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26199. #if JUCE_WINDOWS
  26200. #undef _WIN32_WINNT
  26201. #define _WIN32_WINNT 0x500
  26202. #undef STRICT
  26203. #define STRICT
  26204. #include <windows.h>
  26205. #include <float.h>
  26206. #pragma warning (disable : 4312 4355)
  26207. #ifdef __INTEL_COMPILER
  26208. #pragma warning (disable : 1899)
  26209. #endif
  26210. #elif JUCE_LINUX
  26211. #include <float.h>
  26212. #include <sys/time.h>
  26213. #include <X11/Xlib.h>
  26214. #include <X11/Xutil.h>
  26215. #include <X11/Xatom.h>
  26216. #undef Font
  26217. #undef KeyPress
  26218. #undef Drawable
  26219. #undef Time
  26220. #else
  26221. #include <Cocoa/Cocoa.h>
  26222. #include <Carbon/Carbon.h>
  26223. #endif
  26224. #if ! (JUCE_MAC && JUCE_64BIT)
  26225. BEGIN_JUCE_NAMESPACE
  26226. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26227. #endif
  26228. #undef PRAGMA_ALIGN_SUPPORTED
  26229. #define VST_FORCE_DEPRECATED 0
  26230. #if JUCE_MSVC
  26231. #pragma warning (push)
  26232. #pragma warning (disable: 4996)
  26233. #endif
  26234. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26235. your include path if you want to add VST support.
  26236. If you're not interested in VSTs, you can disable them by changing the
  26237. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26238. */
  26239. #include <pluginterfaces/vst2.x/aeffectx.h>
  26240. #if JUCE_MSVC
  26241. #pragma warning (pop)
  26242. #endif
  26243. #if JUCE_LINUX
  26244. #define Font JUCE_NAMESPACE::Font
  26245. #define KeyPress JUCE_NAMESPACE::KeyPress
  26246. #define Drawable JUCE_NAMESPACE::Drawable
  26247. #define Time JUCE_NAMESPACE::Time
  26248. #endif
  26249. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26250. #ifdef __aeffect__
  26251. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26252. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26253. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26254. events to the list.
  26255. This is used by both the VST hosting code and the plugin wrapper.
  26256. */
  26257. class VSTMidiEventList
  26258. {
  26259. public:
  26260. VSTMidiEventList()
  26261. : numEventsUsed (0), numEventsAllocated (0)
  26262. {
  26263. }
  26264. ~VSTMidiEventList()
  26265. {
  26266. freeEvents();
  26267. }
  26268. void clear()
  26269. {
  26270. numEventsUsed = 0;
  26271. if (events != 0)
  26272. events->numEvents = 0;
  26273. }
  26274. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26275. {
  26276. ensureSize (numEventsUsed + 1);
  26277. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26278. events->numEvents = ++numEventsUsed;
  26279. if (numBytes <= 4)
  26280. {
  26281. if (e->type == kVstSysExType)
  26282. {
  26283. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26284. e->type = kVstMidiType;
  26285. e->byteSize = sizeof (VstMidiEvent);
  26286. e->noteLength = 0;
  26287. e->noteOffset = 0;
  26288. e->detune = 0;
  26289. e->noteOffVelocity = 0;
  26290. }
  26291. e->deltaFrames = frameOffset;
  26292. memcpy (e->midiData, midiData, numBytes);
  26293. }
  26294. else
  26295. {
  26296. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26297. if (se->type == kVstSysExType)
  26298. delete[] se->sysexDump;
  26299. se->sysexDump = new char [numBytes];
  26300. memcpy (se->sysexDump, midiData, numBytes);
  26301. se->type = kVstSysExType;
  26302. se->byteSize = sizeof (VstMidiSysexEvent);
  26303. se->deltaFrames = frameOffset;
  26304. se->flags = 0;
  26305. se->dumpBytes = numBytes;
  26306. se->resvd1 = 0;
  26307. se->resvd2 = 0;
  26308. }
  26309. }
  26310. // Handy method to pull the events out of an event buffer supplied by the host
  26311. // or plugin.
  26312. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26313. {
  26314. for (int i = 0; i < events->numEvents; ++i)
  26315. {
  26316. const VstEvent* const e = events->events[i];
  26317. if (e != 0)
  26318. {
  26319. if (e->type == kVstMidiType)
  26320. {
  26321. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26322. 4, e->deltaFrames);
  26323. }
  26324. else if (e->type == kVstSysExType)
  26325. {
  26326. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26327. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26328. e->deltaFrames);
  26329. }
  26330. }
  26331. }
  26332. }
  26333. void ensureSize (int numEventsNeeded)
  26334. {
  26335. if (numEventsNeeded > numEventsAllocated)
  26336. {
  26337. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26338. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26339. if (events == 0)
  26340. events.calloc (size, 1);
  26341. else
  26342. events.realloc (size, 1);
  26343. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26344. {
  26345. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26346. (int) sizeof (VstMidiSysexEvent)));
  26347. e->type = kVstMidiType;
  26348. e->byteSize = sizeof (VstMidiEvent);
  26349. events->events[i] = (VstEvent*) e;
  26350. }
  26351. numEventsAllocated = numEventsNeeded;
  26352. }
  26353. }
  26354. void freeEvents()
  26355. {
  26356. if (events != 0)
  26357. {
  26358. for (int i = numEventsAllocated; --i >= 0;)
  26359. {
  26360. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26361. if (e->type == kVstSysExType)
  26362. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26363. juce_free (e);
  26364. }
  26365. events.free();
  26366. numEventsUsed = 0;
  26367. numEventsAllocated = 0;
  26368. }
  26369. }
  26370. HeapBlock <VstEvents> events;
  26371. private:
  26372. int numEventsUsed, numEventsAllocated;
  26373. };
  26374. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26375. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26376. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26377. #if ! JUCE_WINDOWS
  26378. static void _fpreset() {}
  26379. static void _clearfp() {}
  26380. #endif
  26381. extern void juce_callAnyTimersSynchronously();
  26382. const int fxbVersionNum = 1;
  26383. struct fxProgram
  26384. {
  26385. long chunkMagic; // 'CcnK'
  26386. long byteSize; // of this chunk, excl. magic + byteSize
  26387. long fxMagic; // 'FxCk'
  26388. long version;
  26389. long fxID; // fx unique id
  26390. long fxVersion;
  26391. long numParams;
  26392. char prgName[28];
  26393. float params[1]; // variable no. of parameters
  26394. };
  26395. struct fxSet
  26396. {
  26397. long chunkMagic; // 'CcnK'
  26398. long byteSize; // of this chunk, excl. magic + byteSize
  26399. long fxMagic; // 'FxBk'
  26400. long version;
  26401. long fxID; // fx unique id
  26402. long fxVersion;
  26403. long numPrograms;
  26404. char future[128];
  26405. fxProgram programs[1]; // variable no. of programs
  26406. };
  26407. struct fxChunkSet
  26408. {
  26409. long chunkMagic; // 'CcnK'
  26410. long byteSize; // of this chunk, excl. magic + byteSize
  26411. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26412. long version;
  26413. long fxID; // fx unique id
  26414. long fxVersion;
  26415. long numPrograms;
  26416. char future[128];
  26417. long chunkSize;
  26418. char chunk[8]; // variable
  26419. };
  26420. struct fxProgramSet
  26421. {
  26422. long chunkMagic; // 'CcnK'
  26423. long byteSize; // of this chunk, excl. magic + byteSize
  26424. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26425. long version;
  26426. long fxID; // fx unique id
  26427. long fxVersion;
  26428. long numPrograms;
  26429. char name[28];
  26430. long chunkSize;
  26431. char chunk[8]; // variable
  26432. };
  26433. namespace
  26434. {
  26435. long vst_swap (const long x) throw()
  26436. {
  26437. #ifdef JUCE_LITTLE_ENDIAN
  26438. return (long) ByteOrder::swap ((uint32) x);
  26439. #else
  26440. return x;
  26441. #endif
  26442. }
  26443. float vst_swapFloat (const float x) throw()
  26444. {
  26445. #ifdef JUCE_LITTLE_ENDIAN
  26446. union { uint32 asInt; float asFloat; } n;
  26447. n.asFloat = x;
  26448. n.asInt = ByteOrder::swap (n.asInt);
  26449. return n.asFloat;
  26450. #else
  26451. return x;
  26452. #endif
  26453. }
  26454. double getVSTHostTimeNanoseconds()
  26455. {
  26456. #if JUCE_WINDOWS
  26457. return timeGetTime() * 1000000.0;
  26458. #elif JUCE_LINUX
  26459. timeval micro;
  26460. gettimeofday (&micro, 0);
  26461. return micro.tv_usec * 1000.0;
  26462. #elif JUCE_MAC
  26463. UnsignedWide micro;
  26464. Microseconds (&micro);
  26465. return micro.lo * 1000.0;
  26466. #endif
  26467. }
  26468. }
  26469. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26470. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26471. static int shellUIDToCreate = 0;
  26472. static int insideVSTCallback = 0;
  26473. class VSTPluginWindow;
  26474. // Change this to disable logging of various VST activities
  26475. #ifndef VST_LOGGING
  26476. #define VST_LOGGING 1
  26477. #endif
  26478. #if VST_LOGGING
  26479. #define log(a) Logger::writeToLog(a);
  26480. #else
  26481. #define log(a)
  26482. #endif
  26483. #if JUCE_MAC && JUCE_PPC
  26484. static void* NewCFMFromMachO (void* const machofp) throw()
  26485. {
  26486. void* result = (void*) new char[8];
  26487. ((void**) result)[0] = machofp;
  26488. ((void**) result)[1] = result;
  26489. return result;
  26490. }
  26491. #endif
  26492. #if JUCE_LINUX
  26493. extern Display* display;
  26494. extern XContext windowHandleXContext;
  26495. typedef void (*EventProcPtr) (XEvent* ev);
  26496. static bool xErrorTriggered;
  26497. namespace
  26498. {
  26499. int temporaryErrorHandler (Display*, XErrorEvent*)
  26500. {
  26501. xErrorTriggered = true;
  26502. return 0;
  26503. }
  26504. int getPropertyFromXWindow (Window handle, Atom atom)
  26505. {
  26506. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26507. xErrorTriggered = false;
  26508. int userSize;
  26509. unsigned long bytes, userCount;
  26510. unsigned char* data;
  26511. Atom userType;
  26512. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26513. &userType, &userSize, &userCount, &bytes, &data);
  26514. XSetErrorHandler (oldErrorHandler);
  26515. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26516. : 0;
  26517. }
  26518. Window getChildWindow (Window windowToCheck)
  26519. {
  26520. Window rootWindow, parentWindow;
  26521. Window* childWindows;
  26522. unsigned int numChildren;
  26523. XQueryTree (display,
  26524. windowToCheck,
  26525. &rootWindow,
  26526. &parentWindow,
  26527. &childWindows,
  26528. &numChildren);
  26529. if (numChildren > 0)
  26530. return childWindows [0];
  26531. return 0;
  26532. }
  26533. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26534. {
  26535. if (e.mods.isLeftButtonDown())
  26536. {
  26537. ev.xbutton.button = Button1;
  26538. ev.xbutton.state |= Button1Mask;
  26539. }
  26540. else if (e.mods.isRightButtonDown())
  26541. {
  26542. ev.xbutton.button = Button3;
  26543. ev.xbutton.state |= Button3Mask;
  26544. }
  26545. else if (e.mods.isMiddleButtonDown())
  26546. {
  26547. ev.xbutton.button = Button2;
  26548. ev.xbutton.state |= Button2Mask;
  26549. }
  26550. }
  26551. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26552. {
  26553. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26554. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26555. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26556. }
  26557. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26558. {
  26559. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26560. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26561. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26562. }
  26563. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26564. {
  26565. if (increment < 0)
  26566. {
  26567. ev.xbutton.button = Button5;
  26568. ev.xbutton.state |= Button5Mask;
  26569. }
  26570. else if (increment > 0)
  26571. {
  26572. ev.xbutton.button = Button4;
  26573. ev.xbutton.state |= Button4Mask;
  26574. }
  26575. }
  26576. }
  26577. #endif
  26578. class ModuleHandle : public ReferenceCountedObject
  26579. {
  26580. public:
  26581. File file;
  26582. MainCall moduleMain;
  26583. String pluginName;
  26584. static Array <ModuleHandle*>& getActiveModules()
  26585. {
  26586. static Array <ModuleHandle*> activeModules;
  26587. return activeModules;
  26588. }
  26589. static ModuleHandle* findOrCreateModule (const File& file)
  26590. {
  26591. for (int i = getActiveModules().size(); --i >= 0;)
  26592. {
  26593. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26594. if (module->file == file)
  26595. return module;
  26596. }
  26597. _fpreset(); // (doesn't do any harm)
  26598. ++insideVSTCallback;
  26599. shellUIDToCreate = 0;
  26600. log ("Attempting to load VST: " + file.getFullPathName());
  26601. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26602. if (! m->open())
  26603. m = 0;
  26604. --insideVSTCallback;
  26605. _fpreset(); // (doesn't do any harm)
  26606. return m.release();
  26607. }
  26608. ModuleHandle (const File& file_)
  26609. : file (file_),
  26610. moduleMain (0),
  26611. #if JUCE_WINDOWS || JUCE_LINUX
  26612. hModule (0)
  26613. #elif JUCE_MAC
  26614. fragId (0),
  26615. resHandle (0),
  26616. bundleRef (0),
  26617. resFileId (0)
  26618. #endif
  26619. {
  26620. getActiveModules().add (this);
  26621. #if JUCE_WINDOWS || JUCE_LINUX
  26622. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26623. #elif JUCE_MAC
  26624. FSRef ref;
  26625. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26626. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26627. #endif
  26628. }
  26629. ~ModuleHandle()
  26630. {
  26631. getActiveModules().removeValue (this);
  26632. close();
  26633. }
  26634. #if JUCE_WINDOWS || JUCE_LINUX
  26635. void* hModule;
  26636. String fullParentDirectoryPathName;
  26637. bool open()
  26638. {
  26639. #if JUCE_WINDOWS
  26640. static bool timePeriodSet = false;
  26641. if (! timePeriodSet)
  26642. {
  26643. timePeriodSet = true;
  26644. timeBeginPeriod (2);
  26645. }
  26646. #endif
  26647. pluginName = file.getFileNameWithoutExtension();
  26648. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26649. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26650. if (moduleMain == 0)
  26651. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26652. return moduleMain != 0;
  26653. }
  26654. void close()
  26655. {
  26656. _fpreset(); // (doesn't do any harm)
  26657. PlatformUtilities::freeDynamicLibrary (hModule);
  26658. }
  26659. void closeEffect (AEffect* eff)
  26660. {
  26661. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26662. }
  26663. #else
  26664. CFragConnectionID fragId;
  26665. Handle resHandle;
  26666. CFBundleRef bundleRef;
  26667. FSSpec parentDirFSSpec;
  26668. short resFileId;
  26669. bool open()
  26670. {
  26671. bool ok = false;
  26672. const String filename (file.getFullPathName());
  26673. if (file.hasFileExtension (".vst"))
  26674. {
  26675. const char* const utf8 = filename.toUTF8();
  26676. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26677. strlen (utf8), file.isDirectory());
  26678. if (url != 0)
  26679. {
  26680. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26681. CFRelease (url);
  26682. if (bundleRef != 0)
  26683. {
  26684. if (CFBundleLoadExecutable (bundleRef))
  26685. {
  26686. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26687. if (moduleMain == 0)
  26688. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26689. if (moduleMain != 0)
  26690. {
  26691. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26692. if (name != 0)
  26693. {
  26694. if (CFGetTypeID (name) == CFStringGetTypeID())
  26695. {
  26696. char buffer[1024];
  26697. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26698. pluginName = buffer;
  26699. }
  26700. }
  26701. if (pluginName.isEmpty())
  26702. pluginName = file.getFileNameWithoutExtension();
  26703. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26704. ok = true;
  26705. }
  26706. }
  26707. if (! ok)
  26708. {
  26709. CFBundleUnloadExecutable (bundleRef);
  26710. CFRelease (bundleRef);
  26711. bundleRef = 0;
  26712. }
  26713. }
  26714. }
  26715. }
  26716. #if JUCE_PPC
  26717. else
  26718. {
  26719. FSRef fn;
  26720. if (FSPathMakeRef ((UInt8*) filename.toUTF8().getAddress(), &fn, 0) == noErr)
  26721. {
  26722. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26723. if (resFileId != -1)
  26724. {
  26725. const int numEffs = Count1Resources ('aEff');
  26726. for (int i = 0; i < numEffs; ++i)
  26727. {
  26728. resHandle = Get1IndResource ('aEff', i + 1);
  26729. if (resHandle != 0)
  26730. {
  26731. OSType type;
  26732. Str255 name;
  26733. SInt16 id;
  26734. GetResInfo (resHandle, &id, &type, name);
  26735. pluginName = String ((const char*) name + 1, name[0]);
  26736. DetachResource (resHandle);
  26737. HLock (resHandle);
  26738. Ptr ptr;
  26739. Str255 errorText;
  26740. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26741. name, kPrivateCFragCopy,
  26742. &fragId, &ptr, errorText);
  26743. if (err == noErr)
  26744. {
  26745. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26746. ok = true;
  26747. }
  26748. else
  26749. {
  26750. HUnlock (resHandle);
  26751. }
  26752. break;
  26753. }
  26754. }
  26755. if (! ok)
  26756. CloseResFile (resFileId);
  26757. }
  26758. }
  26759. }
  26760. #endif
  26761. return ok;
  26762. }
  26763. void close()
  26764. {
  26765. #if JUCE_PPC
  26766. if (fragId != 0)
  26767. {
  26768. if (moduleMain != 0)
  26769. disposeMachOFromCFM ((void*) moduleMain);
  26770. CloseConnection (&fragId);
  26771. HUnlock (resHandle);
  26772. if (resFileId != 0)
  26773. CloseResFile (resFileId);
  26774. }
  26775. else
  26776. #endif
  26777. if (bundleRef != 0)
  26778. {
  26779. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26780. if (CFGetRetainCount (bundleRef) == 1)
  26781. CFBundleUnloadExecutable (bundleRef);
  26782. if (CFGetRetainCount (bundleRef) > 0)
  26783. CFRelease (bundleRef);
  26784. }
  26785. }
  26786. void closeEffect (AEffect* eff)
  26787. {
  26788. #if JUCE_PPC
  26789. if (fragId != 0)
  26790. {
  26791. Array<void*> thingsToDelete;
  26792. thingsToDelete.add ((void*) eff->dispatcher);
  26793. thingsToDelete.add ((void*) eff->process);
  26794. thingsToDelete.add ((void*) eff->setParameter);
  26795. thingsToDelete.add ((void*) eff->getParameter);
  26796. thingsToDelete.add ((void*) eff->processReplacing);
  26797. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26798. for (int i = thingsToDelete.size(); --i >= 0;)
  26799. disposeMachOFromCFM (thingsToDelete[i]);
  26800. }
  26801. else
  26802. #endif
  26803. {
  26804. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26805. }
  26806. }
  26807. #if JUCE_PPC
  26808. static void* newMachOFromCFM (void* cfmfp)
  26809. {
  26810. if (cfmfp == 0)
  26811. return 0;
  26812. UInt32* const mfp = new UInt32[6];
  26813. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26814. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26815. mfp[2] = 0x800c0000;
  26816. mfp[3] = 0x804c0004;
  26817. mfp[4] = 0x7c0903a6;
  26818. mfp[5] = 0x4e800420;
  26819. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26820. return mfp;
  26821. }
  26822. static void disposeMachOFromCFM (void* ptr)
  26823. {
  26824. delete[] static_cast <UInt32*> (ptr);
  26825. }
  26826. void coerceAEffectFunctionCalls (AEffect* eff)
  26827. {
  26828. if (fragId != 0)
  26829. {
  26830. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26831. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26832. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26833. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26834. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26835. }
  26836. }
  26837. #endif
  26838. #endif
  26839. private:
  26840. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  26841. };
  26842. /**
  26843. An instance of a plugin, created by a VSTPluginFormat.
  26844. */
  26845. class VSTPluginInstance : public AudioPluginInstance,
  26846. private Timer,
  26847. private AsyncUpdater
  26848. {
  26849. public:
  26850. ~VSTPluginInstance();
  26851. // AudioPluginInstance methods:
  26852. void fillInPluginDescription (PluginDescription& desc) const
  26853. {
  26854. desc.name = name;
  26855. {
  26856. char buffer [512];
  26857. zerostruct (buffer);
  26858. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26859. desc.descriptiveName = String (buffer).trim();
  26860. if (desc.descriptiveName.isEmpty())
  26861. desc.descriptiveName = name;
  26862. }
  26863. desc.fileOrIdentifier = module->file.getFullPathName();
  26864. desc.uid = getUID();
  26865. desc.lastFileModTime = module->file.getLastModificationTime();
  26866. desc.pluginFormatName = "VST";
  26867. desc.category = getCategory();
  26868. {
  26869. char buffer [kVstMaxVendorStrLen + 8];
  26870. zerostruct (buffer);
  26871. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26872. desc.manufacturerName = buffer;
  26873. }
  26874. desc.version = getVersion();
  26875. desc.numInputChannels = getNumInputChannels();
  26876. desc.numOutputChannels = getNumOutputChannels();
  26877. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26878. }
  26879. void* getPlatformSpecificData() { return effect; }
  26880. const String getName() const { return name; }
  26881. int getUID() const;
  26882. bool acceptsMidi() const { return wantsMidiMessages; }
  26883. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26884. // AudioProcessor methods:
  26885. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26886. void releaseResources();
  26887. void processBlock (AudioSampleBuffer& buffer,
  26888. MidiBuffer& midiMessages);
  26889. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26890. AudioProcessorEditor* createEditor();
  26891. const String getInputChannelName (int index) const;
  26892. bool isInputChannelStereoPair (int index) const;
  26893. const String getOutputChannelName (int index) const;
  26894. bool isOutputChannelStereoPair (int index) const;
  26895. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26896. float getParameter (int index);
  26897. void setParameter (int index, float newValue);
  26898. const String getParameterName (int index);
  26899. const String getParameterText (int index);
  26900. bool isParameterAutomatable (int index) const;
  26901. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26902. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26903. void setCurrentProgram (int index);
  26904. const String getProgramName (int index);
  26905. void changeProgramName (int index, const String& newName);
  26906. void getStateInformation (MemoryBlock& destData);
  26907. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26908. void setStateInformation (const void* data, int sizeInBytes);
  26909. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26910. void timerCallback();
  26911. void handleAsyncUpdate();
  26912. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26913. private:
  26914. friend class VSTPluginWindow;
  26915. friend class VSTPluginFormat;
  26916. AEffect* effect;
  26917. String name;
  26918. CriticalSection lock;
  26919. bool wantsMidiMessages, initialised, isPowerOn;
  26920. mutable StringArray programNames;
  26921. AudioSampleBuffer tempBuffer;
  26922. CriticalSection midiInLock;
  26923. MidiBuffer incomingMidi;
  26924. VSTMidiEventList midiEventsToSend;
  26925. VstTimeInfo vstHostTime;
  26926. ReferenceCountedObjectPtr <ModuleHandle> module;
  26927. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26928. bool restoreProgramSettings (const fxProgram* const prog);
  26929. const String getCurrentProgramName();
  26930. void setParamsInProgramBlock (fxProgram* const prog);
  26931. void updateStoredProgramNames();
  26932. void initialise();
  26933. void handleMidiFromPlugin (const VstEvents* const events);
  26934. void createTempParameterStore (MemoryBlock& dest);
  26935. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26936. const String getParameterLabel (int index) const;
  26937. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26938. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26939. void setChunkData (const char* data, int size, bool isPreset);
  26940. bool loadFromFXBFile (const void* data, int numBytes);
  26941. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26942. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26943. const String getVersion() const;
  26944. const String getCategory() const;
  26945. void setPower (const bool on);
  26946. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26947. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  26948. };
  26949. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26950. : effect (0),
  26951. wantsMidiMessages (false),
  26952. initialised (false),
  26953. isPowerOn (false),
  26954. tempBuffer (1, 1),
  26955. module (module_)
  26956. {
  26957. try
  26958. {
  26959. _fpreset();
  26960. ++insideVSTCallback;
  26961. name = module->pluginName;
  26962. log ("Creating VST instance: " + name);
  26963. #if JUCE_MAC
  26964. if (module->resFileId != 0)
  26965. UseResFile (module->resFileId);
  26966. #if JUCE_PPC
  26967. if (module->fragId != 0)
  26968. {
  26969. static void* audioMasterCoerced = 0;
  26970. if (audioMasterCoerced == 0)
  26971. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26972. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26973. }
  26974. else
  26975. #endif
  26976. #endif
  26977. {
  26978. effect = module->moduleMain (&audioMaster);
  26979. }
  26980. --insideVSTCallback;
  26981. if (effect != 0 && effect->magic == kEffectMagic)
  26982. {
  26983. #if JUCE_PPC
  26984. module->coerceAEffectFunctionCalls (effect);
  26985. #endif
  26986. jassert (effect->resvd2 == 0);
  26987. jassert (effect->object != 0);
  26988. _fpreset(); // some dodgy plugs fuck around with this
  26989. }
  26990. else
  26991. {
  26992. effect = 0;
  26993. }
  26994. }
  26995. catch (...)
  26996. {
  26997. --insideVSTCallback;
  26998. }
  26999. }
  27000. VSTPluginInstance::~VSTPluginInstance()
  27001. {
  27002. const ScopedLock sl (lock);
  27003. jassert (insideVSTCallback == 0);
  27004. if (effect != 0 && effect->magic == kEffectMagic)
  27005. {
  27006. try
  27007. {
  27008. #if JUCE_MAC
  27009. if (module->resFileId != 0)
  27010. UseResFile (module->resFileId);
  27011. #endif
  27012. // Must delete any editors before deleting the plugin instance!
  27013. jassert (getActiveEditor() == 0);
  27014. _fpreset(); // some dodgy plugs fuck around with this
  27015. module->closeEffect (effect);
  27016. }
  27017. catch (...)
  27018. {}
  27019. }
  27020. module = 0;
  27021. effect = 0;
  27022. }
  27023. void VSTPluginInstance::initialise()
  27024. {
  27025. if (initialised || effect == 0)
  27026. return;
  27027. log ("Initialising VST: " + module->pluginName);
  27028. initialised = true;
  27029. dispatch (effIdentify, 0, 0, 0, 0);
  27030. if (getSampleRate() > 0)
  27031. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27032. if (getBlockSize() > 0)
  27033. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27034. dispatch (effOpen, 0, 0, 0, 0);
  27035. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27036. getSampleRate(), getBlockSize());
  27037. if (getNumPrograms() > 1)
  27038. setCurrentProgram (0);
  27039. else
  27040. dispatch (effSetProgram, 0, 0, 0, 0);
  27041. int i;
  27042. for (i = effect->numInputs; --i >= 0;)
  27043. dispatch (effConnectInput, i, 1, 0, 0);
  27044. for (i = effect->numOutputs; --i >= 0;)
  27045. dispatch (effConnectOutput, i, 1, 0, 0);
  27046. updateStoredProgramNames();
  27047. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27048. setLatencySamples (effect->initialDelay);
  27049. }
  27050. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27051. int samplesPerBlockExpected)
  27052. {
  27053. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27054. sampleRate_, samplesPerBlockExpected);
  27055. setLatencySamples (effect->initialDelay);
  27056. vstHostTime.tempo = 120.0;
  27057. vstHostTime.timeSigNumerator = 4;
  27058. vstHostTime.timeSigDenominator = 4;
  27059. vstHostTime.sampleRate = sampleRate_;
  27060. vstHostTime.samplePos = 0;
  27061. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27062. initialise();
  27063. if (initialised)
  27064. {
  27065. wantsMidiMessages = wantsMidiMessages
  27066. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27067. if (wantsMidiMessages)
  27068. midiEventsToSend.ensureSize (256);
  27069. else
  27070. midiEventsToSend.freeEvents();
  27071. incomingMidi.clear();
  27072. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27073. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27074. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27075. if (! isPowerOn)
  27076. setPower (true);
  27077. // dodgy hack to force some plugins to initialise the sample rate..
  27078. if ((! hasEditor()) && getNumParameters() > 0)
  27079. {
  27080. const float old = getParameter (0);
  27081. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27082. setParameter (0, old);
  27083. }
  27084. dispatch (effStartProcess, 0, 0, 0, 0);
  27085. }
  27086. }
  27087. void VSTPluginInstance::releaseResources()
  27088. {
  27089. if (initialised)
  27090. {
  27091. dispatch (effStopProcess, 0, 0, 0, 0);
  27092. setPower (false);
  27093. }
  27094. tempBuffer.setSize (1, 1);
  27095. incomingMidi.clear();
  27096. midiEventsToSend.freeEvents();
  27097. }
  27098. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27099. MidiBuffer& midiMessages)
  27100. {
  27101. const int numSamples = buffer.getNumSamples();
  27102. if (initialised)
  27103. {
  27104. AudioPlayHead* playHead = getPlayHead();
  27105. if (playHead != 0)
  27106. {
  27107. AudioPlayHead::CurrentPositionInfo position;
  27108. playHead->getCurrentPosition (position);
  27109. vstHostTime.tempo = position.bpm;
  27110. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27111. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27112. vstHostTime.ppqPos = position.ppqPosition;
  27113. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27114. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27115. if (position.isPlaying)
  27116. vstHostTime.flags |= kVstTransportPlaying;
  27117. else
  27118. vstHostTime.flags &= ~kVstTransportPlaying;
  27119. }
  27120. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27121. if (wantsMidiMessages)
  27122. {
  27123. midiEventsToSend.clear();
  27124. midiEventsToSend.ensureSize (1);
  27125. MidiBuffer::Iterator iter (midiMessages);
  27126. const uint8* midiData;
  27127. int numBytesOfMidiData, samplePosition;
  27128. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27129. {
  27130. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27131. jlimit (0, numSamples - 1, samplePosition));
  27132. }
  27133. try
  27134. {
  27135. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27136. }
  27137. catch (...)
  27138. {}
  27139. }
  27140. _clearfp();
  27141. if ((effect->flags & effFlagsCanReplacing) != 0)
  27142. {
  27143. try
  27144. {
  27145. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27146. }
  27147. catch (...)
  27148. {}
  27149. }
  27150. else
  27151. {
  27152. tempBuffer.setSize (effect->numOutputs, numSamples);
  27153. tempBuffer.clear();
  27154. try
  27155. {
  27156. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27157. }
  27158. catch (...)
  27159. {}
  27160. for (int i = effect->numOutputs; --i >= 0;)
  27161. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27162. }
  27163. }
  27164. else
  27165. {
  27166. // Not initialised, so just bypass..
  27167. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27168. buffer.clear (i, 0, buffer.getNumSamples());
  27169. }
  27170. {
  27171. // copy any incoming midi..
  27172. const ScopedLock sl (midiInLock);
  27173. midiMessages.swapWith (incomingMidi);
  27174. incomingMidi.clear();
  27175. }
  27176. }
  27177. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27178. {
  27179. if (events != 0)
  27180. {
  27181. const ScopedLock sl (midiInLock);
  27182. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27183. }
  27184. }
  27185. static Array <VSTPluginWindow*> activeVSTWindows;
  27186. class VSTPluginWindow : public AudioProcessorEditor,
  27187. #if ! JUCE_MAC
  27188. public ComponentMovementWatcher,
  27189. #endif
  27190. public Timer
  27191. {
  27192. public:
  27193. VSTPluginWindow (VSTPluginInstance& plugin_)
  27194. : AudioProcessorEditor (&plugin_),
  27195. #if ! JUCE_MAC
  27196. ComponentMovementWatcher (this),
  27197. #endif
  27198. plugin (plugin_),
  27199. isOpen (false),
  27200. recursiveResize (false),
  27201. pluginWantsKeys (false),
  27202. pluginRefusesToResize (false),
  27203. alreadyInside (false)
  27204. {
  27205. #if JUCE_WINDOWS
  27206. sizeCheckCount = 0;
  27207. pluginHWND = 0;
  27208. #elif JUCE_LINUX
  27209. pluginWindow = None;
  27210. pluginProc = None;
  27211. #else
  27212. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27213. #endif
  27214. activeVSTWindows.add (this);
  27215. setSize (1, 1);
  27216. setOpaque (true);
  27217. setVisible (true);
  27218. }
  27219. ~VSTPluginWindow()
  27220. {
  27221. #if JUCE_MAC
  27222. innerWrapper = 0;
  27223. #else
  27224. closePluginWindow();
  27225. #endif
  27226. activeVSTWindows.removeValue (this);
  27227. plugin.editorBeingDeleted (this);
  27228. }
  27229. #if ! JUCE_MAC
  27230. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27231. {
  27232. if (recursiveResize)
  27233. return;
  27234. Component* const topComp = getTopLevelComponent();
  27235. if (topComp->getPeer() != 0)
  27236. {
  27237. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27238. recursiveResize = true;
  27239. #if JUCE_WINDOWS
  27240. if (pluginHWND != 0)
  27241. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27242. #elif JUCE_LINUX
  27243. if (pluginWindow != 0)
  27244. {
  27245. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27246. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27247. XMapRaised (display, pluginWindow);
  27248. }
  27249. #endif
  27250. recursiveResize = false;
  27251. }
  27252. }
  27253. void componentVisibilityChanged()
  27254. {
  27255. if (isShowing())
  27256. openPluginWindow();
  27257. else
  27258. closePluginWindow();
  27259. componentMovedOrResized (true, true);
  27260. }
  27261. void componentPeerChanged()
  27262. {
  27263. closePluginWindow();
  27264. openPluginWindow();
  27265. }
  27266. #endif
  27267. bool keyStateChanged (bool)
  27268. {
  27269. return pluginWantsKeys;
  27270. }
  27271. bool keyPressed (const KeyPress&)
  27272. {
  27273. return pluginWantsKeys;
  27274. }
  27275. #if JUCE_MAC
  27276. void paint (Graphics& g)
  27277. {
  27278. g.fillAll (Colours::black);
  27279. }
  27280. #else
  27281. void paint (Graphics& g)
  27282. {
  27283. if (isOpen)
  27284. {
  27285. ComponentPeer* const peer = getPeer();
  27286. if (peer != 0)
  27287. {
  27288. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27289. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27290. #if JUCE_LINUX
  27291. if (pluginWindow != 0)
  27292. {
  27293. const Rectangle<int> clip (g.getClipBounds());
  27294. XEvent ev;
  27295. zerostruct (ev);
  27296. ev.xexpose.type = Expose;
  27297. ev.xexpose.display = display;
  27298. ev.xexpose.window = pluginWindow;
  27299. ev.xexpose.x = clip.getX();
  27300. ev.xexpose.y = clip.getY();
  27301. ev.xexpose.width = clip.getWidth();
  27302. ev.xexpose.height = clip.getHeight();
  27303. sendEventToChild (&ev);
  27304. }
  27305. #endif
  27306. }
  27307. }
  27308. else
  27309. {
  27310. g.fillAll (Colours::black);
  27311. }
  27312. }
  27313. #endif
  27314. void timerCallback()
  27315. {
  27316. #if JUCE_WINDOWS
  27317. if (--sizeCheckCount <= 0)
  27318. {
  27319. sizeCheckCount = 10;
  27320. checkPluginWindowSize();
  27321. }
  27322. #endif
  27323. try
  27324. {
  27325. static bool reentrant = false;
  27326. if (! reentrant)
  27327. {
  27328. reentrant = true;
  27329. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27330. reentrant = false;
  27331. }
  27332. }
  27333. catch (...)
  27334. {}
  27335. }
  27336. void mouseDown (const MouseEvent& e)
  27337. {
  27338. #if JUCE_LINUX
  27339. if (pluginWindow == 0)
  27340. return;
  27341. toFront (true);
  27342. XEvent ev;
  27343. zerostruct (ev);
  27344. ev.xbutton.display = display;
  27345. ev.xbutton.type = ButtonPress;
  27346. ev.xbutton.window = pluginWindow;
  27347. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27348. ev.xbutton.time = CurrentTime;
  27349. ev.xbutton.x = e.x;
  27350. ev.xbutton.y = e.y;
  27351. ev.xbutton.x_root = e.getScreenX();
  27352. ev.xbutton.y_root = e.getScreenY();
  27353. translateJuceToXButtonModifiers (e, ev);
  27354. sendEventToChild (&ev);
  27355. #elif JUCE_WINDOWS
  27356. (void) e;
  27357. toFront (true);
  27358. #endif
  27359. }
  27360. void broughtToFront()
  27361. {
  27362. activeVSTWindows.removeValue (this);
  27363. activeVSTWindows.add (this);
  27364. #if JUCE_MAC
  27365. dispatch (effEditTop, 0, 0, 0, 0);
  27366. #endif
  27367. }
  27368. private:
  27369. VSTPluginInstance& plugin;
  27370. bool isOpen, recursiveResize;
  27371. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27372. #if JUCE_WINDOWS
  27373. HWND pluginHWND;
  27374. void* originalWndProc;
  27375. int sizeCheckCount;
  27376. #elif JUCE_LINUX
  27377. Window pluginWindow;
  27378. EventProcPtr pluginProc;
  27379. #endif
  27380. #if JUCE_MAC
  27381. void openPluginWindow (WindowRef parentWindow)
  27382. {
  27383. if (isOpen || parentWindow == 0)
  27384. return;
  27385. isOpen = true;
  27386. ERect* rect = 0;
  27387. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27388. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27389. // do this before and after like in the steinberg example
  27390. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27391. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27392. // Install keyboard hooks
  27393. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27394. // double-check it's not too tiny
  27395. int w = 250, h = 150;
  27396. if (rect != 0)
  27397. {
  27398. w = rect->right - rect->left;
  27399. h = rect->bottom - rect->top;
  27400. if (w == 0 || h == 0)
  27401. {
  27402. w = 250;
  27403. h = 150;
  27404. }
  27405. }
  27406. w = jmax (w, 32);
  27407. h = jmax (h, 32);
  27408. setSize (w, h);
  27409. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27410. repaint();
  27411. }
  27412. #else
  27413. void openPluginWindow()
  27414. {
  27415. if (isOpen || getWindowHandle() == 0)
  27416. return;
  27417. log ("Opening VST UI: " + plugin.name);
  27418. isOpen = true;
  27419. ERect* rect = 0;
  27420. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27421. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27422. // do this before and after like in the steinberg example
  27423. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27424. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27425. // Install keyboard hooks
  27426. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27427. #if JUCE_WINDOWS
  27428. originalWndProc = 0;
  27429. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27430. if (pluginHWND == 0)
  27431. {
  27432. isOpen = false;
  27433. setSize (300, 150);
  27434. return;
  27435. }
  27436. #pragma warning (push)
  27437. #pragma warning (disable: 4244)
  27438. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27439. if (! pluginWantsKeys)
  27440. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27441. #pragma warning (pop)
  27442. int w, h;
  27443. RECT r;
  27444. GetWindowRect (pluginHWND, &r);
  27445. w = r.right - r.left;
  27446. h = r.bottom - r.top;
  27447. if (rect != 0)
  27448. {
  27449. const int rw = rect->right - rect->left;
  27450. const int rh = rect->bottom - rect->top;
  27451. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27452. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27453. {
  27454. // very dodgy logic to decide which size is right.
  27455. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27456. {
  27457. SetWindowPos (pluginHWND, 0,
  27458. 0, 0, rw, rh,
  27459. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27460. GetWindowRect (pluginHWND, &r);
  27461. w = r.right - r.left;
  27462. h = r.bottom - r.top;
  27463. pluginRefusesToResize = (w != rw) || (h != rh);
  27464. w = rw;
  27465. h = rh;
  27466. }
  27467. }
  27468. }
  27469. #elif JUCE_LINUX
  27470. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27471. if (pluginWindow != 0)
  27472. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27473. XInternAtom (display, "_XEventProc", False));
  27474. int w = 250, h = 150;
  27475. if (rect != 0)
  27476. {
  27477. w = rect->right - rect->left;
  27478. h = rect->bottom - rect->top;
  27479. if (w == 0 || h == 0)
  27480. {
  27481. w = 250;
  27482. h = 150;
  27483. }
  27484. }
  27485. if (pluginWindow != 0)
  27486. XMapRaised (display, pluginWindow);
  27487. #endif
  27488. // double-check it's not too tiny
  27489. w = jmax (w, 32);
  27490. h = jmax (h, 32);
  27491. setSize (w, h);
  27492. #if JUCE_WINDOWS
  27493. checkPluginWindowSize();
  27494. #endif
  27495. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27496. repaint();
  27497. }
  27498. #endif
  27499. #if ! JUCE_MAC
  27500. void closePluginWindow()
  27501. {
  27502. if (isOpen)
  27503. {
  27504. log ("Closing VST UI: " + plugin.getName());
  27505. isOpen = false;
  27506. dispatch (effEditClose, 0, 0, 0, 0);
  27507. #if JUCE_WINDOWS
  27508. #pragma warning (push)
  27509. #pragma warning (disable: 4244)
  27510. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27511. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27512. #pragma warning (pop)
  27513. stopTimer();
  27514. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27515. DestroyWindow (pluginHWND);
  27516. pluginHWND = 0;
  27517. #elif JUCE_LINUX
  27518. stopTimer();
  27519. pluginWindow = 0;
  27520. pluginProc = 0;
  27521. #endif
  27522. }
  27523. }
  27524. #endif
  27525. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27526. {
  27527. return plugin.dispatch (opcode, index, value, ptr, opt);
  27528. }
  27529. #if JUCE_WINDOWS
  27530. void checkPluginWindowSize()
  27531. {
  27532. RECT r;
  27533. GetWindowRect (pluginHWND, &r);
  27534. const int w = r.right - r.left;
  27535. const int h = r.bottom - r.top;
  27536. if (isShowing() && w > 0 && h > 0
  27537. && (w != getWidth() || h != getHeight())
  27538. && ! pluginRefusesToResize)
  27539. {
  27540. setSize (w, h);
  27541. sizeCheckCount = 0;
  27542. }
  27543. }
  27544. // hooks to get keyboard events from VST windows..
  27545. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27546. {
  27547. for (int i = activeVSTWindows.size(); --i >= 0;)
  27548. {
  27549. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27550. if (w->pluginHWND == hW)
  27551. {
  27552. if (message == WM_CHAR
  27553. || message == WM_KEYDOWN
  27554. || message == WM_SYSKEYDOWN
  27555. || message == WM_KEYUP
  27556. || message == WM_SYSKEYUP
  27557. || message == WM_APPCOMMAND)
  27558. {
  27559. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27560. message, wParam, lParam);
  27561. }
  27562. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27563. (HWND) w->pluginHWND,
  27564. message,
  27565. wParam,
  27566. lParam);
  27567. }
  27568. }
  27569. return DefWindowProc (hW, message, wParam, lParam);
  27570. }
  27571. #endif
  27572. #if JUCE_LINUX
  27573. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27574. void sendEventToChild (XEvent* event)
  27575. {
  27576. if (pluginProc != 0)
  27577. {
  27578. // if the plugin publishes an event procedure, pass the event directly..
  27579. pluginProc (event);
  27580. }
  27581. else if (pluginWindow != 0)
  27582. {
  27583. // if the plugin has a window, then send the event to the window so that
  27584. // its message thread will pick it up..
  27585. XSendEvent (display, pluginWindow, False, 0L, event);
  27586. XFlush (display);
  27587. }
  27588. }
  27589. void mouseEnter (const MouseEvent& e)
  27590. {
  27591. if (pluginWindow != 0)
  27592. {
  27593. XEvent ev;
  27594. zerostruct (ev);
  27595. ev.xcrossing.display = display;
  27596. ev.xcrossing.type = EnterNotify;
  27597. ev.xcrossing.window = pluginWindow;
  27598. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27599. ev.xcrossing.time = CurrentTime;
  27600. ev.xcrossing.x = e.x;
  27601. ev.xcrossing.y = e.y;
  27602. ev.xcrossing.x_root = e.getScreenX();
  27603. ev.xcrossing.y_root = e.getScreenY();
  27604. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27605. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27606. translateJuceToXCrossingModifiers (e, ev);
  27607. sendEventToChild (&ev);
  27608. }
  27609. }
  27610. void mouseExit (const MouseEvent& e)
  27611. {
  27612. if (pluginWindow != 0)
  27613. {
  27614. XEvent ev;
  27615. zerostruct (ev);
  27616. ev.xcrossing.display = display;
  27617. ev.xcrossing.type = LeaveNotify;
  27618. ev.xcrossing.window = pluginWindow;
  27619. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27620. ev.xcrossing.time = CurrentTime;
  27621. ev.xcrossing.x = e.x;
  27622. ev.xcrossing.y = e.y;
  27623. ev.xcrossing.x_root = e.getScreenX();
  27624. ev.xcrossing.y_root = e.getScreenY();
  27625. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27626. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27627. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27628. translateJuceToXCrossingModifiers (e, ev);
  27629. sendEventToChild (&ev);
  27630. }
  27631. }
  27632. void mouseMove (const MouseEvent& e)
  27633. {
  27634. if (pluginWindow != 0)
  27635. {
  27636. XEvent ev;
  27637. zerostruct (ev);
  27638. ev.xmotion.display = display;
  27639. ev.xmotion.type = MotionNotify;
  27640. ev.xmotion.window = pluginWindow;
  27641. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27642. ev.xmotion.time = CurrentTime;
  27643. ev.xmotion.is_hint = NotifyNormal;
  27644. ev.xmotion.x = e.x;
  27645. ev.xmotion.y = e.y;
  27646. ev.xmotion.x_root = e.getScreenX();
  27647. ev.xmotion.y_root = e.getScreenY();
  27648. sendEventToChild (&ev);
  27649. }
  27650. }
  27651. void mouseDrag (const MouseEvent& e)
  27652. {
  27653. if (pluginWindow != 0)
  27654. {
  27655. XEvent ev;
  27656. zerostruct (ev);
  27657. ev.xmotion.display = display;
  27658. ev.xmotion.type = MotionNotify;
  27659. ev.xmotion.window = pluginWindow;
  27660. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27661. ev.xmotion.time = CurrentTime;
  27662. ev.xmotion.x = e.x ;
  27663. ev.xmotion.y = e.y;
  27664. ev.xmotion.x_root = e.getScreenX();
  27665. ev.xmotion.y_root = e.getScreenY();
  27666. ev.xmotion.is_hint = NotifyNormal;
  27667. translateJuceToXMotionModifiers (e, ev);
  27668. sendEventToChild (&ev);
  27669. }
  27670. }
  27671. void mouseUp (const MouseEvent& e)
  27672. {
  27673. if (pluginWindow != 0)
  27674. {
  27675. XEvent ev;
  27676. zerostruct (ev);
  27677. ev.xbutton.display = display;
  27678. ev.xbutton.type = ButtonRelease;
  27679. ev.xbutton.window = pluginWindow;
  27680. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27681. ev.xbutton.time = CurrentTime;
  27682. ev.xbutton.x = e.x;
  27683. ev.xbutton.y = e.y;
  27684. ev.xbutton.x_root = e.getScreenX();
  27685. ev.xbutton.y_root = e.getScreenY();
  27686. translateJuceToXButtonModifiers (e, ev);
  27687. sendEventToChild (&ev);
  27688. }
  27689. }
  27690. void mouseWheelMove (const MouseEvent& e,
  27691. float incrementX,
  27692. float incrementY)
  27693. {
  27694. if (pluginWindow != 0)
  27695. {
  27696. XEvent ev;
  27697. zerostruct (ev);
  27698. ev.xbutton.display = display;
  27699. ev.xbutton.type = ButtonPress;
  27700. ev.xbutton.window = pluginWindow;
  27701. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27702. ev.xbutton.time = CurrentTime;
  27703. ev.xbutton.x = e.x;
  27704. ev.xbutton.y = e.y;
  27705. ev.xbutton.x_root = e.getScreenX();
  27706. ev.xbutton.y_root = e.getScreenY();
  27707. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27708. sendEventToChild (&ev);
  27709. // TODO - put a usleep here ?
  27710. ev.xbutton.type = ButtonRelease;
  27711. sendEventToChild (&ev);
  27712. }
  27713. }
  27714. #endif
  27715. #if JUCE_MAC
  27716. #if ! JUCE_SUPPORT_CARBON
  27717. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27718. #endif
  27719. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27720. {
  27721. public:
  27722. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27723. : owner (owner_),
  27724. alreadyInside (false)
  27725. {
  27726. }
  27727. ~InnerWrapperComponent()
  27728. {
  27729. deleteWindow();
  27730. }
  27731. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27732. {
  27733. owner->openPluginWindow (windowRef);
  27734. return 0;
  27735. }
  27736. void removeView (HIViewRef)
  27737. {
  27738. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27739. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27740. }
  27741. bool getEmbeddedViewSize (int& w, int& h)
  27742. {
  27743. ERect* rect = 0;
  27744. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27745. w = rect->right - rect->left;
  27746. h = rect->bottom - rect->top;
  27747. return true;
  27748. }
  27749. void mouseDown (int x, int y)
  27750. {
  27751. if (! alreadyInside)
  27752. {
  27753. alreadyInside = true;
  27754. getTopLevelComponent()->toFront (true);
  27755. owner->dispatch (effEditMouse, x, y, 0, 0);
  27756. alreadyInside = false;
  27757. }
  27758. else
  27759. {
  27760. PostEvent (::mouseDown, 0);
  27761. }
  27762. }
  27763. void paint()
  27764. {
  27765. ComponentPeer* const peer = getPeer();
  27766. if (peer != 0)
  27767. {
  27768. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27769. ERect r;
  27770. r.left = pos.getX();
  27771. r.right = r.left + getWidth();
  27772. r.top = pos.getY();
  27773. r.bottom = r.top + getHeight();
  27774. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27775. }
  27776. }
  27777. private:
  27778. VSTPluginWindow* const owner;
  27779. bool alreadyInside;
  27780. };
  27781. friend class InnerWrapperComponent;
  27782. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27783. void resized()
  27784. {
  27785. innerWrapper->setSize (getWidth(), getHeight());
  27786. }
  27787. #endif
  27788. private:
  27789. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27790. };
  27791. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27792. {
  27793. if (hasEditor())
  27794. return new VSTPluginWindow (*this);
  27795. return 0;
  27796. }
  27797. void VSTPluginInstance::handleAsyncUpdate()
  27798. {
  27799. // indicates that something about the plugin has changed..
  27800. updateHostDisplay();
  27801. }
  27802. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27803. {
  27804. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27805. {
  27806. changeProgramName (getCurrentProgram(), prog->prgName);
  27807. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27808. setParameter (i, vst_swapFloat (prog->params[i]));
  27809. return true;
  27810. }
  27811. return false;
  27812. }
  27813. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27814. const int dataSize)
  27815. {
  27816. if (dataSize < 28)
  27817. return false;
  27818. const fxSet* const set = (const fxSet*) data;
  27819. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27820. || vst_swap (set->version) > fxbVersionNum)
  27821. return false;
  27822. if (vst_swap (set->fxMagic) == 'FxBk')
  27823. {
  27824. // bank of programs
  27825. if (vst_swap (set->numPrograms) >= 0)
  27826. {
  27827. const int oldProg = getCurrentProgram();
  27828. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27829. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27830. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27831. {
  27832. if (i != oldProg)
  27833. {
  27834. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27835. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27836. return false;
  27837. if (vst_swap (set->numPrograms) > 0)
  27838. setCurrentProgram (i);
  27839. if (! restoreProgramSettings (prog))
  27840. return false;
  27841. }
  27842. }
  27843. if (vst_swap (set->numPrograms) > 0)
  27844. setCurrentProgram (oldProg);
  27845. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27846. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27847. return false;
  27848. if (! restoreProgramSettings (prog))
  27849. return false;
  27850. }
  27851. }
  27852. else if (vst_swap (set->fxMagic) == 'FxCk')
  27853. {
  27854. // single program
  27855. const fxProgram* const prog = (const fxProgram*) data;
  27856. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27857. return false;
  27858. changeProgramName (getCurrentProgram(), prog->prgName);
  27859. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27860. setParameter (i, vst_swapFloat (prog->params[i]));
  27861. }
  27862. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27863. {
  27864. // non-preset chunk
  27865. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27866. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27867. return false;
  27868. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27869. }
  27870. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27871. {
  27872. // preset chunk
  27873. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27874. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27875. return false;
  27876. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27877. changeProgramName (getCurrentProgram(), cset->name);
  27878. }
  27879. else
  27880. {
  27881. return false;
  27882. }
  27883. return true;
  27884. }
  27885. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27886. {
  27887. const int numParams = getNumParameters();
  27888. prog->chunkMagic = vst_swap ('CcnK');
  27889. prog->byteSize = 0;
  27890. prog->fxMagic = vst_swap ('FxCk');
  27891. prog->version = vst_swap (fxbVersionNum);
  27892. prog->fxID = vst_swap (getUID());
  27893. prog->fxVersion = vst_swap (getVersionNumber());
  27894. prog->numParams = vst_swap (numParams);
  27895. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27896. for (int i = 0; i < numParams; ++i)
  27897. prog->params[i] = vst_swapFloat (getParameter (i));
  27898. }
  27899. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27900. {
  27901. const int numPrograms = getNumPrograms();
  27902. const int numParams = getNumParameters();
  27903. if (usesChunks())
  27904. {
  27905. if (isFXB)
  27906. {
  27907. MemoryBlock chunk;
  27908. getChunkData (chunk, false, maxSizeMB);
  27909. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27910. dest.setSize (totalLen, true);
  27911. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27912. set->chunkMagic = vst_swap ('CcnK');
  27913. set->byteSize = 0;
  27914. set->fxMagic = vst_swap ('FBCh');
  27915. set->version = vst_swap (fxbVersionNum);
  27916. set->fxID = vst_swap (getUID());
  27917. set->fxVersion = vst_swap (getVersionNumber());
  27918. set->numPrograms = vst_swap (numPrograms);
  27919. set->chunkSize = vst_swap ((long) chunk.getSize());
  27920. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27921. }
  27922. else
  27923. {
  27924. MemoryBlock chunk;
  27925. getChunkData (chunk, true, maxSizeMB);
  27926. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27927. dest.setSize (totalLen, true);
  27928. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27929. set->chunkMagic = vst_swap ('CcnK');
  27930. set->byteSize = 0;
  27931. set->fxMagic = vst_swap ('FPCh');
  27932. set->version = vst_swap (fxbVersionNum);
  27933. set->fxID = vst_swap (getUID());
  27934. set->fxVersion = vst_swap (getVersionNumber());
  27935. set->numPrograms = vst_swap (numPrograms);
  27936. set->chunkSize = vst_swap ((long) chunk.getSize());
  27937. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27938. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27939. }
  27940. }
  27941. else
  27942. {
  27943. if (isFXB)
  27944. {
  27945. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27946. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27947. dest.setSize (len, true);
  27948. fxSet* const set = (fxSet*) dest.getData();
  27949. set->chunkMagic = vst_swap ('CcnK');
  27950. set->byteSize = 0;
  27951. set->fxMagic = vst_swap ('FxBk');
  27952. set->version = vst_swap (fxbVersionNum);
  27953. set->fxID = vst_swap (getUID());
  27954. set->fxVersion = vst_swap (getVersionNumber());
  27955. set->numPrograms = vst_swap (numPrograms);
  27956. const int oldProgram = getCurrentProgram();
  27957. MemoryBlock oldSettings;
  27958. createTempParameterStore (oldSettings);
  27959. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27960. for (int i = 0; i < numPrograms; ++i)
  27961. {
  27962. if (i != oldProgram)
  27963. {
  27964. setCurrentProgram (i);
  27965. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27966. }
  27967. }
  27968. setCurrentProgram (oldProgram);
  27969. restoreFromTempParameterStore (oldSettings);
  27970. }
  27971. else
  27972. {
  27973. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27974. dest.setSize (totalLen, true);
  27975. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27976. }
  27977. }
  27978. return true;
  27979. }
  27980. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27981. {
  27982. if (usesChunks())
  27983. {
  27984. void* data = 0;
  27985. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27986. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27987. {
  27988. mb.setSize (bytes);
  27989. mb.copyFrom (data, 0, bytes);
  27990. }
  27991. }
  27992. }
  27993. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27994. {
  27995. if (size > 0 && usesChunks())
  27996. {
  27997. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27998. if (! isPreset)
  27999. updateStoredProgramNames();
  28000. }
  28001. }
  28002. void VSTPluginInstance::timerCallback()
  28003. {
  28004. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28005. stopTimer();
  28006. }
  28007. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28008. {
  28009. const ScopedLock sl (lock);
  28010. ++insideVSTCallback;
  28011. int result = 0;
  28012. try
  28013. {
  28014. if (effect != 0)
  28015. {
  28016. #if JUCE_MAC
  28017. if (module->resFileId != 0)
  28018. UseResFile (module->resFileId);
  28019. #endif
  28020. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28021. #if JUCE_MAC
  28022. module->resFileId = CurResFile();
  28023. #endif
  28024. --insideVSTCallback;
  28025. return result;
  28026. }
  28027. }
  28028. catch (...)
  28029. {
  28030. }
  28031. --insideVSTCallback;
  28032. return result;
  28033. }
  28034. namespace
  28035. {
  28036. static const int defaultVSTSampleRateValue = 16384;
  28037. static const int defaultVSTBlockSizeValue = 512;
  28038. // handles non plugin-specific callbacks..
  28039. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28040. {
  28041. (void) index;
  28042. (void) value;
  28043. (void) opt;
  28044. switch (opcode)
  28045. {
  28046. case audioMasterCanDo:
  28047. {
  28048. static const char* canDos[] = { "supplyIdle",
  28049. "sendVstEvents",
  28050. "sendVstMidiEvent",
  28051. "sendVstTimeInfo",
  28052. "receiveVstEvents",
  28053. "receiveVstMidiEvent",
  28054. "supportShell",
  28055. "shellCategory" };
  28056. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28057. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28058. return 1;
  28059. return 0;
  28060. }
  28061. case audioMasterVersion: return 0x2400;
  28062. case audioMasterCurrentId: return shellUIDToCreate;
  28063. case audioMasterGetNumAutomatableParameters: return 0;
  28064. case audioMasterGetAutomationState: return 1;
  28065. case audioMasterGetVendorVersion: return 0x0101;
  28066. case audioMasterGetVendorString:
  28067. case audioMasterGetProductString:
  28068. {
  28069. String hostName ("Juce VST Host");
  28070. if (JUCEApplication::getInstance() != 0)
  28071. hostName = JUCEApplication::getInstance()->getApplicationName();
  28072. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28073. break;
  28074. }
  28075. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28076. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28077. case audioMasterSetOutputSampleRate: return 0;
  28078. default:
  28079. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28080. break;
  28081. }
  28082. return 0;
  28083. }
  28084. }
  28085. // handles callbacks for a specific plugin
  28086. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28087. {
  28088. switch (opcode)
  28089. {
  28090. case audioMasterAutomate:
  28091. sendParamChangeMessageToListeners (index, opt);
  28092. break;
  28093. case audioMasterProcessEvents:
  28094. handleMidiFromPlugin ((const VstEvents*) ptr);
  28095. break;
  28096. case audioMasterGetTime:
  28097. #if JUCE_MSVC
  28098. #pragma warning (push)
  28099. #pragma warning (disable: 4311)
  28100. #endif
  28101. return (VstIntPtr) &vstHostTime;
  28102. #if JUCE_MSVC
  28103. #pragma warning (pop)
  28104. #endif
  28105. break;
  28106. case audioMasterIdle:
  28107. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28108. {
  28109. ++insideVSTCallback;
  28110. #if JUCE_MAC
  28111. if (getActiveEditor() != 0)
  28112. dispatch (effEditIdle, 0, 0, 0, 0);
  28113. #endif
  28114. juce_callAnyTimersSynchronously();
  28115. handleUpdateNowIfNeeded();
  28116. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28117. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28118. --insideVSTCallback;
  28119. }
  28120. break;
  28121. case audioMasterUpdateDisplay:
  28122. triggerAsyncUpdate();
  28123. break;
  28124. case audioMasterTempoAt:
  28125. // returns (10000 * bpm)
  28126. break;
  28127. case audioMasterNeedIdle:
  28128. startTimer (50);
  28129. break;
  28130. case audioMasterSizeWindow:
  28131. if (getActiveEditor() != 0)
  28132. getActiveEditor()->setSize (index, value);
  28133. return 1;
  28134. case audioMasterGetSampleRate:
  28135. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28136. case audioMasterGetBlockSize:
  28137. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28138. case audioMasterWantMidi:
  28139. wantsMidiMessages = true;
  28140. break;
  28141. case audioMasterGetDirectory:
  28142. #if JUCE_MAC
  28143. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28144. #else
  28145. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8().getAddress();
  28146. #endif
  28147. case audioMasterGetAutomationState:
  28148. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28149. break;
  28150. // none of these are handled (yet)..
  28151. case audioMasterBeginEdit:
  28152. case audioMasterEndEdit:
  28153. case audioMasterSetTime:
  28154. case audioMasterPinConnected:
  28155. case audioMasterGetParameterQuantization:
  28156. case audioMasterIOChanged:
  28157. case audioMasterGetInputLatency:
  28158. case audioMasterGetOutputLatency:
  28159. case audioMasterGetPreviousPlug:
  28160. case audioMasterGetNextPlug:
  28161. case audioMasterWillReplaceOrAccumulate:
  28162. case audioMasterGetCurrentProcessLevel:
  28163. case audioMasterOfflineStart:
  28164. case audioMasterOfflineRead:
  28165. case audioMasterOfflineWrite:
  28166. case audioMasterOfflineGetCurrentPass:
  28167. case audioMasterOfflineGetCurrentMetaPass:
  28168. case audioMasterVendorSpecific:
  28169. case audioMasterSetIcon:
  28170. case audioMasterGetLanguage:
  28171. case audioMasterOpenWindow:
  28172. case audioMasterCloseWindow:
  28173. break;
  28174. default:
  28175. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28176. }
  28177. return 0;
  28178. }
  28179. // entry point for all callbacks from the plugin
  28180. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28181. {
  28182. try
  28183. {
  28184. if (effect != 0 && effect->resvd2 != 0)
  28185. {
  28186. return ((VSTPluginInstance*)(effect->resvd2))
  28187. ->handleCallback (opcode, index, value, ptr, opt);
  28188. }
  28189. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28190. }
  28191. catch (...)
  28192. {
  28193. return 0;
  28194. }
  28195. }
  28196. const String VSTPluginInstance::getVersion() const
  28197. {
  28198. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28199. String s;
  28200. if (v == 0 || v == -1)
  28201. v = getVersionNumber();
  28202. if (v != 0)
  28203. {
  28204. int versionBits[4];
  28205. int n = 0;
  28206. while (v != 0)
  28207. {
  28208. versionBits [n++] = (v & 0xff);
  28209. v >>= 8;
  28210. }
  28211. s << 'V';
  28212. while (n > 0)
  28213. {
  28214. s << versionBits [--n];
  28215. if (n > 0)
  28216. s << '.';
  28217. }
  28218. }
  28219. return s;
  28220. }
  28221. int VSTPluginInstance::getUID() const
  28222. {
  28223. int uid = effect != 0 ? effect->uniqueID : 0;
  28224. if (uid == 0)
  28225. uid = module->file.hashCode();
  28226. return uid;
  28227. }
  28228. const String VSTPluginInstance::getCategory() const
  28229. {
  28230. const char* result = 0;
  28231. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28232. {
  28233. case kPlugCategEffect: result = "Effect"; break;
  28234. case kPlugCategSynth: result = "Synth"; break;
  28235. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28236. case kPlugCategMastering: result = "Mastering"; break;
  28237. case kPlugCategSpacializer: result = "Spacial"; break;
  28238. case kPlugCategRoomFx: result = "Reverb"; break;
  28239. case kPlugSurroundFx: result = "Surround"; break;
  28240. case kPlugCategRestoration: result = "Restoration"; break;
  28241. case kPlugCategGenerator: result = "Tone generation"; break;
  28242. default: break;
  28243. }
  28244. return result;
  28245. }
  28246. float VSTPluginInstance::getParameter (int index)
  28247. {
  28248. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28249. {
  28250. try
  28251. {
  28252. const ScopedLock sl (lock);
  28253. return effect->getParameter (effect, index);
  28254. }
  28255. catch (...)
  28256. {
  28257. }
  28258. }
  28259. return 0.0f;
  28260. }
  28261. void VSTPluginInstance::setParameter (int index, float newValue)
  28262. {
  28263. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28264. {
  28265. try
  28266. {
  28267. const ScopedLock sl (lock);
  28268. if (effect->getParameter (effect, index) != newValue)
  28269. effect->setParameter (effect, index, newValue);
  28270. }
  28271. catch (...)
  28272. {
  28273. }
  28274. }
  28275. }
  28276. const String VSTPluginInstance::getParameterName (int index)
  28277. {
  28278. if (effect != 0)
  28279. {
  28280. jassert (index >= 0 && index < effect->numParams);
  28281. char nm [256];
  28282. zerostruct (nm);
  28283. dispatch (effGetParamName, index, 0, nm, 0);
  28284. return String (nm).trim();
  28285. }
  28286. return String::empty;
  28287. }
  28288. const String VSTPluginInstance::getParameterLabel (int index) const
  28289. {
  28290. if (effect != 0)
  28291. {
  28292. jassert (index >= 0 && index < effect->numParams);
  28293. char nm [256];
  28294. zerostruct (nm);
  28295. dispatch (effGetParamLabel, index, 0, nm, 0);
  28296. return String (nm).trim();
  28297. }
  28298. return String::empty;
  28299. }
  28300. const String VSTPluginInstance::getParameterText (int index)
  28301. {
  28302. if (effect != 0)
  28303. {
  28304. jassert (index >= 0 && index < effect->numParams);
  28305. char nm [256];
  28306. zerostruct (nm);
  28307. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28308. return String (nm).trim();
  28309. }
  28310. return String::empty;
  28311. }
  28312. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28313. {
  28314. if (effect != 0)
  28315. {
  28316. jassert (index >= 0 && index < effect->numParams);
  28317. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28318. }
  28319. return false;
  28320. }
  28321. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28322. {
  28323. dest.setSize (64 + 4 * getNumParameters());
  28324. dest.fillWith (0);
  28325. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28326. float* const p = (float*) (((char*) dest.getData()) + 64);
  28327. for (int i = 0; i < getNumParameters(); ++i)
  28328. p[i] = getParameter(i);
  28329. }
  28330. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28331. {
  28332. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28333. float* p = (float*) (((char*) m.getData()) + 64);
  28334. for (int i = 0; i < getNumParameters(); ++i)
  28335. setParameter (i, p[i]);
  28336. }
  28337. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28338. {
  28339. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28340. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28341. }
  28342. const String VSTPluginInstance::getProgramName (int index)
  28343. {
  28344. if (index == getCurrentProgram())
  28345. {
  28346. return getCurrentProgramName();
  28347. }
  28348. else if (effect != 0)
  28349. {
  28350. char nm [256];
  28351. zerostruct (nm);
  28352. if (dispatch (effGetProgramNameIndexed,
  28353. jlimit (0, getNumPrograms(), index),
  28354. -1, nm, 0) != 0)
  28355. {
  28356. return String (nm).trim();
  28357. }
  28358. }
  28359. return programNames [index];
  28360. }
  28361. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28362. {
  28363. if (index == getCurrentProgram())
  28364. {
  28365. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28366. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28367. }
  28368. else
  28369. {
  28370. jassertfalse; // xxx not implemented!
  28371. }
  28372. }
  28373. void VSTPluginInstance::updateStoredProgramNames()
  28374. {
  28375. if (effect != 0 && getNumPrograms() > 0)
  28376. {
  28377. char nm [256];
  28378. zerostruct (nm);
  28379. // only do this if the plugin can't use indexed names..
  28380. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28381. {
  28382. const int oldProgram = getCurrentProgram();
  28383. MemoryBlock oldSettings;
  28384. createTempParameterStore (oldSettings);
  28385. for (int i = 0; i < getNumPrograms(); ++i)
  28386. {
  28387. setCurrentProgram (i);
  28388. getCurrentProgramName(); // (this updates the list)
  28389. }
  28390. setCurrentProgram (oldProgram);
  28391. restoreFromTempParameterStore (oldSettings);
  28392. }
  28393. }
  28394. }
  28395. const String VSTPluginInstance::getCurrentProgramName()
  28396. {
  28397. if (effect != 0)
  28398. {
  28399. char nm [256];
  28400. zerostruct (nm);
  28401. dispatch (effGetProgramName, 0, 0, nm, 0);
  28402. const int index = getCurrentProgram();
  28403. if (programNames[index].isEmpty())
  28404. {
  28405. while (programNames.size() < index)
  28406. programNames.add (String::empty);
  28407. programNames.set (index, String (nm).trim());
  28408. }
  28409. return String (nm).trim();
  28410. }
  28411. return String::empty;
  28412. }
  28413. const String VSTPluginInstance::getInputChannelName (int index) const
  28414. {
  28415. if (index >= 0 && index < getNumInputChannels())
  28416. {
  28417. VstPinProperties pinProps;
  28418. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28419. return String (pinProps.label, sizeof (pinProps.label));
  28420. }
  28421. return String::empty;
  28422. }
  28423. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28424. {
  28425. if (index < 0 || index >= getNumInputChannels())
  28426. return false;
  28427. VstPinProperties pinProps;
  28428. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28429. return (pinProps.flags & kVstPinIsStereo) != 0;
  28430. return true;
  28431. }
  28432. const String VSTPluginInstance::getOutputChannelName (int index) const
  28433. {
  28434. if (index >= 0 && index < getNumOutputChannels())
  28435. {
  28436. VstPinProperties pinProps;
  28437. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28438. return String (pinProps.label, sizeof (pinProps.label));
  28439. }
  28440. return String::empty;
  28441. }
  28442. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28443. {
  28444. if (index < 0 || index >= getNumOutputChannels())
  28445. return false;
  28446. VstPinProperties pinProps;
  28447. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28448. return (pinProps.flags & kVstPinIsStereo) != 0;
  28449. return true;
  28450. }
  28451. void VSTPluginInstance::setPower (const bool on)
  28452. {
  28453. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28454. isPowerOn = on;
  28455. }
  28456. const int defaultMaxSizeMB = 64;
  28457. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28458. {
  28459. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28460. }
  28461. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28462. {
  28463. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28464. }
  28465. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28466. {
  28467. loadFromFXBFile (data, sizeInBytes);
  28468. }
  28469. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28470. {
  28471. loadFromFXBFile (data, sizeInBytes);
  28472. }
  28473. VSTPluginFormat::VSTPluginFormat()
  28474. {
  28475. }
  28476. VSTPluginFormat::~VSTPluginFormat()
  28477. {
  28478. }
  28479. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28480. const String& fileOrIdentifier)
  28481. {
  28482. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28483. return;
  28484. PluginDescription desc;
  28485. desc.fileOrIdentifier = fileOrIdentifier;
  28486. desc.uid = 0;
  28487. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28488. if (instance == 0)
  28489. return;
  28490. try
  28491. {
  28492. #if JUCE_MAC
  28493. if (instance->module->resFileId != 0)
  28494. UseResFile (instance->module->resFileId);
  28495. #endif
  28496. instance->fillInPluginDescription (desc);
  28497. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28498. if (category != kPlugCategShell)
  28499. {
  28500. // Normal plugin...
  28501. results.add (new PluginDescription (desc));
  28502. ++insideVSTCallback;
  28503. instance->dispatch (effOpen, 0, 0, 0, 0);
  28504. --insideVSTCallback;
  28505. }
  28506. else
  28507. {
  28508. // It's a shell plugin, so iterate all the subtypes...
  28509. char shellEffectName [64];
  28510. for (;;)
  28511. {
  28512. zerostruct (shellEffectName);
  28513. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28514. if (uid == 0)
  28515. {
  28516. break;
  28517. }
  28518. else
  28519. {
  28520. desc.uid = uid;
  28521. desc.name = shellEffectName;
  28522. desc.descriptiveName = shellEffectName;
  28523. bool alreadyThere = false;
  28524. for (int i = results.size(); --i >= 0;)
  28525. {
  28526. PluginDescription* const d = results.getUnchecked(i);
  28527. if (d->isDuplicateOf (desc))
  28528. {
  28529. alreadyThere = true;
  28530. break;
  28531. }
  28532. }
  28533. if (! alreadyThere)
  28534. results.add (new PluginDescription (desc));
  28535. }
  28536. }
  28537. }
  28538. }
  28539. catch (...)
  28540. {
  28541. // crashed while loading...
  28542. }
  28543. }
  28544. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28545. {
  28546. ScopedPointer <VSTPluginInstance> result;
  28547. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28548. {
  28549. File file (desc.fileOrIdentifier);
  28550. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28551. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28552. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28553. if (module != 0)
  28554. {
  28555. shellUIDToCreate = desc.uid;
  28556. result = new VSTPluginInstance (module);
  28557. if (result->effect != 0)
  28558. {
  28559. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28560. result->initialise();
  28561. }
  28562. else
  28563. {
  28564. result = 0;
  28565. }
  28566. }
  28567. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28568. }
  28569. return result.release();
  28570. }
  28571. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28572. {
  28573. const File f (fileOrIdentifier);
  28574. #if JUCE_MAC
  28575. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28576. return true;
  28577. #if JUCE_PPC
  28578. FSRef fileRef;
  28579. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28580. {
  28581. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28582. if (resFileId != -1)
  28583. {
  28584. const int numEffects = Count1Resources ('aEff');
  28585. CloseResFile (resFileId);
  28586. if (numEffects > 0)
  28587. return true;
  28588. }
  28589. }
  28590. #endif
  28591. return false;
  28592. #elif JUCE_WINDOWS
  28593. return f.existsAsFile() && f.hasFileExtension (".dll");
  28594. #elif JUCE_LINUX
  28595. return f.existsAsFile() && f.hasFileExtension (".so");
  28596. #endif
  28597. }
  28598. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28599. {
  28600. return fileOrIdentifier;
  28601. }
  28602. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28603. {
  28604. return File (desc.fileOrIdentifier).exists();
  28605. }
  28606. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28607. {
  28608. StringArray results;
  28609. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28610. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28611. return results;
  28612. }
  28613. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28614. {
  28615. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28616. // .component or .vst directories.
  28617. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28618. while (iter.next())
  28619. {
  28620. const File f (iter.getFile());
  28621. bool isPlugin = false;
  28622. if (fileMightContainThisPluginType (f.getFullPathName()))
  28623. {
  28624. isPlugin = true;
  28625. results.add (f.getFullPathName());
  28626. }
  28627. if (recursive && (! isPlugin) && f.isDirectory())
  28628. recursiveFileSearch (results, f, true);
  28629. }
  28630. }
  28631. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28632. {
  28633. #if JUCE_MAC
  28634. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28635. #elif JUCE_WINDOWS
  28636. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28637. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28638. #elif JUCE_LINUX
  28639. return FileSearchPath ("/usr/lib/vst");
  28640. #endif
  28641. }
  28642. END_JUCE_NAMESPACE
  28643. #endif
  28644. #undef log
  28645. #endif
  28646. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28647. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28648. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28649. BEGIN_JUCE_NAMESPACE
  28650. AudioProcessor::AudioProcessor()
  28651. : playHead (0),
  28652. sampleRate (0),
  28653. blockSize (0),
  28654. numInputChannels (0),
  28655. numOutputChannels (0),
  28656. latencySamples (0),
  28657. suspended (false),
  28658. nonRealtime (false)
  28659. {
  28660. }
  28661. AudioProcessor::~AudioProcessor()
  28662. {
  28663. // ooh, nasty - the editor should have been deleted before the filter
  28664. // that it refers to is deleted..
  28665. jassert (activeEditor == 0);
  28666. #if JUCE_DEBUG
  28667. // This will fail if you've called beginParameterChangeGesture() for one
  28668. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28669. jassert (changingParams.countNumberOfSetBits() == 0);
  28670. #endif
  28671. }
  28672. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28673. {
  28674. playHead = newPlayHead;
  28675. }
  28676. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28677. {
  28678. const ScopedLock sl (listenerLock);
  28679. listeners.addIfNotAlreadyThere (newListener);
  28680. }
  28681. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28682. {
  28683. const ScopedLock sl (listenerLock);
  28684. listeners.removeValue (listenerToRemove);
  28685. }
  28686. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28687. const int numOuts,
  28688. const double sampleRate_,
  28689. const int blockSize_) throw()
  28690. {
  28691. numInputChannels = numIns;
  28692. numOutputChannels = numOuts;
  28693. sampleRate = sampleRate_;
  28694. blockSize = blockSize_;
  28695. }
  28696. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28697. {
  28698. nonRealtime = nonRealtime_;
  28699. }
  28700. void AudioProcessor::setLatencySamples (const int newLatency)
  28701. {
  28702. if (latencySamples != newLatency)
  28703. {
  28704. latencySamples = newLatency;
  28705. updateHostDisplay();
  28706. }
  28707. }
  28708. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28709. const float newValue)
  28710. {
  28711. setParameter (parameterIndex, newValue);
  28712. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28713. }
  28714. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28715. {
  28716. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28717. for (int i = listeners.size(); --i >= 0;)
  28718. {
  28719. AudioProcessorListener* l;
  28720. {
  28721. const ScopedLock sl (listenerLock);
  28722. l = listeners [i];
  28723. }
  28724. if (l != 0)
  28725. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28726. }
  28727. }
  28728. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28729. {
  28730. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28731. #if JUCE_DEBUG
  28732. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28733. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28734. jassert (! changingParams [parameterIndex]);
  28735. changingParams.setBit (parameterIndex);
  28736. #endif
  28737. for (int i = listeners.size(); --i >= 0;)
  28738. {
  28739. AudioProcessorListener* l;
  28740. {
  28741. const ScopedLock sl (listenerLock);
  28742. l = listeners [i];
  28743. }
  28744. if (l != 0)
  28745. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28746. }
  28747. }
  28748. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28749. {
  28750. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28751. #if JUCE_DEBUG
  28752. // This means you've called endParameterChangeGesture without having previously called
  28753. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28754. // calls matched correctly.
  28755. jassert (changingParams [parameterIndex]);
  28756. changingParams.clearBit (parameterIndex);
  28757. #endif
  28758. for (int i = listeners.size(); --i >= 0;)
  28759. {
  28760. AudioProcessorListener* l;
  28761. {
  28762. const ScopedLock sl (listenerLock);
  28763. l = listeners [i];
  28764. }
  28765. if (l != 0)
  28766. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28767. }
  28768. }
  28769. void AudioProcessor::updateHostDisplay()
  28770. {
  28771. for (int i = listeners.size(); --i >= 0;)
  28772. {
  28773. AudioProcessorListener* l;
  28774. {
  28775. const ScopedLock sl (listenerLock);
  28776. l = listeners [i];
  28777. }
  28778. if (l != 0)
  28779. l->audioProcessorChanged (this);
  28780. }
  28781. }
  28782. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28783. {
  28784. return true;
  28785. }
  28786. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28787. {
  28788. return false;
  28789. }
  28790. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28791. {
  28792. const ScopedLock sl (callbackLock);
  28793. suspended = shouldBeSuspended;
  28794. }
  28795. void AudioProcessor::reset()
  28796. {
  28797. }
  28798. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28799. {
  28800. const ScopedLock sl (callbackLock);
  28801. if (activeEditor == editor)
  28802. activeEditor = 0;
  28803. }
  28804. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28805. {
  28806. if (activeEditor != 0)
  28807. return activeEditor;
  28808. AudioProcessorEditor* const ed = createEditor();
  28809. // You must make your hasEditor() method return a consistent result!
  28810. jassert (hasEditor() == (ed != 0));
  28811. if (ed != 0)
  28812. {
  28813. // you must give your editor comp a size before returning it..
  28814. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28815. const ScopedLock sl (callbackLock);
  28816. activeEditor = ed;
  28817. }
  28818. return ed;
  28819. }
  28820. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28821. {
  28822. getStateInformation (destData);
  28823. }
  28824. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28825. {
  28826. setStateInformation (data, sizeInBytes);
  28827. }
  28828. // magic number to identify memory blocks that we've stored as XML
  28829. const uint32 magicXmlNumber = 0x21324356;
  28830. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28831. JUCE_NAMESPACE::MemoryBlock& destData)
  28832. {
  28833. const String xmlString (xml.createDocument (String::empty, true, false));
  28834. const int stringLength = xmlString.getNumBytesAsUTF8();
  28835. destData.setSize (stringLength + 10);
  28836. char* const d = static_cast<char*> (destData.getData());
  28837. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28838. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28839. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28840. }
  28841. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28842. const int sizeInBytes)
  28843. {
  28844. if (sizeInBytes > 8
  28845. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28846. {
  28847. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28848. if (stringLength > 0)
  28849. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28850. jmin ((sizeInBytes - 8), stringLength)));
  28851. }
  28852. return 0;
  28853. }
  28854. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28855. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28856. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28857. {
  28858. return timeInSeconds == other.timeInSeconds
  28859. && ppqPosition == other.ppqPosition
  28860. && editOriginTime == other.editOriginTime
  28861. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28862. && frameRate == other.frameRate
  28863. && isPlaying == other.isPlaying
  28864. && isRecording == other.isRecording
  28865. && bpm == other.bpm
  28866. && timeSigNumerator == other.timeSigNumerator
  28867. && timeSigDenominator == other.timeSigDenominator;
  28868. }
  28869. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28870. {
  28871. return ! operator== (other);
  28872. }
  28873. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28874. {
  28875. zerostruct (*this);
  28876. timeSigNumerator = 4;
  28877. timeSigDenominator = 4;
  28878. bpm = 120;
  28879. }
  28880. END_JUCE_NAMESPACE
  28881. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28882. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28883. BEGIN_JUCE_NAMESPACE
  28884. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28885. : owner (owner_)
  28886. {
  28887. // the filter must be valid..
  28888. jassert (owner != 0);
  28889. }
  28890. AudioProcessorEditor::~AudioProcessorEditor()
  28891. {
  28892. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28893. // filter for some reason..
  28894. jassert (owner->getActiveEditor() != this);
  28895. }
  28896. END_JUCE_NAMESPACE
  28897. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28898. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28899. BEGIN_JUCE_NAMESPACE
  28900. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28901. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28902. : id (id_),
  28903. processor (processor_),
  28904. isPrepared (false)
  28905. {
  28906. jassert (processor_ != 0);
  28907. }
  28908. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28909. AudioProcessorGraph* const graph)
  28910. {
  28911. if (! isPrepared)
  28912. {
  28913. isPrepared = true;
  28914. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28915. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28916. if (ioProc != 0)
  28917. ioProc->setParentGraph (graph);
  28918. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28919. processor->getNumOutputChannels(),
  28920. sampleRate, blockSize);
  28921. processor->prepareToPlay (sampleRate, blockSize);
  28922. }
  28923. }
  28924. void AudioProcessorGraph::Node::unprepare()
  28925. {
  28926. if (isPrepared)
  28927. {
  28928. isPrepared = false;
  28929. processor->releaseResources();
  28930. }
  28931. }
  28932. AudioProcessorGraph::AudioProcessorGraph()
  28933. : lastNodeId (0),
  28934. renderingBuffers (1, 1),
  28935. currentAudioOutputBuffer (1, 1)
  28936. {
  28937. }
  28938. AudioProcessorGraph::~AudioProcessorGraph()
  28939. {
  28940. clearRenderingSequence();
  28941. clear();
  28942. }
  28943. const String AudioProcessorGraph::getName() const
  28944. {
  28945. return "Audio Graph";
  28946. }
  28947. void AudioProcessorGraph::clear()
  28948. {
  28949. nodes.clear();
  28950. connections.clear();
  28951. triggerAsyncUpdate();
  28952. }
  28953. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28954. {
  28955. for (int i = nodes.size(); --i >= 0;)
  28956. if (nodes.getUnchecked(i)->id == nodeId)
  28957. return nodes.getUnchecked(i);
  28958. return 0;
  28959. }
  28960. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28961. uint32 nodeId)
  28962. {
  28963. if (newProcessor == 0)
  28964. {
  28965. jassertfalse;
  28966. return 0;
  28967. }
  28968. if (nodeId == 0)
  28969. {
  28970. nodeId = ++lastNodeId;
  28971. }
  28972. else
  28973. {
  28974. // you can't add a node with an id that already exists in the graph..
  28975. jassert (getNodeForId (nodeId) == 0);
  28976. removeNode (nodeId);
  28977. }
  28978. lastNodeId = nodeId;
  28979. Node* const n = new Node (nodeId, newProcessor);
  28980. nodes.add (n);
  28981. triggerAsyncUpdate();
  28982. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28983. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  28984. if (ioProc != 0)
  28985. ioProc->setParentGraph (this);
  28986. return n;
  28987. }
  28988. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28989. {
  28990. disconnectNode (nodeId);
  28991. for (int i = nodes.size(); --i >= 0;)
  28992. {
  28993. if (nodes.getUnchecked(i)->id == nodeId)
  28994. {
  28995. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28996. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  28997. if (ioProc != 0)
  28998. ioProc->setParentGraph (0);
  28999. nodes.remove (i);
  29000. triggerAsyncUpdate();
  29001. return true;
  29002. }
  29003. }
  29004. return false;
  29005. }
  29006. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29007. const int sourceChannelIndex,
  29008. const uint32 destNodeId,
  29009. const int destChannelIndex) const
  29010. {
  29011. for (int i = connections.size(); --i >= 0;)
  29012. {
  29013. const Connection* const c = connections.getUnchecked(i);
  29014. if (c->sourceNodeId == sourceNodeId
  29015. && c->destNodeId == destNodeId
  29016. && c->sourceChannelIndex == sourceChannelIndex
  29017. && c->destChannelIndex == destChannelIndex)
  29018. {
  29019. return c;
  29020. }
  29021. }
  29022. return 0;
  29023. }
  29024. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29025. const uint32 possibleDestNodeId) const
  29026. {
  29027. for (int i = connections.size(); --i >= 0;)
  29028. {
  29029. const Connection* const c = connections.getUnchecked(i);
  29030. if (c->sourceNodeId == possibleSourceNodeId
  29031. && c->destNodeId == possibleDestNodeId)
  29032. {
  29033. return true;
  29034. }
  29035. }
  29036. return false;
  29037. }
  29038. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29039. const int sourceChannelIndex,
  29040. const uint32 destNodeId,
  29041. const int destChannelIndex) const
  29042. {
  29043. if (sourceChannelIndex < 0
  29044. || destChannelIndex < 0
  29045. || sourceNodeId == destNodeId
  29046. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29047. return false;
  29048. const Node* const source = getNodeForId (sourceNodeId);
  29049. if (source == 0
  29050. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29051. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29052. return false;
  29053. const Node* const dest = getNodeForId (destNodeId);
  29054. if (dest == 0
  29055. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29056. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29057. return false;
  29058. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29059. destNodeId, destChannelIndex) == 0;
  29060. }
  29061. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29062. const int sourceChannelIndex,
  29063. const uint32 destNodeId,
  29064. const int destChannelIndex)
  29065. {
  29066. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29067. return false;
  29068. Connection* const c = new Connection();
  29069. c->sourceNodeId = sourceNodeId;
  29070. c->sourceChannelIndex = sourceChannelIndex;
  29071. c->destNodeId = destNodeId;
  29072. c->destChannelIndex = destChannelIndex;
  29073. connections.add (c);
  29074. triggerAsyncUpdate();
  29075. return true;
  29076. }
  29077. void AudioProcessorGraph::removeConnection (const int index)
  29078. {
  29079. connections.remove (index);
  29080. triggerAsyncUpdate();
  29081. }
  29082. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29083. const uint32 destNodeId, const int destChannelIndex)
  29084. {
  29085. bool doneAnything = false;
  29086. for (int i = connections.size(); --i >= 0;)
  29087. {
  29088. const Connection* const c = connections.getUnchecked(i);
  29089. if (c->sourceNodeId == sourceNodeId
  29090. && c->destNodeId == destNodeId
  29091. && c->sourceChannelIndex == sourceChannelIndex
  29092. && c->destChannelIndex == destChannelIndex)
  29093. {
  29094. removeConnection (i);
  29095. doneAnything = true;
  29096. triggerAsyncUpdate();
  29097. }
  29098. }
  29099. return doneAnything;
  29100. }
  29101. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29102. {
  29103. bool doneAnything = false;
  29104. for (int i = connections.size(); --i >= 0;)
  29105. {
  29106. const Connection* const c = connections.getUnchecked(i);
  29107. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29108. {
  29109. removeConnection (i);
  29110. doneAnything = true;
  29111. triggerAsyncUpdate();
  29112. }
  29113. }
  29114. return doneAnything;
  29115. }
  29116. bool AudioProcessorGraph::removeIllegalConnections()
  29117. {
  29118. bool doneAnything = false;
  29119. for (int i = connections.size(); --i >= 0;)
  29120. {
  29121. const Connection* const c = connections.getUnchecked(i);
  29122. const Node* const source = getNodeForId (c->sourceNodeId);
  29123. const Node* const dest = getNodeForId (c->destNodeId);
  29124. if (source == 0 || dest == 0
  29125. || (c->sourceChannelIndex != midiChannelIndex
  29126. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  29127. || (c->sourceChannelIndex == midiChannelIndex
  29128. && ! source->processor->producesMidi())
  29129. || (c->destChannelIndex != midiChannelIndex
  29130. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  29131. || (c->destChannelIndex == midiChannelIndex
  29132. && ! dest->processor->acceptsMidi()))
  29133. {
  29134. removeConnection (i);
  29135. doneAnything = true;
  29136. triggerAsyncUpdate();
  29137. }
  29138. }
  29139. return doneAnything;
  29140. }
  29141. namespace GraphRenderingOps
  29142. {
  29143. class AudioGraphRenderingOp
  29144. {
  29145. public:
  29146. AudioGraphRenderingOp() {}
  29147. virtual ~AudioGraphRenderingOp() {}
  29148. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29149. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29150. const int numSamples) = 0;
  29151. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29152. };
  29153. class ClearChannelOp : public AudioGraphRenderingOp
  29154. {
  29155. public:
  29156. ClearChannelOp (const int channelNum_)
  29157. : channelNum (channelNum_)
  29158. {}
  29159. ~ClearChannelOp() {}
  29160. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29161. {
  29162. sharedBufferChans.clear (channelNum, 0, numSamples);
  29163. }
  29164. private:
  29165. const int channelNum;
  29166. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29167. };
  29168. class CopyChannelOp : public AudioGraphRenderingOp
  29169. {
  29170. public:
  29171. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29172. : srcChannelNum (srcChannelNum_),
  29173. dstChannelNum (dstChannelNum_)
  29174. {}
  29175. ~CopyChannelOp() {}
  29176. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29177. {
  29178. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29179. }
  29180. private:
  29181. const int srcChannelNum, dstChannelNum;
  29182. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29183. };
  29184. class AddChannelOp : public AudioGraphRenderingOp
  29185. {
  29186. public:
  29187. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29188. : srcChannelNum (srcChannelNum_),
  29189. dstChannelNum (dstChannelNum_)
  29190. {}
  29191. ~AddChannelOp() {}
  29192. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29193. {
  29194. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29195. }
  29196. private:
  29197. const int srcChannelNum, dstChannelNum;
  29198. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29199. };
  29200. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29201. {
  29202. public:
  29203. ClearMidiBufferOp (const int bufferNum_)
  29204. : bufferNum (bufferNum_)
  29205. {}
  29206. ~ClearMidiBufferOp() {}
  29207. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29208. {
  29209. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29210. }
  29211. private:
  29212. const int bufferNum;
  29213. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29214. };
  29215. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29216. {
  29217. public:
  29218. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29219. : srcBufferNum (srcBufferNum_),
  29220. dstBufferNum (dstBufferNum_)
  29221. {}
  29222. ~CopyMidiBufferOp() {}
  29223. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29224. {
  29225. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29226. }
  29227. private:
  29228. const int srcBufferNum, dstBufferNum;
  29229. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29230. };
  29231. class AddMidiBufferOp : public AudioGraphRenderingOp
  29232. {
  29233. public:
  29234. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29235. : srcBufferNum (srcBufferNum_),
  29236. dstBufferNum (dstBufferNum_)
  29237. {}
  29238. ~AddMidiBufferOp() {}
  29239. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29240. {
  29241. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29242. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29243. }
  29244. private:
  29245. const int srcBufferNum, dstBufferNum;
  29246. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29247. };
  29248. class ProcessBufferOp : public AudioGraphRenderingOp
  29249. {
  29250. public:
  29251. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29252. const Array <int>& audioChannelsToUse_,
  29253. const int totalChans_,
  29254. const int midiBufferToUse_)
  29255. : node (node_),
  29256. processor (node_->getProcessor()),
  29257. audioChannelsToUse (audioChannelsToUse_),
  29258. totalChans (jmax (1, totalChans_)),
  29259. midiBufferToUse (midiBufferToUse_)
  29260. {
  29261. channels.calloc (totalChans);
  29262. while (audioChannelsToUse.size() < totalChans)
  29263. audioChannelsToUse.add (0);
  29264. }
  29265. ~ProcessBufferOp()
  29266. {
  29267. }
  29268. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29269. {
  29270. for (int i = totalChans; --i >= 0;)
  29271. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29272. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29273. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29274. }
  29275. const AudioProcessorGraph::Node::Ptr node;
  29276. AudioProcessor* const processor;
  29277. private:
  29278. Array <int> audioChannelsToUse;
  29279. HeapBlock <float*> channels;
  29280. int totalChans;
  29281. int midiBufferToUse;
  29282. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29283. };
  29284. /** Used to calculate the correct sequence of rendering ops needed, based on
  29285. the best re-use of shared buffers at each stage.
  29286. */
  29287. class RenderingOpSequenceCalculator
  29288. {
  29289. public:
  29290. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29291. const Array<void*>& orderedNodes_,
  29292. Array<void*>& renderingOps)
  29293. : graph (graph_),
  29294. orderedNodes (orderedNodes_)
  29295. {
  29296. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29297. channels.add (0);
  29298. midiNodeIds.add ((uint32) zeroNodeID);
  29299. for (int i = 0; i < orderedNodes.size(); ++i)
  29300. {
  29301. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29302. renderingOps, i);
  29303. markAnyUnusedBuffersAsFree (i);
  29304. }
  29305. }
  29306. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29307. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29308. private:
  29309. AudioProcessorGraph& graph;
  29310. const Array<void*>& orderedNodes;
  29311. Array <int> channels;
  29312. Array <uint32> nodeIds, midiNodeIds;
  29313. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29314. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29315. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29316. Array<void*>& renderingOps,
  29317. const int ourRenderingIndex)
  29318. {
  29319. const int numIns = node->getProcessor()->getNumInputChannels();
  29320. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29321. const int totalChans = jmax (numIns, numOuts);
  29322. Array <int> audioChannelsToUse;
  29323. int midiBufferToUse = -1;
  29324. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29325. {
  29326. // get a list of all the inputs to this node
  29327. Array <int> sourceNodes, sourceOutputChans;
  29328. for (int i = graph.getNumConnections(); --i >= 0;)
  29329. {
  29330. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29331. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29332. {
  29333. sourceNodes.add (c->sourceNodeId);
  29334. sourceOutputChans.add (c->sourceChannelIndex);
  29335. }
  29336. }
  29337. int bufIndex = -1;
  29338. if (sourceNodes.size() == 0)
  29339. {
  29340. // unconnected input channel
  29341. if (inputChan >= numOuts)
  29342. {
  29343. bufIndex = getReadOnlyEmptyBuffer();
  29344. jassert (bufIndex >= 0);
  29345. }
  29346. else
  29347. {
  29348. bufIndex = getFreeBuffer (false);
  29349. renderingOps.add (new ClearChannelOp (bufIndex));
  29350. }
  29351. }
  29352. else if (sourceNodes.size() == 1)
  29353. {
  29354. // channel with a straightforward single input..
  29355. const int srcNode = sourceNodes.getUnchecked(0);
  29356. const int srcChan = sourceOutputChans.getUnchecked(0);
  29357. bufIndex = getBufferContaining (srcNode, srcChan);
  29358. if (bufIndex < 0)
  29359. {
  29360. // if not found, this is probably a feedback loop
  29361. bufIndex = getReadOnlyEmptyBuffer();
  29362. jassert (bufIndex >= 0);
  29363. }
  29364. if (inputChan < numOuts
  29365. && isBufferNeededLater (ourRenderingIndex,
  29366. inputChan,
  29367. srcNode, srcChan))
  29368. {
  29369. // can't mess up this channel because it's needed later by another node, so we
  29370. // need to use a copy of it..
  29371. const int newFreeBuffer = getFreeBuffer (false);
  29372. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29373. bufIndex = newFreeBuffer;
  29374. }
  29375. }
  29376. else
  29377. {
  29378. // channel with a mix of several inputs..
  29379. // try to find a re-usable channel from our inputs..
  29380. int reusableInputIndex = -1;
  29381. for (int i = 0; i < sourceNodes.size(); ++i)
  29382. {
  29383. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29384. sourceOutputChans.getUnchecked(i));
  29385. if (sourceBufIndex >= 0
  29386. && ! isBufferNeededLater (ourRenderingIndex,
  29387. inputChan,
  29388. sourceNodes.getUnchecked(i),
  29389. sourceOutputChans.getUnchecked(i)))
  29390. {
  29391. // we've found one of our input chans that can be re-used..
  29392. reusableInputIndex = i;
  29393. bufIndex = sourceBufIndex;
  29394. break;
  29395. }
  29396. }
  29397. if (reusableInputIndex < 0)
  29398. {
  29399. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29400. bufIndex = getFreeBuffer (false);
  29401. jassert (bufIndex != 0);
  29402. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29403. sourceOutputChans.getUnchecked (0));
  29404. if (srcIndex < 0)
  29405. {
  29406. // if not found, this is probably a feedback loop
  29407. renderingOps.add (new ClearChannelOp (bufIndex));
  29408. }
  29409. else
  29410. {
  29411. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29412. }
  29413. reusableInputIndex = 0;
  29414. }
  29415. for (int j = 0; j < sourceNodes.size(); ++j)
  29416. {
  29417. if (j != reusableInputIndex)
  29418. {
  29419. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29420. sourceOutputChans.getUnchecked(j));
  29421. if (srcIndex >= 0)
  29422. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29423. }
  29424. }
  29425. }
  29426. jassert (bufIndex >= 0);
  29427. audioChannelsToUse.add (bufIndex);
  29428. if (inputChan < numOuts)
  29429. markBufferAsContaining (bufIndex, node->id, inputChan);
  29430. }
  29431. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29432. {
  29433. const int bufIndex = getFreeBuffer (false);
  29434. jassert (bufIndex != 0);
  29435. audioChannelsToUse.add (bufIndex);
  29436. markBufferAsContaining (bufIndex, node->id, outputChan);
  29437. }
  29438. // Now the same thing for midi..
  29439. Array <int> midiSourceNodes;
  29440. for (int i = graph.getNumConnections(); --i >= 0;)
  29441. {
  29442. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29443. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29444. midiSourceNodes.add (c->sourceNodeId);
  29445. }
  29446. if (midiSourceNodes.size() == 0)
  29447. {
  29448. // No midi inputs..
  29449. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29450. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29451. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29452. }
  29453. else if (midiSourceNodes.size() == 1)
  29454. {
  29455. // One midi input..
  29456. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29457. AudioProcessorGraph::midiChannelIndex);
  29458. if (midiBufferToUse >= 0)
  29459. {
  29460. if (isBufferNeededLater (ourRenderingIndex,
  29461. AudioProcessorGraph::midiChannelIndex,
  29462. midiSourceNodes.getUnchecked(0),
  29463. AudioProcessorGraph::midiChannelIndex))
  29464. {
  29465. // can't mess up this channel because it's needed later by another node, so we
  29466. // need to use a copy of it..
  29467. const int newFreeBuffer = getFreeBuffer (true);
  29468. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29469. midiBufferToUse = newFreeBuffer;
  29470. }
  29471. }
  29472. else
  29473. {
  29474. // probably a feedback loop, so just use an empty one..
  29475. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29476. }
  29477. }
  29478. else
  29479. {
  29480. // More than one midi input being mixed..
  29481. int reusableInputIndex = -1;
  29482. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29483. {
  29484. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29485. AudioProcessorGraph::midiChannelIndex);
  29486. if (sourceBufIndex >= 0
  29487. && ! isBufferNeededLater (ourRenderingIndex,
  29488. AudioProcessorGraph::midiChannelIndex,
  29489. midiSourceNodes.getUnchecked(i),
  29490. AudioProcessorGraph::midiChannelIndex))
  29491. {
  29492. // we've found one of our input buffers that can be re-used..
  29493. reusableInputIndex = i;
  29494. midiBufferToUse = sourceBufIndex;
  29495. break;
  29496. }
  29497. }
  29498. if (reusableInputIndex < 0)
  29499. {
  29500. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29501. midiBufferToUse = getFreeBuffer (true);
  29502. jassert (midiBufferToUse >= 0);
  29503. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29504. AudioProcessorGraph::midiChannelIndex);
  29505. if (srcIndex >= 0)
  29506. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29507. else
  29508. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29509. reusableInputIndex = 0;
  29510. }
  29511. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29512. {
  29513. if (j != reusableInputIndex)
  29514. {
  29515. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29516. AudioProcessorGraph::midiChannelIndex);
  29517. if (srcIndex >= 0)
  29518. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29519. }
  29520. }
  29521. }
  29522. if (node->getProcessor()->producesMidi())
  29523. markBufferAsContaining (midiBufferToUse, node->id,
  29524. AudioProcessorGraph::midiChannelIndex);
  29525. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29526. totalChans, midiBufferToUse));
  29527. }
  29528. int getFreeBuffer (const bool forMidi)
  29529. {
  29530. if (forMidi)
  29531. {
  29532. for (int i = 1; i < midiNodeIds.size(); ++i)
  29533. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29534. return i;
  29535. midiNodeIds.add ((uint32) freeNodeID);
  29536. return midiNodeIds.size() - 1;
  29537. }
  29538. else
  29539. {
  29540. for (int i = 1; i < nodeIds.size(); ++i)
  29541. if (nodeIds.getUnchecked(i) == freeNodeID)
  29542. return i;
  29543. nodeIds.add ((uint32) freeNodeID);
  29544. channels.add (0);
  29545. return nodeIds.size() - 1;
  29546. }
  29547. }
  29548. int getReadOnlyEmptyBuffer() const
  29549. {
  29550. return 0;
  29551. }
  29552. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29553. {
  29554. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29555. {
  29556. for (int i = midiNodeIds.size(); --i >= 0;)
  29557. if (midiNodeIds.getUnchecked(i) == nodeId)
  29558. return i;
  29559. }
  29560. else
  29561. {
  29562. for (int i = nodeIds.size(); --i >= 0;)
  29563. if (nodeIds.getUnchecked(i) == nodeId
  29564. && channels.getUnchecked(i) == outputChannel)
  29565. return i;
  29566. }
  29567. return -1;
  29568. }
  29569. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29570. {
  29571. int i;
  29572. for (i = 0; i < nodeIds.size(); ++i)
  29573. {
  29574. if (isNodeBusy (nodeIds.getUnchecked(i))
  29575. && ! isBufferNeededLater (stepIndex, -1,
  29576. nodeIds.getUnchecked(i),
  29577. channels.getUnchecked(i)))
  29578. {
  29579. nodeIds.set (i, (uint32) freeNodeID);
  29580. }
  29581. }
  29582. for (i = 0; i < midiNodeIds.size(); ++i)
  29583. {
  29584. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29585. && ! isBufferNeededLater (stepIndex, -1,
  29586. midiNodeIds.getUnchecked(i),
  29587. AudioProcessorGraph::midiChannelIndex))
  29588. {
  29589. midiNodeIds.set (i, (uint32) freeNodeID);
  29590. }
  29591. }
  29592. }
  29593. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29594. int inputChannelOfIndexToIgnore,
  29595. const uint32 nodeId,
  29596. const int outputChanIndex) const
  29597. {
  29598. while (stepIndexToSearchFrom < orderedNodes.size())
  29599. {
  29600. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29601. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29602. {
  29603. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29604. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29605. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29606. return true;
  29607. }
  29608. else
  29609. {
  29610. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29611. if (i != inputChannelOfIndexToIgnore
  29612. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29613. node->id, i) != 0)
  29614. return true;
  29615. }
  29616. inputChannelOfIndexToIgnore = -1;
  29617. ++stepIndexToSearchFrom;
  29618. }
  29619. return false;
  29620. }
  29621. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29622. {
  29623. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29624. {
  29625. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29626. midiNodeIds.set (bufferNum, nodeId);
  29627. }
  29628. else
  29629. {
  29630. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29631. nodeIds.set (bufferNum, nodeId);
  29632. channels.set (bufferNum, outputIndex);
  29633. }
  29634. }
  29635. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29636. };
  29637. }
  29638. void AudioProcessorGraph::clearRenderingSequence()
  29639. {
  29640. const ScopedLock sl (renderLock);
  29641. for (int i = renderingOps.size(); --i >= 0;)
  29642. {
  29643. GraphRenderingOps::AudioGraphRenderingOp* const r
  29644. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29645. renderingOps.remove (i);
  29646. delete r;
  29647. }
  29648. }
  29649. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29650. const uint32 possibleDestinationId,
  29651. const int recursionCheck) const
  29652. {
  29653. if (recursionCheck > 0)
  29654. {
  29655. for (int i = connections.size(); --i >= 0;)
  29656. {
  29657. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29658. if (c->destNodeId == possibleDestinationId
  29659. && (c->sourceNodeId == possibleInputId
  29660. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29661. return true;
  29662. }
  29663. }
  29664. return false;
  29665. }
  29666. void AudioProcessorGraph::buildRenderingSequence()
  29667. {
  29668. Array<void*> newRenderingOps;
  29669. int numRenderingBuffersNeeded = 2;
  29670. int numMidiBuffersNeeded = 1;
  29671. {
  29672. MessageManagerLock mml;
  29673. Array<void*> orderedNodes;
  29674. int i;
  29675. for (i = 0; i < nodes.size(); ++i)
  29676. {
  29677. Node* const node = nodes.getUnchecked(i);
  29678. node->prepare (getSampleRate(), getBlockSize(), this);
  29679. int j = 0;
  29680. for (; j < orderedNodes.size(); ++j)
  29681. if (isAnInputTo (node->id,
  29682. ((Node*) orderedNodes.getUnchecked (j))->id,
  29683. nodes.size() + 1))
  29684. break;
  29685. orderedNodes.insert (j, node);
  29686. }
  29687. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29688. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29689. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29690. }
  29691. Array<void*> oldRenderingOps (renderingOps);
  29692. {
  29693. // swap over to the new rendering sequence..
  29694. const ScopedLock sl (renderLock);
  29695. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29696. renderingBuffers.clear();
  29697. for (int i = midiBuffers.size(); --i >= 0;)
  29698. midiBuffers.getUnchecked(i)->clear();
  29699. while (midiBuffers.size() < numMidiBuffersNeeded)
  29700. midiBuffers.add (new MidiBuffer());
  29701. renderingOps = newRenderingOps;
  29702. }
  29703. for (int i = oldRenderingOps.size(); --i >= 0;)
  29704. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29705. }
  29706. void AudioProcessorGraph::handleAsyncUpdate()
  29707. {
  29708. buildRenderingSequence();
  29709. }
  29710. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29711. {
  29712. currentAudioInputBuffer = 0;
  29713. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29714. currentMidiInputBuffer = 0;
  29715. currentMidiOutputBuffer.clear();
  29716. clearRenderingSequence();
  29717. buildRenderingSequence();
  29718. }
  29719. void AudioProcessorGraph::releaseResources()
  29720. {
  29721. for (int i = 0; i < nodes.size(); ++i)
  29722. nodes.getUnchecked(i)->unprepare();
  29723. renderingBuffers.setSize (1, 1);
  29724. midiBuffers.clear();
  29725. currentAudioInputBuffer = 0;
  29726. currentAudioOutputBuffer.setSize (1, 1);
  29727. currentMidiInputBuffer = 0;
  29728. currentMidiOutputBuffer.clear();
  29729. }
  29730. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29731. {
  29732. const int numSamples = buffer.getNumSamples();
  29733. const ScopedLock sl (renderLock);
  29734. currentAudioInputBuffer = &buffer;
  29735. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29736. currentAudioOutputBuffer.clear();
  29737. currentMidiInputBuffer = &midiMessages;
  29738. currentMidiOutputBuffer.clear();
  29739. int i;
  29740. for (i = 0; i < renderingOps.size(); ++i)
  29741. {
  29742. GraphRenderingOps::AudioGraphRenderingOp* const op
  29743. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29744. op->perform (renderingBuffers, midiBuffers, numSamples);
  29745. }
  29746. for (i = 0; i < buffer.getNumChannels(); ++i)
  29747. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29748. midiMessages.clear();
  29749. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29750. }
  29751. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29752. {
  29753. return "Input " + String (channelIndex + 1);
  29754. }
  29755. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29756. {
  29757. return "Output " + String (channelIndex + 1);
  29758. }
  29759. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29760. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29761. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29762. bool AudioProcessorGraph::producesMidi() const { return true; }
  29763. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29764. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29765. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29766. : type (type_),
  29767. graph (0)
  29768. {
  29769. }
  29770. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29771. {
  29772. }
  29773. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29774. {
  29775. switch (type)
  29776. {
  29777. case audioOutputNode: return "Audio Output";
  29778. case audioInputNode: return "Audio Input";
  29779. case midiOutputNode: return "Midi Output";
  29780. case midiInputNode: return "Midi Input";
  29781. default: break;
  29782. }
  29783. return String::empty;
  29784. }
  29785. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29786. {
  29787. d.name = getName();
  29788. d.uid = d.name.hashCode();
  29789. d.category = "I/O devices";
  29790. d.pluginFormatName = "Internal";
  29791. d.manufacturerName = "Raw Material Software";
  29792. d.version = "1.0";
  29793. d.isInstrument = false;
  29794. d.numInputChannels = getNumInputChannels();
  29795. if (type == audioOutputNode && graph != 0)
  29796. d.numInputChannels = graph->getNumInputChannels();
  29797. d.numOutputChannels = getNumOutputChannels();
  29798. if (type == audioInputNode && graph != 0)
  29799. d.numOutputChannels = graph->getNumOutputChannels();
  29800. }
  29801. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29802. {
  29803. jassert (graph != 0);
  29804. }
  29805. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29806. {
  29807. }
  29808. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29809. MidiBuffer& midiMessages)
  29810. {
  29811. jassert (graph != 0);
  29812. switch (type)
  29813. {
  29814. case audioOutputNode:
  29815. {
  29816. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29817. buffer.getNumChannels()); --i >= 0;)
  29818. {
  29819. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29820. }
  29821. break;
  29822. }
  29823. case audioInputNode:
  29824. {
  29825. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29826. buffer.getNumChannels()); --i >= 0;)
  29827. {
  29828. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29829. }
  29830. break;
  29831. }
  29832. case midiOutputNode:
  29833. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29834. break;
  29835. case midiInputNode:
  29836. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29837. break;
  29838. default:
  29839. break;
  29840. }
  29841. }
  29842. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29843. {
  29844. return type == midiOutputNode;
  29845. }
  29846. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29847. {
  29848. return type == midiInputNode;
  29849. }
  29850. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29851. {
  29852. switch (type)
  29853. {
  29854. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29855. case midiOutputNode: return "Midi Output";
  29856. default: break;
  29857. }
  29858. return String::empty;
  29859. }
  29860. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29861. {
  29862. switch (type)
  29863. {
  29864. case audioInputNode: return "Input " + String (channelIndex + 1);
  29865. case midiInputNode: return "Midi Input";
  29866. default: break;
  29867. }
  29868. return String::empty;
  29869. }
  29870. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29871. {
  29872. return type == audioInputNode || type == audioOutputNode;
  29873. }
  29874. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29875. {
  29876. return isInputChannelStereoPair (index);
  29877. }
  29878. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29879. {
  29880. return type == audioInputNode || type == midiInputNode;
  29881. }
  29882. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29883. {
  29884. return type == audioOutputNode || type == midiOutputNode;
  29885. }
  29886. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29887. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29888. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29889. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29890. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29891. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29892. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29893. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29894. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29895. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29896. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29897. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29898. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29899. {
  29900. }
  29901. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29902. {
  29903. }
  29904. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29905. {
  29906. graph = newGraph;
  29907. if (graph != 0)
  29908. {
  29909. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29910. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29911. getSampleRate(),
  29912. getBlockSize());
  29913. updateHostDisplay();
  29914. }
  29915. }
  29916. END_JUCE_NAMESPACE
  29917. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29918. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29919. BEGIN_JUCE_NAMESPACE
  29920. AudioProcessorPlayer::AudioProcessorPlayer()
  29921. : processor (0),
  29922. sampleRate (0),
  29923. blockSize (0),
  29924. isPrepared (false),
  29925. numInputChans (0),
  29926. numOutputChans (0),
  29927. tempBuffer (1, 1)
  29928. {
  29929. }
  29930. AudioProcessorPlayer::~AudioProcessorPlayer()
  29931. {
  29932. setProcessor (0);
  29933. }
  29934. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29935. {
  29936. if (processor != processorToPlay)
  29937. {
  29938. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29939. {
  29940. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29941. sampleRate, blockSize);
  29942. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29943. }
  29944. AudioProcessor* oldOne;
  29945. {
  29946. const ScopedLock sl (lock);
  29947. oldOne = isPrepared ? processor : 0;
  29948. processor = processorToPlay;
  29949. isPrepared = true;
  29950. }
  29951. if (oldOne != 0)
  29952. oldOne->releaseResources();
  29953. }
  29954. }
  29955. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29956. const int numInputChannels,
  29957. float** const outputChannelData,
  29958. const int numOutputChannels,
  29959. const int numSamples)
  29960. {
  29961. // these should have been prepared by audioDeviceAboutToStart()...
  29962. jassert (sampleRate > 0 && blockSize > 0);
  29963. incomingMidi.clear();
  29964. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29965. int i, totalNumChans = 0;
  29966. if (numInputChannels > numOutputChannels)
  29967. {
  29968. // if there aren't enough output channels for the number of
  29969. // inputs, we need to create some temporary extra ones (can't
  29970. // use the input data in case it gets written to)
  29971. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29972. false, false, true);
  29973. for (i = 0; i < numOutputChannels; ++i)
  29974. {
  29975. channels[totalNumChans] = outputChannelData[i];
  29976. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29977. ++totalNumChans;
  29978. }
  29979. for (i = numOutputChannels; i < numInputChannels; ++i)
  29980. {
  29981. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29982. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29983. ++totalNumChans;
  29984. }
  29985. }
  29986. else
  29987. {
  29988. for (i = 0; i < numInputChannels; ++i)
  29989. {
  29990. channels[totalNumChans] = outputChannelData[i];
  29991. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29992. ++totalNumChans;
  29993. }
  29994. for (i = numInputChannels; i < numOutputChannels; ++i)
  29995. {
  29996. channels[totalNumChans] = outputChannelData[i];
  29997. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29998. ++totalNumChans;
  29999. }
  30000. }
  30001. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30002. const ScopedLock sl (lock);
  30003. if (processor != 0)
  30004. {
  30005. const ScopedLock sl2 (processor->getCallbackLock());
  30006. if (processor->isSuspended())
  30007. {
  30008. for (i = 0; i < numOutputChannels; ++i)
  30009. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30010. }
  30011. else
  30012. {
  30013. processor->processBlock (buffer, incomingMidi);
  30014. }
  30015. }
  30016. }
  30017. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30018. {
  30019. const ScopedLock sl (lock);
  30020. sampleRate = device->getCurrentSampleRate();
  30021. blockSize = device->getCurrentBufferSizeSamples();
  30022. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30023. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30024. messageCollector.reset (sampleRate);
  30025. zeromem (channels, sizeof (channels));
  30026. if (processor != 0)
  30027. {
  30028. if (isPrepared)
  30029. processor->releaseResources();
  30030. AudioProcessor* const oldProcessor = processor;
  30031. setProcessor (0);
  30032. setProcessor (oldProcessor);
  30033. }
  30034. }
  30035. void AudioProcessorPlayer::audioDeviceStopped()
  30036. {
  30037. const ScopedLock sl (lock);
  30038. if (processor != 0 && isPrepared)
  30039. processor->releaseResources();
  30040. sampleRate = 0.0;
  30041. blockSize = 0;
  30042. isPrepared = false;
  30043. tempBuffer.setSize (1, 1);
  30044. }
  30045. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30046. {
  30047. messageCollector.addMessageToQueue (message);
  30048. }
  30049. END_JUCE_NAMESPACE
  30050. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30051. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30052. BEGIN_JUCE_NAMESPACE
  30053. class ProcessorParameterPropertyComp : public PropertyComponent,
  30054. public AudioProcessorListener,
  30055. public Timer
  30056. {
  30057. public:
  30058. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30059. : PropertyComponent (name),
  30060. owner (owner_),
  30061. index (index_),
  30062. paramHasChanged (false),
  30063. slider (owner_, index_)
  30064. {
  30065. startTimer (100);
  30066. addAndMakeVisible (&slider);
  30067. owner_.addListener (this);
  30068. }
  30069. ~ProcessorParameterPropertyComp()
  30070. {
  30071. owner.removeListener (this);
  30072. }
  30073. void refresh()
  30074. {
  30075. paramHasChanged = false;
  30076. slider.setValue (owner.getParameter (index), false);
  30077. }
  30078. void audioProcessorChanged (AudioProcessor*) {}
  30079. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30080. {
  30081. if (parameterIndex == index)
  30082. paramHasChanged = true;
  30083. }
  30084. void timerCallback()
  30085. {
  30086. if (paramHasChanged)
  30087. {
  30088. refresh();
  30089. startTimer (1000 / 50);
  30090. }
  30091. else
  30092. {
  30093. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30094. }
  30095. }
  30096. private:
  30097. class ParamSlider : public Slider
  30098. {
  30099. public:
  30100. ParamSlider (AudioProcessor& owner_, const int index_)
  30101. : owner (owner_),
  30102. index (index_)
  30103. {
  30104. setRange (0.0, 1.0, 0.0);
  30105. setSliderStyle (Slider::LinearBar);
  30106. setTextBoxIsEditable (false);
  30107. setScrollWheelEnabled (false);
  30108. }
  30109. void valueChanged()
  30110. {
  30111. const float newVal = (float) getValue();
  30112. if (owner.getParameter (index) != newVal)
  30113. owner.setParameter (index, newVal);
  30114. }
  30115. const String getTextFromValue (double /*value*/)
  30116. {
  30117. return owner.getParameterText (index);
  30118. }
  30119. private:
  30120. AudioProcessor& owner;
  30121. const int index;
  30122. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  30123. };
  30124. AudioProcessor& owner;
  30125. const int index;
  30126. bool volatile paramHasChanged;
  30127. ParamSlider slider;
  30128. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  30129. };
  30130. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30131. : AudioProcessorEditor (owner_)
  30132. {
  30133. jassert (owner_ != 0);
  30134. setOpaque (true);
  30135. addAndMakeVisible (&panel);
  30136. Array <PropertyComponent*> params;
  30137. const int numParams = owner_->getNumParameters();
  30138. int totalHeight = 0;
  30139. for (int i = 0; i < numParams; ++i)
  30140. {
  30141. String name (owner_->getParameterName (i));
  30142. if (name.trim().isEmpty())
  30143. name = "Unnamed";
  30144. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30145. params.add (pc);
  30146. totalHeight += pc->getPreferredHeight();
  30147. }
  30148. panel.addProperties (params);
  30149. setSize (400, jlimit (25, 400, totalHeight));
  30150. }
  30151. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30152. {
  30153. }
  30154. void GenericAudioProcessorEditor::paint (Graphics& g)
  30155. {
  30156. g.fillAll (Colours::white);
  30157. }
  30158. void GenericAudioProcessorEditor::resized()
  30159. {
  30160. panel.setBounds (getLocalBounds());
  30161. }
  30162. END_JUCE_NAMESPACE
  30163. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30164. /*** Start of inlined file: juce_Sampler.cpp ***/
  30165. BEGIN_JUCE_NAMESPACE
  30166. SamplerSound::SamplerSound (const String& name_,
  30167. AudioFormatReader& source,
  30168. const BigInteger& midiNotes_,
  30169. const int midiNoteForNormalPitch,
  30170. const double attackTimeSecs,
  30171. const double releaseTimeSecs,
  30172. const double maxSampleLengthSeconds)
  30173. : name (name_),
  30174. midiNotes (midiNotes_),
  30175. midiRootNote (midiNoteForNormalPitch)
  30176. {
  30177. sourceSampleRate = source.sampleRate;
  30178. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30179. {
  30180. length = 0;
  30181. attackSamples = 0;
  30182. releaseSamples = 0;
  30183. }
  30184. else
  30185. {
  30186. length = jmin ((int) source.lengthInSamples,
  30187. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30188. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30189. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30190. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30191. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30192. }
  30193. }
  30194. SamplerSound::~SamplerSound()
  30195. {
  30196. }
  30197. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30198. {
  30199. return midiNotes [midiNoteNumber];
  30200. }
  30201. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30202. {
  30203. return true;
  30204. }
  30205. SamplerVoice::SamplerVoice()
  30206. : pitchRatio (0.0),
  30207. sourceSamplePosition (0.0),
  30208. lgain (0.0f),
  30209. rgain (0.0f),
  30210. isInAttack (false),
  30211. isInRelease (false)
  30212. {
  30213. }
  30214. SamplerVoice::~SamplerVoice()
  30215. {
  30216. }
  30217. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30218. {
  30219. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30220. }
  30221. void SamplerVoice::startNote (const int midiNoteNumber,
  30222. const float velocity,
  30223. SynthesiserSound* s,
  30224. const int /*currentPitchWheelPosition*/)
  30225. {
  30226. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30227. jassert (sound != 0); // this object can only play SamplerSounds!
  30228. if (sound != 0)
  30229. {
  30230. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30231. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30232. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30233. sourceSamplePosition = 0.0;
  30234. lgain = velocity;
  30235. rgain = velocity;
  30236. isInAttack = (sound->attackSamples > 0);
  30237. isInRelease = false;
  30238. if (isInAttack)
  30239. {
  30240. attackReleaseLevel = 0.0f;
  30241. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30242. }
  30243. else
  30244. {
  30245. attackReleaseLevel = 1.0f;
  30246. attackDelta = 0.0f;
  30247. }
  30248. if (sound->releaseSamples > 0)
  30249. {
  30250. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30251. }
  30252. else
  30253. {
  30254. releaseDelta = 0.0f;
  30255. }
  30256. }
  30257. }
  30258. void SamplerVoice::stopNote (const bool allowTailOff)
  30259. {
  30260. if (allowTailOff)
  30261. {
  30262. isInAttack = false;
  30263. isInRelease = true;
  30264. }
  30265. else
  30266. {
  30267. clearCurrentNote();
  30268. }
  30269. }
  30270. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30271. {
  30272. }
  30273. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30274. const int /*newValue*/)
  30275. {
  30276. }
  30277. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30278. {
  30279. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30280. if (playingSound != 0)
  30281. {
  30282. const float* const inL = playingSound->data->getSampleData (0, 0);
  30283. const float* const inR = playingSound->data->getNumChannels() > 1
  30284. ? playingSound->data->getSampleData (1, 0) : 0;
  30285. float* outL = outputBuffer.getSampleData (0, startSample);
  30286. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30287. while (--numSamples >= 0)
  30288. {
  30289. const int pos = (int) sourceSamplePosition;
  30290. const float alpha = (float) (sourceSamplePosition - pos);
  30291. const float invAlpha = 1.0f - alpha;
  30292. // just using a very simple linear interpolation here..
  30293. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30294. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30295. : l;
  30296. l *= lgain;
  30297. r *= rgain;
  30298. if (isInAttack)
  30299. {
  30300. l *= attackReleaseLevel;
  30301. r *= attackReleaseLevel;
  30302. attackReleaseLevel += attackDelta;
  30303. if (attackReleaseLevel >= 1.0f)
  30304. {
  30305. attackReleaseLevel = 1.0f;
  30306. isInAttack = false;
  30307. }
  30308. }
  30309. else if (isInRelease)
  30310. {
  30311. l *= attackReleaseLevel;
  30312. r *= attackReleaseLevel;
  30313. attackReleaseLevel += releaseDelta;
  30314. if (attackReleaseLevel <= 0.0f)
  30315. {
  30316. stopNote (false);
  30317. break;
  30318. }
  30319. }
  30320. if (outR != 0)
  30321. {
  30322. *outL++ += l;
  30323. *outR++ += r;
  30324. }
  30325. else
  30326. {
  30327. *outL++ += (l + r) * 0.5f;
  30328. }
  30329. sourceSamplePosition += pitchRatio;
  30330. if (sourceSamplePosition > playingSound->length)
  30331. {
  30332. stopNote (false);
  30333. break;
  30334. }
  30335. }
  30336. }
  30337. }
  30338. END_JUCE_NAMESPACE
  30339. /*** End of inlined file: juce_Sampler.cpp ***/
  30340. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30341. BEGIN_JUCE_NAMESPACE
  30342. SynthesiserSound::SynthesiserSound()
  30343. {
  30344. }
  30345. SynthesiserSound::~SynthesiserSound()
  30346. {
  30347. }
  30348. SynthesiserVoice::SynthesiserVoice()
  30349. : currentSampleRate (44100.0),
  30350. currentlyPlayingNote (-1),
  30351. noteOnTime (0),
  30352. currentlyPlayingSound (0)
  30353. {
  30354. }
  30355. SynthesiserVoice::~SynthesiserVoice()
  30356. {
  30357. }
  30358. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30359. {
  30360. return currentlyPlayingSound != 0
  30361. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30362. }
  30363. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30364. {
  30365. currentSampleRate = newRate;
  30366. }
  30367. void SynthesiserVoice::clearCurrentNote()
  30368. {
  30369. currentlyPlayingNote = -1;
  30370. currentlyPlayingSound = 0;
  30371. }
  30372. Synthesiser::Synthesiser()
  30373. : sampleRate (0),
  30374. lastNoteOnCounter (0),
  30375. shouldStealNotes (true)
  30376. {
  30377. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30378. lastPitchWheelValues[i] = 0x2000;
  30379. }
  30380. Synthesiser::~Synthesiser()
  30381. {
  30382. }
  30383. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30384. {
  30385. const ScopedLock sl (lock);
  30386. return voices [index];
  30387. }
  30388. void Synthesiser::clearVoices()
  30389. {
  30390. const ScopedLock sl (lock);
  30391. voices.clear();
  30392. }
  30393. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30394. {
  30395. const ScopedLock sl (lock);
  30396. voices.add (newVoice);
  30397. }
  30398. void Synthesiser::removeVoice (const int index)
  30399. {
  30400. const ScopedLock sl (lock);
  30401. voices.remove (index);
  30402. }
  30403. void Synthesiser::clearSounds()
  30404. {
  30405. const ScopedLock sl (lock);
  30406. sounds.clear();
  30407. }
  30408. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30409. {
  30410. const ScopedLock sl (lock);
  30411. sounds.add (newSound);
  30412. }
  30413. void Synthesiser::removeSound (const int index)
  30414. {
  30415. const ScopedLock sl (lock);
  30416. sounds.remove (index);
  30417. }
  30418. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30419. {
  30420. shouldStealNotes = shouldStealNotes_;
  30421. }
  30422. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30423. {
  30424. if (sampleRate != newRate)
  30425. {
  30426. const ScopedLock sl (lock);
  30427. allNotesOff (0, false);
  30428. sampleRate = newRate;
  30429. for (int i = voices.size(); --i >= 0;)
  30430. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30431. }
  30432. }
  30433. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30434. const MidiBuffer& midiData,
  30435. int startSample,
  30436. int numSamples)
  30437. {
  30438. // must set the sample rate before using this!
  30439. jassert (sampleRate != 0);
  30440. const ScopedLock sl (lock);
  30441. MidiBuffer::Iterator midiIterator (midiData);
  30442. midiIterator.setNextSamplePosition (startSample);
  30443. MidiMessage m (0xf4, 0.0);
  30444. while (numSamples > 0)
  30445. {
  30446. int midiEventPos;
  30447. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30448. && midiEventPos < startSample + numSamples;
  30449. const int numThisTime = useEvent ? midiEventPos - startSample
  30450. : numSamples;
  30451. if (numThisTime > 0)
  30452. {
  30453. for (int i = voices.size(); --i >= 0;)
  30454. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30455. }
  30456. if (useEvent)
  30457. {
  30458. if (m.isNoteOn())
  30459. {
  30460. const int channel = m.getChannel();
  30461. noteOn (channel,
  30462. m.getNoteNumber(),
  30463. m.getFloatVelocity());
  30464. }
  30465. else if (m.isNoteOff())
  30466. {
  30467. noteOff (m.getChannel(),
  30468. m.getNoteNumber(),
  30469. true);
  30470. }
  30471. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30472. {
  30473. allNotesOff (m.getChannel(), true);
  30474. }
  30475. else if (m.isPitchWheel())
  30476. {
  30477. const int channel = m.getChannel();
  30478. const int wheelPos = m.getPitchWheelValue();
  30479. lastPitchWheelValues [channel - 1] = wheelPos;
  30480. handlePitchWheel (channel, wheelPos);
  30481. }
  30482. else if (m.isController())
  30483. {
  30484. handleController (m.getChannel(),
  30485. m.getControllerNumber(),
  30486. m.getControllerValue());
  30487. }
  30488. }
  30489. startSample += numThisTime;
  30490. numSamples -= numThisTime;
  30491. }
  30492. }
  30493. void Synthesiser::noteOn (const int midiChannel,
  30494. const int midiNoteNumber,
  30495. const float velocity)
  30496. {
  30497. const ScopedLock sl (lock);
  30498. for (int i = sounds.size(); --i >= 0;)
  30499. {
  30500. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30501. if (sound->appliesToNote (midiNoteNumber)
  30502. && sound->appliesToChannel (midiChannel))
  30503. {
  30504. startVoice (findFreeVoice (sound, shouldStealNotes),
  30505. sound, midiChannel, midiNoteNumber, velocity);
  30506. }
  30507. }
  30508. }
  30509. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30510. SynthesiserSound* const sound,
  30511. const int midiChannel,
  30512. const int midiNoteNumber,
  30513. const float velocity)
  30514. {
  30515. if (voice != 0 && sound != 0)
  30516. {
  30517. if (voice->currentlyPlayingSound != 0)
  30518. voice->stopNote (false);
  30519. voice->startNote (midiNoteNumber,
  30520. velocity,
  30521. sound,
  30522. lastPitchWheelValues [midiChannel - 1]);
  30523. voice->currentlyPlayingNote = midiNoteNumber;
  30524. voice->noteOnTime = ++lastNoteOnCounter;
  30525. voice->currentlyPlayingSound = sound;
  30526. }
  30527. }
  30528. void Synthesiser::noteOff (const int midiChannel,
  30529. const int midiNoteNumber,
  30530. const bool allowTailOff)
  30531. {
  30532. const ScopedLock sl (lock);
  30533. for (int i = voices.size(); --i >= 0;)
  30534. {
  30535. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30536. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30537. {
  30538. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30539. if (sound != 0
  30540. && sound->appliesToNote (midiNoteNumber)
  30541. && sound->appliesToChannel (midiChannel))
  30542. {
  30543. voice->stopNote (allowTailOff);
  30544. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30545. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30546. }
  30547. }
  30548. }
  30549. }
  30550. void Synthesiser::allNotesOff (const int midiChannel,
  30551. const bool allowTailOff)
  30552. {
  30553. const ScopedLock sl (lock);
  30554. for (int i = voices.size(); --i >= 0;)
  30555. {
  30556. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30557. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30558. voice->stopNote (allowTailOff);
  30559. }
  30560. }
  30561. void Synthesiser::handlePitchWheel (const int midiChannel,
  30562. const int wheelValue)
  30563. {
  30564. const ScopedLock sl (lock);
  30565. for (int i = voices.size(); --i >= 0;)
  30566. {
  30567. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30568. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30569. {
  30570. voice->pitchWheelMoved (wheelValue);
  30571. }
  30572. }
  30573. }
  30574. void Synthesiser::handleController (const int midiChannel,
  30575. const int controllerNumber,
  30576. const int controllerValue)
  30577. {
  30578. const ScopedLock sl (lock);
  30579. for (int i = voices.size(); --i >= 0;)
  30580. {
  30581. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30582. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30583. voice->controllerMoved (controllerNumber, controllerValue);
  30584. }
  30585. }
  30586. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30587. const bool stealIfNoneAvailable) const
  30588. {
  30589. const ScopedLock sl (lock);
  30590. for (int i = voices.size(); --i >= 0;)
  30591. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30592. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30593. return voices.getUnchecked (i);
  30594. if (stealIfNoneAvailable)
  30595. {
  30596. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30597. SynthesiserVoice* oldest = 0;
  30598. for (int i = voices.size(); --i >= 0;)
  30599. {
  30600. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30601. if (voice->canPlaySound (soundToPlay)
  30602. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30603. oldest = voice;
  30604. }
  30605. jassert (oldest != 0);
  30606. return oldest;
  30607. }
  30608. return 0;
  30609. }
  30610. END_JUCE_NAMESPACE
  30611. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30612. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30613. BEGIN_JUCE_NAMESPACE
  30614. // special message of our own with a string in it
  30615. class ActionMessage : public Message
  30616. {
  30617. public:
  30618. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30619. : message (messageText)
  30620. {
  30621. pointerParameter = listener_;
  30622. }
  30623. const String message;
  30624. private:
  30625. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30626. };
  30627. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30628. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30629. {
  30630. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30631. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30632. if (owner->actionListeners.contains (target))
  30633. target->actionListenerCallback (am.message);
  30634. }
  30635. ActionBroadcaster::ActionBroadcaster()
  30636. {
  30637. // are you trying to create this object before or after juce has been intialised??
  30638. jassert (MessageManager::instance != 0);
  30639. callback.owner = this;
  30640. }
  30641. ActionBroadcaster::~ActionBroadcaster()
  30642. {
  30643. // all event-based objects must be deleted BEFORE juce is shut down!
  30644. jassert (MessageManager::instance != 0);
  30645. }
  30646. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30647. {
  30648. const ScopedLock sl (actionListenerLock);
  30649. if (listener != 0)
  30650. actionListeners.add (listener);
  30651. }
  30652. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30653. {
  30654. const ScopedLock sl (actionListenerLock);
  30655. actionListeners.removeValue (listener);
  30656. }
  30657. void ActionBroadcaster::removeAllActionListeners()
  30658. {
  30659. const ScopedLock sl (actionListenerLock);
  30660. actionListeners.clear();
  30661. }
  30662. void ActionBroadcaster::sendActionMessage (const String& message) const
  30663. {
  30664. const ScopedLock sl (actionListenerLock);
  30665. for (int i = actionListeners.size(); --i >= 0;)
  30666. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30667. }
  30668. END_JUCE_NAMESPACE
  30669. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30670. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30671. BEGIN_JUCE_NAMESPACE
  30672. class AsyncUpdaterMessage : public CallbackMessage
  30673. {
  30674. public:
  30675. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30676. : owner (owner_)
  30677. {
  30678. }
  30679. void messageCallback()
  30680. {
  30681. if (shouldDeliver.compareAndSetBool (0, 1))
  30682. owner.handleAsyncUpdate();
  30683. }
  30684. Atomic<int> shouldDeliver;
  30685. private:
  30686. AsyncUpdater& owner;
  30687. };
  30688. AsyncUpdater::AsyncUpdater()
  30689. {
  30690. message = new AsyncUpdaterMessage (*this);
  30691. }
  30692. inline Atomic<int>& AsyncUpdater::getDeliveryFlag() const throw()
  30693. {
  30694. return static_cast <AsyncUpdaterMessage*> (message.getObject())->shouldDeliver;
  30695. }
  30696. AsyncUpdater::~AsyncUpdater()
  30697. {
  30698. // You're deleting this object with a background thread while there's an update
  30699. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30700. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30701. // deleting this object, or find some other way to avoid such a race condition.
  30702. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30703. getDeliveryFlag().set (0);
  30704. }
  30705. void AsyncUpdater::triggerAsyncUpdate()
  30706. {
  30707. if (getDeliveryFlag().compareAndSetBool (1, 0))
  30708. message->post();
  30709. }
  30710. void AsyncUpdater::cancelPendingUpdate() throw()
  30711. {
  30712. getDeliveryFlag().set (0);
  30713. }
  30714. void AsyncUpdater::handleUpdateNowIfNeeded()
  30715. {
  30716. // This can only be called by the event thread.
  30717. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30718. if (getDeliveryFlag().exchange (0) != 0)
  30719. handleAsyncUpdate();
  30720. }
  30721. bool AsyncUpdater::isUpdatePending() const throw()
  30722. {
  30723. return getDeliveryFlag().value != 0;
  30724. }
  30725. END_JUCE_NAMESPACE
  30726. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30727. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30728. BEGIN_JUCE_NAMESPACE
  30729. ChangeBroadcaster::ChangeBroadcaster() throw()
  30730. {
  30731. // are you trying to create this object before or after juce has been intialised??
  30732. jassert (MessageManager::instance != 0);
  30733. callback.owner = this;
  30734. }
  30735. ChangeBroadcaster::~ChangeBroadcaster()
  30736. {
  30737. // all event-based objects must be deleted BEFORE juce is shut down!
  30738. jassert (MessageManager::instance != 0);
  30739. }
  30740. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30741. {
  30742. // Listeners can only be safely added when the event thread is locked
  30743. // You can use a MessageManagerLock if you need to call this from another thread.
  30744. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30745. changeListeners.add (listener);
  30746. }
  30747. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30748. {
  30749. // Listeners can only be safely added when the event thread is locked
  30750. // You can use a MessageManagerLock if you need to call this from another thread.
  30751. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30752. changeListeners.remove (listener);
  30753. }
  30754. void ChangeBroadcaster::removeAllChangeListeners()
  30755. {
  30756. // Listeners can only be safely added when the event thread is locked
  30757. // You can use a MessageManagerLock if you need to call this from another thread.
  30758. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30759. changeListeners.clear();
  30760. }
  30761. void ChangeBroadcaster::sendChangeMessage()
  30762. {
  30763. if (changeListeners.size() > 0)
  30764. callback.triggerAsyncUpdate();
  30765. }
  30766. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30767. {
  30768. // This can only be called by the event thread.
  30769. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30770. callback.cancelPendingUpdate();
  30771. callListeners();
  30772. }
  30773. void ChangeBroadcaster::dispatchPendingMessages()
  30774. {
  30775. callback.handleUpdateNowIfNeeded();
  30776. }
  30777. void ChangeBroadcaster::callListeners()
  30778. {
  30779. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30780. }
  30781. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30782. : owner (0)
  30783. {
  30784. }
  30785. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30786. {
  30787. jassert (owner != 0);
  30788. owner->callListeners();
  30789. }
  30790. END_JUCE_NAMESPACE
  30791. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30792. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30793. BEGIN_JUCE_NAMESPACE
  30794. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30795. const uint32 magicMessageHeaderNumber)
  30796. : Thread ("Juce IPC connection"),
  30797. callbackConnectionState (false),
  30798. useMessageThread (callbacksOnMessageThread),
  30799. magicMessageHeader (magicMessageHeaderNumber),
  30800. pipeReceiveMessageTimeout (-1)
  30801. {
  30802. }
  30803. InterprocessConnection::~InterprocessConnection()
  30804. {
  30805. callbackConnectionState = false;
  30806. disconnect();
  30807. }
  30808. bool InterprocessConnection::connectToSocket (const String& hostName,
  30809. const int portNumber,
  30810. const int timeOutMillisecs)
  30811. {
  30812. disconnect();
  30813. const ScopedLock sl (pipeAndSocketLock);
  30814. socket = new StreamingSocket();
  30815. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30816. {
  30817. connectionMadeInt();
  30818. startThread();
  30819. return true;
  30820. }
  30821. else
  30822. {
  30823. socket = 0;
  30824. return false;
  30825. }
  30826. }
  30827. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30828. const int pipeReceiveMessageTimeoutMs)
  30829. {
  30830. disconnect();
  30831. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30832. if (newPipe->openExisting (pipeName))
  30833. {
  30834. const ScopedLock sl (pipeAndSocketLock);
  30835. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30836. initialiseWithPipe (newPipe.release());
  30837. return true;
  30838. }
  30839. return false;
  30840. }
  30841. bool InterprocessConnection::createPipe (const String& pipeName,
  30842. const int pipeReceiveMessageTimeoutMs)
  30843. {
  30844. disconnect();
  30845. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30846. if (newPipe->createNewPipe (pipeName))
  30847. {
  30848. const ScopedLock sl (pipeAndSocketLock);
  30849. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30850. initialiseWithPipe (newPipe.release());
  30851. return true;
  30852. }
  30853. return false;
  30854. }
  30855. void InterprocessConnection::disconnect()
  30856. {
  30857. if (socket != 0)
  30858. socket->close();
  30859. if (pipe != 0)
  30860. {
  30861. pipe->cancelPendingReads();
  30862. pipe->close();
  30863. }
  30864. stopThread (4000);
  30865. {
  30866. const ScopedLock sl (pipeAndSocketLock);
  30867. socket = 0;
  30868. pipe = 0;
  30869. }
  30870. connectionLostInt();
  30871. }
  30872. bool InterprocessConnection::isConnected() const
  30873. {
  30874. const ScopedLock sl (pipeAndSocketLock);
  30875. return ((socket != 0 && socket->isConnected())
  30876. || (pipe != 0 && pipe->isOpen()))
  30877. && isThreadRunning();
  30878. }
  30879. const String InterprocessConnection::getConnectedHostName() const
  30880. {
  30881. if (pipe != 0)
  30882. {
  30883. return "localhost";
  30884. }
  30885. else if (socket != 0)
  30886. {
  30887. if (! socket->isLocal())
  30888. return socket->getHostName();
  30889. return "localhost";
  30890. }
  30891. return String::empty;
  30892. }
  30893. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30894. {
  30895. uint32 messageHeader[2];
  30896. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30897. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30898. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30899. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30900. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30901. int bytesWritten = 0;
  30902. const ScopedLock sl (pipeAndSocketLock);
  30903. if (socket != 0)
  30904. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30905. else if (pipe != 0)
  30906. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30907. return bytesWritten == (int) messageData.getSize();
  30908. }
  30909. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30910. {
  30911. jassert (socket == 0);
  30912. socket = socket_;
  30913. connectionMadeInt();
  30914. startThread();
  30915. }
  30916. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30917. {
  30918. jassert (pipe == 0);
  30919. pipe = pipe_;
  30920. connectionMadeInt();
  30921. startThread();
  30922. }
  30923. const int messageMagicNumber = 0xb734128b;
  30924. void InterprocessConnection::handleMessage (const Message& message)
  30925. {
  30926. if (message.intParameter1 == messageMagicNumber)
  30927. {
  30928. switch (message.intParameter2)
  30929. {
  30930. case 0:
  30931. {
  30932. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30933. messageReceived (*data);
  30934. break;
  30935. }
  30936. case 1:
  30937. connectionMade();
  30938. break;
  30939. case 2:
  30940. connectionLost();
  30941. break;
  30942. }
  30943. }
  30944. }
  30945. void InterprocessConnection::connectionMadeInt()
  30946. {
  30947. if (! callbackConnectionState)
  30948. {
  30949. callbackConnectionState = true;
  30950. if (useMessageThread)
  30951. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30952. else
  30953. connectionMade();
  30954. }
  30955. }
  30956. void InterprocessConnection::connectionLostInt()
  30957. {
  30958. if (callbackConnectionState)
  30959. {
  30960. callbackConnectionState = false;
  30961. if (useMessageThread)
  30962. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30963. else
  30964. connectionLost();
  30965. }
  30966. }
  30967. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30968. {
  30969. jassert (callbackConnectionState);
  30970. if (useMessageThread)
  30971. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30972. else
  30973. messageReceived (data);
  30974. }
  30975. bool InterprocessConnection::readNextMessageInt()
  30976. {
  30977. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30978. uint32 messageHeader[2];
  30979. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30980. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30981. if (bytes == sizeof (messageHeader)
  30982. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30983. {
  30984. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30985. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30986. {
  30987. MemoryBlock messageData (bytesInMessage, true);
  30988. int bytesRead = 0;
  30989. while (bytesInMessage > 0)
  30990. {
  30991. if (threadShouldExit())
  30992. return false;
  30993. const int numThisTime = jmin (bytesInMessage, 65536);
  30994. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30995. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30996. if (bytesIn <= 0)
  30997. break;
  30998. bytesRead += bytesIn;
  30999. bytesInMessage -= bytesIn;
  31000. }
  31001. if (bytesRead >= 0)
  31002. deliverDataInt (messageData);
  31003. }
  31004. }
  31005. else if (bytes < 0)
  31006. {
  31007. {
  31008. const ScopedLock sl (pipeAndSocketLock);
  31009. socket = 0;
  31010. }
  31011. connectionLostInt();
  31012. return false;
  31013. }
  31014. return true;
  31015. }
  31016. void InterprocessConnection::run()
  31017. {
  31018. while (! threadShouldExit())
  31019. {
  31020. if (socket != 0)
  31021. {
  31022. const int ready = socket->waitUntilReady (true, 0);
  31023. if (ready < 0)
  31024. {
  31025. {
  31026. const ScopedLock sl (pipeAndSocketLock);
  31027. socket = 0;
  31028. }
  31029. connectionLostInt();
  31030. break;
  31031. }
  31032. else if (ready > 0)
  31033. {
  31034. if (! readNextMessageInt())
  31035. break;
  31036. }
  31037. else
  31038. {
  31039. Thread::sleep (2);
  31040. }
  31041. }
  31042. else if (pipe != 0)
  31043. {
  31044. if (! pipe->isOpen())
  31045. {
  31046. {
  31047. const ScopedLock sl (pipeAndSocketLock);
  31048. pipe = 0;
  31049. }
  31050. connectionLostInt();
  31051. break;
  31052. }
  31053. else
  31054. {
  31055. if (! readNextMessageInt())
  31056. break;
  31057. }
  31058. }
  31059. else
  31060. {
  31061. break;
  31062. }
  31063. }
  31064. }
  31065. END_JUCE_NAMESPACE
  31066. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31067. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31068. BEGIN_JUCE_NAMESPACE
  31069. InterprocessConnectionServer::InterprocessConnectionServer()
  31070. : Thread ("Juce IPC server")
  31071. {
  31072. }
  31073. InterprocessConnectionServer::~InterprocessConnectionServer()
  31074. {
  31075. stop();
  31076. }
  31077. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31078. {
  31079. stop();
  31080. socket = new StreamingSocket();
  31081. if (socket->createListener (portNumber))
  31082. {
  31083. startThread();
  31084. return true;
  31085. }
  31086. socket = 0;
  31087. return false;
  31088. }
  31089. void InterprocessConnectionServer::stop()
  31090. {
  31091. signalThreadShouldExit();
  31092. if (socket != 0)
  31093. socket->close();
  31094. stopThread (4000);
  31095. socket = 0;
  31096. }
  31097. void InterprocessConnectionServer::run()
  31098. {
  31099. while ((! threadShouldExit()) && socket != 0)
  31100. {
  31101. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31102. if (clientSocket != 0)
  31103. {
  31104. InterprocessConnection* newConnection = createConnectionObject();
  31105. if (newConnection != 0)
  31106. newConnection->initialiseWithSocket (clientSocket.release());
  31107. }
  31108. }
  31109. }
  31110. END_JUCE_NAMESPACE
  31111. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31112. /*** Start of inlined file: juce_Message.cpp ***/
  31113. BEGIN_JUCE_NAMESPACE
  31114. Message::Message() throw()
  31115. : intParameter1 (0),
  31116. intParameter2 (0),
  31117. intParameter3 (0),
  31118. pointerParameter (0),
  31119. messageRecipient (0)
  31120. {
  31121. }
  31122. Message::Message (const int intParameter1_,
  31123. const int intParameter2_,
  31124. const int intParameter3_,
  31125. void* const pointerParameter_) throw()
  31126. : intParameter1 (intParameter1_),
  31127. intParameter2 (intParameter2_),
  31128. intParameter3 (intParameter3_),
  31129. pointerParameter (pointerParameter_),
  31130. messageRecipient (0)
  31131. {
  31132. }
  31133. Message::~Message()
  31134. {
  31135. }
  31136. END_JUCE_NAMESPACE
  31137. /*** End of inlined file: juce_Message.cpp ***/
  31138. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31139. BEGIN_JUCE_NAMESPACE
  31140. MessageListener::MessageListener() throw()
  31141. {
  31142. // are you trying to create a messagelistener before or after juce has been intialised??
  31143. jassert (MessageManager::instance != 0);
  31144. if (MessageManager::instance != 0)
  31145. MessageManager::instance->messageListeners.add (this);
  31146. }
  31147. MessageListener::~MessageListener()
  31148. {
  31149. if (MessageManager::instance != 0)
  31150. MessageManager::instance->messageListeners.removeValue (this);
  31151. }
  31152. void MessageListener::postMessage (Message* const message) const throw()
  31153. {
  31154. message->messageRecipient = const_cast <MessageListener*> (this);
  31155. if (MessageManager::instance == 0)
  31156. MessageManager::getInstance();
  31157. MessageManager::instance->postMessageToQueue (message);
  31158. }
  31159. bool MessageListener::isValidMessageListener() const throw()
  31160. {
  31161. return (MessageManager::instance != 0)
  31162. && MessageManager::instance->messageListeners.contains (this);
  31163. }
  31164. END_JUCE_NAMESPACE
  31165. /*** End of inlined file: juce_MessageListener.cpp ***/
  31166. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31167. BEGIN_JUCE_NAMESPACE
  31168. // platform-specific functions..
  31169. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31170. bool juce_postMessageToSystemQueue (Message* message);
  31171. MessageManager* MessageManager::instance = 0;
  31172. static const int quitMessageId = 0xfffff321;
  31173. MessageManager::MessageManager() throw()
  31174. : quitMessagePosted (false),
  31175. quitMessageReceived (false),
  31176. threadWithLock (0)
  31177. {
  31178. messageThreadId = Thread::getCurrentThreadId();
  31179. if (JUCEApplication::isStandaloneApp())
  31180. Thread::setCurrentThreadName ("Juce Message Thread");
  31181. }
  31182. MessageManager::~MessageManager() throw()
  31183. {
  31184. broadcaster = 0;
  31185. doPlatformSpecificShutdown();
  31186. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31187. jassert (messageListeners.size() == 0);
  31188. jassert (instance == this);
  31189. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31190. }
  31191. MessageManager* MessageManager::getInstance() throw()
  31192. {
  31193. if (instance == 0)
  31194. {
  31195. instance = new MessageManager();
  31196. doPlatformSpecificInitialisation();
  31197. }
  31198. return instance;
  31199. }
  31200. void MessageManager::postMessageToQueue (Message* const message)
  31201. {
  31202. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31203. Message::Ptr deleter (message); // (this will delete messages that were just created with a 0 ref count)
  31204. }
  31205. CallbackMessage::CallbackMessage() throw() {}
  31206. CallbackMessage::~CallbackMessage() {}
  31207. void CallbackMessage::post()
  31208. {
  31209. if (MessageManager::instance != 0)
  31210. MessageManager::instance->postMessageToQueue (this);
  31211. }
  31212. // not for public use..
  31213. void MessageManager::deliverMessage (Message* const message)
  31214. {
  31215. JUCE_TRY
  31216. {
  31217. MessageListener* const recipient = message->messageRecipient;
  31218. if (recipient == 0)
  31219. {
  31220. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31221. if (callbackMessage != 0)
  31222. {
  31223. callbackMessage->messageCallback();
  31224. }
  31225. else if (message->intParameter1 == quitMessageId)
  31226. {
  31227. quitMessageReceived = true;
  31228. }
  31229. }
  31230. else if (messageListeners.contains (recipient))
  31231. {
  31232. recipient->handleMessage (*message);
  31233. }
  31234. }
  31235. JUCE_CATCH_EXCEPTION
  31236. }
  31237. #if JUCE_MODAL_LOOPS_PERMITTED && ! (JUCE_MAC || JUCE_IOS)
  31238. void MessageManager::runDispatchLoop()
  31239. {
  31240. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31241. runDispatchLoopUntil (-1);
  31242. }
  31243. void MessageManager::stopDispatchLoop()
  31244. {
  31245. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31246. quitMessagePosted = true;
  31247. }
  31248. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31249. {
  31250. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31251. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31252. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31253. && ! quitMessageReceived)
  31254. {
  31255. JUCE_TRY
  31256. {
  31257. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31258. {
  31259. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31260. if (msToWait > 0)
  31261. Thread::sleep (jmin (5, msToWait));
  31262. }
  31263. }
  31264. JUCE_CATCH_EXCEPTION
  31265. }
  31266. return ! quitMessageReceived;
  31267. }
  31268. #endif
  31269. void MessageManager::deliverBroadcastMessage (const String& value)
  31270. {
  31271. if (broadcaster != 0)
  31272. broadcaster->sendActionMessage (value);
  31273. }
  31274. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31275. {
  31276. if (broadcaster == 0)
  31277. broadcaster = new ActionBroadcaster();
  31278. broadcaster->addActionListener (listener);
  31279. }
  31280. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31281. {
  31282. if (broadcaster != 0)
  31283. broadcaster->removeActionListener (listener);
  31284. }
  31285. bool MessageManager::isThisTheMessageThread() const throw()
  31286. {
  31287. return Thread::getCurrentThreadId() == messageThreadId;
  31288. }
  31289. void MessageManager::setCurrentThreadAsMessageThread()
  31290. {
  31291. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31292. if (messageThreadId != thisThread)
  31293. {
  31294. messageThreadId = thisThread;
  31295. // This is needed on windows to make sure the message window is created by this thread
  31296. doPlatformSpecificShutdown();
  31297. doPlatformSpecificInitialisation();
  31298. }
  31299. }
  31300. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31301. {
  31302. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31303. return thisThread == messageThreadId || thisThread == threadWithLock;
  31304. }
  31305. /* The only safe way to lock the message thread while another thread does
  31306. some work is by posting a special message, whose purpose is to tie up the event
  31307. loop until the other thread has finished its business.
  31308. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31309. get locked before making an event callback, because if the same OS lock gets indirectly
  31310. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31311. in Cocoa).
  31312. */
  31313. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31314. {
  31315. public:
  31316. BlockingMessage() {}
  31317. void messageCallback()
  31318. {
  31319. lockedEvent.signal();
  31320. releaseEvent.wait();
  31321. }
  31322. WaitableEvent lockedEvent, releaseEvent;
  31323. private:
  31324. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31325. };
  31326. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31327. : locked (false)
  31328. {
  31329. init (threadToCheck, 0);
  31330. }
  31331. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31332. : locked (false)
  31333. {
  31334. init (0, jobToCheckForExitSignal);
  31335. }
  31336. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31337. {
  31338. if (MessageManager::instance != 0)
  31339. {
  31340. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31341. {
  31342. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31343. }
  31344. else
  31345. {
  31346. if (threadToCheck == 0 && job == 0)
  31347. {
  31348. MessageManager::instance->lockingLock.enter();
  31349. }
  31350. else
  31351. {
  31352. while (! MessageManager::instance->lockingLock.tryEnter())
  31353. {
  31354. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31355. || (job != 0 && job->shouldExit()))
  31356. return;
  31357. Thread::sleep (1);
  31358. }
  31359. }
  31360. blockingMessage = new BlockingMessage();
  31361. blockingMessage->post();
  31362. while (! blockingMessage->lockedEvent.wait (20))
  31363. {
  31364. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31365. || (job != 0 && job->shouldExit()))
  31366. {
  31367. blockingMessage->releaseEvent.signal();
  31368. blockingMessage = 0;
  31369. MessageManager::instance->lockingLock.exit();
  31370. return;
  31371. }
  31372. }
  31373. jassert (MessageManager::instance->threadWithLock == 0);
  31374. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31375. locked = true;
  31376. }
  31377. }
  31378. }
  31379. MessageManagerLock::~MessageManagerLock() throw()
  31380. {
  31381. if (blockingMessage != 0)
  31382. {
  31383. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31384. blockingMessage->releaseEvent.signal();
  31385. blockingMessage = 0;
  31386. if (MessageManager::instance != 0)
  31387. {
  31388. MessageManager::instance->threadWithLock = 0;
  31389. MessageManager::instance->lockingLock.exit();
  31390. }
  31391. }
  31392. }
  31393. END_JUCE_NAMESPACE
  31394. /*** End of inlined file: juce_MessageManager.cpp ***/
  31395. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31396. BEGIN_JUCE_NAMESPACE
  31397. class MultiTimer::MultiTimerCallback : public Timer
  31398. {
  31399. public:
  31400. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31401. : timerId (timerId_),
  31402. owner (owner_)
  31403. {
  31404. }
  31405. ~MultiTimerCallback()
  31406. {
  31407. }
  31408. void timerCallback()
  31409. {
  31410. owner.timerCallback (timerId);
  31411. }
  31412. const int timerId;
  31413. private:
  31414. MultiTimer& owner;
  31415. };
  31416. MultiTimer::MultiTimer() throw()
  31417. {
  31418. }
  31419. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31420. {
  31421. }
  31422. MultiTimer::~MultiTimer()
  31423. {
  31424. const ScopedLock sl (timerListLock);
  31425. timers.clear();
  31426. }
  31427. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31428. {
  31429. const ScopedLock sl (timerListLock);
  31430. for (int i = timers.size(); --i >= 0;)
  31431. {
  31432. MultiTimerCallback* const t = timers.getUnchecked(i);
  31433. if (t->timerId == timerId)
  31434. {
  31435. t->startTimer (intervalInMilliseconds);
  31436. return;
  31437. }
  31438. }
  31439. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31440. timers.add (newTimer);
  31441. newTimer->startTimer (intervalInMilliseconds);
  31442. }
  31443. void MultiTimer::stopTimer (const int timerId) throw()
  31444. {
  31445. const ScopedLock sl (timerListLock);
  31446. for (int i = timers.size(); --i >= 0;)
  31447. {
  31448. MultiTimerCallback* const t = timers.getUnchecked(i);
  31449. if (t->timerId == timerId)
  31450. t->stopTimer();
  31451. }
  31452. }
  31453. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31454. {
  31455. const ScopedLock sl (timerListLock);
  31456. for (int i = timers.size(); --i >= 0;)
  31457. {
  31458. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31459. if (t->timerId == timerId)
  31460. return t->isTimerRunning();
  31461. }
  31462. return false;
  31463. }
  31464. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31465. {
  31466. const ScopedLock sl (timerListLock);
  31467. for (int i = timers.size(); --i >= 0;)
  31468. {
  31469. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31470. if (t->timerId == timerId)
  31471. return t->getTimerInterval();
  31472. }
  31473. return 0;
  31474. }
  31475. END_JUCE_NAMESPACE
  31476. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31477. /*** Start of inlined file: juce_Timer.cpp ***/
  31478. BEGIN_JUCE_NAMESPACE
  31479. class InternalTimerThread : private Thread,
  31480. private MessageListener,
  31481. private DeletedAtShutdown,
  31482. private AsyncUpdater
  31483. {
  31484. public:
  31485. InternalTimerThread()
  31486. : Thread ("Juce Timer"),
  31487. firstTimer (0),
  31488. callbackNeeded (0)
  31489. {
  31490. triggerAsyncUpdate();
  31491. }
  31492. ~InternalTimerThread() throw()
  31493. {
  31494. stopThread (4000);
  31495. jassert (instance == this || instance == 0);
  31496. if (instance == this)
  31497. instance = 0;
  31498. }
  31499. void run()
  31500. {
  31501. uint32 lastTime = Time::getMillisecondCounter();
  31502. Message::Ptr message (new Message());
  31503. while (! threadShouldExit())
  31504. {
  31505. const uint32 now = Time::getMillisecondCounter();
  31506. if (now <= lastTime)
  31507. {
  31508. wait (2);
  31509. continue;
  31510. }
  31511. const int elapsed = now - lastTime;
  31512. lastTime = now;
  31513. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31514. if (timeUntilFirstTimer <= 0)
  31515. {
  31516. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31517. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31518. but if it fails it means the message-thread changed the value from under us so at least
  31519. some processing is happenening and we can just loop around and try again
  31520. */
  31521. if (callbackNeeded.compareAndSetBool (1, 0))
  31522. {
  31523. postMessage (message);
  31524. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31525. when the app has a modal loop), so this is how long to wait before assuming the
  31526. message has been lost and trying again.
  31527. */
  31528. const uint32 messageDeliveryTimeout = now + 2000;
  31529. while (callbackNeeded.get() != 0)
  31530. {
  31531. wait (4);
  31532. if (threadShouldExit())
  31533. return;
  31534. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31535. break;
  31536. }
  31537. }
  31538. }
  31539. else
  31540. {
  31541. // don't wait for too long because running this loop also helps keep the
  31542. // Time::getApproximateMillisecondTimer value stay up-to-date
  31543. wait (jlimit (1, 50, timeUntilFirstTimer));
  31544. }
  31545. }
  31546. }
  31547. void callTimers()
  31548. {
  31549. const ScopedLock sl (lock);
  31550. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31551. {
  31552. Timer* const t = firstTimer;
  31553. t->countdownMs = t->periodMs;
  31554. removeTimer (t);
  31555. addTimer (t);
  31556. const ScopedUnlock ul (lock);
  31557. JUCE_TRY
  31558. {
  31559. t->timerCallback();
  31560. }
  31561. JUCE_CATCH_EXCEPTION
  31562. }
  31563. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31564. before the boolean is set. This set should never fail since if it was false in the first place,
  31565. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31566. get a message then the value is true and the other thread can only set it to true again and
  31567. we will get another callback to set it to false.
  31568. */
  31569. callbackNeeded.set (0);
  31570. }
  31571. void handleMessage (const Message&)
  31572. {
  31573. callTimers();
  31574. }
  31575. void callTimersSynchronously()
  31576. {
  31577. if (! isThreadRunning())
  31578. {
  31579. // (This is relied on by some plugins in cases where the MM has
  31580. // had to restart and the async callback never started)
  31581. cancelPendingUpdate();
  31582. triggerAsyncUpdate();
  31583. }
  31584. callTimers();
  31585. }
  31586. static void callAnyTimersSynchronously()
  31587. {
  31588. if (InternalTimerThread::instance != 0)
  31589. InternalTimerThread::instance->callTimersSynchronously();
  31590. }
  31591. static inline void add (Timer* const tim) throw()
  31592. {
  31593. if (instance == 0)
  31594. instance = new InternalTimerThread();
  31595. const ScopedLock sl (instance->lock);
  31596. instance->addTimer (tim);
  31597. }
  31598. static inline void remove (Timer* const tim) throw()
  31599. {
  31600. if (instance != 0)
  31601. {
  31602. const ScopedLock sl (instance->lock);
  31603. instance->removeTimer (tim);
  31604. }
  31605. }
  31606. static inline void resetCounter (Timer* const tim,
  31607. const int newCounter) throw()
  31608. {
  31609. if (instance != 0)
  31610. {
  31611. tim->countdownMs = newCounter;
  31612. tim->periodMs = newCounter;
  31613. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31614. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31615. {
  31616. const ScopedLock sl (instance->lock);
  31617. instance->removeTimer (tim);
  31618. instance->addTimer (tim);
  31619. }
  31620. }
  31621. }
  31622. private:
  31623. friend class Timer;
  31624. static InternalTimerThread* instance;
  31625. static CriticalSection lock;
  31626. Timer* volatile firstTimer;
  31627. Atomic <int> callbackNeeded;
  31628. void addTimer (Timer* const t) throw()
  31629. {
  31630. #if JUCE_DEBUG
  31631. Timer* tt = firstTimer;
  31632. while (tt != 0)
  31633. {
  31634. // trying to add a timer that's already here - shouldn't get to this point,
  31635. // so if you get this assertion, let me know!
  31636. jassert (tt != t);
  31637. tt = tt->next;
  31638. }
  31639. jassert (t->previous == 0 && t->next == 0);
  31640. #endif
  31641. Timer* i = firstTimer;
  31642. if (i == 0 || i->countdownMs > t->countdownMs)
  31643. {
  31644. t->next = firstTimer;
  31645. firstTimer = t;
  31646. }
  31647. else
  31648. {
  31649. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31650. i = i->next;
  31651. jassert (i != 0);
  31652. t->next = i->next;
  31653. t->previous = i;
  31654. i->next = t;
  31655. }
  31656. if (t->next != 0)
  31657. t->next->previous = t;
  31658. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31659. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31660. notify();
  31661. }
  31662. void removeTimer (Timer* const t) throw()
  31663. {
  31664. #if JUCE_DEBUG
  31665. Timer* tt = firstTimer;
  31666. bool found = false;
  31667. while (tt != 0)
  31668. {
  31669. if (tt == t)
  31670. {
  31671. found = true;
  31672. break;
  31673. }
  31674. tt = tt->next;
  31675. }
  31676. // trying to remove a timer that's not here - shouldn't get to this point,
  31677. // so if you get this assertion, let me know!
  31678. jassert (found);
  31679. #endif
  31680. if (t->previous != 0)
  31681. {
  31682. jassert (firstTimer != t);
  31683. t->previous->next = t->next;
  31684. }
  31685. else
  31686. {
  31687. jassert (firstTimer == t);
  31688. firstTimer = t->next;
  31689. }
  31690. if (t->next != 0)
  31691. t->next->previous = t->previous;
  31692. t->next = 0;
  31693. t->previous = 0;
  31694. }
  31695. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31696. {
  31697. const ScopedLock sl (lock);
  31698. for (Timer* t = firstTimer; t != 0; t = t->next)
  31699. t->countdownMs -= numMillisecsElapsed;
  31700. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31701. }
  31702. void handleAsyncUpdate()
  31703. {
  31704. startThread (7);
  31705. }
  31706. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalTimerThread);
  31707. };
  31708. InternalTimerThread* InternalTimerThread::instance = 0;
  31709. CriticalSection InternalTimerThread::lock;
  31710. void juce_callAnyTimersSynchronously()
  31711. {
  31712. InternalTimerThread::callAnyTimersSynchronously();
  31713. }
  31714. #if JUCE_DEBUG
  31715. static SortedSet <Timer*> activeTimers;
  31716. #endif
  31717. Timer::Timer() throw()
  31718. : countdownMs (0),
  31719. periodMs (0),
  31720. previous (0),
  31721. next (0)
  31722. {
  31723. #if JUCE_DEBUG
  31724. activeTimers.add (this);
  31725. #endif
  31726. }
  31727. Timer::Timer (const Timer&) throw()
  31728. : countdownMs (0),
  31729. periodMs (0),
  31730. previous (0),
  31731. next (0)
  31732. {
  31733. #if JUCE_DEBUG
  31734. activeTimers.add (this);
  31735. #endif
  31736. }
  31737. Timer::~Timer()
  31738. {
  31739. stopTimer();
  31740. #if JUCE_DEBUG
  31741. activeTimers.removeValue (this);
  31742. #endif
  31743. }
  31744. void Timer::startTimer (const int interval) throw()
  31745. {
  31746. const ScopedLock sl (InternalTimerThread::lock);
  31747. #if JUCE_DEBUG
  31748. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31749. jassert (activeTimers.contains (this));
  31750. #endif
  31751. if (periodMs == 0)
  31752. {
  31753. countdownMs = interval;
  31754. periodMs = jmax (1, interval);
  31755. InternalTimerThread::add (this);
  31756. }
  31757. else
  31758. {
  31759. InternalTimerThread::resetCounter (this, interval);
  31760. }
  31761. }
  31762. void Timer::stopTimer() throw()
  31763. {
  31764. const ScopedLock sl (InternalTimerThread::lock);
  31765. #if JUCE_DEBUG
  31766. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31767. jassert (activeTimers.contains (this));
  31768. #endif
  31769. if (periodMs > 0)
  31770. {
  31771. InternalTimerThread::remove (this);
  31772. periodMs = 0;
  31773. }
  31774. }
  31775. END_JUCE_NAMESPACE
  31776. /*** End of inlined file: juce_Timer.cpp ***/
  31777. #endif
  31778. #if JUCE_BUILD_GUI
  31779. /*** Start of inlined file: juce_Component.cpp ***/
  31780. BEGIN_JUCE_NAMESPACE
  31781. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31782. Component* Component::currentlyFocusedComponent = 0;
  31783. class Component::MouseListenerList
  31784. {
  31785. public:
  31786. MouseListenerList()
  31787. : numDeepMouseListeners (0)
  31788. {
  31789. }
  31790. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31791. {
  31792. if (! listeners.contains (newListener))
  31793. {
  31794. if (wantsEventsForAllNestedChildComponents)
  31795. {
  31796. listeners.insert (0, newListener);
  31797. ++numDeepMouseListeners;
  31798. }
  31799. else
  31800. {
  31801. listeners.add (newListener);
  31802. }
  31803. }
  31804. }
  31805. void removeListener (MouseListener* const listenerToRemove)
  31806. {
  31807. const int index = listeners.indexOf (listenerToRemove);
  31808. if (index >= 0)
  31809. {
  31810. if (index < numDeepMouseListeners)
  31811. --numDeepMouseListeners;
  31812. listeners.remove (index);
  31813. }
  31814. }
  31815. static void sendMouseEvent (Component& comp, BailOutChecker& checker,
  31816. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  31817. {
  31818. if (checker.shouldBailOut())
  31819. return;
  31820. {
  31821. MouseListenerList* const list = comp.mouseListeners;
  31822. if (list != 0)
  31823. {
  31824. for (int i = list->listeners.size(); --i >= 0;)
  31825. {
  31826. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31827. if (checker.shouldBailOut())
  31828. return;
  31829. i = jmin (i, list->listeners.size());
  31830. }
  31831. }
  31832. }
  31833. Component* p = comp.parentComponent;
  31834. while (p != 0)
  31835. {
  31836. MouseListenerList* const list = p->mouseListeners;
  31837. if (list != 0 && list->numDeepMouseListeners > 0)
  31838. {
  31839. BailOutChecker2 checker2 (checker, p);
  31840. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31841. {
  31842. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31843. if (checker2.shouldBailOut())
  31844. return;
  31845. i = jmin (i, list->numDeepMouseListeners);
  31846. }
  31847. }
  31848. p = p->parentComponent;
  31849. }
  31850. }
  31851. static void sendWheelEvent (Component& comp, BailOutChecker& checker, const MouseEvent& e,
  31852. const float wheelIncrementX, const float wheelIncrementY)
  31853. {
  31854. {
  31855. MouseListenerList* const list = comp.mouseListeners;
  31856. if (list != 0)
  31857. {
  31858. for (int i = list->listeners.size(); --i >= 0;)
  31859. {
  31860. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31861. if (checker.shouldBailOut())
  31862. return;
  31863. i = jmin (i, list->listeners.size());
  31864. }
  31865. }
  31866. }
  31867. Component* p = comp.parentComponent;
  31868. while (p != 0)
  31869. {
  31870. MouseListenerList* const list = p->mouseListeners;
  31871. if (list != 0 && list->numDeepMouseListeners > 0)
  31872. {
  31873. BailOutChecker2 checker2 (checker, p);
  31874. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31875. {
  31876. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31877. if (checker2.shouldBailOut())
  31878. return;
  31879. i = jmin (i, list->numDeepMouseListeners);
  31880. }
  31881. }
  31882. p = p->parentComponent;
  31883. }
  31884. }
  31885. private:
  31886. Array <MouseListener*> listeners;
  31887. int numDeepMouseListeners;
  31888. class BailOutChecker2
  31889. {
  31890. public:
  31891. BailOutChecker2 (BailOutChecker& checker_, Component* const component)
  31892. : checker (checker_), safePointer (component)
  31893. {
  31894. }
  31895. bool shouldBailOut() const throw()
  31896. {
  31897. return checker.shouldBailOut() || safePointer == 0;
  31898. }
  31899. private:
  31900. BailOutChecker& checker;
  31901. const WeakReference<Component> safePointer;
  31902. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2);
  31903. };
  31904. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  31905. };
  31906. class Component::ComponentHelpers
  31907. {
  31908. public:
  31909. #if JUCE_MODAL_LOOPS_PERMITTED
  31910. static void* runModalLoopCallback (void* userData)
  31911. {
  31912. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  31913. }
  31914. #endif
  31915. static const Identifier getColourPropertyId (const int colourId)
  31916. {
  31917. String s;
  31918. s.preallocateStorage (18);
  31919. s << "jcclr_" << String::toHexString (colourId);
  31920. return s;
  31921. }
  31922. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  31923. {
  31924. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  31925. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  31926. && comp.hitTest (localPoint.getX(), localPoint.getY());
  31927. }
  31928. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  31929. {
  31930. if (comp.affineTransform == 0)
  31931. return pointInParentSpace - comp.getPosition();
  31932. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  31933. }
  31934. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  31935. {
  31936. if (comp.affineTransform == 0)
  31937. return areaInParentSpace - comp.getPosition();
  31938. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  31939. }
  31940. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  31941. {
  31942. if (comp.affineTransform == 0)
  31943. return pointInLocalSpace + comp.getPosition();
  31944. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  31945. }
  31946. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  31947. {
  31948. if (comp.affineTransform == 0)
  31949. return areaInLocalSpace + comp.getPosition();
  31950. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  31951. }
  31952. template <typename Type>
  31953. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  31954. {
  31955. const Component* const directParent = target.getParentComponent();
  31956. jassert (directParent != 0);
  31957. if (directParent == parent)
  31958. return convertFromParentSpace (target, coordInParent);
  31959. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  31960. }
  31961. template <typename Type>
  31962. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  31963. {
  31964. while (source != 0)
  31965. {
  31966. if (source == target)
  31967. return p;
  31968. if (source->isParentOf (target))
  31969. return convertFromDistantParentSpace (source, *target, p);
  31970. if (source->isOnDesktop())
  31971. {
  31972. p = source->getPeer()->localToGlobal (p);
  31973. source = 0;
  31974. }
  31975. else
  31976. {
  31977. p = convertToParentSpace (*source, p);
  31978. source = source->getParentComponent();
  31979. }
  31980. }
  31981. jassert (source == 0);
  31982. if (target == 0)
  31983. return p;
  31984. const Component* const topLevelComp = target->getTopLevelComponent();
  31985. if (topLevelComp->isOnDesktop())
  31986. p = topLevelComp->getPeer()->globalToLocal (p);
  31987. else
  31988. p = convertFromParentSpace (*topLevelComp, p);
  31989. if (topLevelComp == target)
  31990. return p;
  31991. return convertFromDistantParentSpace (topLevelComp, *target, p);
  31992. }
  31993. static const Rectangle<int> getUnclippedArea (const Component& comp)
  31994. {
  31995. Rectangle<int> r (comp.getLocalBounds());
  31996. Component* const p = comp.getParentComponent();
  31997. if (p != 0)
  31998. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  31999. return r;
  32000. }
  32001. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  32002. {
  32003. for (int i = comp.childComponentList.size(); --i >= 0;)
  32004. {
  32005. const Component& child = *comp.childComponentList.getUnchecked(i);
  32006. if (child.isVisible() && ! child.isTransformed())
  32007. {
  32008. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  32009. if (! newClip.isEmpty())
  32010. {
  32011. if (child.isOpaque())
  32012. {
  32013. g.excludeClipRegion (newClip + delta);
  32014. }
  32015. else
  32016. {
  32017. const Point<int> childPos (child.getPosition());
  32018. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  32019. }
  32020. }
  32021. }
  32022. }
  32023. }
  32024. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  32025. const Point<int>& delta,
  32026. const Rectangle<int>& clipRect,
  32027. const Component* const compToAvoid)
  32028. {
  32029. for (int i = comp.childComponentList.size(); --i >= 0;)
  32030. {
  32031. const Component* const c = comp.childComponentList.getUnchecked(i);
  32032. if (c != compToAvoid && c->isVisible())
  32033. {
  32034. if (c->isOpaque())
  32035. {
  32036. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  32037. childBounds.translate (delta.getX(), delta.getY());
  32038. result.subtract (childBounds);
  32039. }
  32040. else
  32041. {
  32042. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  32043. newClip.translate (-c->getX(), -c->getY());
  32044. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  32045. newClip, compToAvoid);
  32046. }
  32047. }
  32048. }
  32049. }
  32050. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  32051. {
  32052. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  32053. : Desktop::getInstance().getMainMonitorArea();
  32054. }
  32055. };
  32056. Component::Component()
  32057. : parentComponent (0),
  32058. lookAndFeel (0),
  32059. effect (0),
  32060. componentFlags (0),
  32061. componentTransparency (0)
  32062. {
  32063. }
  32064. Component::Component (const String& name)
  32065. : componentName (name),
  32066. parentComponent (0),
  32067. lookAndFeel (0),
  32068. effect (0),
  32069. componentFlags (0),
  32070. componentTransparency (0)
  32071. {
  32072. }
  32073. Component::~Component()
  32074. {
  32075. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  32076. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  32077. #endif
  32078. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32079. weakReferenceMaster.clear();
  32080. while (childComponentList.size() > 0)
  32081. removeChildComponent (childComponentList.size() - 1, false, true);
  32082. if (parentComponent != 0)
  32083. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  32084. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32085. giveAwayFocus (currentlyFocusedComponent != this);
  32086. if (flags.hasHeavyweightPeerFlag)
  32087. removeFromDesktop();
  32088. // Something has added some children to this component during its destructor! Not a smart idea!
  32089. jassert (childComponentList.size() == 0);
  32090. }
  32091. const WeakReference<Component>::SharedRef& Component::getWeakReference()
  32092. {
  32093. return weakReferenceMaster (this);
  32094. }
  32095. void Component::setName (const String& name)
  32096. {
  32097. // if component methods are being called from threads other than the message
  32098. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32099. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32100. if (componentName != name)
  32101. {
  32102. componentName = name;
  32103. if (flags.hasHeavyweightPeerFlag)
  32104. {
  32105. ComponentPeer* const peer = getPeer();
  32106. jassert (peer != 0);
  32107. if (peer != 0)
  32108. peer->setTitle (name);
  32109. }
  32110. BailOutChecker checker (this);
  32111. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32112. }
  32113. }
  32114. void Component::setComponentID (const String& newID)
  32115. {
  32116. componentID = newID;
  32117. }
  32118. void Component::setVisible (bool shouldBeVisible)
  32119. {
  32120. if (flags.visibleFlag != shouldBeVisible)
  32121. {
  32122. // if component methods are being called from threads other than the message
  32123. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32124. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32125. WeakReference<Component> safePointer (this);
  32126. flags.visibleFlag = shouldBeVisible;
  32127. internalRepaint (0, 0, getWidth(), getHeight());
  32128. sendFakeMouseMove();
  32129. if (! shouldBeVisible)
  32130. {
  32131. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32132. {
  32133. if (parentComponent != 0)
  32134. parentComponent->grabKeyboardFocus();
  32135. else
  32136. giveAwayFocus (true);
  32137. }
  32138. }
  32139. if (safePointer != 0)
  32140. {
  32141. sendVisibilityChangeMessage();
  32142. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32143. {
  32144. ComponentPeer* const peer = getPeer();
  32145. jassert (peer != 0);
  32146. if (peer != 0)
  32147. {
  32148. peer->setVisible (shouldBeVisible);
  32149. internalHierarchyChanged();
  32150. }
  32151. }
  32152. }
  32153. }
  32154. }
  32155. void Component::visibilityChanged()
  32156. {
  32157. }
  32158. void Component::sendVisibilityChangeMessage()
  32159. {
  32160. BailOutChecker checker (this);
  32161. visibilityChanged();
  32162. if (! checker.shouldBailOut())
  32163. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32164. }
  32165. bool Component::isShowing() const
  32166. {
  32167. if (flags.visibleFlag)
  32168. {
  32169. if (parentComponent != 0)
  32170. {
  32171. return parentComponent->isShowing();
  32172. }
  32173. else
  32174. {
  32175. const ComponentPeer* const peer = getPeer();
  32176. return peer != 0 && ! peer->isMinimised();
  32177. }
  32178. }
  32179. return false;
  32180. }
  32181. void* Component::getWindowHandle() const
  32182. {
  32183. const ComponentPeer* const peer = getPeer();
  32184. if (peer != 0)
  32185. return peer->getNativeHandle();
  32186. return 0;
  32187. }
  32188. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32189. {
  32190. // if component methods are being called from threads other than the message
  32191. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32192. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32193. if (isOpaque())
  32194. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32195. else
  32196. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32197. int currentStyleFlags = 0;
  32198. // don't use getPeer(), so that we only get the peer that's specifically
  32199. // for this comp, and not for one of its parents.
  32200. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32201. if (peer != 0)
  32202. currentStyleFlags = peer->getStyleFlags();
  32203. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32204. {
  32205. WeakReference<Component> safePointer (this);
  32206. #if JUCE_LINUX
  32207. // it's wise to give the component a non-zero size before
  32208. // putting it on the desktop, as X windows get confused by this, and
  32209. // a (1, 1) minimum size is enforced here.
  32210. setSize (jmax (1, getWidth()),
  32211. jmax (1, getHeight()));
  32212. #endif
  32213. const Point<int> topLeft (getScreenPosition());
  32214. bool wasFullscreen = false;
  32215. bool wasMinimised = false;
  32216. ComponentBoundsConstrainer* currentConstainer = 0;
  32217. Rectangle<int> oldNonFullScreenBounds;
  32218. if (peer != 0)
  32219. {
  32220. wasFullscreen = peer->isFullScreen();
  32221. wasMinimised = peer->isMinimised();
  32222. currentConstainer = peer->getConstrainer();
  32223. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32224. removeFromDesktop();
  32225. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32226. }
  32227. if (parentComponent != 0)
  32228. parentComponent->removeChildComponent (this);
  32229. if (safePointer != 0)
  32230. {
  32231. flags.hasHeavyweightPeerFlag = true;
  32232. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32233. Desktop::getInstance().addDesktopComponent (this);
  32234. bounds.setPosition (topLeft);
  32235. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32236. peer->setVisible (isVisible());
  32237. if (wasFullscreen)
  32238. {
  32239. peer->setFullScreen (true);
  32240. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32241. }
  32242. if (wasMinimised)
  32243. peer->setMinimised (true);
  32244. if (isAlwaysOnTop())
  32245. peer->setAlwaysOnTop (true);
  32246. peer->setConstrainer (currentConstainer);
  32247. repaint();
  32248. }
  32249. internalHierarchyChanged();
  32250. }
  32251. }
  32252. void Component::removeFromDesktop()
  32253. {
  32254. // if component methods are being called from threads other than the message
  32255. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32256. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32257. if (flags.hasHeavyweightPeerFlag)
  32258. {
  32259. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32260. flags.hasHeavyweightPeerFlag = false;
  32261. jassert (peer != 0);
  32262. delete peer;
  32263. Desktop::getInstance().removeDesktopComponent (this);
  32264. }
  32265. }
  32266. bool Component::isOnDesktop() const throw()
  32267. {
  32268. return flags.hasHeavyweightPeerFlag;
  32269. }
  32270. void Component::userTriedToCloseWindow()
  32271. {
  32272. /* This means that the user's trying to get rid of your window with the 'close window' system
  32273. menu option (on windows) or possibly the task manager - you should really handle this
  32274. and delete or hide your component in an appropriate way.
  32275. If you want to ignore the event and don't want to trigger this assertion, just override
  32276. this method and do nothing.
  32277. */
  32278. jassertfalse;
  32279. }
  32280. void Component::minimisationStateChanged (bool)
  32281. {
  32282. }
  32283. void Component::setOpaque (const bool shouldBeOpaque)
  32284. {
  32285. if (shouldBeOpaque != flags.opaqueFlag)
  32286. {
  32287. flags.opaqueFlag = shouldBeOpaque;
  32288. if (flags.hasHeavyweightPeerFlag)
  32289. {
  32290. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32291. if (peer != 0)
  32292. {
  32293. // to make it recreate the heavyweight window
  32294. addToDesktop (peer->getStyleFlags());
  32295. }
  32296. }
  32297. repaint();
  32298. }
  32299. }
  32300. bool Component::isOpaque() const throw()
  32301. {
  32302. return flags.opaqueFlag;
  32303. }
  32304. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32305. {
  32306. if (shouldBeBuffered != flags.bufferToImageFlag)
  32307. {
  32308. bufferedImage = Image::null;
  32309. flags.bufferToImageFlag = shouldBeBuffered;
  32310. }
  32311. }
  32312. void Component::moveChildInternal (const int sourceIndex, const int destIndex)
  32313. {
  32314. if (sourceIndex != destIndex)
  32315. {
  32316. Component* const c = childComponentList.getUnchecked (sourceIndex);
  32317. jassert (c != 0);
  32318. c->repaintParent();
  32319. childComponentList.move (sourceIndex, destIndex);
  32320. sendFakeMouseMove();
  32321. internalChildrenChanged();
  32322. }
  32323. }
  32324. void Component::toFront (const bool setAsForeground)
  32325. {
  32326. // if component methods are being called from threads other than the message
  32327. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32328. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32329. if (flags.hasHeavyweightPeerFlag)
  32330. {
  32331. ComponentPeer* const peer = getPeer();
  32332. if (peer != 0)
  32333. {
  32334. peer->toFront (setAsForeground);
  32335. if (setAsForeground && ! hasKeyboardFocus (true))
  32336. grabKeyboardFocus();
  32337. }
  32338. }
  32339. else if (parentComponent != 0)
  32340. {
  32341. const Array<Component*>& childList = parentComponent->childComponentList;
  32342. if (childList.getLast() != this)
  32343. {
  32344. const int index = childList.indexOf (this);
  32345. if (index >= 0)
  32346. {
  32347. int insertIndex = -1;
  32348. if (! flags.alwaysOnTopFlag)
  32349. {
  32350. insertIndex = childList.size() - 1;
  32351. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32352. --insertIndex;
  32353. }
  32354. parentComponent->moveChildInternal (index, insertIndex);
  32355. }
  32356. }
  32357. if (setAsForeground)
  32358. {
  32359. internalBroughtToFront();
  32360. grabKeyboardFocus();
  32361. }
  32362. }
  32363. }
  32364. void Component::toBehind (Component* const other)
  32365. {
  32366. if (other != 0 && other != this)
  32367. {
  32368. // the two components must belong to the same parent..
  32369. jassert (parentComponent == other->parentComponent);
  32370. if (parentComponent != 0)
  32371. {
  32372. const Array<Component*>& childList = parentComponent->childComponentList;
  32373. const int index = childList.indexOf (this);
  32374. if (index >= 0 && childList [index + 1] != other)
  32375. {
  32376. int otherIndex = childList.indexOf (other);
  32377. if (otherIndex >= 0)
  32378. {
  32379. if (index < otherIndex)
  32380. --otherIndex;
  32381. parentComponent->moveChildInternal (index, otherIndex);
  32382. }
  32383. }
  32384. }
  32385. else if (isOnDesktop())
  32386. {
  32387. jassert (other->isOnDesktop());
  32388. if (other->isOnDesktop())
  32389. {
  32390. ComponentPeer* const us = getPeer();
  32391. ComponentPeer* const them = other->getPeer();
  32392. jassert (us != 0 && them != 0);
  32393. if (us != 0 && them != 0)
  32394. us->toBehind (them);
  32395. }
  32396. }
  32397. }
  32398. }
  32399. void Component::toBack()
  32400. {
  32401. if (isOnDesktop())
  32402. {
  32403. jassertfalse; //xxx need to add this to native window
  32404. }
  32405. else if (parentComponent != 0)
  32406. {
  32407. const Array<Component*>& childList = parentComponent->childComponentList;
  32408. if (childList.getFirst() != this)
  32409. {
  32410. const int index = childList.indexOf (this);
  32411. if (index > 0)
  32412. {
  32413. int insertIndex = 0;
  32414. if (flags.alwaysOnTopFlag)
  32415. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32416. ++insertIndex;
  32417. parentComponent->moveChildInternal (index, insertIndex);
  32418. }
  32419. }
  32420. }
  32421. }
  32422. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32423. {
  32424. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32425. {
  32426. flags.alwaysOnTopFlag = shouldStayOnTop;
  32427. if (isOnDesktop())
  32428. {
  32429. ComponentPeer* const peer = getPeer();
  32430. jassert (peer != 0);
  32431. if (peer != 0)
  32432. {
  32433. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32434. {
  32435. // some kinds of peer can't change their always-on-top status, so
  32436. // for these, we'll need to create a new window
  32437. const int oldFlags = peer->getStyleFlags();
  32438. removeFromDesktop();
  32439. addToDesktop (oldFlags);
  32440. }
  32441. }
  32442. }
  32443. if (shouldStayOnTop)
  32444. toFront (false);
  32445. internalHierarchyChanged();
  32446. }
  32447. }
  32448. bool Component::isAlwaysOnTop() const throw()
  32449. {
  32450. return flags.alwaysOnTopFlag;
  32451. }
  32452. int Component::proportionOfWidth (const float proportion) const throw()
  32453. {
  32454. return roundToInt (proportion * bounds.getWidth());
  32455. }
  32456. int Component::proportionOfHeight (const float proportion) const throw()
  32457. {
  32458. return roundToInt (proportion * bounds.getHeight());
  32459. }
  32460. int Component::getParentWidth() const throw()
  32461. {
  32462. return (parentComponent != 0) ? parentComponent->getWidth()
  32463. : getParentMonitorArea().getWidth();
  32464. }
  32465. int Component::getParentHeight() const throw()
  32466. {
  32467. return (parentComponent != 0) ? parentComponent->getHeight()
  32468. : getParentMonitorArea().getHeight();
  32469. }
  32470. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32471. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32472. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32473. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32474. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32475. {
  32476. return ComponentHelpers::convertCoordinate (this, source, point);
  32477. }
  32478. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32479. {
  32480. return ComponentHelpers::convertCoordinate (this, source, area);
  32481. }
  32482. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32483. {
  32484. return ComponentHelpers::convertCoordinate (0, this, point);
  32485. }
  32486. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32487. {
  32488. return ComponentHelpers::convertCoordinate (0, this, area);
  32489. }
  32490. /* Deprecated methods... */
  32491. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32492. {
  32493. return localPointToGlobal (relativePosition);
  32494. }
  32495. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32496. {
  32497. return getLocalPoint (0, screenPosition);
  32498. }
  32499. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32500. {
  32501. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32502. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32503. }
  32504. void Component::setBounds (const int x, const int y, int w, int h)
  32505. {
  32506. // if component methods are being called from threads other than the message
  32507. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32508. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32509. if (w < 0) w = 0;
  32510. if (h < 0) h = 0;
  32511. const bool wasResized = (getWidth() != w || getHeight() != h);
  32512. const bool wasMoved = (getX() != x || getY() != y);
  32513. #if JUCE_DEBUG
  32514. // It's a very bad idea to try to resize a window during its paint() method!
  32515. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32516. #endif
  32517. if (wasMoved || wasResized)
  32518. {
  32519. const bool showing = isShowing();
  32520. if (showing)
  32521. {
  32522. // send a fake mouse move to trigger enter/exit messages if needed..
  32523. sendFakeMouseMove();
  32524. if (! flags.hasHeavyweightPeerFlag)
  32525. repaintParent();
  32526. }
  32527. bounds.setBounds (x, y, w, h);
  32528. if (showing)
  32529. {
  32530. if (wasResized)
  32531. repaint();
  32532. else if (! flags.hasHeavyweightPeerFlag)
  32533. repaintParent();
  32534. }
  32535. if (flags.hasHeavyweightPeerFlag)
  32536. {
  32537. ComponentPeer* const peer = getPeer();
  32538. if (peer != 0)
  32539. {
  32540. if (wasMoved && wasResized)
  32541. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32542. else if (wasMoved)
  32543. peer->setPosition (getX(), getY());
  32544. else if (wasResized)
  32545. peer->setSize (getWidth(), getHeight());
  32546. }
  32547. }
  32548. sendMovedResizedMessages (wasMoved, wasResized);
  32549. }
  32550. }
  32551. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32552. {
  32553. BailOutChecker checker (this);
  32554. if (wasMoved)
  32555. {
  32556. moved();
  32557. if (checker.shouldBailOut())
  32558. return;
  32559. }
  32560. if (wasResized)
  32561. {
  32562. resized();
  32563. if (checker.shouldBailOut())
  32564. return;
  32565. for (int i = childComponentList.size(); --i >= 0;)
  32566. {
  32567. childComponentList.getUnchecked(i)->parentSizeChanged();
  32568. if (checker.shouldBailOut())
  32569. return;
  32570. i = jmin (i, childComponentList.size());
  32571. }
  32572. }
  32573. if (parentComponent != 0)
  32574. parentComponent->childBoundsChanged (this);
  32575. if (! checker.shouldBailOut())
  32576. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32577. *this, wasMoved, wasResized);
  32578. }
  32579. void Component::setSize (const int w, const int h)
  32580. {
  32581. setBounds (getX(), getY(), w, h);
  32582. }
  32583. void Component::setTopLeftPosition (const int x, const int y)
  32584. {
  32585. setBounds (x, y, getWidth(), getHeight());
  32586. }
  32587. void Component::setTopRightPosition (const int x, const int y)
  32588. {
  32589. setTopLeftPosition (x - getWidth(), y);
  32590. }
  32591. void Component::setBounds (const Rectangle<int>& r)
  32592. {
  32593. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32594. }
  32595. void Component::setBounds (const RelativeRectangle& newBounds)
  32596. {
  32597. newBounds.applyToComponent (*this);
  32598. }
  32599. void Component::setBounds (const String& newBoundsExpression)
  32600. {
  32601. setBounds (RelativeRectangle (newBoundsExpression));
  32602. }
  32603. void Component::setBoundsRelative (const float x, const float y,
  32604. const float w, const float h)
  32605. {
  32606. const int pw = getParentWidth();
  32607. const int ph = getParentHeight();
  32608. setBounds (roundToInt (x * pw),
  32609. roundToInt (y * ph),
  32610. roundToInt (w * pw),
  32611. roundToInt (h * ph));
  32612. }
  32613. void Component::setCentrePosition (const int x, const int y)
  32614. {
  32615. setTopLeftPosition (x - getWidth() / 2,
  32616. y - getHeight() / 2);
  32617. }
  32618. void Component::setCentreRelative (const float x, const float y)
  32619. {
  32620. setCentrePosition (roundToInt (getParentWidth() * x),
  32621. roundToInt (getParentHeight() * y));
  32622. }
  32623. void Component::centreWithSize (const int width, const int height)
  32624. {
  32625. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32626. setBounds (parentArea.getCentreX() - width / 2,
  32627. parentArea.getCentreY() - height / 2,
  32628. width, height);
  32629. }
  32630. void Component::setBoundsInset (const BorderSize<int>& borders)
  32631. {
  32632. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32633. }
  32634. void Component::setBoundsToFit (int x, int y, int width, int height,
  32635. const Justification& justification,
  32636. const bool onlyReduceInSize)
  32637. {
  32638. // it's no good calling this method unless both the component and
  32639. // target rectangle have a finite size.
  32640. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32641. if (getWidth() > 0 && getHeight() > 0
  32642. && width > 0 && height > 0)
  32643. {
  32644. int newW, newH;
  32645. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32646. {
  32647. newW = getWidth();
  32648. newH = getHeight();
  32649. }
  32650. else
  32651. {
  32652. const double imageRatio = getHeight() / (double) getWidth();
  32653. const double targetRatio = height / (double) width;
  32654. if (imageRatio <= targetRatio)
  32655. {
  32656. newW = width;
  32657. newH = jmin (height, roundToInt (newW * imageRatio));
  32658. }
  32659. else
  32660. {
  32661. newH = height;
  32662. newW = jmin (width, roundToInt (newH / imageRatio));
  32663. }
  32664. }
  32665. if (newW > 0 && newH > 0)
  32666. setBounds (justification.appliedToRectangle (Rectangle<int> (0, 0, newW, newH),
  32667. Rectangle<int> (x, y, width, height)));
  32668. }
  32669. }
  32670. bool Component::isTransformed() const throw()
  32671. {
  32672. return affineTransform != 0;
  32673. }
  32674. void Component::setTransform (const AffineTransform& newTransform)
  32675. {
  32676. // If you pass in a transform with no inverse, the component will have no dimensions,
  32677. // and there will be all sorts of maths errors when converting coordinates.
  32678. jassert (! newTransform.isSingularity());
  32679. if (newTransform.isIdentity())
  32680. {
  32681. if (affineTransform != 0)
  32682. {
  32683. repaint();
  32684. affineTransform = 0;
  32685. repaint();
  32686. sendMovedResizedMessages (false, false);
  32687. }
  32688. }
  32689. else if (affineTransform == 0)
  32690. {
  32691. repaint();
  32692. affineTransform = new AffineTransform (newTransform);
  32693. repaint();
  32694. sendMovedResizedMessages (false, false);
  32695. }
  32696. else if (*affineTransform != newTransform)
  32697. {
  32698. repaint();
  32699. *affineTransform = newTransform;
  32700. repaint();
  32701. sendMovedResizedMessages (false, false);
  32702. }
  32703. }
  32704. const AffineTransform Component::getTransform() const
  32705. {
  32706. return affineTransform != 0 ? *affineTransform : AffineTransform::identity;
  32707. }
  32708. bool Component::hitTest (int x, int y)
  32709. {
  32710. if (! flags.ignoresMouseClicksFlag)
  32711. return true;
  32712. if (flags.allowChildMouseClicksFlag)
  32713. {
  32714. for (int i = getNumChildComponents(); --i >= 0;)
  32715. {
  32716. Component& child = *getChildComponent (i);
  32717. if (child.isVisible()
  32718. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32719. return true;
  32720. }
  32721. }
  32722. return false;
  32723. }
  32724. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32725. const bool allowClicksOnChildComponents) throw()
  32726. {
  32727. flags.ignoresMouseClicksFlag = ! allowClicks;
  32728. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32729. }
  32730. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32731. bool& allowsClicksOnChildComponents) const throw()
  32732. {
  32733. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32734. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32735. }
  32736. bool Component::contains (const Point<int>& point)
  32737. {
  32738. if (ComponentHelpers::hitTest (*this, point))
  32739. {
  32740. if (parentComponent != 0)
  32741. {
  32742. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32743. }
  32744. else if (flags.hasHeavyweightPeerFlag)
  32745. {
  32746. const ComponentPeer* const peer = getPeer();
  32747. if (peer != 0)
  32748. return peer->contains (point, true);
  32749. }
  32750. }
  32751. return false;
  32752. }
  32753. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32754. {
  32755. if (! contains (point))
  32756. return false;
  32757. Component* const top = getTopLevelComponent();
  32758. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32759. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32760. }
  32761. Component* Component::getComponentAt (const Point<int>& position)
  32762. {
  32763. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32764. {
  32765. for (int i = childComponentList.size(); --i >= 0;)
  32766. {
  32767. Component* child = childComponentList.getUnchecked(i);
  32768. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32769. if (child != 0)
  32770. return child;
  32771. }
  32772. return this;
  32773. }
  32774. return 0;
  32775. }
  32776. Component* Component::getComponentAt (const int x, const int y)
  32777. {
  32778. return getComponentAt (Point<int> (x, y));
  32779. }
  32780. void Component::addChildComponent (Component* const child, int zOrder)
  32781. {
  32782. // if component methods are being called from threads other than the message
  32783. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32784. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32785. if (child != 0 && child->parentComponent != this)
  32786. {
  32787. if (child->parentComponent != 0)
  32788. child->parentComponent->removeChildComponent (child);
  32789. else
  32790. child->removeFromDesktop();
  32791. child->parentComponent = this;
  32792. if (child->isVisible())
  32793. child->repaintParent();
  32794. if (! child->isAlwaysOnTop())
  32795. {
  32796. if (zOrder < 0 || zOrder > childComponentList.size())
  32797. zOrder = childComponentList.size();
  32798. while (zOrder > 0)
  32799. {
  32800. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32801. break;
  32802. --zOrder;
  32803. }
  32804. }
  32805. childComponentList.insert (zOrder, child);
  32806. child->internalHierarchyChanged();
  32807. internalChildrenChanged();
  32808. }
  32809. }
  32810. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32811. {
  32812. if (child != 0)
  32813. {
  32814. child->setVisible (true);
  32815. addChildComponent (child, zOrder);
  32816. }
  32817. }
  32818. void Component::removeChildComponent (Component* const child)
  32819. {
  32820. removeChildComponent (childComponentList.indexOf (child), true, true);
  32821. }
  32822. Component* Component::removeChildComponent (const int index)
  32823. {
  32824. return removeChildComponent (index, true, true);
  32825. }
  32826. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  32827. {
  32828. // if component methods are being called from threads other than the message
  32829. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32830. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32831. Component* const child = childComponentList [index];
  32832. if (child != 0)
  32833. {
  32834. sendParentEvents = sendParentEvents && child->isShowing();
  32835. if (sendParentEvents)
  32836. {
  32837. sendFakeMouseMove();
  32838. child->repaintParent();
  32839. }
  32840. childComponentList.remove (index);
  32841. child->parentComponent = 0;
  32842. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  32843. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  32844. {
  32845. if (sendParentEvents)
  32846. {
  32847. const WeakReference<Component> thisPointer (this);
  32848. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32849. if (thisPointer == 0)
  32850. return child;
  32851. grabKeyboardFocus();
  32852. }
  32853. else
  32854. {
  32855. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32856. }
  32857. }
  32858. if (sendChildEvents)
  32859. child->internalHierarchyChanged();
  32860. if (sendParentEvents)
  32861. internalChildrenChanged();
  32862. }
  32863. return child;
  32864. }
  32865. void Component::removeAllChildren()
  32866. {
  32867. while (childComponentList.size() > 0)
  32868. removeChildComponent (childComponentList.size() - 1);
  32869. }
  32870. void Component::deleteAllChildren()
  32871. {
  32872. while (childComponentList.size() > 0)
  32873. delete (removeChildComponent (childComponentList.size() - 1));
  32874. }
  32875. int Component::getNumChildComponents() const throw()
  32876. {
  32877. return childComponentList.size();
  32878. }
  32879. Component* Component::getChildComponent (const int index) const throw()
  32880. {
  32881. return childComponentList [index];
  32882. }
  32883. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32884. {
  32885. return childComponentList.indexOf (const_cast <Component*> (child));
  32886. }
  32887. Component* Component::getTopLevelComponent() const throw()
  32888. {
  32889. const Component* comp = this;
  32890. while (comp->parentComponent != 0)
  32891. comp = comp->parentComponent;
  32892. return const_cast <Component*> (comp);
  32893. }
  32894. bool Component::isParentOf (const Component* possibleChild) const throw()
  32895. {
  32896. while (possibleChild != 0)
  32897. {
  32898. possibleChild = possibleChild->parentComponent;
  32899. if (possibleChild == this)
  32900. return true;
  32901. }
  32902. return false;
  32903. }
  32904. void Component::parentHierarchyChanged()
  32905. {
  32906. }
  32907. void Component::childrenChanged()
  32908. {
  32909. }
  32910. void Component::internalChildrenChanged()
  32911. {
  32912. if (componentListeners.isEmpty())
  32913. {
  32914. childrenChanged();
  32915. }
  32916. else
  32917. {
  32918. BailOutChecker checker (this);
  32919. childrenChanged();
  32920. if (! checker.shouldBailOut())
  32921. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32922. }
  32923. }
  32924. void Component::internalHierarchyChanged()
  32925. {
  32926. BailOutChecker checker (this);
  32927. parentHierarchyChanged();
  32928. if (checker.shouldBailOut())
  32929. return;
  32930. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32931. if (checker.shouldBailOut())
  32932. return;
  32933. for (int i = childComponentList.size(); --i >= 0;)
  32934. {
  32935. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  32936. if (checker.shouldBailOut())
  32937. {
  32938. // you really shouldn't delete the parent component during a callback telling you
  32939. // that it's changed..
  32940. jassertfalse;
  32941. return;
  32942. }
  32943. i = jmin (i, childComponentList.size());
  32944. }
  32945. }
  32946. #if JUCE_MODAL_LOOPS_PERMITTED
  32947. int Component::runModalLoop()
  32948. {
  32949. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32950. {
  32951. // use a callback so this can be called from non-gui threads
  32952. return (int) (pointer_sized_int) MessageManager::getInstance()
  32953. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  32954. }
  32955. if (! isCurrentlyModal())
  32956. enterModalState (true);
  32957. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32958. }
  32959. #endif
  32960. class ModalAutoDeleteCallback : public ModalComponentManager::Callback
  32961. {
  32962. public:
  32963. ModalAutoDeleteCallback (Component* const comp_)
  32964. : comp (comp_)
  32965. {}
  32966. void modalStateFinished (int)
  32967. {
  32968. delete comp.get();
  32969. }
  32970. private:
  32971. WeakReference<Component> comp;
  32972. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModalAutoDeleteCallback);
  32973. };
  32974. void Component::enterModalState (const bool shouldTakeKeyboardFocus,
  32975. ModalComponentManager::Callback* callback,
  32976. const bool deleteWhenDismissed)
  32977. {
  32978. // if component methods are being called from threads other than the message
  32979. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32980. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32981. // Check for an attempt to make a component modal when it already is!
  32982. // This can cause nasty problems..
  32983. jassert (! flags.currentlyModalFlag);
  32984. if (! isCurrentlyModal())
  32985. {
  32986. ModalComponentManager* const mcm = ModalComponentManager::getInstance();
  32987. mcm->startModal (this);
  32988. mcm->attachCallback (this, callback);
  32989. if (deleteWhenDismissed)
  32990. mcm->attachCallback (this, new ModalAutoDeleteCallback (this));
  32991. flags.currentlyModalFlag = true;
  32992. setVisible (true);
  32993. if (shouldTakeKeyboardFocus)
  32994. grabKeyboardFocus();
  32995. }
  32996. }
  32997. void Component::exitModalState (const int returnValue)
  32998. {
  32999. if (flags.currentlyModalFlag)
  33000. {
  33001. if (MessageManager::getInstance()->isThisTheMessageThread())
  33002. {
  33003. ModalComponentManager::getInstance()->endModal (this, returnValue);
  33004. flags.currentlyModalFlag = false;
  33005. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33006. }
  33007. else
  33008. {
  33009. class ExitModalStateMessage : public CallbackMessage
  33010. {
  33011. public:
  33012. ExitModalStateMessage (Component* const target_, const int result_)
  33013. : target (target_), result (result_) {}
  33014. void messageCallback()
  33015. {
  33016. if (target.get() != 0) // (get() required for VS2003 bug)
  33017. target->exitModalState (result);
  33018. }
  33019. private:
  33020. WeakReference<Component> target;
  33021. int result;
  33022. };
  33023. (new ExitModalStateMessage (this, returnValue))->post();
  33024. }
  33025. }
  33026. }
  33027. bool Component::isCurrentlyModal() const throw()
  33028. {
  33029. return flags.currentlyModalFlag
  33030. && getCurrentlyModalComponent() == this;
  33031. }
  33032. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33033. {
  33034. Component* const mc = getCurrentlyModalComponent();
  33035. return mc != 0
  33036. && mc != this
  33037. && (! mc->isParentOf (this))
  33038. && ! mc->canModalEventBeSentToComponent (this);
  33039. }
  33040. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33041. {
  33042. return ModalComponentManager::getInstance()->getNumModalComponents();
  33043. }
  33044. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33045. {
  33046. return ModalComponentManager::getInstance()->getModalComponent (index);
  33047. }
  33048. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33049. {
  33050. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33051. }
  33052. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33053. {
  33054. return flags.bringToFrontOnClickFlag;
  33055. }
  33056. void Component::setMouseCursor (const MouseCursor& newCursor)
  33057. {
  33058. if (cursor != newCursor)
  33059. {
  33060. cursor = newCursor;
  33061. if (flags.visibleFlag)
  33062. updateMouseCursor();
  33063. }
  33064. }
  33065. const MouseCursor Component::getMouseCursor()
  33066. {
  33067. return cursor;
  33068. }
  33069. void Component::updateMouseCursor() const
  33070. {
  33071. sendFakeMouseMove();
  33072. }
  33073. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33074. {
  33075. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33076. }
  33077. void Component::setAlpha (const float newAlpha)
  33078. {
  33079. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33080. if (componentTransparency != newIntAlpha)
  33081. {
  33082. componentTransparency = newIntAlpha;
  33083. if (flags.hasHeavyweightPeerFlag)
  33084. {
  33085. ComponentPeer* const peer = getPeer();
  33086. if (peer != 0)
  33087. peer->setAlpha (newAlpha);
  33088. }
  33089. else
  33090. {
  33091. repaint();
  33092. }
  33093. }
  33094. }
  33095. float Component::getAlpha() const
  33096. {
  33097. return (255 - componentTransparency) / 255.0f;
  33098. }
  33099. void Component::repaintParent()
  33100. {
  33101. if (flags.visibleFlag)
  33102. internalRepaint (0, 0, getWidth(), getHeight());
  33103. }
  33104. void Component::repaint()
  33105. {
  33106. repaint (0, 0, getWidth(), getHeight());
  33107. }
  33108. void Component::repaint (const int x, const int y,
  33109. const int w, const int h)
  33110. {
  33111. bufferedImage = Image::null;
  33112. if (flags.visibleFlag)
  33113. internalRepaint (x, y, w, h);
  33114. }
  33115. void Component::repaint (const Rectangle<int>& area)
  33116. {
  33117. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33118. }
  33119. void Component::internalRepaint (int x, int y, int w, int h)
  33120. {
  33121. // if component methods are being called from threads other than the message
  33122. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33123. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33124. if (x < 0)
  33125. {
  33126. w += x;
  33127. x = 0;
  33128. }
  33129. if (x + w > getWidth())
  33130. w = getWidth() - x;
  33131. if (w > 0)
  33132. {
  33133. if (y < 0)
  33134. {
  33135. h += y;
  33136. y = 0;
  33137. }
  33138. if (y + h > getHeight())
  33139. h = getHeight() - y;
  33140. if (h > 0)
  33141. {
  33142. if (parentComponent != 0)
  33143. {
  33144. if (parentComponent->flags.visibleFlag)
  33145. {
  33146. if (affineTransform == 0)
  33147. {
  33148. parentComponent->internalRepaint (x + getX(), y + getY(), w, h);
  33149. }
  33150. else
  33151. {
  33152. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  33153. parentComponent->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  33154. }
  33155. }
  33156. }
  33157. else if (flags.hasHeavyweightPeerFlag)
  33158. {
  33159. ComponentPeer* const peer = getPeer();
  33160. if (peer != 0)
  33161. peer->repaint (Rectangle<int> (x, y, w, h));
  33162. }
  33163. }
  33164. }
  33165. }
  33166. void Component::paintComponent (Graphics& g)
  33167. {
  33168. if (flags.bufferToImageFlag)
  33169. {
  33170. if (bufferedImage.isNull())
  33171. {
  33172. bufferedImage = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33173. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33174. Graphics imG (bufferedImage);
  33175. paint (imG);
  33176. }
  33177. g.setColour (Colours::black.withAlpha (getAlpha()));
  33178. g.drawImageAt (bufferedImage, 0, 0);
  33179. }
  33180. else
  33181. {
  33182. paint (g);
  33183. }
  33184. }
  33185. void Component::paintWithinParentContext (Graphics& g)
  33186. {
  33187. g.setOrigin (getX(), getY());
  33188. paintEntireComponent (g, false);
  33189. }
  33190. void Component::paintComponentAndChildren (Graphics& g)
  33191. {
  33192. const Rectangle<int> clipBounds (g.getClipBounds());
  33193. if (flags.dontClipGraphicsFlag)
  33194. {
  33195. paintComponent (g);
  33196. }
  33197. else
  33198. {
  33199. g.saveState();
  33200. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33201. if (! g.isClipEmpty())
  33202. paintComponent (g);
  33203. g.restoreState();
  33204. }
  33205. for (int i = 0; i < childComponentList.size(); ++i)
  33206. {
  33207. Component& child = *childComponentList.getUnchecked (i);
  33208. if (child.isVisible())
  33209. {
  33210. if (child.affineTransform != 0)
  33211. {
  33212. g.saveState();
  33213. g.addTransform (*child.affineTransform);
  33214. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33215. child.paintWithinParentContext (g);
  33216. g.restoreState();
  33217. }
  33218. else if (clipBounds.intersects (child.getBounds()))
  33219. {
  33220. g.saveState();
  33221. if (child.flags.dontClipGraphicsFlag)
  33222. {
  33223. child.paintWithinParentContext (g);
  33224. }
  33225. else if (g.reduceClipRegion (child.getBounds()))
  33226. {
  33227. bool nothingClipped = true;
  33228. for (int j = i + 1; j < childComponentList.size(); ++j)
  33229. {
  33230. const Component& sibling = *childComponentList.getUnchecked (j);
  33231. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == 0)
  33232. {
  33233. nothingClipped = false;
  33234. g.excludeClipRegion (sibling.getBounds());
  33235. }
  33236. }
  33237. if (nothingClipped || ! g.isClipEmpty())
  33238. child.paintWithinParentContext (g);
  33239. }
  33240. g.restoreState();
  33241. }
  33242. }
  33243. }
  33244. g.saveState();
  33245. paintOverChildren (g);
  33246. g.restoreState();
  33247. }
  33248. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33249. {
  33250. jassert (! g.isClipEmpty());
  33251. #if JUCE_DEBUG
  33252. flags.isInsidePaintCall = true;
  33253. #endif
  33254. if (effect != 0)
  33255. {
  33256. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33257. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33258. {
  33259. Graphics g2 (effectImage);
  33260. paintComponentAndChildren (g2);
  33261. }
  33262. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33263. }
  33264. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33265. {
  33266. if (componentTransparency < 255)
  33267. {
  33268. g.beginTransparencyLayer (getAlpha());
  33269. paintComponentAndChildren (g);
  33270. g.endTransparencyLayer();
  33271. }
  33272. }
  33273. else
  33274. {
  33275. paintComponentAndChildren (g);
  33276. }
  33277. #if JUCE_DEBUG
  33278. flags.isInsidePaintCall = false;
  33279. #endif
  33280. }
  33281. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33282. {
  33283. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33284. }
  33285. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33286. const bool clipImageToComponentBounds)
  33287. {
  33288. Rectangle<int> r (areaToGrab);
  33289. if (clipImageToComponentBounds)
  33290. r = r.getIntersection (getLocalBounds());
  33291. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33292. jmax (1, r.getWidth()),
  33293. jmax (1, r.getHeight()),
  33294. true);
  33295. Graphics imageContext (componentImage);
  33296. imageContext.setOrigin (-r.getX(), -r.getY());
  33297. paintEntireComponent (imageContext, true);
  33298. return componentImage;
  33299. }
  33300. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  33301. {
  33302. if (effect != newEffect)
  33303. {
  33304. effect = newEffect;
  33305. repaint();
  33306. }
  33307. }
  33308. LookAndFeel& Component::getLookAndFeel() const throw()
  33309. {
  33310. const Component* c = this;
  33311. do
  33312. {
  33313. if (c->lookAndFeel != 0)
  33314. return *(c->lookAndFeel);
  33315. c = c->parentComponent;
  33316. }
  33317. while (c != 0);
  33318. return LookAndFeel::getDefaultLookAndFeel();
  33319. }
  33320. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33321. {
  33322. if (lookAndFeel != newLookAndFeel)
  33323. {
  33324. lookAndFeel = newLookAndFeel;
  33325. sendLookAndFeelChange();
  33326. }
  33327. }
  33328. void Component::lookAndFeelChanged()
  33329. {
  33330. }
  33331. void Component::sendLookAndFeelChange()
  33332. {
  33333. repaint();
  33334. WeakReference<Component> safePointer (this);
  33335. lookAndFeelChanged();
  33336. if (safePointer != 0)
  33337. {
  33338. for (int i = childComponentList.size(); --i >= 0;)
  33339. {
  33340. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  33341. if (safePointer == 0)
  33342. return;
  33343. i = jmin (i, childComponentList.size());
  33344. }
  33345. }
  33346. }
  33347. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33348. {
  33349. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33350. if (v != 0)
  33351. return Colour ((int) *v);
  33352. if (inheritFromParent && parentComponent != 0)
  33353. return parentComponent->findColour (colourId, true);
  33354. return getLookAndFeel().findColour (colourId);
  33355. }
  33356. bool Component::isColourSpecified (const int colourId) const
  33357. {
  33358. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33359. }
  33360. void Component::removeColour (const int colourId)
  33361. {
  33362. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33363. colourChanged();
  33364. }
  33365. void Component::setColour (const int colourId, const Colour& colour)
  33366. {
  33367. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33368. colourChanged();
  33369. }
  33370. void Component::copyAllExplicitColoursTo (Component& target) const
  33371. {
  33372. bool changed = false;
  33373. for (int i = properties.size(); --i >= 0;)
  33374. {
  33375. const Identifier name (properties.getName(i));
  33376. if (name.toString().startsWith ("jcclr_"))
  33377. if (target.properties.set (name, properties [name]))
  33378. changed = true;
  33379. }
  33380. if (changed)
  33381. target.colourChanged();
  33382. }
  33383. void Component::colourChanged()
  33384. {
  33385. }
  33386. MarkerList* Component::getMarkers (bool /*xAxis*/)
  33387. {
  33388. return 0;
  33389. }
  33390. Component::Positioner::Positioner (Component& component_) throw()
  33391. : component (component_)
  33392. {
  33393. }
  33394. Component::Positioner* Component::getPositioner() const throw()
  33395. {
  33396. return positioner;
  33397. }
  33398. void Component::setPositioner (Positioner* newPositioner)
  33399. {
  33400. // You can only assign a positioner to the component that it was created for!
  33401. jassert (newPositioner == 0 || this == &(newPositioner->getComponent()));
  33402. positioner = newPositioner;
  33403. }
  33404. const Rectangle<int> Component::getLocalBounds() const throw()
  33405. {
  33406. return Rectangle<int> (getWidth(), getHeight());
  33407. }
  33408. const Rectangle<int> Component::getBoundsInParent() const throw()
  33409. {
  33410. return affineTransform == 0 ? bounds
  33411. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  33412. }
  33413. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33414. {
  33415. result.clear();
  33416. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33417. if (! unclipped.isEmpty())
  33418. {
  33419. result.add (unclipped);
  33420. if (includeSiblings)
  33421. {
  33422. const Component* const c = getTopLevelComponent();
  33423. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33424. c->getLocalBounds(), this);
  33425. }
  33426. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33427. result.consolidate();
  33428. }
  33429. }
  33430. void Component::mouseEnter (const MouseEvent&)
  33431. {
  33432. // base class does nothing
  33433. }
  33434. void Component::mouseExit (const MouseEvent&)
  33435. {
  33436. // base class does nothing
  33437. }
  33438. void Component::mouseDown (const MouseEvent&)
  33439. {
  33440. // base class does nothing
  33441. }
  33442. void Component::mouseUp (const MouseEvent&)
  33443. {
  33444. // base class does nothing
  33445. }
  33446. void Component::mouseDrag (const MouseEvent&)
  33447. {
  33448. // base class does nothing
  33449. }
  33450. void Component::mouseMove (const MouseEvent&)
  33451. {
  33452. // base class does nothing
  33453. }
  33454. void Component::mouseDoubleClick (const MouseEvent&)
  33455. {
  33456. // base class does nothing
  33457. }
  33458. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33459. {
  33460. // the base class just passes this event up to its parent..
  33461. if (parentComponent != 0)
  33462. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  33463. wheelIncrementX, wheelIncrementY);
  33464. }
  33465. void Component::resized()
  33466. {
  33467. // base class does nothing
  33468. }
  33469. void Component::moved()
  33470. {
  33471. // base class does nothing
  33472. }
  33473. void Component::childBoundsChanged (Component*)
  33474. {
  33475. // base class does nothing
  33476. }
  33477. void Component::parentSizeChanged()
  33478. {
  33479. // base class does nothing
  33480. }
  33481. void Component::addComponentListener (ComponentListener* const newListener)
  33482. {
  33483. // if component methods are being called from threads other than the message
  33484. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33485. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33486. componentListeners.add (newListener);
  33487. }
  33488. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33489. {
  33490. componentListeners.remove (listenerToRemove);
  33491. }
  33492. void Component::inputAttemptWhenModal()
  33493. {
  33494. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33495. getLookAndFeel().playAlertSound();
  33496. }
  33497. bool Component::canModalEventBeSentToComponent (const Component*)
  33498. {
  33499. return false;
  33500. }
  33501. void Component::internalModalInputAttempt()
  33502. {
  33503. Component* const current = getCurrentlyModalComponent();
  33504. if (current != 0)
  33505. current->inputAttemptWhenModal();
  33506. }
  33507. void Component::paint (Graphics&)
  33508. {
  33509. // all painting is done in the subclasses
  33510. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33511. }
  33512. void Component::paintOverChildren (Graphics&)
  33513. {
  33514. // all painting is done in the subclasses
  33515. }
  33516. void Component::postCommandMessage (const int commandId)
  33517. {
  33518. class CustomCommandMessage : public CallbackMessage
  33519. {
  33520. public:
  33521. CustomCommandMessage (Component* const target_, const int commandId_)
  33522. : target (target_), commandId (commandId_) {}
  33523. void messageCallback()
  33524. {
  33525. if (target.get() != 0) // (get() required for VS2003 bug)
  33526. target->handleCommandMessage (commandId);
  33527. }
  33528. private:
  33529. WeakReference<Component> target;
  33530. int commandId;
  33531. };
  33532. (new CustomCommandMessage (this, commandId))->post();
  33533. }
  33534. void Component::handleCommandMessage (int)
  33535. {
  33536. // used by subclasses
  33537. }
  33538. void Component::addMouseListener (MouseListener* const newListener,
  33539. const bool wantsEventsForAllNestedChildComponents)
  33540. {
  33541. // if component methods are being called from threads other than the message
  33542. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33543. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33544. // If you register a component as a mouselistener for itself, it'll receive all the events
  33545. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33546. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33547. if (mouseListeners == 0)
  33548. mouseListeners = new MouseListenerList();
  33549. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33550. }
  33551. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33552. {
  33553. // if component methods are being called from threads other than the message
  33554. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33555. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33556. if (mouseListeners != 0)
  33557. mouseListeners->removeListener (listenerToRemove);
  33558. }
  33559. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33560. {
  33561. if (isCurrentlyBlockedByAnotherModalComponent())
  33562. {
  33563. // if something else is modal, always just show a normal mouse cursor
  33564. source.showMouseCursor (MouseCursor::NormalCursor);
  33565. return;
  33566. }
  33567. if (! flags.mouseInsideFlag)
  33568. {
  33569. flags.mouseInsideFlag = true;
  33570. flags.mouseOverFlag = true;
  33571. flags.mouseDownFlag = false;
  33572. BailOutChecker checker (this);
  33573. if (flags.repaintOnMouseActivityFlag)
  33574. repaint();
  33575. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33576. this, this, time, relativePos, time, 0, false);
  33577. mouseEnter (me);
  33578. if (checker.shouldBailOut())
  33579. return;
  33580. Desktop& desktop = Desktop::getInstance();
  33581. desktop.resetTimer();
  33582. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33583. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  33584. }
  33585. }
  33586. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33587. {
  33588. BailOutChecker checker (this);
  33589. if (flags.mouseDownFlag)
  33590. {
  33591. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33592. if (checker.shouldBailOut())
  33593. return;
  33594. }
  33595. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33596. {
  33597. flags.mouseInsideFlag = false;
  33598. flags.mouseOverFlag = false;
  33599. flags.mouseDownFlag = false;
  33600. if (flags.repaintOnMouseActivityFlag)
  33601. repaint();
  33602. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33603. this, this, time, relativePos, time, 0, false);
  33604. mouseExit (me);
  33605. if (checker.shouldBailOut())
  33606. return;
  33607. Desktop& desktop = Desktop::getInstance();
  33608. desktop.resetTimer();
  33609. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33610. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  33611. }
  33612. }
  33613. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33614. {
  33615. Desktop& desktop = Desktop::getInstance();
  33616. BailOutChecker checker (this);
  33617. if (isCurrentlyBlockedByAnotherModalComponent())
  33618. {
  33619. internalModalInputAttempt();
  33620. if (checker.shouldBailOut())
  33621. return;
  33622. // If processing the input attempt has exited the modal loop, we'll allow the event
  33623. // to be delivered..
  33624. if (isCurrentlyBlockedByAnotherModalComponent())
  33625. {
  33626. // allow blocked mouse-events to go to global listeners..
  33627. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33628. this, this, time, relativePos, time,
  33629. source.getNumberOfMultipleClicks(), false);
  33630. desktop.resetTimer();
  33631. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33632. return;
  33633. }
  33634. }
  33635. {
  33636. Component* c = this;
  33637. while (c != 0)
  33638. {
  33639. if (c->isBroughtToFrontOnMouseClick())
  33640. {
  33641. c->toFront (true);
  33642. if (checker.shouldBailOut())
  33643. return;
  33644. }
  33645. c = c->parentComponent;
  33646. }
  33647. }
  33648. if (! flags.dontFocusOnMouseClickFlag)
  33649. {
  33650. grabFocusInternal (focusChangedByMouseClick);
  33651. if (checker.shouldBailOut())
  33652. return;
  33653. }
  33654. flags.mouseDownFlag = true;
  33655. flags.mouseOverFlag = true;
  33656. if (flags.repaintOnMouseActivityFlag)
  33657. repaint();
  33658. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33659. this, this, time, relativePos, time,
  33660. source.getNumberOfMultipleClicks(), false);
  33661. mouseDown (me);
  33662. if (checker.shouldBailOut())
  33663. return;
  33664. desktop.resetTimer();
  33665. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33666. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  33667. }
  33668. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33669. {
  33670. if (flags.mouseDownFlag)
  33671. {
  33672. flags.mouseDownFlag = false;
  33673. BailOutChecker checker (this);
  33674. if (flags.repaintOnMouseActivityFlag)
  33675. repaint();
  33676. const MouseEvent me (source, relativePos,
  33677. oldModifiers, this, this, time,
  33678. getLocalPoint (0, source.getLastMouseDownPosition()),
  33679. source.getLastMouseDownTime(),
  33680. source.getNumberOfMultipleClicks(),
  33681. source.hasMouseMovedSignificantlySincePressed());
  33682. mouseUp (me);
  33683. if (checker.shouldBailOut())
  33684. return;
  33685. Desktop& desktop = Desktop::getInstance();
  33686. desktop.resetTimer();
  33687. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33688. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  33689. if (checker.shouldBailOut())
  33690. return;
  33691. // check for double-click
  33692. if (me.getNumberOfClicks() >= 2)
  33693. {
  33694. mouseDoubleClick (me);
  33695. if (checker.shouldBailOut())
  33696. return;
  33697. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33698. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  33699. }
  33700. }
  33701. }
  33702. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33703. {
  33704. if (flags.mouseDownFlag)
  33705. {
  33706. flags.mouseOverFlag = reallyContains (relativePos, false);
  33707. BailOutChecker checker (this);
  33708. const MouseEvent me (source, relativePos,
  33709. source.getCurrentModifiers(), this, this, time,
  33710. getLocalPoint (0, source.getLastMouseDownPosition()),
  33711. source.getLastMouseDownTime(),
  33712. source.getNumberOfMultipleClicks(),
  33713. source.hasMouseMovedSignificantlySincePressed());
  33714. mouseDrag (me);
  33715. if (checker.shouldBailOut())
  33716. return;
  33717. Desktop& desktop = Desktop::getInstance();
  33718. desktop.resetTimer();
  33719. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33720. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  33721. }
  33722. }
  33723. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33724. {
  33725. Desktop& desktop = Desktop::getInstance();
  33726. BailOutChecker checker (this);
  33727. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33728. this, this, time, relativePos, time, 0, false);
  33729. if (isCurrentlyBlockedByAnotherModalComponent())
  33730. {
  33731. // allow blocked mouse-events to go to global listeners..
  33732. desktop.sendMouseMove();
  33733. }
  33734. else
  33735. {
  33736. flags.mouseOverFlag = true;
  33737. mouseMove (me);
  33738. if (checker.shouldBailOut())
  33739. return;
  33740. desktop.resetTimer();
  33741. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33742. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  33743. }
  33744. }
  33745. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33746. const Time& time, const float amountX, const float amountY)
  33747. {
  33748. Desktop& desktop = Desktop::getInstance();
  33749. BailOutChecker checker (this);
  33750. const float wheelIncrementX = amountX / 256.0f;
  33751. const float wheelIncrementY = amountY / 256.0f;
  33752. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33753. this, this, time, relativePos, time, 0, false);
  33754. if (isCurrentlyBlockedByAnotherModalComponent())
  33755. {
  33756. // allow blocked mouse-events to go to global listeners..
  33757. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33758. }
  33759. else
  33760. {
  33761. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33762. if (checker.shouldBailOut())
  33763. return;
  33764. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33765. if (! checker.shouldBailOut())
  33766. MouseListenerList::sendWheelEvent (*this, checker, me, wheelIncrementX, wheelIncrementY);
  33767. }
  33768. }
  33769. void Component::sendFakeMouseMove() const
  33770. {
  33771. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33772. if (! mainMouse.isDragging())
  33773. mainMouse.triggerFakeMove();
  33774. }
  33775. void Component::beginDragAutoRepeat (const int interval)
  33776. {
  33777. Desktop::getInstance().beginDragAutoRepeat (interval);
  33778. }
  33779. void Component::broughtToFront()
  33780. {
  33781. }
  33782. void Component::internalBroughtToFront()
  33783. {
  33784. if (flags.hasHeavyweightPeerFlag)
  33785. Desktop::getInstance().componentBroughtToFront (this);
  33786. BailOutChecker checker (this);
  33787. broughtToFront();
  33788. if (checker.shouldBailOut())
  33789. return;
  33790. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33791. if (checker.shouldBailOut())
  33792. return;
  33793. // When brought to the front and there's a modal component blocking this one,
  33794. // we need to bring the modal one to the front instead..
  33795. Component* const cm = getCurrentlyModalComponent();
  33796. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33797. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33798. }
  33799. void Component::focusGained (FocusChangeType)
  33800. {
  33801. // base class does nothing
  33802. }
  33803. void Component::internalFocusGain (const FocusChangeType cause)
  33804. {
  33805. internalFocusGain (cause, WeakReference<Component> (this));
  33806. }
  33807. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  33808. {
  33809. focusGained (cause);
  33810. if (safePointer != 0)
  33811. internalChildFocusChange (cause, safePointer);
  33812. }
  33813. void Component::focusLost (FocusChangeType)
  33814. {
  33815. // base class does nothing
  33816. }
  33817. void Component::internalFocusLoss (const FocusChangeType cause)
  33818. {
  33819. WeakReference<Component> safePointer (this);
  33820. focusLost (focusChangedDirectly);
  33821. if (safePointer != 0)
  33822. internalChildFocusChange (cause, safePointer);
  33823. }
  33824. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33825. {
  33826. // base class does nothing
  33827. }
  33828. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  33829. {
  33830. const bool childIsNowFocused = hasKeyboardFocus (true);
  33831. if (flags.childCompFocusedFlag != childIsNowFocused)
  33832. {
  33833. flags.childCompFocusedFlag = childIsNowFocused;
  33834. focusOfChildComponentChanged (cause);
  33835. if (safePointer == 0)
  33836. return;
  33837. }
  33838. if (parentComponent != 0)
  33839. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  33840. }
  33841. bool Component::isEnabled() const throw()
  33842. {
  33843. return (! flags.isDisabledFlag)
  33844. && (parentComponent == 0 || parentComponent->isEnabled());
  33845. }
  33846. void Component::setEnabled (const bool shouldBeEnabled)
  33847. {
  33848. if (flags.isDisabledFlag == shouldBeEnabled)
  33849. {
  33850. flags.isDisabledFlag = ! shouldBeEnabled;
  33851. // if any parent components are disabled, setting our flag won't make a difference,
  33852. // so no need to send a change message
  33853. if (parentComponent == 0 || parentComponent->isEnabled())
  33854. sendEnablementChangeMessage();
  33855. }
  33856. }
  33857. void Component::sendEnablementChangeMessage()
  33858. {
  33859. WeakReference<Component> safePointer (this);
  33860. enablementChanged();
  33861. if (safePointer == 0)
  33862. return;
  33863. for (int i = getNumChildComponents(); --i >= 0;)
  33864. {
  33865. Component* const c = getChildComponent (i);
  33866. if (c != 0)
  33867. {
  33868. c->sendEnablementChangeMessage();
  33869. if (safePointer == 0)
  33870. return;
  33871. }
  33872. }
  33873. }
  33874. void Component::enablementChanged()
  33875. {
  33876. }
  33877. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33878. {
  33879. flags.wantsFocusFlag = wantsFocus;
  33880. }
  33881. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33882. {
  33883. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33884. }
  33885. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33886. {
  33887. return ! flags.dontFocusOnMouseClickFlag;
  33888. }
  33889. bool Component::getWantsKeyboardFocus() const throw()
  33890. {
  33891. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33892. }
  33893. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33894. {
  33895. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33896. }
  33897. bool Component::isFocusContainer() const throw()
  33898. {
  33899. return flags.isFocusContainerFlag;
  33900. }
  33901. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33902. int Component::getExplicitFocusOrder() const
  33903. {
  33904. return properties [juce_explicitFocusOrderId];
  33905. }
  33906. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33907. {
  33908. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33909. }
  33910. KeyboardFocusTraverser* Component::createFocusTraverser()
  33911. {
  33912. if (flags.isFocusContainerFlag || parentComponent == 0)
  33913. return new KeyboardFocusTraverser();
  33914. return parentComponent->createFocusTraverser();
  33915. }
  33916. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33917. {
  33918. // give the focus to this component
  33919. if (currentlyFocusedComponent != this)
  33920. {
  33921. // get the focus onto our desktop window
  33922. ComponentPeer* const peer = getPeer();
  33923. if (peer != 0)
  33924. {
  33925. WeakReference<Component> safePointer (this);
  33926. peer->grabFocus();
  33927. if (peer->isFocused() && currentlyFocusedComponent != this)
  33928. {
  33929. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  33930. currentlyFocusedComponent = this;
  33931. Desktop::getInstance().triggerFocusCallback();
  33932. // call this after setting currentlyFocusedComponent so that the one that's
  33933. // losing it has a chance to see where focus is going
  33934. if (componentLosingFocus != 0)
  33935. componentLosingFocus->internalFocusLoss (cause);
  33936. if (currentlyFocusedComponent == this)
  33937. internalFocusGain (cause, safePointer);
  33938. }
  33939. }
  33940. }
  33941. }
  33942. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33943. {
  33944. if (isShowing())
  33945. {
  33946. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == 0))
  33947. {
  33948. takeKeyboardFocus (cause);
  33949. }
  33950. else
  33951. {
  33952. if (isParentOf (currentlyFocusedComponent)
  33953. && currentlyFocusedComponent->isShowing())
  33954. {
  33955. // do nothing if the focused component is actually a child of ours..
  33956. }
  33957. else
  33958. {
  33959. // find the default child component..
  33960. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33961. if (traverser != 0)
  33962. {
  33963. Component* const defaultComp = traverser->getDefaultComponent (this);
  33964. traverser = 0;
  33965. if (defaultComp != 0)
  33966. {
  33967. defaultComp->grabFocusInternal (cause, false);
  33968. return;
  33969. }
  33970. }
  33971. if (canTryParent && parentComponent != 0)
  33972. {
  33973. // if no children want it and we're allowed to try our parent comp,
  33974. // then pass up to parent, which will try our siblings.
  33975. parentComponent->grabFocusInternal (cause, true);
  33976. }
  33977. }
  33978. }
  33979. }
  33980. }
  33981. void Component::grabKeyboardFocus()
  33982. {
  33983. // if component methods are being called from threads other than the message
  33984. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33985. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33986. grabFocusInternal (focusChangedDirectly);
  33987. }
  33988. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33989. {
  33990. // if component methods are being called from threads other than the message
  33991. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33992. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33993. if (parentComponent != 0)
  33994. {
  33995. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33996. if (traverser != 0)
  33997. {
  33998. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33999. : traverser->getPreviousComponent (this);
  34000. traverser = 0;
  34001. if (nextComp != 0)
  34002. {
  34003. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34004. {
  34005. WeakReference<Component> nextCompPointer (nextComp);
  34006. internalModalInputAttempt();
  34007. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34008. return;
  34009. }
  34010. nextComp->grabFocusInternal (focusChangedByTabKey);
  34011. return;
  34012. }
  34013. }
  34014. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  34015. }
  34016. }
  34017. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34018. {
  34019. return (currentlyFocusedComponent == this)
  34020. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34021. }
  34022. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34023. {
  34024. return currentlyFocusedComponent;
  34025. }
  34026. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  34027. {
  34028. Component* const componentLosingFocus = currentlyFocusedComponent;
  34029. currentlyFocusedComponent = 0;
  34030. if (sendFocusLossEvent && componentLosingFocus != 0)
  34031. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34032. Desktop::getInstance().triggerFocusCallback();
  34033. }
  34034. bool Component::isMouseOver (const bool includeChildren) const
  34035. {
  34036. if (flags.mouseOverFlag)
  34037. return true;
  34038. if (includeChildren)
  34039. {
  34040. Desktop& desktop = Desktop::getInstance();
  34041. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34042. {
  34043. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  34044. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  34045. return true;
  34046. }
  34047. }
  34048. return false;
  34049. }
  34050. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  34051. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  34052. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34053. {
  34054. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34055. }
  34056. const Point<int> Component::getMouseXYRelative() const
  34057. {
  34058. return getLocalPoint (0, Desktop::getMousePosition());
  34059. }
  34060. const Rectangle<int> Component::getParentMonitorArea() const
  34061. {
  34062. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  34063. }
  34064. void Component::addKeyListener (KeyListener* const newListener)
  34065. {
  34066. if (keyListeners == 0)
  34067. keyListeners = new Array <KeyListener*>();
  34068. keyListeners->addIfNotAlreadyThere (newListener);
  34069. }
  34070. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34071. {
  34072. if (keyListeners != 0)
  34073. keyListeners->removeValue (listenerToRemove);
  34074. }
  34075. bool Component::keyPressed (const KeyPress&)
  34076. {
  34077. return false;
  34078. }
  34079. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34080. {
  34081. return false;
  34082. }
  34083. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34084. {
  34085. if (parentComponent != 0)
  34086. parentComponent->modifierKeysChanged (modifiers);
  34087. }
  34088. void Component::internalModifierKeysChanged()
  34089. {
  34090. sendFakeMouseMove();
  34091. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34092. }
  34093. ComponentPeer* Component::getPeer() const
  34094. {
  34095. if (flags.hasHeavyweightPeerFlag)
  34096. return ComponentPeer::getPeerFor (this);
  34097. else if (parentComponent == 0)
  34098. return 0;
  34099. return parentComponent->getPeer();
  34100. }
  34101. Component::BailOutChecker::BailOutChecker (Component* const component)
  34102. : safePointer (component)
  34103. {
  34104. jassert (component != 0);
  34105. }
  34106. bool Component::BailOutChecker::shouldBailOut() const throw()
  34107. {
  34108. return safePointer == 0;
  34109. }
  34110. END_JUCE_NAMESPACE
  34111. /*** End of inlined file: juce_Component.cpp ***/
  34112. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34113. BEGIN_JUCE_NAMESPACE
  34114. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34115. void ComponentListener::componentBroughtToFront (Component&) {}
  34116. void ComponentListener::componentVisibilityChanged (Component&) {}
  34117. void ComponentListener::componentChildrenChanged (Component&) {}
  34118. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34119. void ComponentListener::componentNameChanged (Component&) {}
  34120. void ComponentListener::componentBeingDeleted (Component&) {}
  34121. END_JUCE_NAMESPACE
  34122. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34123. /*** Start of inlined file: juce_Desktop.cpp ***/
  34124. BEGIN_JUCE_NAMESPACE
  34125. Desktop::Desktop()
  34126. : mouseClickCounter (0),
  34127. kioskModeComponent (0),
  34128. allowedOrientations (allOrientations)
  34129. {
  34130. createMouseInputSources();
  34131. refreshMonitorSizes();
  34132. }
  34133. Desktop::~Desktop()
  34134. {
  34135. jassert (instance == this);
  34136. instance = 0;
  34137. // doh! If you don't delete all your windows before exiting, you're going to
  34138. // be leaking memory!
  34139. jassert (desktopComponents.size() == 0);
  34140. }
  34141. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34142. {
  34143. if (instance == 0)
  34144. instance = new Desktop();
  34145. return *instance;
  34146. }
  34147. Desktop* Desktop::instance = 0;
  34148. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34149. const bool clipToWorkArea);
  34150. void Desktop::refreshMonitorSizes()
  34151. {
  34152. Array <Rectangle<int> > oldClipped, oldUnclipped;
  34153. oldClipped.swapWithArray (monitorCoordsClipped);
  34154. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  34155. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34156. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34157. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34158. if (oldClipped != monitorCoordsClipped
  34159. || oldUnclipped != monitorCoordsUnclipped)
  34160. {
  34161. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34162. {
  34163. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34164. if (p != 0)
  34165. p->handleScreenSizeChange();
  34166. }
  34167. }
  34168. }
  34169. int Desktop::getNumDisplayMonitors() const throw()
  34170. {
  34171. return monitorCoordsClipped.size();
  34172. }
  34173. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34174. {
  34175. return clippedToWorkArea ? monitorCoordsClipped [index]
  34176. : monitorCoordsUnclipped [index];
  34177. }
  34178. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34179. {
  34180. RectangleList rl;
  34181. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34182. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34183. return rl;
  34184. }
  34185. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34186. {
  34187. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34188. }
  34189. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34190. {
  34191. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34192. double bestDistance = 1.0e10;
  34193. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34194. {
  34195. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34196. if (rect.contains (position))
  34197. return rect;
  34198. const double distance = rect.getCentre().getDistanceFrom (position);
  34199. if (distance < bestDistance)
  34200. {
  34201. bestDistance = distance;
  34202. best = rect;
  34203. }
  34204. }
  34205. return best;
  34206. }
  34207. int Desktop::getNumComponents() const throw()
  34208. {
  34209. return desktopComponents.size();
  34210. }
  34211. Component* Desktop::getComponent (const int index) const throw()
  34212. {
  34213. return desktopComponents [index];
  34214. }
  34215. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34216. {
  34217. for (int i = desktopComponents.size(); --i >= 0;)
  34218. {
  34219. Component* const c = desktopComponents.getUnchecked(i);
  34220. if (c->isVisible())
  34221. {
  34222. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34223. if (c->contains (relative))
  34224. return c->getComponentAt (relative);
  34225. }
  34226. }
  34227. return 0;
  34228. }
  34229. void Desktop::addDesktopComponent (Component* const c)
  34230. {
  34231. jassert (c != 0);
  34232. jassert (! desktopComponents.contains (c));
  34233. desktopComponents.addIfNotAlreadyThere (c);
  34234. }
  34235. void Desktop::removeDesktopComponent (Component* const c)
  34236. {
  34237. desktopComponents.removeValue (c);
  34238. }
  34239. void Desktop::componentBroughtToFront (Component* const c)
  34240. {
  34241. const int index = desktopComponents.indexOf (c);
  34242. jassert (index >= 0);
  34243. if (index >= 0)
  34244. {
  34245. int newIndex = -1;
  34246. if (! c->isAlwaysOnTop())
  34247. {
  34248. newIndex = desktopComponents.size();
  34249. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34250. --newIndex;
  34251. --newIndex;
  34252. }
  34253. desktopComponents.move (index, newIndex);
  34254. }
  34255. }
  34256. const Point<int> Desktop::getMousePosition()
  34257. {
  34258. return getInstance().getMainMouseSource().getScreenPosition();
  34259. }
  34260. const Point<int> Desktop::getLastMouseDownPosition()
  34261. {
  34262. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34263. }
  34264. int Desktop::getMouseButtonClickCounter()
  34265. {
  34266. return getInstance().mouseClickCounter;
  34267. }
  34268. void Desktop::incrementMouseClickCounter() throw()
  34269. {
  34270. ++mouseClickCounter;
  34271. }
  34272. int Desktop::getNumDraggingMouseSources() const throw()
  34273. {
  34274. int num = 0;
  34275. for (int i = mouseSources.size(); --i >= 0;)
  34276. if (mouseSources.getUnchecked(i)->isDragging())
  34277. ++num;
  34278. return num;
  34279. }
  34280. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34281. {
  34282. int num = 0;
  34283. for (int i = mouseSources.size(); --i >= 0;)
  34284. {
  34285. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34286. if (mi->isDragging())
  34287. {
  34288. if (index == num)
  34289. return mi;
  34290. ++num;
  34291. }
  34292. }
  34293. return 0;
  34294. }
  34295. class MouseDragAutoRepeater : public Timer
  34296. {
  34297. public:
  34298. MouseDragAutoRepeater() {}
  34299. void timerCallback()
  34300. {
  34301. Desktop& desktop = Desktop::getInstance();
  34302. int numMiceDown = 0;
  34303. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34304. {
  34305. MouseInputSource* const source = desktop.getMouseSource(i);
  34306. if (source->isDragging())
  34307. {
  34308. source->triggerFakeMove();
  34309. ++numMiceDown;
  34310. }
  34311. }
  34312. if (numMiceDown == 0)
  34313. desktop.beginDragAutoRepeat (0);
  34314. }
  34315. private:
  34316. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34317. };
  34318. void Desktop::beginDragAutoRepeat (const int interval)
  34319. {
  34320. if (interval > 0)
  34321. {
  34322. if (dragRepeater == 0)
  34323. dragRepeater = new MouseDragAutoRepeater();
  34324. if (dragRepeater->getTimerInterval() != interval)
  34325. dragRepeater->startTimer (interval);
  34326. }
  34327. else
  34328. {
  34329. dragRepeater = 0;
  34330. }
  34331. }
  34332. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34333. {
  34334. focusListeners.add (listener);
  34335. }
  34336. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34337. {
  34338. focusListeners.remove (listener);
  34339. }
  34340. void Desktop::triggerFocusCallback()
  34341. {
  34342. triggerAsyncUpdate();
  34343. }
  34344. void Desktop::handleAsyncUpdate()
  34345. {
  34346. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34347. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34348. WeakReference<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34349. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34350. }
  34351. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34352. {
  34353. mouseListeners.add (listener);
  34354. resetTimer();
  34355. }
  34356. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34357. {
  34358. mouseListeners.remove (listener);
  34359. resetTimer();
  34360. }
  34361. void Desktop::timerCallback()
  34362. {
  34363. if (lastFakeMouseMove != getMousePosition())
  34364. sendMouseMove();
  34365. }
  34366. void Desktop::sendMouseMove()
  34367. {
  34368. if (! mouseListeners.isEmpty())
  34369. {
  34370. startTimer (20);
  34371. lastFakeMouseMove = getMousePosition();
  34372. Component* const target = findComponentAt (lastFakeMouseMove);
  34373. if (target != 0)
  34374. {
  34375. Component::BailOutChecker checker (target);
  34376. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34377. const Time now (Time::getCurrentTime());
  34378. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34379. target, target, now, pos, now, 0, false);
  34380. if (me.mods.isAnyMouseButtonDown())
  34381. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34382. else
  34383. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34384. }
  34385. }
  34386. }
  34387. void Desktop::resetTimer()
  34388. {
  34389. if (mouseListeners.size() == 0)
  34390. stopTimer();
  34391. else
  34392. startTimer (100);
  34393. lastFakeMouseMove = getMousePosition();
  34394. }
  34395. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34396. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34397. {
  34398. if (kioskModeComponent != componentToUse)
  34399. {
  34400. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34401. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34402. if (kioskModeComponent != 0)
  34403. {
  34404. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34405. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34406. }
  34407. kioskModeComponent = componentToUse;
  34408. if (kioskModeComponent != 0)
  34409. {
  34410. // Only components that are already on the desktop can be put into kiosk mode!
  34411. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34412. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34413. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34414. }
  34415. }
  34416. }
  34417. void Desktop::setOrientationsEnabled (const int newOrientations)
  34418. {
  34419. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34420. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34421. allowedOrientations = newOrientations;
  34422. }
  34423. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34424. {
  34425. // Make sure you only pass one valid flag in here...
  34426. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34427. return (allowedOrientations & orientation) != 0;
  34428. }
  34429. END_JUCE_NAMESPACE
  34430. /*** End of inlined file: juce_Desktop.cpp ***/
  34431. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34432. BEGIN_JUCE_NAMESPACE
  34433. class ModalComponentManager::ModalItem : public ComponentMovementWatcher
  34434. {
  34435. public:
  34436. ModalItem (Component* const comp)
  34437. : ComponentMovementWatcher (comp),
  34438. component (comp), returnValue (0), isActive (true)
  34439. {
  34440. jassert (comp != 0);
  34441. }
  34442. void componentMovedOrResized (bool, bool) {}
  34443. void componentPeerChanged()
  34444. {
  34445. if (! component->isShowing())
  34446. cancel();
  34447. }
  34448. void componentVisibilityChanged()
  34449. {
  34450. if (! component->isShowing())
  34451. cancel();
  34452. }
  34453. void componentBeingDeleted (Component& comp)
  34454. {
  34455. ComponentMovementWatcher::componentBeingDeleted (comp);
  34456. if (component == &comp || comp.isParentOf (component))
  34457. cancel();
  34458. }
  34459. void cancel()
  34460. {
  34461. if (isActive)
  34462. {
  34463. isActive = false;
  34464. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34465. }
  34466. }
  34467. Component* component;
  34468. OwnedArray<Callback> callbacks;
  34469. int returnValue;
  34470. bool isActive;
  34471. private:
  34472. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34473. };
  34474. ModalComponentManager::ModalComponentManager()
  34475. {
  34476. }
  34477. ModalComponentManager::~ModalComponentManager()
  34478. {
  34479. clearSingletonInstance();
  34480. }
  34481. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34482. void ModalComponentManager::startModal (Component* component)
  34483. {
  34484. if (component != 0)
  34485. stack.add (new ModalItem (component));
  34486. }
  34487. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34488. {
  34489. if (callback != 0)
  34490. {
  34491. ScopedPointer<Callback> callbackDeleter (callback);
  34492. for (int i = stack.size(); --i >= 0;)
  34493. {
  34494. ModalItem* const item = stack.getUnchecked(i);
  34495. if (item->component == component)
  34496. {
  34497. item->callbacks.add (callback);
  34498. callbackDeleter.release();
  34499. break;
  34500. }
  34501. }
  34502. }
  34503. }
  34504. void ModalComponentManager::endModal (Component* component)
  34505. {
  34506. for (int i = stack.size(); --i >= 0;)
  34507. {
  34508. ModalItem* const item = stack.getUnchecked(i);
  34509. if (item->component == component)
  34510. item->cancel();
  34511. }
  34512. }
  34513. void ModalComponentManager::endModal (Component* component, int returnValue)
  34514. {
  34515. for (int i = stack.size(); --i >= 0;)
  34516. {
  34517. ModalItem* const item = stack.getUnchecked(i);
  34518. if (item->component == component)
  34519. {
  34520. item->returnValue = returnValue;
  34521. item->cancel();
  34522. }
  34523. }
  34524. }
  34525. int ModalComponentManager::getNumModalComponents() const
  34526. {
  34527. int n = 0;
  34528. for (int i = 0; i < stack.size(); ++i)
  34529. if (stack.getUnchecked(i)->isActive)
  34530. ++n;
  34531. return n;
  34532. }
  34533. Component* ModalComponentManager::getModalComponent (const int index) const
  34534. {
  34535. int n = 0;
  34536. for (int i = stack.size(); --i >= 0;)
  34537. {
  34538. const ModalItem* const item = stack.getUnchecked(i);
  34539. if (item->isActive)
  34540. if (n++ == index)
  34541. return item->component;
  34542. }
  34543. return 0;
  34544. }
  34545. bool ModalComponentManager::isModal (Component* const comp) const
  34546. {
  34547. for (int i = stack.size(); --i >= 0;)
  34548. {
  34549. const ModalItem* const item = stack.getUnchecked(i);
  34550. if (item->isActive && item->component == comp)
  34551. return true;
  34552. }
  34553. return false;
  34554. }
  34555. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34556. {
  34557. return comp == getModalComponent (0);
  34558. }
  34559. void ModalComponentManager::handleAsyncUpdate()
  34560. {
  34561. for (int i = stack.size(); --i >= 0;)
  34562. {
  34563. const ModalItem* const item = stack.getUnchecked(i);
  34564. if (! item->isActive)
  34565. {
  34566. ScopedPointer<ModalItem> item (stack.removeAndReturn (i));
  34567. for (int j = item->callbacks.size(); --j >= 0;)
  34568. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34569. }
  34570. }
  34571. }
  34572. void ModalComponentManager::bringModalComponentsToFront()
  34573. {
  34574. ComponentPeer* lastOne = 0;
  34575. for (int i = 0; i < getNumModalComponents(); ++i)
  34576. {
  34577. Component* const c = getModalComponent (i);
  34578. if (c == 0)
  34579. break;
  34580. ComponentPeer* peer = c->getPeer();
  34581. if (peer != 0 && peer != lastOne)
  34582. {
  34583. if (lastOne == 0)
  34584. {
  34585. peer->toFront (true);
  34586. peer->grabFocus();
  34587. }
  34588. else
  34589. peer->toBehind (lastOne);
  34590. lastOne = peer;
  34591. }
  34592. }
  34593. }
  34594. #if JUCE_MODAL_LOOPS_PERMITTED
  34595. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34596. {
  34597. public:
  34598. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34599. void modalStateFinished (int returnValue)
  34600. {
  34601. finished = true;
  34602. value = returnValue;
  34603. }
  34604. private:
  34605. int& value;
  34606. bool& finished;
  34607. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34608. };
  34609. int ModalComponentManager::runEventLoopForCurrentComponent()
  34610. {
  34611. // This can only be run from the message thread!
  34612. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34613. Component* currentlyModal = getModalComponent (0);
  34614. if (currentlyModal == 0)
  34615. return 0;
  34616. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34617. int returnValue = 0;
  34618. bool finished = false;
  34619. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34620. JUCE_TRY
  34621. {
  34622. while (! finished)
  34623. {
  34624. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34625. break;
  34626. }
  34627. }
  34628. JUCE_CATCH_EXCEPTION
  34629. if (prevFocused != 0)
  34630. prevFocused->grabKeyboardFocus();
  34631. return returnValue;
  34632. }
  34633. #endif
  34634. END_JUCE_NAMESPACE
  34635. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34636. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34637. BEGIN_JUCE_NAMESPACE
  34638. ArrowButton::ArrowButton (const String& name,
  34639. float arrowDirectionInRadians,
  34640. const Colour& arrowColour)
  34641. : Button (name),
  34642. colour (arrowColour)
  34643. {
  34644. path.lineTo (0.0f, 1.0f);
  34645. path.lineTo (1.0f, 0.5f);
  34646. path.closeSubPath();
  34647. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34648. 0.5f, 0.5f));
  34649. setComponentEffect (&shadow);
  34650. buttonStateChanged();
  34651. }
  34652. ArrowButton::~ArrowButton()
  34653. {
  34654. }
  34655. void ArrowButton::paintButton (Graphics& g,
  34656. bool /*isMouseOverButton*/,
  34657. bool /*isButtonDown*/)
  34658. {
  34659. g.setColour (colour);
  34660. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34661. (float) offset,
  34662. (float) (getWidth() - 3),
  34663. (float) (getHeight() - 3),
  34664. false));
  34665. }
  34666. void ArrowButton::buttonStateChanged()
  34667. {
  34668. offset = (isDown()) ? 1 : 0;
  34669. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34670. 0.3f, -1, 0);
  34671. }
  34672. END_JUCE_NAMESPACE
  34673. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34674. /*** Start of inlined file: juce_Button.cpp ***/
  34675. BEGIN_JUCE_NAMESPACE
  34676. class Button::RepeatTimer : public Timer
  34677. {
  34678. public:
  34679. RepeatTimer (Button& owner_) : owner (owner_) {}
  34680. void timerCallback() { owner.repeatTimerCallback(); }
  34681. private:
  34682. Button& owner;
  34683. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34684. };
  34685. Button::Button (const String& name)
  34686. : Component (name),
  34687. text (name),
  34688. buttonPressTime (0),
  34689. lastRepeatTime (0),
  34690. commandManagerToUse (0),
  34691. autoRepeatDelay (-1),
  34692. autoRepeatSpeed (0),
  34693. autoRepeatMinimumDelay (-1),
  34694. radioGroupId (0),
  34695. commandID (0),
  34696. connectedEdgeFlags (0),
  34697. buttonState (buttonNormal),
  34698. lastToggleState (false),
  34699. clickTogglesState (false),
  34700. needsToRelease (false),
  34701. needsRepainting (false),
  34702. isKeyDown (false),
  34703. triggerOnMouseDown (false),
  34704. generateTooltip (false)
  34705. {
  34706. setWantsKeyboardFocus (true);
  34707. isOn.addListener (this);
  34708. }
  34709. Button::~Button()
  34710. {
  34711. isOn.removeListener (this);
  34712. if (commandManagerToUse != 0)
  34713. commandManagerToUse->removeListener (this);
  34714. repeatTimer = 0;
  34715. clearShortcuts();
  34716. }
  34717. void Button::setButtonText (const String& newText)
  34718. {
  34719. if (text != newText)
  34720. {
  34721. text = newText;
  34722. repaint();
  34723. }
  34724. }
  34725. void Button::setTooltip (const String& newTooltip)
  34726. {
  34727. SettableTooltipClient::setTooltip (newTooltip);
  34728. generateTooltip = false;
  34729. }
  34730. const String Button::getTooltip()
  34731. {
  34732. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34733. {
  34734. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34735. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34736. for (int i = 0; i < keyPresses.size(); ++i)
  34737. {
  34738. const String key (keyPresses.getReference(i).getTextDescription());
  34739. tt << " [";
  34740. if (key.length() == 1)
  34741. tt << TRANS("shortcut") << ": '" << key << "']";
  34742. else
  34743. tt << key << ']';
  34744. }
  34745. return tt;
  34746. }
  34747. return SettableTooltipClient::getTooltip();
  34748. }
  34749. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34750. {
  34751. if (connectedEdgeFlags != connectedEdgeFlags_)
  34752. {
  34753. connectedEdgeFlags = connectedEdgeFlags_;
  34754. repaint();
  34755. }
  34756. }
  34757. void Button::setToggleState (const bool shouldBeOn,
  34758. const bool sendChangeNotification)
  34759. {
  34760. if (shouldBeOn != lastToggleState)
  34761. {
  34762. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34763. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34764. lastToggleState = shouldBeOn;
  34765. repaint();
  34766. WeakReference<Component> deletionWatcher (this);
  34767. if (sendChangeNotification)
  34768. {
  34769. sendClickMessage (ModifierKeys());
  34770. if (deletionWatcher == 0)
  34771. return;
  34772. }
  34773. if (lastToggleState)
  34774. {
  34775. turnOffOtherButtonsInGroup (sendChangeNotification);
  34776. if (deletionWatcher == 0)
  34777. return;
  34778. }
  34779. sendStateMessage();
  34780. }
  34781. }
  34782. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34783. {
  34784. clickTogglesState = shouldToggle;
  34785. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34786. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34787. // it is that this button represents, and the button will update its state to reflect this
  34788. // in the applicationCommandListChanged() method.
  34789. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34790. }
  34791. bool Button::getClickingTogglesState() const throw()
  34792. {
  34793. return clickTogglesState;
  34794. }
  34795. void Button::valueChanged (Value& value)
  34796. {
  34797. if (value.refersToSameSourceAs (isOn))
  34798. setToggleState (isOn.getValue(), true);
  34799. }
  34800. void Button::setRadioGroupId (const int newGroupId)
  34801. {
  34802. if (radioGroupId != newGroupId)
  34803. {
  34804. radioGroupId = newGroupId;
  34805. if (lastToggleState)
  34806. turnOffOtherButtonsInGroup (true);
  34807. }
  34808. }
  34809. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34810. {
  34811. Component* const p = getParentComponent();
  34812. if (p != 0 && radioGroupId != 0)
  34813. {
  34814. WeakReference<Component> deletionWatcher (this);
  34815. for (int i = p->getNumChildComponents(); --i >= 0;)
  34816. {
  34817. Component* const c = p->getChildComponent (i);
  34818. if (c != this)
  34819. {
  34820. Button* const b = dynamic_cast <Button*> (c);
  34821. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34822. {
  34823. b->setToggleState (false, sendChangeNotification);
  34824. if (deletionWatcher == 0)
  34825. return;
  34826. }
  34827. }
  34828. }
  34829. }
  34830. }
  34831. void Button::enablementChanged()
  34832. {
  34833. updateState();
  34834. repaint();
  34835. }
  34836. Button::ButtonState Button::updateState()
  34837. {
  34838. return updateState (isMouseOver (true), isMouseButtonDown());
  34839. }
  34840. Button::ButtonState Button::updateState (const bool over, const bool down)
  34841. {
  34842. ButtonState newState = buttonNormal;
  34843. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34844. {
  34845. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34846. newState = buttonDown;
  34847. else if (over)
  34848. newState = buttonOver;
  34849. }
  34850. setState (newState);
  34851. return newState;
  34852. }
  34853. void Button::setState (const ButtonState newState)
  34854. {
  34855. if (buttonState != newState)
  34856. {
  34857. buttonState = newState;
  34858. repaint();
  34859. if (buttonState == buttonDown)
  34860. {
  34861. buttonPressTime = Time::getApproximateMillisecondCounter();
  34862. lastRepeatTime = 0;
  34863. }
  34864. sendStateMessage();
  34865. }
  34866. }
  34867. bool Button::isDown() const throw()
  34868. {
  34869. return buttonState == buttonDown;
  34870. }
  34871. bool Button::isOver() const throw()
  34872. {
  34873. return buttonState != buttonNormal;
  34874. }
  34875. void Button::buttonStateChanged()
  34876. {
  34877. }
  34878. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34879. {
  34880. const uint32 now = Time::getApproximateMillisecondCounter();
  34881. return now > buttonPressTime ? now - buttonPressTime : 0;
  34882. }
  34883. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34884. {
  34885. triggerOnMouseDown = isTriggeredOnMouseDown;
  34886. }
  34887. void Button::clicked()
  34888. {
  34889. }
  34890. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34891. {
  34892. clicked();
  34893. }
  34894. static const int clickMessageId = 0x2f3f4f99;
  34895. void Button::triggerClick()
  34896. {
  34897. postCommandMessage (clickMessageId);
  34898. }
  34899. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34900. {
  34901. if (clickTogglesState)
  34902. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34903. sendClickMessage (modifiers);
  34904. }
  34905. void Button::flashButtonState()
  34906. {
  34907. if (isEnabled())
  34908. {
  34909. needsToRelease = true;
  34910. setState (buttonDown);
  34911. getRepeatTimer().startTimer (100);
  34912. }
  34913. }
  34914. void Button::handleCommandMessage (int commandId)
  34915. {
  34916. if (commandId == clickMessageId)
  34917. {
  34918. if (isEnabled())
  34919. {
  34920. flashButtonState();
  34921. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34922. }
  34923. }
  34924. else
  34925. {
  34926. Component::handleCommandMessage (commandId);
  34927. }
  34928. }
  34929. void Button::addListener (ButtonListener* const newListener)
  34930. {
  34931. buttonListeners.add (newListener);
  34932. }
  34933. void Button::removeListener (ButtonListener* const listener)
  34934. {
  34935. buttonListeners.remove (listener);
  34936. }
  34937. void Button::addButtonListener (ButtonListener* l) { addListener (l); }
  34938. void Button::removeButtonListener (ButtonListener* l) { removeListener (l); }
  34939. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34940. {
  34941. Component::BailOutChecker checker (this);
  34942. if (commandManagerToUse != 0 && commandID != 0)
  34943. {
  34944. ApplicationCommandTarget::InvocationInfo info (commandID);
  34945. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34946. info.originatingComponent = this;
  34947. commandManagerToUse->invoke (info, true);
  34948. }
  34949. clicked (modifiers);
  34950. if (! checker.shouldBailOut())
  34951. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  34952. }
  34953. void Button::sendStateMessage()
  34954. {
  34955. Component::BailOutChecker checker (this);
  34956. buttonStateChanged();
  34957. if (! checker.shouldBailOut())
  34958. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34959. }
  34960. void Button::paint (Graphics& g)
  34961. {
  34962. if (needsToRelease && isEnabled())
  34963. {
  34964. needsToRelease = false;
  34965. needsRepainting = true;
  34966. }
  34967. paintButton (g, isOver(), isDown());
  34968. }
  34969. void Button::mouseEnter (const MouseEvent&)
  34970. {
  34971. updateState (true, false);
  34972. }
  34973. void Button::mouseExit (const MouseEvent&)
  34974. {
  34975. updateState (false, false);
  34976. }
  34977. void Button::mouseDown (const MouseEvent& e)
  34978. {
  34979. updateState (true, true);
  34980. if (isDown())
  34981. {
  34982. if (autoRepeatDelay >= 0)
  34983. getRepeatTimer().startTimer (autoRepeatDelay);
  34984. if (triggerOnMouseDown)
  34985. internalClickCallback (e.mods);
  34986. }
  34987. }
  34988. void Button::mouseUp (const MouseEvent& e)
  34989. {
  34990. const bool wasDown = isDown();
  34991. updateState (isMouseOver(), false);
  34992. if (wasDown && isOver() && ! triggerOnMouseDown)
  34993. internalClickCallback (e.mods);
  34994. }
  34995. void Button::mouseDrag (const MouseEvent&)
  34996. {
  34997. const ButtonState oldState = buttonState;
  34998. updateState (isMouseOver(), true);
  34999. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35000. getRepeatTimer().startTimer (autoRepeatSpeed);
  35001. }
  35002. void Button::focusGained (FocusChangeType)
  35003. {
  35004. updateState();
  35005. repaint();
  35006. }
  35007. void Button::focusLost (FocusChangeType)
  35008. {
  35009. updateState();
  35010. repaint();
  35011. }
  35012. void Button::visibilityChanged()
  35013. {
  35014. needsToRelease = false;
  35015. updateState();
  35016. }
  35017. void Button::parentHierarchyChanged()
  35018. {
  35019. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35020. if (newKeySource != keySource.get())
  35021. {
  35022. if (keySource != 0)
  35023. keySource->removeKeyListener (this);
  35024. keySource = newKeySource;
  35025. if (keySource != 0)
  35026. keySource->addKeyListener (this);
  35027. }
  35028. }
  35029. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35030. const int commandID_,
  35031. const bool generateTooltip_)
  35032. {
  35033. commandID = commandID_;
  35034. generateTooltip = generateTooltip_;
  35035. if (commandManagerToUse != commandManagerToUse_)
  35036. {
  35037. if (commandManagerToUse != 0)
  35038. commandManagerToUse->removeListener (this);
  35039. commandManagerToUse = commandManagerToUse_;
  35040. if (commandManagerToUse != 0)
  35041. commandManagerToUse->addListener (this);
  35042. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35043. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35044. // it is that this button represents, and the button will update its state to reflect this
  35045. // in the applicationCommandListChanged() method.
  35046. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35047. }
  35048. if (commandManagerToUse != 0)
  35049. applicationCommandListChanged();
  35050. else
  35051. setEnabled (true);
  35052. }
  35053. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35054. {
  35055. if (info.commandID == commandID
  35056. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35057. {
  35058. flashButtonState();
  35059. }
  35060. }
  35061. void Button::applicationCommandListChanged()
  35062. {
  35063. if (commandManagerToUse != 0)
  35064. {
  35065. ApplicationCommandInfo info (0);
  35066. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35067. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35068. if (target != 0)
  35069. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35070. }
  35071. }
  35072. void Button::addShortcut (const KeyPress& key)
  35073. {
  35074. if (key.isValid())
  35075. {
  35076. jassert (! isRegisteredForShortcut (key)); // already registered!
  35077. shortcuts.add (key);
  35078. parentHierarchyChanged();
  35079. }
  35080. }
  35081. void Button::clearShortcuts()
  35082. {
  35083. shortcuts.clear();
  35084. parentHierarchyChanged();
  35085. }
  35086. bool Button::isShortcutPressed() const
  35087. {
  35088. if (! isCurrentlyBlockedByAnotherModalComponent())
  35089. {
  35090. for (int i = shortcuts.size(); --i >= 0;)
  35091. if (shortcuts.getReference(i).isCurrentlyDown())
  35092. return true;
  35093. }
  35094. return false;
  35095. }
  35096. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35097. {
  35098. for (int i = shortcuts.size(); --i >= 0;)
  35099. if (key == shortcuts.getReference(i))
  35100. return true;
  35101. return false;
  35102. }
  35103. bool Button::keyStateChanged (const bool, Component*)
  35104. {
  35105. if (! isEnabled())
  35106. return false;
  35107. const bool wasDown = isKeyDown;
  35108. isKeyDown = isShortcutPressed();
  35109. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35110. getRepeatTimer().startTimer (autoRepeatDelay);
  35111. updateState();
  35112. if (isEnabled() && wasDown && ! isKeyDown)
  35113. {
  35114. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35115. // (return immediately - this button may now have been deleted)
  35116. return true;
  35117. }
  35118. return wasDown || isKeyDown;
  35119. }
  35120. bool Button::keyPressed (const KeyPress&, Component*)
  35121. {
  35122. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35123. return isShortcutPressed();
  35124. }
  35125. bool Button::keyPressed (const KeyPress& key)
  35126. {
  35127. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35128. {
  35129. triggerClick();
  35130. return true;
  35131. }
  35132. return false;
  35133. }
  35134. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35135. const int repeatMillisecs,
  35136. const int minimumDelayInMillisecs) throw()
  35137. {
  35138. autoRepeatDelay = initialDelayMillisecs;
  35139. autoRepeatSpeed = repeatMillisecs;
  35140. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35141. }
  35142. void Button::repeatTimerCallback()
  35143. {
  35144. if (needsRepainting)
  35145. {
  35146. getRepeatTimer().stopTimer();
  35147. updateState();
  35148. needsRepainting = false;
  35149. }
  35150. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  35151. {
  35152. int repeatSpeed = autoRepeatSpeed;
  35153. if (autoRepeatMinimumDelay >= 0)
  35154. {
  35155. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35156. timeHeldDown *= timeHeldDown;
  35157. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35158. }
  35159. repeatSpeed = jmax (1, repeatSpeed);
  35160. const uint32 now = Time::getMillisecondCounter();
  35161. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  35162. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  35163. repeatSpeed = jmax (1, repeatSpeed / 2);
  35164. lastRepeatTime = now;
  35165. getRepeatTimer().startTimer (repeatSpeed);
  35166. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35167. }
  35168. else if (! needsToRelease)
  35169. {
  35170. getRepeatTimer().stopTimer();
  35171. }
  35172. }
  35173. Button::RepeatTimer& Button::getRepeatTimer()
  35174. {
  35175. if (repeatTimer == 0)
  35176. repeatTimer = new RepeatTimer (*this);
  35177. return *repeatTimer;
  35178. }
  35179. END_JUCE_NAMESPACE
  35180. /*** End of inlined file: juce_Button.cpp ***/
  35181. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35182. BEGIN_JUCE_NAMESPACE
  35183. DrawableButton::DrawableButton (const String& name,
  35184. const DrawableButton::ButtonStyle buttonStyle)
  35185. : Button (name),
  35186. style (buttonStyle),
  35187. currentImage (0),
  35188. edgeIndent (3)
  35189. {
  35190. if (buttonStyle == ImageOnButtonBackground)
  35191. {
  35192. backgroundOff = Colour (0xffbbbbff);
  35193. backgroundOn = Colour (0xff3333ff);
  35194. }
  35195. else
  35196. {
  35197. backgroundOff = Colours::transparentBlack;
  35198. backgroundOn = Colour (0xaabbbbff);
  35199. }
  35200. }
  35201. DrawableButton::~DrawableButton()
  35202. {
  35203. }
  35204. void DrawableButton::setImages (const Drawable* normal,
  35205. const Drawable* over,
  35206. const Drawable* down,
  35207. const Drawable* disabled,
  35208. const Drawable* normalOn,
  35209. const Drawable* overOn,
  35210. const Drawable* downOn,
  35211. const Drawable* disabledOn)
  35212. {
  35213. jassert (normal != 0); // you really need to give it at least a normal image..
  35214. if (normal != 0) normalImage = normal->createCopy();
  35215. if (over != 0) overImage = over->createCopy();
  35216. if (down != 0) downImage = down->createCopy();
  35217. if (disabled != 0) disabledImage = disabled->createCopy();
  35218. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35219. if (overOn != 0) overImageOn = overOn->createCopy();
  35220. if (downOn != 0) downImageOn = downOn->createCopy();
  35221. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35222. buttonStateChanged();
  35223. }
  35224. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35225. {
  35226. if (style != newStyle)
  35227. {
  35228. style = newStyle;
  35229. buttonStateChanged();
  35230. }
  35231. }
  35232. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35233. const Colour& toggledOnColour)
  35234. {
  35235. if (backgroundOff != toggledOffColour
  35236. || backgroundOn != toggledOnColour)
  35237. {
  35238. backgroundOff = toggledOffColour;
  35239. backgroundOn = toggledOnColour;
  35240. repaint();
  35241. }
  35242. }
  35243. const Colour& DrawableButton::getBackgroundColour() const throw()
  35244. {
  35245. return getToggleState() ? backgroundOn
  35246. : backgroundOff;
  35247. }
  35248. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35249. {
  35250. edgeIndent = numPixelsIndent;
  35251. repaint();
  35252. resized();
  35253. }
  35254. void DrawableButton::resized()
  35255. {
  35256. Button::resized();
  35257. if (currentImage != 0)
  35258. {
  35259. if (style == ImageRaw)
  35260. {
  35261. currentImage->setOriginWithOriginalSize (Point<float>());
  35262. }
  35263. else
  35264. {
  35265. Rectangle<int> imageSpace;
  35266. if (style == ImageOnButtonBackground)
  35267. {
  35268. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35269. }
  35270. else
  35271. {
  35272. const int textH = (style == ImageAboveTextLabel) ? jmin (16, proportionOfHeight (0.25f)) : 0;
  35273. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35274. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35275. imageSpace.setBounds (indentX, indentY,
  35276. getWidth() - indentX * 2,
  35277. getHeight() - indentY * 2 - textH);
  35278. }
  35279. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35280. }
  35281. }
  35282. }
  35283. void DrawableButton::buttonStateChanged()
  35284. {
  35285. repaint();
  35286. Drawable* imageToDraw = 0;
  35287. float opacity = 1.0f;
  35288. if (isEnabled())
  35289. {
  35290. imageToDraw = getCurrentImage();
  35291. }
  35292. else
  35293. {
  35294. imageToDraw = getToggleState() ? disabledImageOn
  35295. : disabledImage;
  35296. if (imageToDraw == 0)
  35297. {
  35298. opacity = 0.4f;
  35299. imageToDraw = getNormalImage();
  35300. }
  35301. }
  35302. if (imageToDraw != currentImage)
  35303. {
  35304. removeChildComponent (currentImage);
  35305. currentImage = imageToDraw;
  35306. if (currentImage != 0)
  35307. {
  35308. currentImage->setInterceptsMouseClicks (false, false);
  35309. addAndMakeVisible (currentImage);
  35310. DrawableButton::resized();
  35311. }
  35312. }
  35313. if (currentImage != 0)
  35314. currentImage->setAlpha (opacity);
  35315. }
  35316. void DrawableButton::paintButton (Graphics& g,
  35317. bool isMouseOverButton,
  35318. bool isButtonDown)
  35319. {
  35320. if (style == ImageOnButtonBackground)
  35321. {
  35322. getLookAndFeel().drawButtonBackground (g, *this,
  35323. getBackgroundColour(),
  35324. isMouseOverButton,
  35325. isButtonDown);
  35326. }
  35327. else
  35328. {
  35329. g.fillAll (getBackgroundColour());
  35330. const int textH = (style == ImageAboveTextLabel)
  35331. ? jmin (16, proportionOfHeight (0.25f))
  35332. : 0;
  35333. if (textH > 0)
  35334. {
  35335. g.setFont ((float) textH);
  35336. g.setColour (findColour (DrawableButton::textColourId)
  35337. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35338. g.drawFittedText (getButtonText(),
  35339. 2, getHeight() - textH - 1,
  35340. getWidth() - 4, textH,
  35341. Justification::centred, 1);
  35342. }
  35343. }
  35344. }
  35345. Drawable* DrawableButton::getCurrentImage() const throw()
  35346. {
  35347. if (isDown())
  35348. return getDownImage();
  35349. if (isOver())
  35350. return getOverImage();
  35351. return getNormalImage();
  35352. }
  35353. Drawable* DrawableButton::getNormalImage() const throw()
  35354. {
  35355. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35356. : normalImage;
  35357. }
  35358. Drawable* DrawableButton::getOverImage() const throw()
  35359. {
  35360. Drawable* d = normalImage;
  35361. if (getToggleState())
  35362. {
  35363. if (overImageOn != 0)
  35364. d = overImageOn;
  35365. else if (normalImageOn != 0)
  35366. d = normalImageOn;
  35367. else if (overImage != 0)
  35368. d = overImage;
  35369. }
  35370. else
  35371. {
  35372. if (overImage != 0)
  35373. d = overImage;
  35374. }
  35375. return d;
  35376. }
  35377. Drawable* DrawableButton::getDownImage() const throw()
  35378. {
  35379. Drawable* d = normalImage;
  35380. if (getToggleState())
  35381. {
  35382. if (downImageOn != 0)
  35383. d = downImageOn;
  35384. else if (overImageOn != 0)
  35385. d = overImageOn;
  35386. else if (normalImageOn != 0)
  35387. d = normalImageOn;
  35388. else if (downImage != 0)
  35389. d = downImage;
  35390. else
  35391. d = getOverImage();
  35392. }
  35393. else
  35394. {
  35395. if (downImage != 0)
  35396. d = downImage;
  35397. else
  35398. d = getOverImage();
  35399. }
  35400. return d;
  35401. }
  35402. END_JUCE_NAMESPACE
  35403. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35404. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35405. BEGIN_JUCE_NAMESPACE
  35406. HyperlinkButton::HyperlinkButton (const String& linkText,
  35407. const URL& linkURL)
  35408. : Button (linkText),
  35409. url (linkURL),
  35410. font (14.0f, Font::underlined),
  35411. resizeFont (true),
  35412. justification (Justification::centred)
  35413. {
  35414. setMouseCursor (MouseCursor::PointingHandCursor);
  35415. setTooltip (linkURL.toString (false));
  35416. }
  35417. HyperlinkButton::~HyperlinkButton()
  35418. {
  35419. }
  35420. void HyperlinkButton::setFont (const Font& newFont,
  35421. const bool resizeToMatchComponentHeight,
  35422. const Justification& justificationType)
  35423. {
  35424. font = newFont;
  35425. resizeFont = resizeToMatchComponentHeight;
  35426. justification = justificationType;
  35427. repaint();
  35428. }
  35429. void HyperlinkButton::setURL (const URL& newURL) throw()
  35430. {
  35431. url = newURL;
  35432. setTooltip (newURL.toString (false));
  35433. }
  35434. const Font HyperlinkButton::getFontToUse() const
  35435. {
  35436. Font f (font);
  35437. if (resizeFont)
  35438. f.setHeight (getHeight() * 0.7f);
  35439. return f;
  35440. }
  35441. void HyperlinkButton::changeWidthToFitText()
  35442. {
  35443. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35444. }
  35445. void HyperlinkButton::colourChanged()
  35446. {
  35447. repaint();
  35448. }
  35449. void HyperlinkButton::clicked()
  35450. {
  35451. if (url.isWellFormed())
  35452. url.launchInDefaultBrowser();
  35453. }
  35454. void HyperlinkButton::paintButton (Graphics& g,
  35455. bool isMouseOverButton,
  35456. bool isButtonDown)
  35457. {
  35458. const Colour textColour (findColour (textColourId));
  35459. if (isEnabled())
  35460. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35461. : textColour);
  35462. else
  35463. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35464. g.setFont (getFontToUse());
  35465. g.drawText (getButtonText(),
  35466. 2, 0, getWidth() - 2, getHeight(),
  35467. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35468. true);
  35469. }
  35470. END_JUCE_NAMESPACE
  35471. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35472. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35473. BEGIN_JUCE_NAMESPACE
  35474. ImageButton::ImageButton (const String& text_)
  35475. : Button (text_),
  35476. scaleImageToFit (true),
  35477. preserveProportions (true),
  35478. alphaThreshold (0),
  35479. imageX (0),
  35480. imageY (0),
  35481. imageW (0),
  35482. imageH (0),
  35483. normalImage (0),
  35484. overImage (0),
  35485. downImage (0)
  35486. {
  35487. }
  35488. ImageButton::~ImageButton()
  35489. {
  35490. }
  35491. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35492. const bool rescaleImagesWhenButtonSizeChanges,
  35493. const bool preserveImageProportions,
  35494. const Image& normalImage_,
  35495. const float imageOpacityWhenNormal,
  35496. const Colour& overlayColourWhenNormal,
  35497. const Image& overImage_,
  35498. const float imageOpacityWhenOver,
  35499. const Colour& overlayColourWhenOver,
  35500. const Image& downImage_,
  35501. const float imageOpacityWhenDown,
  35502. const Colour& overlayColourWhenDown,
  35503. const float hitTestAlphaThreshold)
  35504. {
  35505. normalImage = normalImage_;
  35506. overImage = overImage_;
  35507. downImage = downImage_;
  35508. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35509. {
  35510. imageW = normalImage.getWidth();
  35511. imageH = normalImage.getHeight();
  35512. setSize (imageW, imageH);
  35513. }
  35514. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35515. preserveProportions = preserveImageProportions;
  35516. normalOpacity = imageOpacityWhenNormal;
  35517. normalOverlay = overlayColourWhenNormal;
  35518. overOpacity = imageOpacityWhenOver;
  35519. overOverlay = overlayColourWhenOver;
  35520. downOpacity = imageOpacityWhenDown;
  35521. downOverlay = overlayColourWhenDown;
  35522. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35523. repaint();
  35524. }
  35525. const Image ImageButton::getCurrentImage() const
  35526. {
  35527. if (isDown() || getToggleState())
  35528. return getDownImage();
  35529. if (isOver())
  35530. return getOverImage();
  35531. return getNormalImage();
  35532. }
  35533. const Image ImageButton::getNormalImage() const
  35534. {
  35535. return normalImage;
  35536. }
  35537. const Image ImageButton::getOverImage() const
  35538. {
  35539. return overImage.isValid() ? overImage
  35540. : normalImage;
  35541. }
  35542. const Image ImageButton::getDownImage() const
  35543. {
  35544. return downImage.isValid() ? downImage
  35545. : getOverImage();
  35546. }
  35547. void ImageButton::paintButton (Graphics& g,
  35548. bool isMouseOverButton,
  35549. bool isButtonDown)
  35550. {
  35551. if (! isEnabled())
  35552. {
  35553. isMouseOverButton = false;
  35554. isButtonDown = false;
  35555. }
  35556. Image im (getCurrentImage());
  35557. if (im.isValid())
  35558. {
  35559. const int iw = im.getWidth();
  35560. const int ih = im.getHeight();
  35561. imageW = getWidth();
  35562. imageH = getHeight();
  35563. imageX = (imageW - iw) >> 1;
  35564. imageY = (imageH - ih) >> 1;
  35565. if (scaleImageToFit)
  35566. {
  35567. if (preserveProportions)
  35568. {
  35569. int newW, newH;
  35570. const float imRatio = ih / (float)iw;
  35571. const float destRatio = imageH / (float)imageW;
  35572. if (imRatio > destRatio)
  35573. {
  35574. newW = roundToInt (imageH / imRatio);
  35575. newH = imageH;
  35576. }
  35577. else
  35578. {
  35579. newW = imageW;
  35580. newH = roundToInt (imageW * imRatio);
  35581. }
  35582. imageX = (imageW - newW) / 2;
  35583. imageY = (imageH - newH) / 2;
  35584. imageW = newW;
  35585. imageH = newH;
  35586. }
  35587. else
  35588. {
  35589. imageX = 0;
  35590. imageY = 0;
  35591. }
  35592. }
  35593. if (! scaleImageToFit)
  35594. {
  35595. imageW = iw;
  35596. imageH = ih;
  35597. }
  35598. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35599. isButtonDown ? downOverlay
  35600. : (isMouseOverButton ? overOverlay
  35601. : normalOverlay),
  35602. isButtonDown ? downOpacity
  35603. : (isMouseOverButton ? overOpacity
  35604. : normalOpacity),
  35605. *this);
  35606. }
  35607. }
  35608. bool ImageButton::hitTest (int x, int y)
  35609. {
  35610. if (alphaThreshold == 0)
  35611. return true;
  35612. Image im (getCurrentImage());
  35613. return im.isNull() || (imageW > 0 && imageH > 0
  35614. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35615. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35616. }
  35617. END_JUCE_NAMESPACE
  35618. /*** End of inlined file: juce_ImageButton.cpp ***/
  35619. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35620. BEGIN_JUCE_NAMESPACE
  35621. ShapeButton::ShapeButton (const String& text_,
  35622. const Colour& normalColour_,
  35623. const Colour& overColour_,
  35624. const Colour& downColour_)
  35625. : Button (text_),
  35626. normalColour (normalColour_),
  35627. overColour (overColour_),
  35628. downColour (downColour_),
  35629. maintainShapeProportions (false),
  35630. outlineWidth (0.0f)
  35631. {
  35632. }
  35633. ShapeButton::~ShapeButton()
  35634. {
  35635. }
  35636. void ShapeButton::setColours (const Colour& newNormalColour,
  35637. const Colour& newOverColour,
  35638. const Colour& newDownColour)
  35639. {
  35640. normalColour = newNormalColour;
  35641. overColour = newOverColour;
  35642. downColour = newDownColour;
  35643. }
  35644. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35645. const float newOutlineWidth)
  35646. {
  35647. outlineColour = newOutlineColour;
  35648. outlineWidth = newOutlineWidth;
  35649. }
  35650. void ShapeButton::setShape (const Path& newShape,
  35651. const bool resizeNowToFitThisShape,
  35652. const bool maintainShapeProportions_,
  35653. const bool hasShadow)
  35654. {
  35655. shape = newShape;
  35656. maintainShapeProportions = maintainShapeProportions_;
  35657. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35658. setComponentEffect ((hasShadow) ? &shadow : 0);
  35659. if (resizeNowToFitThisShape)
  35660. {
  35661. Rectangle<float> bounds (shape.getBounds());
  35662. if (hasShadow)
  35663. bounds.expand (4.0f, 4.0f);
  35664. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35665. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35666. 1 + (int) (bounds.getHeight() + outlineWidth));
  35667. }
  35668. }
  35669. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35670. {
  35671. if (! isEnabled())
  35672. {
  35673. isMouseOverButton = false;
  35674. isButtonDown = false;
  35675. }
  35676. g.setColour ((isButtonDown) ? downColour
  35677. : (isMouseOverButton) ? overColour
  35678. : normalColour);
  35679. int w = getWidth();
  35680. int h = getHeight();
  35681. if (getComponentEffect() != 0)
  35682. {
  35683. w -= 4;
  35684. h -= 4;
  35685. }
  35686. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35687. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35688. w - offset - outlineWidth,
  35689. h - offset - outlineWidth,
  35690. maintainShapeProportions));
  35691. g.fillPath (shape, trans);
  35692. if (outlineWidth > 0.0f)
  35693. {
  35694. g.setColour (outlineColour);
  35695. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35696. }
  35697. }
  35698. END_JUCE_NAMESPACE
  35699. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35700. /*** Start of inlined file: juce_TextButton.cpp ***/
  35701. BEGIN_JUCE_NAMESPACE
  35702. TextButton::TextButton (const String& name,
  35703. const String& toolTip)
  35704. : Button (name)
  35705. {
  35706. setTooltip (toolTip);
  35707. }
  35708. TextButton::~TextButton()
  35709. {
  35710. }
  35711. void TextButton::paintButton (Graphics& g,
  35712. bool isMouseOverButton,
  35713. bool isButtonDown)
  35714. {
  35715. getLookAndFeel().drawButtonBackground (g, *this,
  35716. findColour (getToggleState() ? buttonOnColourId
  35717. : buttonColourId),
  35718. isMouseOverButton,
  35719. isButtonDown);
  35720. getLookAndFeel().drawButtonText (g, *this,
  35721. isMouseOverButton,
  35722. isButtonDown);
  35723. }
  35724. void TextButton::colourChanged()
  35725. {
  35726. repaint();
  35727. }
  35728. const Font TextButton::getFont()
  35729. {
  35730. return Font (jmin (15.0f, getHeight() * 0.6f));
  35731. }
  35732. void TextButton::changeWidthToFitText (const int newHeight)
  35733. {
  35734. if (newHeight >= 0)
  35735. setSize (jmax (1, getWidth()), newHeight);
  35736. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35737. getHeight());
  35738. }
  35739. END_JUCE_NAMESPACE
  35740. /*** End of inlined file: juce_TextButton.cpp ***/
  35741. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35742. BEGIN_JUCE_NAMESPACE
  35743. ToggleButton::ToggleButton (const String& buttonText)
  35744. : Button (buttonText)
  35745. {
  35746. setClickingTogglesState (true);
  35747. }
  35748. ToggleButton::~ToggleButton()
  35749. {
  35750. }
  35751. void ToggleButton::paintButton (Graphics& g,
  35752. bool isMouseOverButton,
  35753. bool isButtonDown)
  35754. {
  35755. getLookAndFeel().drawToggleButton (g, *this,
  35756. isMouseOverButton,
  35757. isButtonDown);
  35758. }
  35759. void ToggleButton::changeWidthToFitText()
  35760. {
  35761. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35762. }
  35763. void ToggleButton::colourChanged()
  35764. {
  35765. repaint();
  35766. }
  35767. END_JUCE_NAMESPACE
  35768. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35769. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35770. BEGIN_JUCE_NAMESPACE
  35771. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35772. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35773. : ToolbarItemComponent (itemId_, buttonText, true),
  35774. normalImage (normalImage_),
  35775. toggledOnImage (toggledOnImage_),
  35776. currentImage (0)
  35777. {
  35778. jassert (normalImage_ != 0);
  35779. }
  35780. ToolbarButton::~ToolbarButton()
  35781. {
  35782. }
  35783. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35784. {
  35785. preferredSize = minSize = maxSize = toolbarDepth;
  35786. return true;
  35787. }
  35788. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35789. {
  35790. }
  35791. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35792. {
  35793. buttonStateChanged();
  35794. }
  35795. void ToolbarButton::updateDrawable()
  35796. {
  35797. if (currentImage != 0)
  35798. {
  35799. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35800. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35801. }
  35802. }
  35803. void ToolbarButton::resized()
  35804. {
  35805. ToolbarItemComponent::resized();
  35806. updateDrawable();
  35807. }
  35808. void ToolbarButton::enablementChanged()
  35809. {
  35810. ToolbarItemComponent::enablementChanged();
  35811. updateDrawable();
  35812. }
  35813. void ToolbarButton::buttonStateChanged()
  35814. {
  35815. Drawable* d = normalImage;
  35816. if (getToggleState() && toggledOnImage != 0)
  35817. d = toggledOnImage;
  35818. if (d != currentImage)
  35819. {
  35820. removeChildComponent (currentImage);
  35821. currentImage = d;
  35822. if (d != 0)
  35823. {
  35824. enablementChanged();
  35825. addAndMakeVisible (d);
  35826. updateDrawable();
  35827. }
  35828. }
  35829. }
  35830. END_JUCE_NAMESPACE
  35831. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35832. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35833. BEGIN_JUCE_NAMESPACE
  35834. class CodeDocumentLine
  35835. {
  35836. public:
  35837. CodeDocumentLine (const String::CharPointerType& line_,
  35838. const int lineLength_,
  35839. const int numNewLineChars,
  35840. const int lineStartInFile_)
  35841. : line (line_, lineLength_),
  35842. lineStartInFile (lineStartInFile_),
  35843. lineLength (lineLength_),
  35844. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35845. {
  35846. }
  35847. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35848. {
  35849. String::CharPointerType t (text.getCharPointer());
  35850. int charNumInFile = 0;
  35851. bool finished = t.isEmpty();
  35852. while (! finished)
  35853. {
  35854. String::CharPointerType startOfLine (t);
  35855. int startOfLineInFile = charNumInFile;
  35856. int lineLength = 0;
  35857. int numNewLineChars = 0;
  35858. for (;;)
  35859. {
  35860. const juce_wchar c = t.getAndAdvance();
  35861. if (c == 0)
  35862. {
  35863. finished = true;
  35864. break;
  35865. }
  35866. ++charNumInFile;
  35867. ++lineLength;
  35868. if (c == '\r')
  35869. {
  35870. ++numNewLineChars;
  35871. if (*t == '\n')
  35872. {
  35873. ++t;
  35874. ++charNumInFile;
  35875. ++lineLength;
  35876. ++numNewLineChars;
  35877. }
  35878. break;
  35879. }
  35880. if (c == '\n')
  35881. {
  35882. ++numNewLineChars;
  35883. break;
  35884. }
  35885. }
  35886. newLines.add (new CodeDocumentLine (startOfLine, lineLength,
  35887. numNewLineChars, startOfLineInFile));
  35888. }
  35889. jassert (charNumInFile == text.length());
  35890. }
  35891. bool endsWithLineBreak() const throw()
  35892. {
  35893. return lineLengthWithoutNewLines != lineLength;
  35894. }
  35895. void updateLength() throw()
  35896. {
  35897. lineLengthWithoutNewLines = lineLength = line.length();
  35898. while (lineLengthWithoutNewLines > 0
  35899. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35900. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35901. {
  35902. --lineLengthWithoutNewLines;
  35903. }
  35904. }
  35905. String line;
  35906. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35907. };
  35908. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35909. : document (document_),
  35910. currentLine (document_->lines[0]),
  35911. line (0),
  35912. position (0)
  35913. {
  35914. }
  35915. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35916. : document (other.document),
  35917. currentLine (other.currentLine),
  35918. line (other.line),
  35919. position (other.position)
  35920. {
  35921. }
  35922. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35923. {
  35924. document = other.document;
  35925. currentLine = other.currentLine;
  35926. line = other.line;
  35927. position = other.position;
  35928. return *this;
  35929. }
  35930. CodeDocument::Iterator::~Iterator() throw()
  35931. {
  35932. }
  35933. juce_wchar CodeDocument::Iterator::nextChar()
  35934. {
  35935. if (currentLine == 0)
  35936. return 0;
  35937. jassert (currentLine == document->lines.getUnchecked (line));
  35938. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35939. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35940. {
  35941. ++line;
  35942. currentLine = document->lines [line];
  35943. }
  35944. return result;
  35945. }
  35946. void CodeDocument::Iterator::skip()
  35947. {
  35948. if (currentLine != 0)
  35949. {
  35950. jassert (currentLine == document->lines.getUnchecked (line));
  35951. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35952. {
  35953. ++line;
  35954. currentLine = document->lines [line];
  35955. }
  35956. }
  35957. }
  35958. void CodeDocument::Iterator::skipToEndOfLine()
  35959. {
  35960. if (currentLine != 0)
  35961. {
  35962. jassert (currentLine == document->lines.getUnchecked (line));
  35963. ++line;
  35964. currentLine = document->lines [line];
  35965. if (currentLine != 0)
  35966. position = currentLine->lineStartInFile;
  35967. else
  35968. position = document->getNumCharacters();
  35969. }
  35970. }
  35971. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35972. {
  35973. if (currentLine == 0)
  35974. return 0;
  35975. jassert (currentLine == document->lines.getUnchecked (line));
  35976. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35977. }
  35978. void CodeDocument::Iterator::skipWhitespace()
  35979. {
  35980. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35981. skip();
  35982. }
  35983. bool CodeDocument::Iterator::isEOF() const throw()
  35984. {
  35985. return currentLine == 0;
  35986. }
  35987. CodeDocument::Position::Position() throw()
  35988. : owner (0), characterPos (0), line (0),
  35989. indexInLine (0), positionMaintained (false)
  35990. {
  35991. }
  35992. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35993. const int line_, const int indexInLine_) throw()
  35994. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35995. characterPos (0), line (line_),
  35996. indexInLine (indexInLine_), positionMaintained (false)
  35997. {
  35998. setLineAndIndex (line_, indexInLine_);
  35999. }
  36000. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36001. const int characterPos_) throw()
  36002. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36003. positionMaintained (false)
  36004. {
  36005. setPosition (characterPos_);
  36006. }
  36007. CodeDocument::Position::Position (const Position& other) throw()
  36008. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36009. indexInLine (other.indexInLine), positionMaintained (false)
  36010. {
  36011. jassert (*this == other);
  36012. }
  36013. CodeDocument::Position::~Position()
  36014. {
  36015. setPositionMaintained (false);
  36016. }
  36017. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36018. {
  36019. if (this != &other)
  36020. {
  36021. const bool wasPositionMaintained = positionMaintained;
  36022. if (owner != other.owner)
  36023. setPositionMaintained (false);
  36024. owner = other.owner;
  36025. line = other.line;
  36026. indexInLine = other.indexInLine;
  36027. characterPos = other.characterPos;
  36028. setPositionMaintained (wasPositionMaintained);
  36029. jassert (*this == other);
  36030. }
  36031. return *this;
  36032. }
  36033. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36034. {
  36035. jassert ((characterPos == other.characterPos)
  36036. == (line == other.line && indexInLine == other.indexInLine));
  36037. return characterPos == other.characterPos
  36038. && line == other.line
  36039. && indexInLine == other.indexInLine
  36040. && owner == other.owner;
  36041. }
  36042. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36043. {
  36044. return ! operator== (other);
  36045. }
  36046. void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine)
  36047. {
  36048. jassert (owner != 0);
  36049. if (owner->lines.size() == 0)
  36050. {
  36051. line = 0;
  36052. indexInLine = 0;
  36053. characterPos = 0;
  36054. }
  36055. else
  36056. {
  36057. if (newLineNum >= owner->lines.size())
  36058. {
  36059. line = owner->lines.size() - 1;
  36060. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36061. jassert (l != 0);
  36062. indexInLine = l->lineLengthWithoutNewLines;
  36063. characterPos = l->lineStartInFile + indexInLine;
  36064. }
  36065. else
  36066. {
  36067. line = jmax (0, newLineNum);
  36068. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36069. jassert (l != 0);
  36070. if (l->lineLengthWithoutNewLines > 0)
  36071. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36072. else
  36073. indexInLine = 0;
  36074. characterPos = l->lineStartInFile + indexInLine;
  36075. }
  36076. }
  36077. }
  36078. void CodeDocument::Position::setPosition (const int newPosition)
  36079. {
  36080. jassert (owner != 0);
  36081. line = 0;
  36082. indexInLine = 0;
  36083. characterPos = 0;
  36084. if (newPosition > 0)
  36085. {
  36086. int lineStart = 0;
  36087. int lineEnd = owner->lines.size();
  36088. for (;;)
  36089. {
  36090. if (lineEnd - lineStart < 4)
  36091. {
  36092. for (int i = lineStart; i < lineEnd; ++i)
  36093. {
  36094. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36095. int index = newPosition - l->lineStartInFile;
  36096. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36097. {
  36098. line = i;
  36099. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36100. characterPos = l->lineStartInFile + indexInLine;
  36101. }
  36102. }
  36103. break;
  36104. }
  36105. else
  36106. {
  36107. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36108. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36109. if (newPosition >= mid->lineStartInFile)
  36110. lineStart = midIndex;
  36111. else
  36112. lineEnd = midIndex;
  36113. }
  36114. }
  36115. }
  36116. }
  36117. void CodeDocument::Position::moveBy (int characterDelta)
  36118. {
  36119. jassert (owner != 0);
  36120. if (characterDelta == 1)
  36121. {
  36122. setPosition (getPosition());
  36123. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36124. if (line < owner->lines.size())
  36125. {
  36126. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36127. if (indexInLine + characterDelta < l->lineLength
  36128. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36129. ++characterDelta;
  36130. }
  36131. }
  36132. setPosition (characterPos + characterDelta);
  36133. }
  36134. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36135. {
  36136. CodeDocument::Position p (*this);
  36137. p.moveBy (characterDelta);
  36138. return p;
  36139. }
  36140. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36141. {
  36142. CodeDocument::Position p (*this);
  36143. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36144. return p;
  36145. }
  36146. const juce_wchar CodeDocument::Position::getCharacter() const
  36147. {
  36148. const CodeDocumentLine* const l = owner->lines [line];
  36149. return l == 0 ? 0 : l->line [getIndexInLine()];
  36150. }
  36151. const String CodeDocument::Position::getLineText() const
  36152. {
  36153. const CodeDocumentLine* const l = owner->lines [line];
  36154. return l == 0 ? String::empty : l->line;
  36155. }
  36156. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36157. {
  36158. if (isMaintained != positionMaintained)
  36159. {
  36160. positionMaintained = isMaintained;
  36161. if (owner != 0)
  36162. {
  36163. if (isMaintained)
  36164. {
  36165. jassert (! owner->positionsToMaintain.contains (this));
  36166. owner->positionsToMaintain.add (this);
  36167. }
  36168. else
  36169. {
  36170. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36171. jassert (owner->positionsToMaintain.contains (this));
  36172. owner->positionsToMaintain.removeValue (this);
  36173. }
  36174. }
  36175. }
  36176. }
  36177. CodeDocument::CodeDocument()
  36178. : undoManager (std::numeric_limits<int>::max(), 10000),
  36179. currentActionIndex (0),
  36180. indexOfSavedState (-1),
  36181. maximumLineLength (-1),
  36182. newLineChars ("\r\n")
  36183. {
  36184. }
  36185. CodeDocument::~CodeDocument()
  36186. {
  36187. }
  36188. const String CodeDocument::getAllContent() const
  36189. {
  36190. return getTextBetween (Position (this, 0),
  36191. Position (this, lines.size(), 0));
  36192. }
  36193. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36194. {
  36195. if (end.getPosition() <= start.getPosition())
  36196. return String::empty;
  36197. const int startLine = start.getLineNumber();
  36198. const int endLine = end.getLineNumber();
  36199. if (startLine == endLine)
  36200. {
  36201. CodeDocumentLine* const line = lines [startLine];
  36202. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36203. }
  36204. String result;
  36205. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36206. String::Concatenator concatenator (result);
  36207. const int maxLine = jmin (lines.size() - 1, endLine);
  36208. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36209. {
  36210. const CodeDocumentLine* line = lines.getUnchecked(i);
  36211. int len = line->lineLength;
  36212. if (i == startLine)
  36213. {
  36214. const int index = start.getIndexInLine();
  36215. concatenator.append (line->line.substring (index, len));
  36216. }
  36217. else if (i == endLine)
  36218. {
  36219. len = end.getIndexInLine();
  36220. concatenator.append (line->line.substring (0, len));
  36221. }
  36222. else
  36223. {
  36224. concatenator.append (line->line);
  36225. }
  36226. }
  36227. return result;
  36228. }
  36229. int CodeDocument::getNumCharacters() const throw()
  36230. {
  36231. const CodeDocumentLine* const lastLine = lines.getLast();
  36232. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36233. }
  36234. const String CodeDocument::getLine (const int lineIndex) const throw()
  36235. {
  36236. const CodeDocumentLine* const line = lines [lineIndex];
  36237. return (line == 0) ? String::empty : line->line;
  36238. }
  36239. int CodeDocument::getMaximumLineLength() throw()
  36240. {
  36241. if (maximumLineLength < 0)
  36242. {
  36243. maximumLineLength = 0;
  36244. for (int i = lines.size(); --i >= 0;)
  36245. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36246. }
  36247. return maximumLineLength;
  36248. }
  36249. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36250. {
  36251. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36252. }
  36253. void CodeDocument::insertText (const Position& position, const String& text)
  36254. {
  36255. insert (text, position.getPosition(), true);
  36256. }
  36257. void CodeDocument::replaceAllContent (const String& newContent)
  36258. {
  36259. remove (0, getNumCharacters(), true);
  36260. insert (newContent, 0, true);
  36261. }
  36262. bool CodeDocument::loadFromStream (InputStream& stream)
  36263. {
  36264. replaceAllContent (stream.readEntireStreamAsString());
  36265. setSavePoint();
  36266. clearUndoHistory();
  36267. return true;
  36268. }
  36269. bool CodeDocument::writeToStream (OutputStream& stream)
  36270. {
  36271. for (int i = 0; i < lines.size(); ++i)
  36272. {
  36273. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36274. const char* utf8 = temp.toUTF8();
  36275. if (! stream.write (utf8, (int) strlen (utf8)))
  36276. return false;
  36277. }
  36278. return true;
  36279. }
  36280. void CodeDocument::setNewLineCharacters (const String& newLineChars_) throw()
  36281. {
  36282. jassert (newLineChars_ == "\r\n" || newLineChars_ == "\n" || newLineChars_ == "\r");
  36283. newLineChars = newLineChars_;
  36284. }
  36285. void CodeDocument::newTransaction()
  36286. {
  36287. undoManager.beginNewTransaction (String::empty);
  36288. }
  36289. void CodeDocument::undo()
  36290. {
  36291. newTransaction();
  36292. undoManager.undo();
  36293. }
  36294. void CodeDocument::redo()
  36295. {
  36296. undoManager.redo();
  36297. }
  36298. void CodeDocument::clearUndoHistory()
  36299. {
  36300. undoManager.clearUndoHistory();
  36301. }
  36302. void CodeDocument::setSavePoint() throw()
  36303. {
  36304. indexOfSavedState = currentActionIndex;
  36305. }
  36306. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36307. {
  36308. return currentActionIndex != indexOfSavedState;
  36309. }
  36310. namespace CodeDocumentHelpers
  36311. {
  36312. int getCharacterType (const juce_wchar character) throw()
  36313. {
  36314. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36315. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36316. }
  36317. }
  36318. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36319. {
  36320. Position p (position);
  36321. const int maxDistance = 256;
  36322. int i = 0;
  36323. while (i < maxDistance
  36324. && CharacterFunctions::isWhitespace (p.getCharacter())
  36325. && (i == 0 || (p.getCharacter() != '\n'
  36326. && p.getCharacter() != '\r')))
  36327. {
  36328. ++i;
  36329. p.moveBy (1);
  36330. }
  36331. if (i == 0)
  36332. {
  36333. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36334. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36335. {
  36336. ++i;
  36337. p.moveBy (1);
  36338. }
  36339. while (i < maxDistance
  36340. && CharacterFunctions::isWhitespace (p.getCharacter())
  36341. && (i == 0 || (p.getCharacter() != '\n'
  36342. && p.getCharacter() != '\r')))
  36343. {
  36344. ++i;
  36345. p.moveBy (1);
  36346. }
  36347. }
  36348. return p;
  36349. }
  36350. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36351. {
  36352. Position p (position);
  36353. const int maxDistance = 256;
  36354. int i = 0;
  36355. bool stoppedAtLineStart = false;
  36356. while (i < maxDistance)
  36357. {
  36358. const juce_wchar c = p.movedBy (-1).getCharacter();
  36359. if (c == '\r' || c == '\n')
  36360. {
  36361. stoppedAtLineStart = true;
  36362. if (i > 0)
  36363. break;
  36364. }
  36365. if (! CharacterFunctions::isWhitespace (c))
  36366. break;
  36367. p.moveBy (-1);
  36368. ++i;
  36369. }
  36370. if (i < maxDistance && ! stoppedAtLineStart)
  36371. {
  36372. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36373. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36374. {
  36375. p.moveBy (-1);
  36376. ++i;
  36377. }
  36378. }
  36379. return p;
  36380. }
  36381. void CodeDocument::checkLastLineStatus()
  36382. {
  36383. while (lines.size() > 0
  36384. && lines.getLast()->lineLength == 0
  36385. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36386. {
  36387. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36388. lines.removeLast();
  36389. }
  36390. const CodeDocumentLine* const lastLine = lines.getLast();
  36391. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36392. {
  36393. // check that there's an empty line at the end if the preceding one ends in a newline..
  36394. lines.add (new CodeDocumentLine (String::empty.getCharPointer(), 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36395. }
  36396. }
  36397. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36398. {
  36399. listeners.add (listener);
  36400. }
  36401. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36402. {
  36403. listeners.remove (listener);
  36404. }
  36405. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36406. {
  36407. Position startPos (this, startLine, 0);
  36408. Position endPos (this, endLine, 0);
  36409. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36410. }
  36411. class CodeDocumentInsertAction : public UndoableAction
  36412. {
  36413. public:
  36414. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36415. : owner (owner_),
  36416. text (text_),
  36417. insertPos (insertPos_)
  36418. {
  36419. }
  36420. bool perform()
  36421. {
  36422. owner.currentActionIndex++;
  36423. owner.insert (text, insertPos, false);
  36424. return true;
  36425. }
  36426. bool undo()
  36427. {
  36428. owner.currentActionIndex--;
  36429. owner.remove (insertPos, insertPos + text.length(), false);
  36430. return true;
  36431. }
  36432. int getSizeInUnits() { return text.length() + 32; }
  36433. private:
  36434. CodeDocument& owner;
  36435. const String text;
  36436. int insertPos;
  36437. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36438. };
  36439. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36440. {
  36441. if (text.isEmpty())
  36442. return;
  36443. if (undoable)
  36444. {
  36445. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36446. }
  36447. else
  36448. {
  36449. Position pos (this, insertPos);
  36450. const int firstAffectedLine = pos.getLineNumber();
  36451. int lastAffectedLine = firstAffectedLine + 1;
  36452. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36453. String textInsideOriginalLine (text);
  36454. if (firstLine != 0)
  36455. {
  36456. const int index = pos.getIndexInLine();
  36457. textInsideOriginalLine = firstLine->line.substring (0, index)
  36458. + textInsideOriginalLine
  36459. + firstLine->line.substring (index);
  36460. }
  36461. maximumLineLength = -1;
  36462. Array <CodeDocumentLine*> newLines;
  36463. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36464. jassert (newLines.size() > 0);
  36465. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36466. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36467. lines.set (firstAffectedLine, newFirstLine);
  36468. if (newLines.size() > 1)
  36469. {
  36470. for (int i = 1; i < newLines.size(); ++i)
  36471. {
  36472. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36473. lines.insert (firstAffectedLine + i, l);
  36474. }
  36475. lastAffectedLine = lines.size();
  36476. }
  36477. int i, lineStart = newFirstLine->lineStartInFile;
  36478. for (i = firstAffectedLine; i < lines.size(); ++i)
  36479. {
  36480. CodeDocumentLine* const l = lines.getUnchecked (i);
  36481. l->lineStartInFile = lineStart;
  36482. lineStart += l->lineLength;
  36483. }
  36484. checkLastLineStatus();
  36485. const int newTextLength = text.length();
  36486. for (i = 0; i < positionsToMaintain.size(); ++i)
  36487. {
  36488. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36489. if (p->getPosition() >= insertPos)
  36490. p->setPosition (p->getPosition() + newTextLength);
  36491. }
  36492. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36493. }
  36494. }
  36495. class CodeDocumentDeleteAction : public UndoableAction
  36496. {
  36497. public:
  36498. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36499. : owner (owner_),
  36500. startPos (startPos_),
  36501. endPos (endPos_)
  36502. {
  36503. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36504. CodeDocument::Position (&owner, endPos));
  36505. }
  36506. bool perform()
  36507. {
  36508. owner.currentActionIndex++;
  36509. owner.remove (startPos, endPos, false);
  36510. return true;
  36511. }
  36512. bool undo()
  36513. {
  36514. owner.currentActionIndex--;
  36515. owner.insert (removedText, startPos, false);
  36516. return true;
  36517. }
  36518. int getSizeInUnits() { return removedText.length() + 32; }
  36519. private:
  36520. CodeDocument& owner;
  36521. int startPos, endPos;
  36522. String removedText;
  36523. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36524. };
  36525. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36526. {
  36527. if (endPos <= startPos)
  36528. return;
  36529. if (undoable)
  36530. {
  36531. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36532. }
  36533. else
  36534. {
  36535. Position startPosition (this, startPos);
  36536. Position endPosition (this, endPos);
  36537. maximumLineLength = -1;
  36538. const int firstAffectedLine = startPosition.getLineNumber();
  36539. const int endLine = endPosition.getLineNumber();
  36540. int lastAffectedLine = firstAffectedLine + 1;
  36541. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36542. if (firstAffectedLine == endLine)
  36543. {
  36544. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36545. + firstLine->line.substring (endPosition.getIndexInLine());
  36546. firstLine->updateLength();
  36547. }
  36548. else
  36549. {
  36550. lastAffectedLine = lines.size();
  36551. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36552. jassert (lastLine != 0);
  36553. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36554. + lastLine->line.substring (endPosition.getIndexInLine());
  36555. firstLine->updateLength();
  36556. int numLinesToRemove = endLine - firstAffectedLine;
  36557. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36558. }
  36559. int i;
  36560. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36561. {
  36562. CodeDocumentLine* const l = lines.getUnchecked (i);
  36563. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36564. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36565. }
  36566. checkLastLineStatus();
  36567. const int totalChars = getNumCharacters();
  36568. for (i = 0; i < positionsToMaintain.size(); ++i)
  36569. {
  36570. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36571. if (p->getPosition() > startPosition.getPosition())
  36572. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36573. if (p->getPosition() > totalChars)
  36574. p->setPosition (totalChars);
  36575. }
  36576. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36577. }
  36578. }
  36579. END_JUCE_NAMESPACE
  36580. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36581. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36582. BEGIN_JUCE_NAMESPACE
  36583. class CodeEditorComponent::CaretComponent : public Component,
  36584. public Timer
  36585. {
  36586. public:
  36587. CaretComponent (CodeEditorComponent& owner_)
  36588. : owner (owner_)
  36589. {
  36590. setAlwaysOnTop (true);
  36591. setInterceptsMouseClicks (false, false);
  36592. }
  36593. void paint (Graphics& g)
  36594. {
  36595. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36596. }
  36597. void timerCallback()
  36598. {
  36599. setVisible (shouldBeShown() && ! isVisible());
  36600. }
  36601. void updatePosition()
  36602. {
  36603. startTimer (400);
  36604. setVisible (shouldBeShown());
  36605. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36606. }
  36607. private:
  36608. CodeEditorComponent& owner;
  36609. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36610. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36611. };
  36612. class CodeEditorComponent::CodeEditorLine
  36613. {
  36614. public:
  36615. CodeEditorLine() throw()
  36616. : highlightColumnStart (0), highlightColumnEnd (0)
  36617. {
  36618. }
  36619. bool update (CodeDocument& document, int lineNum,
  36620. CodeDocument::Iterator& source,
  36621. CodeTokeniser* analyser, const int spacesPerTab,
  36622. const CodeDocument::Position& selectionStart,
  36623. const CodeDocument::Position& selectionEnd)
  36624. {
  36625. Array <SyntaxToken> newTokens;
  36626. newTokens.ensureStorageAllocated (8);
  36627. if (analyser == 0)
  36628. {
  36629. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36630. }
  36631. else if (lineNum < document.getNumLines())
  36632. {
  36633. const CodeDocument::Position pos (&document, lineNum, 0);
  36634. createTokens (pos.getPosition(), pos.getLineText(),
  36635. source, analyser, newTokens);
  36636. }
  36637. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36638. int newHighlightStart = 0;
  36639. int newHighlightEnd = 0;
  36640. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36641. {
  36642. const String line (document.getLine (lineNum));
  36643. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36644. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36645. line, spacesPerTab);
  36646. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36647. line, spacesPerTab);
  36648. }
  36649. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36650. {
  36651. highlightColumnStart = newHighlightStart;
  36652. highlightColumnEnd = newHighlightEnd;
  36653. }
  36654. else
  36655. {
  36656. if (tokens.size() == newTokens.size())
  36657. {
  36658. bool allTheSame = true;
  36659. for (int i = newTokens.size(); --i >= 0;)
  36660. {
  36661. if (tokens.getReference(i) != newTokens.getReference(i))
  36662. {
  36663. allTheSame = false;
  36664. break;
  36665. }
  36666. }
  36667. if (allTheSame)
  36668. return false;
  36669. }
  36670. }
  36671. tokens.swapWithArray (newTokens);
  36672. return true;
  36673. }
  36674. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36675. float x, const int y, const int baselineOffset, const int lineHeight,
  36676. const Colour& highlightColour) const
  36677. {
  36678. if (highlightColumnStart < highlightColumnEnd)
  36679. {
  36680. g.setColour (highlightColour);
  36681. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36682. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36683. }
  36684. int lastType = std::numeric_limits<int>::min();
  36685. for (int i = 0; i < tokens.size(); ++i)
  36686. {
  36687. SyntaxToken& token = tokens.getReference(i);
  36688. if (lastType != token.tokenType)
  36689. {
  36690. lastType = token.tokenType;
  36691. g.setColour (owner.getColourForTokenType (lastType));
  36692. }
  36693. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36694. if (i < tokens.size() - 1)
  36695. {
  36696. if (token.width < 0)
  36697. token.width = font.getStringWidthFloat (token.text);
  36698. x += token.width;
  36699. }
  36700. }
  36701. }
  36702. private:
  36703. struct SyntaxToken
  36704. {
  36705. SyntaxToken (const String& text_, const int type) throw()
  36706. : text (text_), tokenType (type), width (-1.0f)
  36707. {
  36708. }
  36709. bool operator!= (const SyntaxToken& other) const throw()
  36710. {
  36711. return text != other.text || tokenType != other.tokenType;
  36712. }
  36713. String text;
  36714. int tokenType;
  36715. float width;
  36716. };
  36717. Array <SyntaxToken> tokens;
  36718. int highlightColumnStart, highlightColumnEnd;
  36719. static void createTokens (int startPosition, const String& lineText,
  36720. CodeDocument::Iterator& source,
  36721. CodeTokeniser* analyser,
  36722. Array <SyntaxToken>& newTokens)
  36723. {
  36724. CodeDocument::Iterator lastIterator (source);
  36725. const int lineLength = lineText.length();
  36726. for (;;)
  36727. {
  36728. int tokenType = analyser->readNextToken (source);
  36729. int tokenStart = lastIterator.getPosition();
  36730. int tokenEnd = source.getPosition();
  36731. if (tokenEnd <= tokenStart)
  36732. break;
  36733. tokenEnd -= startPosition;
  36734. if (tokenEnd > 0)
  36735. {
  36736. tokenStart -= startPosition;
  36737. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36738. tokenType));
  36739. if (tokenEnd >= lineLength)
  36740. break;
  36741. }
  36742. lastIterator = source;
  36743. }
  36744. source = lastIterator;
  36745. }
  36746. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36747. {
  36748. int x = 0;
  36749. for (int i = 0; i < tokens.size(); ++i)
  36750. {
  36751. SyntaxToken& t = tokens.getReference(i);
  36752. for (;;)
  36753. {
  36754. int tabPos = t.text.indexOfChar ('\t');
  36755. if (tabPos < 0)
  36756. break;
  36757. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36758. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36759. }
  36760. x += t.text.length();
  36761. }
  36762. }
  36763. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36764. {
  36765. jassert (index <= line.length());
  36766. int col = 0;
  36767. for (int i = 0; i < index; ++i)
  36768. {
  36769. if (line[i] != '\t')
  36770. ++col;
  36771. else
  36772. col += spacesPerTab - (col % spacesPerTab);
  36773. }
  36774. return col;
  36775. }
  36776. };
  36777. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36778. CodeTokeniser* const codeTokeniser_)
  36779. : document (document_),
  36780. firstLineOnScreen (0),
  36781. gutter (5),
  36782. spacesPerTab (4),
  36783. lineHeight (0),
  36784. linesOnScreen (0),
  36785. columnsOnScreen (0),
  36786. scrollbarThickness (16),
  36787. columnToTryToMaintain (-1),
  36788. useSpacesForTabs (false),
  36789. xOffset (0),
  36790. verticalScrollBar (true),
  36791. horizontalScrollBar (false),
  36792. codeTokeniser (codeTokeniser_)
  36793. {
  36794. caretPos = CodeDocument::Position (&document_, 0, 0);
  36795. caretPos.setPositionMaintained (true);
  36796. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36797. selectionStart.setPositionMaintained (true);
  36798. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36799. selectionEnd.setPositionMaintained (true);
  36800. setOpaque (true);
  36801. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36802. setWantsKeyboardFocus (true);
  36803. addAndMakeVisible (&verticalScrollBar);
  36804. verticalScrollBar.setSingleStepSize (1.0);
  36805. addAndMakeVisible (&horizontalScrollBar);
  36806. horizontalScrollBar.setSingleStepSize (1.0);
  36807. addAndMakeVisible (caret = new CaretComponent (*this));
  36808. Font f (12.0f);
  36809. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36810. setFont (f);
  36811. resetToDefaultColours();
  36812. verticalScrollBar.addListener (this);
  36813. horizontalScrollBar.addListener (this);
  36814. document.addListener (this);
  36815. }
  36816. CodeEditorComponent::~CodeEditorComponent()
  36817. {
  36818. document.removeListener (this);
  36819. }
  36820. void CodeEditorComponent::loadContent (const String& newContent)
  36821. {
  36822. clearCachedIterators (0);
  36823. document.replaceAllContent (newContent);
  36824. document.clearUndoHistory();
  36825. document.setSavePoint();
  36826. caretPos.setPosition (0);
  36827. selectionStart.setPosition (0);
  36828. selectionEnd.setPosition (0);
  36829. scrollToLine (0);
  36830. }
  36831. bool CodeEditorComponent::isTextInputActive() const
  36832. {
  36833. return true;
  36834. }
  36835. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36836. const CodeDocument::Position& affectedTextEnd)
  36837. {
  36838. clearCachedIterators (affectedTextStart.getLineNumber());
  36839. triggerAsyncUpdate();
  36840. caret->updatePosition();
  36841. columnToTryToMaintain = -1;
  36842. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36843. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36844. deselectAll();
  36845. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36846. || caretPos.getPosition() < affectedTextStart.getPosition())
  36847. moveCaretTo (affectedTextStart, false);
  36848. updateScrollBars();
  36849. }
  36850. void CodeEditorComponent::resized()
  36851. {
  36852. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36853. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36854. lines.clear();
  36855. rebuildLineTokens();
  36856. caret->updatePosition();
  36857. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36858. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36859. updateScrollBars();
  36860. }
  36861. void CodeEditorComponent::paint (Graphics& g)
  36862. {
  36863. handleUpdateNowIfNeeded();
  36864. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36865. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36866. g.setFont (font);
  36867. const int baselineOffset = (int) font.getAscent();
  36868. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36869. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36870. const Rectangle<int> clip (g.getClipBounds());
  36871. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36872. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36873. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36874. {
  36875. lines.getUnchecked(j)->draw (*this, g, font,
  36876. (float) (gutter - xOffset * charWidth),
  36877. lineHeight * j, baselineOffset, lineHeight,
  36878. highlightColour);
  36879. }
  36880. }
  36881. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36882. {
  36883. if (scrollbarThickness != thickness)
  36884. {
  36885. scrollbarThickness = thickness;
  36886. resized();
  36887. }
  36888. }
  36889. void CodeEditorComponent::handleAsyncUpdate()
  36890. {
  36891. rebuildLineTokens();
  36892. }
  36893. void CodeEditorComponent::rebuildLineTokens()
  36894. {
  36895. cancelPendingUpdate();
  36896. const int numNeeded = linesOnScreen + 1;
  36897. int minLineToRepaint = numNeeded;
  36898. int maxLineToRepaint = 0;
  36899. if (numNeeded != lines.size())
  36900. {
  36901. lines.clear();
  36902. for (int i = numNeeded; --i >= 0;)
  36903. lines.add (new CodeEditorLine());
  36904. minLineToRepaint = 0;
  36905. maxLineToRepaint = numNeeded;
  36906. }
  36907. jassert (numNeeded == lines.size());
  36908. CodeDocument::Iterator source (&document);
  36909. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36910. for (int i = 0; i < numNeeded; ++i)
  36911. {
  36912. CodeEditorLine* const line = lines.getUnchecked(i);
  36913. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36914. selectionStart, selectionEnd))
  36915. {
  36916. minLineToRepaint = jmin (minLineToRepaint, i);
  36917. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36918. }
  36919. }
  36920. if (minLineToRepaint <= maxLineToRepaint)
  36921. {
  36922. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36923. verticalScrollBar.getX() - gutter,
  36924. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36925. }
  36926. }
  36927. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36928. {
  36929. caretPos = newPos;
  36930. columnToTryToMaintain = -1;
  36931. if (highlighting)
  36932. {
  36933. if (dragType == notDragging)
  36934. {
  36935. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36936. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36937. dragType = draggingSelectionStart;
  36938. else
  36939. dragType = draggingSelectionEnd;
  36940. }
  36941. if (dragType == draggingSelectionStart)
  36942. {
  36943. selectionStart = caretPos;
  36944. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36945. {
  36946. const CodeDocument::Position temp (selectionStart);
  36947. selectionStart = selectionEnd;
  36948. selectionEnd = temp;
  36949. dragType = draggingSelectionEnd;
  36950. }
  36951. }
  36952. else
  36953. {
  36954. selectionEnd = caretPos;
  36955. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36956. {
  36957. const CodeDocument::Position temp (selectionStart);
  36958. selectionStart = selectionEnd;
  36959. selectionEnd = temp;
  36960. dragType = draggingSelectionStart;
  36961. }
  36962. }
  36963. triggerAsyncUpdate();
  36964. }
  36965. else
  36966. {
  36967. deselectAll();
  36968. }
  36969. caret->updatePosition();
  36970. scrollToKeepCaretOnScreen();
  36971. updateScrollBars();
  36972. }
  36973. void CodeEditorComponent::deselectAll()
  36974. {
  36975. if (selectionStart != selectionEnd)
  36976. triggerAsyncUpdate();
  36977. selectionStart = caretPos;
  36978. selectionEnd = caretPos;
  36979. }
  36980. void CodeEditorComponent::updateScrollBars()
  36981. {
  36982. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36983. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  36984. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36985. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  36986. }
  36987. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36988. {
  36989. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36990. newFirstLineOnScreen);
  36991. if (newFirstLineOnScreen != firstLineOnScreen)
  36992. {
  36993. firstLineOnScreen = newFirstLineOnScreen;
  36994. caret->updatePosition();
  36995. updateCachedIterators (firstLineOnScreen);
  36996. triggerAsyncUpdate();
  36997. }
  36998. }
  36999. void CodeEditorComponent::scrollToColumnInternal (double column)
  37000. {
  37001. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37002. if (xOffset != newOffset)
  37003. {
  37004. xOffset = newOffset;
  37005. caret->updatePosition();
  37006. repaint();
  37007. }
  37008. }
  37009. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37010. {
  37011. scrollToLineInternal (newFirstLineOnScreen);
  37012. updateScrollBars();
  37013. }
  37014. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37015. {
  37016. scrollToColumnInternal (newFirstColumnOnScreen);
  37017. updateScrollBars();
  37018. }
  37019. void CodeEditorComponent::scrollBy (int deltaLines)
  37020. {
  37021. scrollToLine (firstLineOnScreen + deltaLines);
  37022. }
  37023. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37024. {
  37025. if (caretPos.getLineNumber() < firstLineOnScreen)
  37026. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37027. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37028. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37029. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37030. if (column >= xOffset + columnsOnScreen - 1)
  37031. scrollToColumn (column + 1 - columnsOnScreen);
  37032. else if (column < xOffset)
  37033. scrollToColumn (column);
  37034. }
  37035. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37036. {
  37037. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37038. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37039. roundToInt (charWidth),
  37040. lineHeight);
  37041. }
  37042. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37043. {
  37044. const int line = y / lineHeight + firstLineOnScreen;
  37045. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37046. const int index = columnToIndex (line, column);
  37047. return CodeDocument::Position (&document, line, index);
  37048. }
  37049. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37050. {
  37051. document.deleteSection (selectionStart, selectionEnd);
  37052. if (newText.isNotEmpty())
  37053. document.insertText (caretPos, newText);
  37054. scrollToKeepCaretOnScreen();
  37055. }
  37056. void CodeEditorComponent::insertTabAtCaret()
  37057. {
  37058. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37059. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37060. {
  37061. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37062. }
  37063. if (useSpacesForTabs)
  37064. {
  37065. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37066. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37067. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37068. }
  37069. else
  37070. {
  37071. insertTextAtCaret ("\t");
  37072. }
  37073. }
  37074. void CodeEditorComponent::cut()
  37075. {
  37076. insertTextAtCaret (String::empty);
  37077. }
  37078. void CodeEditorComponent::copy()
  37079. {
  37080. newTransaction();
  37081. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37082. if (selection.isNotEmpty())
  37083. SystemClipboard::copyTextToClipboard (selection);
  37084. }
  37085. void CodeEditorComponent::copyThenCut()
  37086. {
  37087. copy();
  37088. cut();
  37089. newTransaction();
  37090. }
  37091. void CodeEditorComponent::paste()
  37092. {
  37093. newTransaction();
  37094. const String clip (SystemClipboard::getTextFromClipboard());
  37095. if (clip.isNotEmpty())
  37096. insertTextAtCaret (clip);
  37097. newTransaction();
  37098. }
  37099. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37100. {
  37101. newTransaction();
  37102. if (moveInWholeWordSteps)
  37103. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37104. else
  37105. moveCaretTo (caretPos.movedBy (-1), selecting);
  37106. }
  37107. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37108. {
  37109. newTransaction();
  37110. if (moveInWholeWordSteps)
  37111. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37112. else
  37113. moveCaretTo (caretPos.movedBy (1), selecting);
  37114. }
  37115. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37116. {
  37117. CodeDocument::Position pos (caretPos);
  37118. const int newLineNum = pos.getLineNumber() + delta;
  37119. if (columnToTryToMaintain < 0)
  37120. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37121. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37122. const int colToMaintain = columnToTryToMaintain;
  37123. moveCaretTo (pos, selecting);
  37124. columnToTryToMaintain = colToMaintain;
  37125. }
  37126. void CodeEditorComponent::cursorDown (const bool selecting)
  37127. {
  37128. newTransaction();
  37129. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37130. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37131. else
  37132. moveLineDelta (1, selecting);
  37133. }
  37134. void CodeEditorComponent::cursorUp (const bool selecting)
  37135. {
  37136. newTransaction();
  37137. if (caretPos.getLineNumber() == 0)
  37138. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37139. else
  37140. moveLineDelta (-1, selecting);
  37141. }
  37142. void CodeEditorComponent::pageDown (const bool selecting)
  37143. {
  37144. newTransaction();
  37145. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37146. moveLineDelta (linesOnScreen, selecting);
  37147. }
  37148. void CodeEditorComponent::pageUp (const bool selecting)
  37149. {
  37150. newTransaction();
  37151. scrollBy (-linesOnScreen);
  37152. moveLineDelta (-linesOnScreen, selecting);
  37153. }
  37154. void CodeEditorComponent::scrollUp()
  37155. {
  37156. newTransaction();
  37157. scrollBy (1);
  37158. if (caretPos.getLineNumber() < firstLineOnScreen)
  37159. moveLineDelta (1, false);
  37160. }
  37161. void CodeEditorComponent::scrollDown()
  37162. {
  37163. newTransaction();
  37164. scrollBy (-1);
  37165. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37166. moveLineDelta (-1, false);
  37167. }
  37168. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37169. {
  37170. newTransaction();
  37171. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37172. }
  37173. namespace CodeEditorHelpers
  37174. {
  37175. int findFirstNonWhitespaceChar (const String& line) throw()
  37176. {
  37177. const int len = line.length();
  37178. for (int i = 0; i < len; ++i)
  37179. if (! CharacterFunctions::isWhitespace (line [i]))
  37180. return i;
  37181. return 0;
  37182. }
  37183. }
  37184. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37185. {
  37186. newTransaction();
  37187. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37188. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37189. index = 0;
  37190. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37191. }
  37192. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37193. {
  37194. newTransaction();
  37195. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37196. }
  37197. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37198. {
  37199. newTransaction();
  37200. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37201. }
  37202. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37203. {
  37204. if (moveInWholeWordSteps)
  37205. {
  37206. cut(); // in case something is already highlighted
  37207. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37208. }
  37209. else
  37210. {
  37211. if (selectionStart == selectionEnd)
  37212. selectionStart.moveBy (-1);
  37213. }
  37214. cut();
  37215. }
  37216. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37217. {
  37218. if (moveInWholeWordSteps)
  37219. {
  37220. cut(); // in case something is already highlighted
  37221. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37222. }
  37223. else
  37224. {
  37225. if (selectionStart == selectionEnd)
  37226. selectionEnd.moveBy (1);
  37227. else
  37228. newTransaction();
  37229. }
  37230. cut();
  37231. }
  37232. void CodeEditorComponent::selectAll()
  37233. {
  37234. newTransaction();
  37235. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37236. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37237. }
  37238. void CodeEditorComponent::undo()
  37239. {
  37240. document.undo();
  37241. scrollToKeepCaretOnScreen();
  37242. }
  37243. void CodeEditorComponent::redo()
  37244. {
  37245. document.redo();
  37246. scrollToKeepCaretOnScreen();
  37247. }
  37248. void CodeEditorComponent::newTransaction()
  37249. {
  37250. document.newTransaction();
  37251. startTimer (600);
  37252. }
  37253. void CodeEditorComponent::timerCallback()
  37254. {
  37255. newTransaction();
  37256. }
  37257. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37258. {
  37259. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37260. }
  37261. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37262. {
  37263. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37264. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37265. }
  37266. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37267. {
  37268. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37269. CodeDocument::Position (&document, range.getEnd()));
  37270. }
  37271. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37272. {
  37273. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37274. const bool shiftDown = key.getModifiers().isShiftDown();
  37275. if (key.isKeyCode (KeyPress::leftKey))
  37276. {
  37277. cursorLeft (moveInWholeWordSteps, shiftDown);
  37278. }
  37279. else if (key.isKeyCode (KeyPress::rightKey))
  37280. {
  37281. cursorRight (moveInWholeWordSteps, shiftDown);
  37282. }
  37283. else if (key.isKeyCode (KeyPress::upKey))
  37284. {
  37285. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37286. scrollDown();
  37287. #if JUCE_MAC
  37288. else if (key.getModifiers().isCommandDown())
  37289. goToStartOfDocument (shiftDown);
  37290. #endif
  37291. else
  37292. cursorUp (shiftDown);
  37293. }
  37294. else if (key.isKeyCode (KeyPress::downKey))
  37295. {
  37296. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37297. scrollUp();
  37298. #if JUCE_MAC
  37299. else if (key.getModifiers().isCommandDown())
  37300. goToEndOfDocument (shiftDown);
  37301. #endif
  37302. else
  37303. cursorDown (shiftDown);
  37304. }
  37305. else if (key.isKeyCode (KeyPress::pageDownKey))
  37306. {
  37307. pageDown (shiftDown);
  37308. }
  37309. else if (key.isKeyCode (KeyPress::pageUpKey))
  37310. {
  37311. pageUp (shiftDown);
  37312. }
  37313. else if (key.isKeyCode (KeyPress::homeKey))
  37314. {
  37315. if (moveInWholeWordSteps)
  37316. goToStartOfDocument (shiftDown);
  37317. else
  37318. goToStartOfLine (shiftDown);
  37319. }
  37320. else if (key.isKeyCode (KeyPress::endKey))
  37321. {
  37322. if (moveInWholeWordSteps)
  37323. goToEndOfDocument (shiftDown);
  37324. else
  37325. goToEndOfLine (shiftDown);
  37326. }
  37327. else if (key.isKeyCode (KeyPress::backspaceKey))
  37328. {
  37329. backspace (moveInWholeWordSteps);
  37330. }
  37331. else if (key.isKeyCode (KeyPress::deleteKey))
  37332. {
  37333. deleteForward (moveInWholeWordSteps);
  37334. }
  37335. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37336. {
  37337. copy();
  37338. }
  37339. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37340. {
  37341. copyThenCut();
  37342. }
  37343. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37344. {
  37345. paste();
  37346. }
  37347. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37348. {
  37349. undo();
  37350. }
  37351. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37352. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37353. {
  37354. redo();
  37355. }
  37356. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37357. {
  37358. selectAll();
  37359. }
  37360. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37361. {
  37362. insertTabAtCaret();
  37363. }
  37364. else if (key == KeyPress::returnKey)
  37365. {
  37366. newTransaction();
  37367. insertTextAtCaret (document.getNewLineCharacters());
  37368. }
  37369. else if (key.isKeyCode (KeyPress::escapeKey))
  37370. {
  37371. newTransaction();
  37372. }
  37373. else if (key.getTextCharacter() >= ' ')
  37374. {
  37375. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37376. }
  37377. else
  37378. {
  37379. return false;
  37380. }
  37381. return true;
  37382. }
  37383. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37384. {
  37385. newTransaction();
  37386. dragType = notDragging;
  37387. if (! e.mods.isPopupMenu())
  37388. {
  37389. beginDragAutoRepeat (100);
  37390. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37391. }
  37392. else
  37393. {
  37394. /*PopupMenu m;
  37395. addPopupMenuItems (m, &e);
  37396. const int result = m.show();
  37397. if (result != 0)
  37398. performPopupMenuAction (result);
  37399. */
  37400. }
  37401. }
  37402. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37403. {
  37404. if (! e.mods.isPopupMenu())
  37405. moveCaretTo (getPositionAt (e.x, e.y), true);
  37406. }
  37407. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37408. {
  37409. newTransaction();
  37410. beginDragAutoRepeat (0);
  37411. dragType = notDragging;
  37412. }
  37413. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37414. {
  37415. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37416. CodeDocument::Position tokenEnd (tokenStart);
  37417. if (e.getNumberOfClicks() > 2)
  37418. {
  37419. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37420. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37421. }
  37422. else
  37423. {
  37424. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37425. tokenEnd.moveBy (1);
  37426. tokenStart = tokenEnd;
  37427. while (tokenStart.getIndexInLine() > 0
  37428. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37429. tokenStart.moveBy (-1);
  37430. }
  37431. moveCaretTo (tokenEnd, false);
  37432. moveCaretTo (tokenStart, true);
  37433. }
  37434. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37435. {
  37436. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37437. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37438. {
  37439. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37440. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37441. }
  37442. else
  37443. {
  37444. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37445. }
  37446. }
  37447. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37448. {
  37449. if (scrollBarThatHasMoved == &verticalScrollBar)
  37450. scrollToLineInternal ((int) newRangeStart);
  37451. else
  37452. scrollToColumnInternal (newRangeStart);
  37453. }
  37454. void CodeEditorComponent::focusGained (FocusChangeType)
  37455. {
  37456. caret->updatePosition();
  37457. }
  37458. void CodeEditorComponent::focusLost (FocusChangeType)
  37459. {
  37460. caret->updatePosition();
  37461. }
  37462. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37463. {
  37464. useSpacesForTabs = insertSpaces;
  37465. if (spacesPerTab != numSpaces)
  37466. {
  37467. spacesPerTab = numSpaces;
  37468. triggerAsyncUpdate();
  37469. }
  37470. }
  37471. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37472. {
  37473. const String line (document.getLine (lineNum));
  37474. jassert (index <= line.length());
  37475. int col = 0;
  37476. for (int i = 0; i < index; ++i)
  37477. {
  37478. if (line[i] != '\t')
  37479. ++col;
  37480. else
  37481. col += getTabSize() - (col % getTabSize());
  37482. }
  37483. return col;
  37484. }
  37485. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37486. {
  37487. const String line (document.getLine (lineNum));
  37488. const int lineLength = line.length();
  37489. int i, col = 0;
  37490. for (i = 0; i < lineLength; ++i)
  37491. {
  37492. if (line[i] != '\t')
  37493. ++col;
  37494. else
  37495. col += getTabSize() - (col % getTabSize());
  37496. if (col > column)
  37497. break;
  37498. }
  37499. return i;
  37500. }
  37501. void CodeEditorComponent::setFont (const Font& newFont)
  37502. {
  37503. font = newFont;
  37504. charWidth = font.getStringWidthFloat ("0");
  37505. lineHeight = roundToInt (font.getHeight());
  37506. resized();
  37507. }
  37508. void CodeEditorComponent::resetToDefaultColours()
  37509. {
  37510. coloursForTokenCategories.clear();
  37511. if (codeTokeniser != 0)
  37512. {
  37513. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37514. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37515. }
  37516. }
  37517. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37518. {
  37519. jassert (tokenType < 256);
  37520. while (coloursForTokenCategories.size() < tokenType)
  37521. coloursForTokenCategories.add (Colours::black);
  37522. coloursForTokenCategories.set (tokenType, colour);
  37523. repaint();
  37524. }
  37525. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37526. {
  37527. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37528. return findColour (CodeEditorComponent::defaultTextColourId);
  37529. return coloursForTokenCategories.getReference (tokenType);
  37530. }
  37531. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37532. {
  37533. int i;
  37534. for (i = cachedIterators.size(); --i >= 0;)
  37535. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37536. break;
  37537. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37538. }
  37539. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37540. {
  37541. const int maxNumCachedPositions = 5000;
  37542. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37543. if (cachedIterators.size() == 0)
  37544. cachedIterators.add (new CodeDocument::Iterator (&document));
  37545. if (codeTokeniser == 0)
  37546. return;
  37547. for (;;)
  37548. {
  37549. CodeDocument::Iterator* last = cachedIterators.getLast();
  37550. if (last->getLine() >= maxLineNum)
  37551. break;
  37552. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37553. cachedIterators.add (t);
  37554. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37555. for (;;)
  37556. {
  37557. codeTokeniser->readNextToken (*t);
  37558. if (t->getLine() >= targetLine)
  37559. break;
  37560. if (t->isEOF())
  37561. return;
  37562. }
  37563. }
  37564. }
  37565. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37566. {
  37567. if (codeTokeniser == 0)
  37568. return;
  37569. for (int i = cachedIterators.size(); --i >= 0;)
  37570. {
  37571. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37572. if (t->getPosition() <= position)
  37573. {
  37574. source = *t;
  37575. break;
  37576. }
  37577. }
  37578. while (source.getPosition() < position)
  37579. {
  37580. const CodeDocument::Iterator original (source);
  37581. codeTokeniser->readNextToken (source);
  37582. if (source.getPosition() > position || source.isEOF())
  37583. {
  37584. source = original;
  37585. break;
  37586. }
  37587. }
  37588. }
  37589. END_JUCE_NAMESPACE
  37590. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37591. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37592. BEGIN_JUCE_NAMESPACE
  37593. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37594. {
  37595. }
  37596. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37597. {
  37598. }
  37599. namespace CppTokeniser
  37600. {
  37601. bool isIdentifierStart (const juce_wchar c) throw()
  37602. {
  37603. return CharacterFunctions::isLetter (c)
  37604. || c == '_' || c == '@';
  37605. }
  37606. bool isIdentifierBody (const juce_wchar c) throw()
  37607. {
  37608. return CharacterFunctions::isLetterOrDigit (c)
  37609. || c == '_' || c == '@';
  37610. }
  37611. bool isReservedKeyword (String::CharPointerType token, const int tokenLength) throw()
  37612. {
  37613. static const char* const keywords2Char[] =
  37614. { "if", "do", "or", "id", 0 };
  37615. static const char* const keywords3Char[] =
  37616. { "for", "int", "new", "try", "xor", "and", "asm", "not", 0 };
  37617. static const char* const keywords4Char[] =
  37618. { "bool", "void", "this", "true", "long", "else", "char",
  37619. "enum", "case", "goto", "auto", 0 };
  37620. static const char* const keywords5Char[] =
  37621. { "while", "bitor", "break", "catch", "class", "compl", "const", "false",
  37622. "float", "short", "throw", "union", "using", "or_eq", 0 };
  37623. static const char* const keywords6Char[] =
  37624. { "return", "struct", "and_eq", "bitand", "delete", "double", "extern",
  37625. "friend", "inline", "not_eq", "public", "sizeof", "static", "signed",
  37626. "switch", "typeid", "wchar_t", "xor_eq", 0};
  37627. static const char* const keywordsOther[] =
  37628. { "const_cast", "continue", "default", "explicit", "mutable", "namespace",
  37629. "operator", "private", "protected", "register", "reinterpret_cast", "static_cast",
  37630. "template", "typedef", "typename", "unsigned", "virtual", "volatile",
  37631. "@implementation", "@interface", "@end", "@synthesize", "@dynamic", "@public",
  37632. "@private", "@property", "@protected", "@class", 0 };
  37633. const char* const* k;
  37634. switch (tokenLength)
  37635. {
  37636. case 2: k = keywords2Char; break;
  37637. case 3: k = keywords3Char; break;
  37638. case 4: k = keywords4Char; break;
  37639. case 5: k = keywords5Char; break;
  37640. case 6: k = keywords6Char; break;
  37641. default:
  37642. if (tokenLength < 2 || tokenLength > 16)
  37643. return false;
  37644. k = keywordsOther;
  37645. break;
  37646. }
  37647. int i = 0;
  37648. while (k[i] != 0)
  37649. {
  37650. if (token.compare (CharPointer_ASCII (k[i])) == 0)
  37651. return true;
  37652. ++i;
  37653. }
  37654. return false;
  37655. }
  37656. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37657. {
  37658. int tokenLength = 0;
  37659. juce_wchar possibleIdentifier [19];
  37660. while (isIdentifierBody (source.peekNextChar()))
  37661. {
  37662. const juce_wchar c = source.nextChar();
  37663. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37664. possibleIdentifier [tokenLength] = c;
  37665. ++tokenLength;
  37666. }
  37667. if (tokenLength > 1 && tokenLength <= 16)
  37668. {
  37669. possibleIdentifier [tokenLength] = 0;
  37670. if (isReservedKeyword (CharPointer_UTF32 (possibleIdentifier), tokenLength))
  37671. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37672. }
  37673. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37674. }
  37675. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37676. {
  37677. const juce_wchar c = source.peekNextChar();
  37678. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37679. source.skip();
  37680. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37681. return false;
  37682. return true;
  37683. }
  37684. bool isHexDigit (const juce_wchar c) throw()
  37685. {
  37686. return (c >= '0' && c <= '9')
  37687. || (c >= 'a' && c <= 'f')
  37688. || (c >= 'A' && c <= 'F');
  37689. }
  37690. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37691. {
  37692. if (source.nextChar() != '0')
  37693. return false;
  37694. juce_wchar c = source.nextChar();
  37695. if (c != 'x' && c != 'X')
  37696. return false;
  37697. int numDigits = 0;
  37698. while (isHexDigit (source.peekNextChar()))
  37699. {
  37700. ++numDigits;
  37701. source.skip();
  37702. }
  37703. if (numDigits == 0)
  37704. return false;
  37705. return skipNumberSuffix (source);
  37706. }
  37707. bool isOctalDigit (const juce_wchar c) throw()
  37708. {
  37709. return c >= '0' && c <= '7';
  37710. }
  37711. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37712. {
  37713. if (source.nextChar() != '0')
  37714. return false;
  37715. if (! isOctalDigit (source.nextChar()))
  37716. return false;
  37717. while (isOctalDigit (source.peekNextChar()))
  37718. source.skip();
  37719. return skipNumberSuffix (source);
  37720. }
  37721. bool isDecimalDigit (const juce_wchar c) throw()
  37722. {
  37723. return c >= '0' && c <= '9';
  37724. }
  37725. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37726. {
  37727. int numChars = 0;
  37728. while (isDecimalDigit (source.peekNextChar()))
  37729. {
  37730. ++numChars;
  37731. source.skip();
  37732. }
  37733. if (numChars == 0)
  37734. return false;
  37735. return skipNumberSuffix (source);
  37736. }
  37737. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37738. {
  37739. int numDigits = 0;
  37740. while (isDecimalDigit (source.peekNextChar()))
  37741. {
  37742. source.skip();
  37743. ++numDigits;
  37744. }
  37745. const bool hasPoint = (source.peekNextChar() == '.');
  37746. if (hasPoint)
  37747. {
  37748. source.skip();
  37749. while (isDecimalDigit (source.peekNextChar()))
  37750. {
  37751. source.skip();
  37752. ++numDigits;
  37753. }
  37754. }
  37755. if (numDigits == 0)
  37756. return false;
  37757. juce_wchar c = source.peekNextChar();
  37758. const bool hasExponent = (c == 'e' || c == 'E');
  37759. if (hasExponent)
  37760. {
  37761. source.skip();
  37762. c = source.peekNextChar();
  37763. if (c == '+' || c == '-')
  37764. source.skip();
  37765. int numExpDigits = 0;
  37766. while (isDecimalDigit (source.peekNextChar()))
  37767. {
  37768. source.skip();
  37769. ++numExpDigits;
  37770. }
  37771. if (numExpDigits == 0)
  37772. return false;
  37773. }
  37774. c = source.peekNextChar();
  37775. if (c == 'f' || c == 'F')
  37776. source.skip();
  37777. else if (! (hasExponent || hasPoint))
  37778. return false;
  37779. return true;
  37780. }
  37781. int parseNumber (CodeDocument::Iterator& source)
  37782. {
  37783. const CodeDocument::Iterator original (source);
  37784. if (parseFloatLiteral (source))
  37785. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37786. source = original;
  37787. if (parseHexLiteral (source))
  37788. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37789. source = original;
  37790. if (parseOctalLiteral (source))
  37791. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37792. source = original;
  37793. if (parseDecimalLiteral (source))
  37794. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37795. source = original;
  37796. source.skip();
  37797. return CPlusPlusCodeTokeniser::tokenType_error;
  37798. }
  37799. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37800. {
  37801. const juce_wchar quote = source.nextChar();
  37802. for (;;)
  37803. {
  37804. const juce_wchar c = source.nextChar();
  37805. if (c == quote || c == 0)
  37806. break;
  37807. if (c == '\\')
  37808. source.skip();
  37809. }
  37810. }
  37811. void skipComment (CodeDocument::Iterator& source) throw()
  37812. {
  37813. bool lastWasStar = false;
  37814. for (;;)
  37815. {
  37816. const juce_wchar c = source.nextChar();
  37817. if (c == 0 || (c == '/' && lastWasStar))
  37818. break;
  37819. lastWasStar = (c == '*');
  37820. }
  37821. }
  37822. }
  37823. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37824. {
  37825. int result = tokenType_error;
  37826. source.skipWhitespace();
  37827. juce_wchar firstChar = source.peekNextChar();
  37828. switch (firstChar)
  37829. {
  37830. case 0:
  37831. source.skip();
  37832. break;
  37833. case '0':
  37834. case '1':
  37835. case '2':
  37836. case '3':
  37837. case '4':
  37838. case '5':
  37839. case '6':
  37840. case '7':
  37841. case '8':
  37842. case '9':
  37843. result = CppTokeniser::parseNumber (source);
  37844. break;
  37845. case '.':
  37846. result = CppTokeniser::parseNumber (source);
  37847. if (result == tokenType_error)
  37848. result = tokenType_punctuation;
  37849. break;
  37850. case ',':
  37851. case ';':
  37852. case ':':
  37853. source.skip();
  37854. result = tokenType_punctuation;
  37855. break;
  37856. case '(':
  37857. case ')':
  37858. case '{':
  37859. case '}':
  37860. case '[':
  37861. case ']':
  37862. source.skip();
  37863. result = tokenType_bracket;
  37864. break;
  37865. case '"':
  37866. case '\'':
  37867. CppTokeniser::skipQuotedString (source);
  37868. result = tokenType_stringLiteral;
  37869. break;
  37870. case '+':
  37871. result = tokenType_operator;
  37872. source.skip();
  37873. if (source.peekNextChar() == '+')
  37874. source.skip();
  37875. else if (source.peekNextChar() == '=')
  37876. source.skip();
  37877. break;
  37878. case '-':
  37879. source.skip();
  37880. result = CppTokeniser::parseNumber (source);
  37881. if (result == tokenType_error)
  37882. {
  37883. result = tokenType_operator;
  37884. if (source.peekNextChar() == '-')
  37885. source.skip();
  37886. else if (source.peekNextChar() == '=')
  37887. source.skip();
  37888. }
  37889. break;
  37890. case '*':
  37891. case '%':
  37892. case '=':
  37893. case '!':
  37894. result = tokenType_operator;
  37895. source.skip();
  37896. if (source.peekNextChar() == '=')
  37897. source.skip();
  37898. break;
  37899. case '/':
  37900. result = tokenType_operator;
  37901. source.skip();
  37902. if (source.peekNextChar() == '=')
  37903. {
  37904. source.skip();
  37905. }
  37906. else if (source.peekNextChar() == '/')
  37907. {
  37908. result = tokenType_comment;
  37909. source.skipToEndOfLine();
  37910. }
  37911. else if (source.peekNextChar() == '*')
  37912. {
  37913. source.skip();
  37914. result = tokenType_comment;
  37915. CppTokeniser::skipComment (source);
  37916. }
  37917. break;
  37918. case '?':
  37919. case '~':
  37920. source.skip();
  37921. result = tokenType_operator;
  37922. break;
  37923. case '<':
  37924. source.skip();
  37925. result = tokenType_operator;
  37926. if (source.peekNextChar() == '=')
  37927. {
  37928. source.skip();
  37929. }
  37930. else if (source.peekNextChar() == '<')
  37931. {
  37932. source.skip();
  37933. if (source.peekNextChar() == '=')
  37934. source.skip();
  37935. }
  37936. break;
  37937. case '>':
  37938. source.skip();
  37939. result = tokenType_operator;
  37940. if (source.peekNextChar() == '=')
  37941. {
  37942. source.skip();
  37943. }
  37944. else if (source.peekNextChar() == '<')
  37945. {
  37946. source.skip();
  37947. if (source.peekNextChar() == '=')
  37948. source.skip();
  37949. }
  37950. break;
  37951. case '|':
  37952. source.skip();
  37953. result = tokenType_operator;
  37954. if (source.peekNextChar() == '=')
  37955. {
  37956. source.skip();
  37957. }
  37958. else if (source.peekNextChar() == '|')
  37959. {
  37960. source.skip();
  37961. if (source.peekNextChar() == '=')
  37962. source.skip();
  37963. }
  37964. break;
  37965. case '&':
  37966. source.skip();
  37967. result = tokenType_operator;
  37968. if (source.peekNextChar() == '=')
  37969. {
  37970. source.skip();
  37971. }
  37972. else if (source.peekNextChar() == '&')
  37973. {
  37974. source.skip();
  37975. if (source.peekNextChar() == '=')
  37976. source.skip();
  37977. }
  37978. break;
  37979. case '^':
  37980. source.skip();
  37981. result = tokenType_operator;
  37982. if (source.peekNextChar() == '=')
  37983. {
  37984. source.skip();
  37985. }
  37986. else if (source.peekNextChar() == '^')
  37987. {
  37988. source.skip();
  37989. if (source.peekNextChar() == '=')
  37990. source.skip();
  37991. }
  37992. break;
  37993. case '#':
  37994. result = tokenType_preprocessor;
  37995. source.skipToEndOfLine();
  37996. break;
  37997. default:
  37998. if (CppTokeniser::isIdentifierStart (firstChar))
  37999. result = CppTokeniser::parseIdentifier (source);
  38000. else
  38001. source.skip();
  38002. break;
  38003. }
  38004. return result;
  38005. }
  38006. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38007. {
  38008. const char* const types[] =
  38009. {
  38010. "Error",
  38011. "Comment",
  38012. "C++ keyword",
  38013. "Identifier",
  38014. "Integer literal",
  38015. "Float literal",
  38016. "String literal",
  38017. "Operator",
  38018. "Bracket",
  38019. "Punctuation",
  38020. "Preprocessor line",
  38021. 0
  38022. };
  38023. return StringArray (types);
  38024. }
  38025. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38026. {
  38027. const uint32 colours[] =
  38028. {
  38029. 0xffcc0000, // error
  38030. 0xff00aa00, // comment
  38031. 0xff0000cc, // keyword
  38032. 0xff000000, // identifier
  38033. 0xff880000, // int literal
  38034. 0xff885500, // float literal
  38035. 0xff990099, // string literal
  38036. 0xff225500, // operator
  38037. 0xff000055, // bracket
  38038. 0xff004400, // punctuation
  38039. 0xff660000 // preprocessor
  38040. };
  38041. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38042. return Colour (colours [tokenType]);
  38043. return Colours::black;
  38044. }
  38045. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38046. {
  38047. return CppTokeniser::isReservedKeyword (token.getCharPointer(), token.length());
  38048. }
  38049. END_JUCE_NAMESPACE
  38050. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38051. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38052. BEGIN_JUCE_NAMESPACE
  38053. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  38054. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  38055. {
  38056. }
  38057. bool ComboBox::ItemInfo::isSeparator() const throw()
  38058. {
  38059. return name.isEmpty();
  38060. }
  38061. bool ComboBox::ItemInfo::isRealItem() const throw()
  38062. {
  38063. return ! (isHeading || name.isEmpty());
  38064. }
  38065. ComboBox::ComboBox (const String& name)
  38066. : Component (name),
  38067. lastCurrentId (0),
  38068. isButtonDown (false),
  38069. separatorPending (false),
  38070. menuActive (false),
  38071. noChoicesMessage (TRANS("(no choices)"))
  38072. {
  38073. setRepaintsOnMouseActivity (true);
  38074. lookAndFeelChanged();
  38075. currentId.addListener (this);
  38076. }
  38077. ComboBox::~ComboBox()
  38078. {
  38079. currentId.removeListener (this);
  38080. if (menuActive)
  38081. PopupMenu::dismissAllActiveMenus();
  38082. label = 0;
  38083. }
  38084. void ComboBox::setEditableText (const bool isEditable)
  38085. {
  38086. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38087. {
  38088. label->setEditable (isEditable, isEditable, false);
  38089. setWantsKeyboardFocus (! isEditable);
  38090. resized();
  38091. }
  38092. }
  38093. bool ComboBox::isTextEditable() const throw()
  38094. {
  38095. return label->isEditable();
  38096. }
  38097. void ComboBox::setJustificationType (const Justification& justification)
  38098. {
  38099. label->setJustificationType (justification);
  38100. }
  38101. const Justification ComboBox::getJustificationType() const throw()
  38102. {
  38103. return label->getJustificationType();
  38104. }
  38105. void ComboBox::setTooltip (const String& newTooltip)
  38106. {
  38107. SettableTooltipClient::setTooltip (newTooltip);
  38108. label->setTooltip (newTooltip);
  38109. }
  38110. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38111. {
  38112. // you can't add empty strings to the list..
  38113. jassert (newItemText.isNotEmpty());
  38114. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38115. jassert (newItemId != 0);
  38116. // you shouldn't use duplicate item IDs!
  38117. jassert (getItemForId (newItemId) == 0);
  38118. if (newItemText.isNotEmpty() && newItemId != 0)
  38119. {
  38120. if (separatorPending)
  38121. {
  38122. separatorPending = false;
  38123. items.add (new ItemInfo (String::empty, 0, false, false));
  38124. }
  38125. items.add (new ItemInfo (newItemText, newItemId, true, false));
  38126. }
  38127. }
  38128. void ComboBox::addSeparator()
  38129. {
  38130. separatorPending = (items.size() > 0);
  38131. }
  38132. void ComboBox::addSectionHeading (const String& headingName)
  38133. {
  38134. // you can't add empty strings to the list..
  38135. jassert (headingName.isNotEmpty());
  38136. if (headingName.isNotEmpty())
  38137. {
  38138. if (separatorPending)
  38139. {
  38140. separatorPending = false;
  38141. items.add (new ItemInfo (String::empty, 0, false, false));
  38142. }
  38143. items.add (new ItemInfo (headingName, 0, true, true));
  38144. }
  38145. }
  38146. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38147. {
  38148. ItemInfo* const item = getItemForId (itemId);
  38149. if (item != 0)
  38150. item->isEnabled = shouldBeEnabled;
  38151. }
  38152. bool ComboBox::isItemEnabled (int itemId) const throw()
  38153. {
  38154. const ItemInfo* const item = getItemForId (itemId);
  38155. return item != 0 && item->isEnabled;
  38156. }
  38157. void ComboBox::changeItemText (const int itemId, const String& newText)
  38158. {
  38159. ItemInfo* const item = getItemForId (itemId);
  38160. jassert (item != 0);
  38161. if (item != 0)
  38162. item->name = newText;
  38163. }
  38164. void ComboBox::clear (const bool dontSendChangeMessage)
  38165. {
  38166. items.clear();
  38167. separatorPending = false;
  38168. if (! label->isEditable())
  38169. setSelectedItemIndex (-1, dontSendChangeMessage);
  38170. }
  38171. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38172. {
  38173. if (itemId != 0)
  38174. {
  38175. for (int i = items.size(); --i >= 0;)
  38176. if (items.getUnchecked(i)->itemId == itemId)
  38177. return items.getUnchecked(i);
  38178. }
  38179. return 0;
  38180. }
  38181. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38182. {
  38183. for (int n = 0, i = 0; i < items.size(); ++i)
  38184. {
  38185. ItemInfo* const item = items.getUnchecked(i);
  38186. if (item->isRealItem())
  38187. if (n++ == index)
  38188. return item;
  38189. }
  38190. return 0;
  38191. }
  38192. int ComboBox::getNumItems() const throw()
  38193. {
  38194. int n = 0;
  38195. for (int i = items.size(); --i >= 0;)
  38196. if (items.getUnchecked(i)->isRealItem())
  38197. ++n;
  38198. return n;
  38199. }
  38200. const String ComboBox::getItemText (const int index) const
  38201. {
  38202. const ItemInfo* const item = getItemForIndex (index);
  38203. return item != 0 ? item->name : String::empty;
  38204. }
  38205. int ComboBox::getItemId (const int index) const throw()
  38206. {
  38207. const ItemInfo* const item = getItemForIndex (index);
  38208. return item != 0 ? item->itemId : 0;
  38209. }
  38210. int ComboBox::indexOfItemId (const int itemId) const throw()
  38211. {
  38212. for (int n = 0, i = 0; i < items.size(); ++i)
  38213. {
  38214. const ItemInfo* const item = items.getUnchecked(i);
  38215. if (item->isRealItem())
  38216. {
  38217. if (item->itemId == itemId)
  38218. return n;
  38219. ++n;
  38220. }
  38221. }
  38222. return -1;
  38223. }
  38224. int ComboBox::getSelectedItemIndex() const
  38225. {
  38226. int index = indexOfItemId (currentId.getValue());
  38227. if (getText() != getItemText (index))
  38228. index = -1;
  38229. return index;
  38230. }
  38231. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38232. {
  38233. setSelectedId (getItemId (index), dontSendChangeMessage);
  38234. }
  38235. int ComboBox::getSelectedId() const throw()
  38236. {
  38237. const ItemInfo* const item = getItemForId (currentId.getValue());
  38238. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38239. }
  38240. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38241. {
  38242. const ItemInfo* const item = getItemForId (newItemId);
  38243. const String newItemText (item != 0 ? item->name : String::empty);
  38244. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38245. {
  38246. if (! dontSendChangeMessage)
  38247. triggerAsyncUpdate();
  38248. label->setText (newItemText, false);
  38249. lastCurrentId = newItemId;
  38250. currentId = newItemId;
  38251. repaint(); // for the benefit of the 'none selected' text
  38252. }
  38253. }
  38254. bool ComboBox::selectIfEnabled (const int index)
  38255. {
  38256. const ItemInfo* const item = getItemForIndex (index);
  38257. if (item != 0 && item->isEnabled)
  38258. {
  38259. setSelectedItemIndex (index);
  38260. return true;
  38261. }
  38262. return false;
  38263. }
  38264. void ComboBox::valueChanged (Value&)
  38265. {
  38266. if (lastCurrentId != (int) currentId.getValue())
  38267. setSelectedId (currentId.getValue(), false);
  38268. }
  38269. const String ComboBox::getText() const
  38270. {
  38271. return label->getText();
  38272. }
  38273. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38274. {
  38275. for (int i = items.size(); --i >= 0;)
  38276. {
  38277. const ItemInfo* const item = items.getUnchecked(i);
  38278. if (item->isRealItem()
  38279. && item->name == newText)
  38280. {
  38281. setSelectedId (item->itemId, dontSendChangeMessage);
  38282. return;
  38283. }
  38284. }
  38285. lastCurrentId = 0;
  38286. currentId = 0;
  38287. if (label->getText() != newText)
  38288. {
  38289. label->setText (newText, false);
  38290. if (! dontSendChangeMessage)
  38291. triggerAsyncUpdate();
  38292. }
  38293. repaint();
  38294. }
  38295. void ComboBox::showEditor()
  38296. {
  38297. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38298. label->showEditor();
  38299. }
  38300. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38301. {
  38302. if (textWhenNothingSelected != newMessage)
  38303. {
  38304. textWhenNothingSelected = newMessage;
  38305. repaint();
  38306. }
  38307. }
  38308. const String ComboBox::getTextWhenNothingSelected() const
  38309. {
  38310. return textWhenNothingSelected;
  38311. }
  38312. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38313. {
  38314. noChoicesMessage = newMessage;
  38315. }
  38316. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38317. {
  38318. return noChoicesMessage;
  38319. }
  38320. void ComboBox::paint (Graphics& g)
  38321. {
  38322. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38323. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38324. *this);
  38325. if (textWhenNothingSelected.isNotEmpty()
  38326. && label->getText().isEmpty()
  38327. && ! label->isBeingEdited())
  38328. {
  38329. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38330. g.setFont (label->getFont());
  38331. g.drawFittedText (textWhenNothingSelected,
  38332. label->getX() + 2, label->getY() + 1,
  38333. label->getWidth() - 4, label->getHeight() - 2,
  38334. label->getJustificationType(),
  38335. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38336. }
  38337. }
  38338. void ComboBox::resized()
  38339. {
  38340. if (getHeight() > 0 && getWidth() > 0)
  38341. getLookAndFeel().positionComboBoxText (*this, *label);
  38342. }
  38343. void ComboBox::enablementChanged()
  38344. {
  38345. repaint();
  38346. }
  38347. void ComboBox::lookAndFeelChanged()
  38348. {
  38349. repaint();
  38350. {
  38351. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38352. jassert (newLabel != 0);
  38353. if (label != 0)
  38354. {
  38355. newLabel->setEditable (label->isEditable());
  38356. newLabel->setJustificationType (label->getJustificationType());
  38357. newLabel->setTooltip (label->getTooltip());
  38358. newLabel->setText (label->getText(), false);
  38359. }
  38360. label = newLabel;
  38361. }
  38362. addAndMakeVisible (label);
  38363. label->addListener (this);
  38364. label->addMouseListener (this, false);
  38365. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38366. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38367. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38368. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38369. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38370. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38371. resized();
  38372. }
  38373. void ComboBox::colourChanged()
  38374. {
  38375. lookAndFeelChanged();
  38376. }
  38377. bool ComboBox::keyPressed (const KeyPress& key)
  38378. {
  38379. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38380. {
  38381. int index = getSelectedItemIndex() - 1;
  38382. while (index >= 0 && ! selectIfEnabled (index))
  38383. --index;
  38384. return true;
  38385. }
  38386. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38387. {
  38388. int index = getSelectedItemIndex() + 1;
  38389. while (index < getNumItems() && ! selectIfEnabled (index))
  38390. ++index;
  38391. return true;
  38392. }
  38393. else if (key.isKeyCode (KeyPress::returnKey))
  38394. {
  38395. showPopup();
  38396. return true;
  38397. }
  38398. return false;
  38399. }
  38400. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38401. {
  38402. // only forward key events that aren't used by this component
  38403. return isKeyDown
  38404. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38405. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38406. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38407. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38408. }
  38409. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38410. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38411. void ComboBox::labelTextChanged (Label*)
  38412. {
  38413. triggerAsyncUpdate();
  38414. }
  38415. void ComboBox::popupMenuFinishedCallback (int result, ComboBox* box)
  38416. {
  38417. if (box != 0)
  38418. {
  38419. box->menuActive = false;
  38420. if (result != 0)
  38421. box->setSelectedId (result);
  38422. }
  38423. }
  38424. void ComboBox::showPopup()
  38425. {
  38426. if (! menuActive)
  38427. {
  38428. const int selectedId = getSelectedId();
  38429. PopupMenu menu;
  38430. menu.setLookAndFeel (&getLookAndFeel());
  38431. for (int i = 0; i < items.size(); ++i)
  38432. {
  38433. const ItemInfo* const item = items.getUnchecked(i);
  38434. if (item->isSeparator())
  38435. menu.addSeparator();
  38436. else if (item->isHeading)
  38437. menu.addSectionHeader (item->name);
  38438. else
  38439. menu.addItem (item->itemId, item->name,
  38440. item->isEnabled, item->itemId == selectedId);
  38441. }
  38442. if (items.size() == 0)
  38443. menu.addItem (1, noChoicesMessage, false);
  38444. menuActive = true;
  38445. menu.showMenuAsync (PopupMenu::Options().withTargetComponent (this)
  38446. .withItemThatMustBeVisible (selectedId)
  38447. .withMinimumWidth (getWidth())
  38448. .withMaximumNumColumns (1)
  38449. .withStandardItemHeight (jlimit (12, 24, getHeight())),
  38450. ModalCallbackFunction::forComponent (popupMenuFinishedCallback, this));
  38451. }
  38452. }
  38453. void ComboBox::mouseDown (const MouseEvent& e)
  38454. {
  38455. beginDragAutoRepeat (300);
  38456. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38457. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38458. showPopup();
  38459. }
  38460. void ComboBox::mouseDrag (const MouseEvent& e)
  38461. {
  38462. beginDragAutoRepeat (50);
  38463. if (isButtonDown && ! e.mouseWasClicked())
  38464. showPopup();
  38465. }
  38466. void ComboBox::mouseUp (const MouseEvent& e2)
  38467. {
  38468. if (isButtonDown)
  38469. {
  38470. isButtonDown = false;
  38471. repaint();
  38472. const MouseEvent e (e2.getEventRelativeTo (this));
  38473. if (reallyContains (e.getPosition(), true)
  38474. && (e2.eventComponent == this || ! label->isEditable()))
  38475. {
  38476. showPopup();
  38477. }
  38478. }
  38479. }
  38480. void ComboBox::addListener (ComboBoxListener* const listener)
  38481. {
  38482. listeners.add (listener);
  38483. }
  38484. void ComboBox::removeListener (ComboBoxListener* const listener)
  38485. {
  38486. listeners.remove (listener);
  38487. }
  38488. void ComboBox::handleAsyncUpdate()
  38489. {
  38490. Component::BailOutChecker checker (this);
  38491. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38492. }
  38493. END_JUCE_NAMESPACE
  38494. /*** End of inlined file: juce_ComboBox.cpp ***/
  38495. /*** Start of inlined file: juce_Label.cpp ***/
  38496. BEGIN_JUCE_NAMESPACE
  38497. Label::Label (const String& componentName,
  38498. const String& labelText)
  38499. : Component (componentName),
  38500. textValue (labelText),
  38501. lastTextValue (labelText),
  38502. font (15.0f),
  38503. justification (Justification::centredLeft),
  38504. ownerComponent (0),
  38505. horizontalBorderSize (5),
  38506. verticalBorderSize (1),
  38507. minimumHorizontalScale (0.7f),
  38508. editSingleClick (false),
  38509. editDoubleClick (false),
  38510. lossOfFocusDiscardsChanges (false)
  38511. {
  38512. setColour (TextEditor::textColourId, Colours::black);
  38513. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38514. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38515. textValue.addListener (this);
  38516. }
  38517. Label::~Label()
  38518. {
  38519. textValue.removeListener (this);
  38520. if (ownerComponent != 0)
  38521. ownerComponent->removeComponentListener (this);
  38522. editor = 0;
  38523. }
  38524. void Label::setText (const String& newText,
  38525. const bool broadcastChangeMessage)
  38526. {
  38527. hideEditor (true);
  38528. if (lastTextValue != newText)
  38529. {
  38530. lastTextValue = newText;
  38531. textValue = newText;
  38532. repaint();
  38533. textWasChanged();
  38534. if (ownerComponent != 0)
  38535. componentMovedOrResized (*ownerComponent, true, true);
  38536. if (broadcastChangeMessage)
  38537. callChangeListeners();
  38538. }
  38539. }
  38540. const String Label::getText (const bool returnActiveEditorContents) const
  38541. {
  38542. return (returnActiveEditorContents && isBeingEdited())
  38543. ? editor->getText()
  38544. : textValue.toString();
  38545. }
  38546. void Label::valueChanged (Value&)
  38547. {
  38548. if (lastTextValue != textValue.toString())
  38549. setText (textValue.toString(), true);
  38550. }
  38551. void Label::setFont (const Font& newFont)
  38552. {
  38553. if (font != newFont)
  38554. {
  38555. font = newFont;
  38556. repaint();
  38557. }
  38558. }
  38559. const Font& Label::getFont() const throw()
  38560. {
  38561. return font;
  38562. }
  38563. void Label::setEditable (const bool editOnSingleClick,
  38564. const bool editOnDoubleClick,
  38565. const bool lossOfFocusDiscardsChanges_)
  38566. {
  38567. editSingleClick = editOnSingleClick;
  38568. editDoubleClick = editOnDoubleClick;
  38569. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38570. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38571. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38572. }
  38573. void Label::setJustificationType (const Justification& newJustification)
  38574. {
  38575. if (justification != newJustification)
  38576. {
  38577. justification = newJustification;
  38578. repaint();
  38579. }
  38580. }
  38581. void Label::setBorderSize (int h, int v)
  38582. {
  38583. if (horizontalBorderSize != h || verticalBorderSize != v)
  38584. {
  38585. horizontalBorderSize = h;
  38586. verticalBorderSize = v;
  38587. repaint();
  38588. }
  38589. }
  38590. Component* Label::getAttachedComponent() const
  38591. {
  38592. return static_cast<Component*> (ownerComponent);
  38593. }
  38594. void Label::attachToComponent (Component* owner,
  38595. const bool onLeft)
  38596. {
  38597. if (ownerComponent != 0)
  38598. ownerComponent->removeComponentListener (this);
  38599. ownerComponent = owner;
  38600. leftOfOwnerComp = onLeft;
  38601. if (ownerComponent != 0)
  38602. {
  38603. setVisible (owner->isVisible());
  38604. ownerComponent->addComponentListener (this);
  38605. componentParentHierarchyChanged (*ownerComponent);
  38606. componentMovedOrResized (*ownerComponent, true, true);
  38607. }
  38608. }
  38609. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38610. {
  38611. if (leftOfOwnerComp)
  38612. {
  38613. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38614. component.getHeight());
  38615. setTopRightPosition (component.getX(), component.getY());
  38616. }
  38617. else
  38618. {
  38619. setSize (component.getWidth(),
  38620. 8 + roundToInt (getFont().getHeight()));
  38621. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38622. }
  38623. }
  38624. void Label::componentParentHierarchyChanged (Component& component)
  38625. {
  38626. if (component.getParentComponent() != 0)
  38627. component.getParentComponent()->addChildComponent (this);
  38628. }
  38629. void Label::componentVisibilityChanged (Component& component)
  38630. {
  38631. setVisible (component.isVisible());
  38632. }
  38633. void Label::textWasEdited()
  38634. {
  38635. }
  38636. void Label::textWasChanged()
  38637. {
  38638. }
  38639. void Label::showEditor()
  38640. {
  38641. if (editor == 0)
  38642. {
  38643. addAndMakeVisible (editor = createEditorComponent());
  38644. editor->setText (getText(), false);
  38645. editor->addListener (this);
  38646. editor->grabKeyboardFocus();
  38647. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38648. editor->addListener (this);
  38649. resized();
  38650. repaint();
  38651. editorShown (editor);
  38652. enterModalState (false);
  38653. editor->grabKeyboardFocus();
  38654. }
  38655. }
  38656. void Label::editorShown (TextEditor*)
  38657. {
  38658. }
  38659. void Label::editorAboutToBeHidden (TextEditor*)
  38660. {
  38661. }
  38662. bool Label::updateFromTextEditorContents (TextEditor& ed)
  38663. {
  38664. const String newText (ed.getText());
  38665. if (textValue.toString() != newText)
  38666. {
  38667. lastTextValue = newText;
  38668. textValue = newText;
  38669. repaint();
  38670. textWasChanged();
  38671. if (ownerComponent != 0)
  38672. componentMovedOrResized (*ownerComponent, true, true);
  38673. return true;
  38674. }
  38675. return false;
  38676. }
  38677. void Label::hideEditor (const bool discardCurrentEditorContents)
  38678. {
  38679. if (editor != 0)
  38680. {
  38681. WeakReference<Component> deletionChecker (this);
  38682. ScopedPointer<TextEditor> outgoingEditor (editor);
  38683. editorAboutToBeHidden (outgoingEditor);
  38684. const bool changed = (! discardCurrentEditorContents)
  38685. && updateFromTextEditorContents (*outgoingEditor);
  38686. outgoingEditor = 0;
  38687. repaint();
  38688. if (changed)
  38689. textWasEdited();
  38690. if (deletionChecker != 0)
  38691. exitModalState (0);
  38692. if (changed && deletionChecker != 0)
  38693. callChangeListeners();
  38694. }
  38695. }
  38696. void Label::inputAttemptWhenModal()
  38697. {
  38698. if (editor != 0)
  38699. {
  38700. if (lossOfFocusDiscardsChanges)
  38701. textEditorEscapeKeyPressed (*editor);
  38702. else
  38703. textEditorReturnKeyPressed (*editor);
  38704. }
  38705. }
  38706. bool Label::isBeingEdited() const throw()
  38707. {
  38708. return editor != 0;
  38709. }
  38710. TextEditor* Label::createEditorComponent()
  38711. {
  38712. TextEditor* const ed = new TextEditor (getName());
  38713. ed->setFont (font);
  38714. // copy these colours from our own settings..
  38715. const int cols[] = { TextEditor::backgroundColourId,
  38716. TextEditor::textColourId,
  38717. TextEditor::highlightColourId,
  38718. TextEditor::highlightedTextColourId,
  38719. TextEditor::caretColourId,
  38720. TextEditor::outlineColourId,
  38721. TextEditor::focusedOutlineColourId,
  38722. TextEditor::shadowColourId };
  38723. for (int i = 0; i < numElementsInArray (cols); ++i)
  38724. ed->setColour (cols[i], findColour (cols[i]));
  38725. return ed;
  38726. }
  38727. void Label::paint (Graphics& g)
  38728. {
  38729. getLookAndFeel().drawLabel (g, *this);
  38730. }
  38731. void Label::mouseUp (const MouseEvent& e)
  38732. {
  38733. if (editSingleClick
  38734. && e.mouseWasClicked()
  38735. && contains (e.getPosition())
  38736. && ! e.mods.isPopupMenu())
  38737. {
  38738. showEditor();
  38739. }
  38740. }
  38741. void Label::mouseDoubleClick (const MouseEvent& e)
  38742. {
  38743. if (editDoubleClick && ! e.mods.isPopupMenu())
  38744. showEditor();
  38745. }
  38746. void Label::resized()
  38747. {
  38748. if (editor != 0)
  38749. editor->setBoundsInset (BorderSize<int> (0));
  38750. }
  38751. void Label::focusGained (FocusChangeType cause)
  38752. {
  38753. if (editSingleClick && cause == focusChangedByTabKey)
  38754. showEditor();
  38755. }
  38756. void Label::enablementChanged()
  38757. {
  38758. repaint();
  38759. }
  38760. void Label::colourChanged()
  38761. {
  38762. repaint();
  38763. }
  38764. void Label::setMinimumHorizontalScale (const float newScale)
  38765. {
  38766. if (minimumHorizontalScale != newScale)
  38767. {
  38768. minimumHorizontalScale = newScale;
  38769. repaint();
  38770. }
  38771. }
  38772. // We'll use a custom focus traverser here to make sure focus goes from the
  38773. // text editor to another component rather than back to the label itself.
  38774. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38775. {
  38776. public:
  38777. LabelKeyboardFocusTraverser() {}
  38778. Component* getNextComponent (Component* current)
  38779. {
  38780. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38781. ? current->getParentComponent() : current);
  38782. }
  38783. Component* getPreviousComponent (Component* current)
  38784. {
  38785. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38786. ? current->getParentComponent() : current);
  38787. }
  38788. };
  38789. KeyboardFocusTraverser* Label::createFocusTraverser()
  38790. {
  38791. return new LabelKeyboardFocusTraverser();
  38792. }
  38793. void Label::addListener (LabelListener* const listener)
  38794. {
  38795. listeners.add (listener);
  38796. }
  38797. void Label::removeListener (LabelListener* const listener)
  38798. {
  38799. listeners.remove (listener);
  38800. }
  38801. void Label::callChangeListeners()
  38802. {
  38803. Component::BailOutChecker checker (this);
  38804. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38805. }
  38806. void Label::textEditorTextChanged (TextEditor& ed)
  38807. {
  38808. if (editor != 0)
  38809. {
  38810. jassert (&ed == editor);
  38811. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38812. {
  38813. if (lossOfFocusDiscardsChanges)
  38814. textEditorEscapeKeyPressed (ed);
  38815. else
  38816. textEditorReturnKeyPressed (ed);
  38817. }
  38818. }
  38819. }
  38820. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38821. {
  38822. if (editor != 0)
  38823. {
  38824. jassert (&ed == editor);
  38825. const bool changed = updateFromTextEditorContents (ed);
  38826. hideEditor (true);
  38827. if (changed)
  38828. {
  38829. WeakReference<Component> deletionChecker (this);
  38830. textWasEdited();
  38831. if (deletionChecker != 0)
  38832. callChangeListeners();
  38833. }
  38834. }
  38835. }
  38836. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38837. {
  38838. if (editor != 0)
  38839. {
  38840. jassert (&ed == editor);
  38841. (void) ed;
  38842. editor->setText (textValue.toString(), false);
  38843. hideEditor (true);
  38844. }
  38845. }
  38846. void Label::textEditorFocusLost (TextEditor& ed)
  38847. {
  38848. textEditorTextChanged (ed);
  38849. }
  38850. END_JUCE_NAMESPACE
  38851. /*** End of inlined file: juce_Label.cpp ***/
  38852. /*** Start of inlined file: juce_ListBox.cpp ***/
  38853. BEGIN_JUCE_NAMESPACE
  38854. class ListBoxRowComponent : public Component,
  38855. public TooltipClient
  38856. {
  38857. public:
  38858. ListBoxRowComponent (ListBox& owner_)
  38859. : owner (owner_), row (-1),
  38860. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38861. {
  38862. }
  38863. void paint (Graphics& g)
  38864. {
  38865. if (owner.getModel() != 0)
  38866. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38867. }
  38868. void update (const int row_, const bool selected_)
  38869. {
  38870. if (row != row_ || selected != selected_)
  38871. {
  38872. repaint();
  38873. row = row_;
  38874. selected = selected_;
  38875. }
  38876. if (owner.getModel() != 0)
  38877. {
  38878. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  38879. if (customComponent != 0)
  38880. {
  38881. addAndMakeVisible (customComponent);
  38882. customComponent->setBounds (getLocalBounds());
  38883. }
  38884. }
  38885. }
  38886. void mouseDown (const MouseEvent& e)
  38887. {
  38888. isDragging = false;
  38889. selectRowOnMouseUp = false;
  38890. if (isEnabled())
  38891. {
  38892. if (! selected)
  38893. {
  38894. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  38895. if (owner.getModel() != 0)
  38896. owner.getModel()->listBoxItemClicked (row, e);
  38897. }
  38898. else
  38899. {
  38900. selectRowOnMouseUp = true;
  38901. }
  38902. }
  38903. }
  38904. void mouseUp (const MouseEvent& e)
  38905. {
  38906. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38907. {
  38908. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  38909. if (owner.getModel() != 0)
  38910. owner.getModel()->listBoxItemClicked (row, e);
  38911. }
  38912. }
  38913. void mouseDoubleClick (const MouseEvent& e)
  38914. {
  38915. if (owner.getModel() != 0 && isEnabled())
  38916. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38917. }
  38918. void mouseDrag (const MouseEvent& e)
  38919. {
  38920. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38921. {
  38922. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38923. if (selectedRows.size() > 0)
  38924. {
  38925. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38926. if (dragDescription.isNotEmpty())
  38927. {
  38928. isDragging = true;
  38929. owner.startDragAndDrop (e, dragDescription);
  38930. }
  38931. }
  38932. }
  38933. }
  38934. void resized()
  38935. {
  38936. if (customComponent != 0)
  38937. customComponent->setBounds (getLocalBounds());
  38938. }
  38939. const String getTooltip()
  38940. {
  38941. if (owner.getModel() != 0)
  38942. return owner.getModel()->getTooltipForRow (row);
  38943. return String::empty;
  38944. }
  38945. ScopedPointer<Component> customComponent;
  38946. private:
  38947. ListBox& owner;
  38948. int row;
  38949. bool selected, isDragging, selectRowOnMouseUp;
  38950. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  38951. };
  38952. class ListViewport : public Viewport
  38953. {
  38954. public:
  38955. ListViewport (ListBox& owner_)
  38956. : owner (owner_)
  38957. {
  38958. setWantsKeyboardFocus (false);
  38959. Component* const content = new Component();
  38960. setViewedComponent (content);
  38961. content->addMouseListener (this, false);
  38962. content->setWantsKeyboardFocus (false);
  38963. }
  38964. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38965. {
  38966. return rows [row % jmax (1, rows.size())];
  38967. }
  38968. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  38969. {
  38970. return (row >= firstIndex && row < firstIndex + rows.size())
  38971. ? getComponentForRow (row) : 0;
  38972. }
  38973. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38974. {
  38975. const int index = getIndexOfChildComponent (rowComponent);
  38976. const int num = rows.size();
  38977. for (int i = num; --i >= 0;)
  38978. if (((firstIndex + i) % jmax (1, num)) == index)
  38979. return firstIndex + i;
  38980. return -1;
  38981. }
  38982. void visibleAreaChanged (const Rectangle<int>&)
  38983. {
  38984. updateVisibleArea (true);
  38985. if (owner.getModel() != 0)
  38986. owner.getModel()->listWasScrolled();
  38987. }
  38988. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38989. {
  38990. hasUpdated = false;
  38991. const int newX = getViewedComponent()->getX();
  38992. int newY = getViewedComponent()->getY();
  38993. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38994. const int newH = owner.totalItems * owner.getRowHeight();
  38995. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38996. newY = getMaximumVisibleHeight() - newH;
  38997. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38998. if (makeSureItUpdatesContent && ! hasUpdated)
  38999. updateContents();
  39000. }
  39001. void updateContents()
  39002. {
  39003. hasUpdated = true;
  39004. const int rowHeight = owner.getRowHeight();
  39005. if (rowHeight > 0)
  39006. {
  39007. const int y = getViewPositionY();
  39008. const int w = getViewedComponent()->getWidth();
  39009. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39010. rows.removeRange (numNeeded, rows.size());
  39011. while (numNeeded > rows.size())
  39012. {
  39013. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  39014. rows.add (newRow);
  39015. getViewedComponent()->addAndMakeVisible (newRow);
  39016. }
  39017. firstIndex = y / rowHeight;
  39018. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39019. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39020. for (int i = 0; i < numNeeded; ++i)
  39021. {
  39022. const int row = i + firstIndex;
  39023. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39024. if (rowComp != 0)
  39025. {
  39026. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39027. rowComp->update (row, owner.isRowSelected (row));
  39028. }
  39029. }
  39030. }
  39031. if (owner.headerComponent != 0)
  39032. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39033. owner.outlineThickness,
  39034. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39035. getViewedComponent()->getWidth()),
  39036. owner.headerComponent->getHeight());
  39037. }
  39038. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39039. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39040. {
  39041. hasUpdated = false;
  39042. if (row < firstWholeIndex && ! dontScroll)
  39043. {
  39044. setViewPosition (getViewPositionX(), row * rowHeight);
  39045. }
  39046. else if (row >= lastWholeIndex && ! dontScroll)
  39047. {
  39048. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39049. if (row >= lastRowSelected + rowsOnScreen
  39050. && rowsOnScreen < totalItems - 1
  39051. && ! isMouseClick)
  39052. {
  39053. setViewPosition (getViewPositionX(),
  39054. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39055. }
  39056. else
  39057. {
  39058. setViewPosition (getViewPositionX(),
  39059. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39060. }
  39061. }
  39062. if (! hasUpdated)
  39063. updateContents();
  39064. }
  39065. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39066. {
  39067. if (row < firstWholeIndex)
  39068. {
  39069. setViewPosition (getViewPositionX(), row * rowHeight);
  39070. }
  39071. else if (row >= lastWholeIndex)
  39072. {
  39073. setViewPosition (getViewPositionX(),
  39074. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39075. }
  39076. }
  39077. void paint (Graphics& g)
  39078. {
  39079. if (isOpaque())
  39080. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39081. }
  39082. bool keyPressed (const KeyPress& key)
  39083. {
  39084. if (key.isKeyCode (KeyPress::upKey)
  39085. || key.isKeyCode (KeyPress::downKey)
  39086. || key.isKeyCode (KeyPress::pageUpKey)
  39087. || key.isKeyCode (KeyPress::pageDownKey)
  39088. || key.isKeyCode (KeyPress::homeKey)
  39089. || key.isKeyCode (KeyPress::endKey))
  39090. {
  39091. // we want to avoid these keypresses going to the viewport, and instead allow
  39092. // them to pass up to our listbox..
  39093. return false;
  39094. }
  39095. return Viewport::keyPressed (key);
  39096. }
  39097. private:
  39098. ListBox& owner;
  39099. OwnedArray<ListBoxRowComponent> rows;
  39100. int firstIndex, firstWholeIndex, lastWholeIndex;
  39101. bool hasUpdated;
  39102. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  39103. };
  39104. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39105. : Component (name),
  39106. model (model_),
  39107. totalItems (0),
  39108. rowHeight (22),
  39109. minimumRowWidth (0),
  39110. outlineThickness (0),
  39111. lastRowSelected (-1),
  39112. mouseMoveSelects (false),
  39113. multipleSelection (false),
  39114. hasDoneInitialUpdate (false)
  39115. {
  39116. addAndMakeVisible (viewport = new ListViewport (*this));
  39117. setWantsKeyboardFocus (true);
  39118. colourChanged();
  39119. }
  39120. ListBox::~ListBox()
  39121. {
  39122. headerComponent = 0;
  39123. viewport = 0;
  39124. }
  39125. void ListBox::setModel (ListBoxModel* const newModel)
  39126. {
  39127. if (model != newModel)
  39128. {
  39129. model = newModel;
  39130. repaint();
  39131. updateContent();
  39132. }
  39133. }
  39134. void ListBox::setMultipleSelectionEnabled (bool b)
  39135. {
  39136. multipleSelection = b;
  39137. }
  39138. void ListBox::setMouseMoveSelectsRows (bool b)
  39139. {
  39140. mouseMoveSelects = b;
  39141. if (b)
  39142. addMouseListener (this, true);
  39143. }
  39144. void ListBox::paint (Graphics& g)
  39145. {
  39146. if (! hasDoneInitialUpdate)
  39147. updateContent();
  39148. g.fillAll (findColour (backgroundColourId));
  39149. }
  39150. void ListBox::paintOverChildren (Graphics& g)
  39151. {
  39152. if (outlineThickness > 0)
  39153. {
  39154. g.setColour (findColour (outlineColourId));
  39155. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39156. }
  39157. }
  39158. void ListBox::resized()
  39159. {
  39160. viewport->setBoundsInset (BorderSize<int> (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39161. outlineThickness, outlineThickness, outlineThickness));
  39162. viewport->setSingleStepSizes (20, getRowHeight());
  39163. viewport->updateVisibleArea (false);
  39164. }
  39165. void ListBox::visibilityChanged()
  39166. {
  39167. viewport->updateVisibleArea (true);
  39168. }
  39169. Viewport* ListBox::getViewport() const throw()
  39170. {
  39171. return viewport;
  39172. }
  39173. void ListBox::updateContent()
  39174. {
  39175. hasDoneInitialUpdate = true;
  39176. totalItems = (model != 0) ? model->getNumRows() : 0;
  39177. bool selectionChanged = false;
  39178. if (selected.size() > 0 && selected [selected.size() - 1] >= totalItems)
  39179. {
  39180. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39181. lastRowSelected = getSelectedRow (0);
  39182. selectionChanged = true;
  39183. }
  39184. viewport->updateVisibleArea (isVisible());
  39185. viewport->resized();
  39186. if (selectionChanged && model != 0)
  39187. model->selectedRowsChanged (lastRowSelected);
  39188. }
  39189. void ListBox::selectRow (const int row,
  39190. bool dontScroll,
  39191. bool deselectOthersFirst)
  39192. {
  39193. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39194. }
  39195. void ListBox::selectRowInternal (const int row,
  39196. bool dontScroll,
  39197. bool deselectOthersFirst,
  39198. bool isMouseClick)
  39199. {
  39200. if (! multipleSelection)
  39201. deselectOthersFirst = true;
  39202. if ((! isRowSelected (row))
  39203. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39204. {
  39205. if (isPositiveAndBelow (row, totalItems))
  39206. {
  39207. if (deselectOthersFirst)
  39208. selected.clear();
  39209. selected.addRange (Range<int> (row, row + 1));
  39210. if (getHeight() == 0 || getWidth() == 0)
  39211. dontScroll = true;
  39212. viewport->selectRow (row, getRowHeight(), dontScroll,
  39213. lastRowSelected, totalItems, isMouseClick);
  39214. lastRowSelected = row;
  39215. model->selectedRowsChanged (row);
  39216. }
  39217. else
  39218. {
  39219. if (deselectOthersFirst)
  39220. deselectAllRows();
  39221. }
  39222. }
  39223. }
  39224. void ListBox::deselectRow (const int row)
  39225. {
  39226. if (selected.contains (row))
  39227. {
  39228. selected.removeRange (Range <int> (row, row + 1));
  39229. if (row == lastRowSelected)
  39230. lastRowSelected = getSelectedRow (0);
  39231. viewport->updateContents();
  39232. model->selectedRowsChanged (lastRowSelected);
  39233. }
  39234. }
  39235. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39236. const bool sendNotificationEventToModel)
  39237. {
  39238. selected = setOfRowsToBeSelected;
  39239. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39240. if (! isRowSelected (lastRowSelected))
  39241. lastRowSelected = getSelectedRow (0);
  39242. viewport->updateContents();
  39243. if ((model != 0) && sendNotificationEventToModel)
  39244. model->selectedRowsChanged (lastRowSelected);
  39245. }
  39246. const SparseSet<int> ListBox::getSelectedRows() const
  39247. {
  39248. return selected;
  39249. }
  39250. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39251. {
  39252. if (multipleSelection && (firstRow != lastRow))
  39253. {
  39254. const int numRows = totalItems - 1;
  39255. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39256. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39257. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39258. jmax (firstRow, lastRow) + 1));
  39259. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39260. }
  39261. selectRowInternal (lastRow, false, false, true);
  39262. }
  39263. void ListBox::flipRowSelection (const int row)
  39264. {
  39265. if (isRowSelected (row))
  39266. deselectRow (row);
  39267. else
  39268. selectRowInternal (row, false, false, true);
  39269. }
  39270. void ListBox::deselectAllRows()
  39271. {
  39272. if (! selected.isEmpty())
  39273. {
  39274. selected.clear();
  39275. lastRowSelected = -1;
  39276. viewport->updateContents();
  39277. if (model != 0)
  39278. model->selectedRowsChanged (lastRowSelected);
  39279. }
  39280. }
  39281. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39282. const ModifierKeys& mods,
  39283. const bool isMouseUpEvent)
  39284. {
  39285. if (multipleSelection && mods.isCommandDown())
  39286. {
  39287. flipRowSelection (row);
  39288. }
  39289. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39290. {
  39291. selectRangeOfRows (lastRowSelected, row);
  39292. }
  39293. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39294. {
  39295. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  39296. }
  39297. }
  39298. int ListBox::getNumSelectedRows() const
  39299. {
  39300. return selected.size();
  39301. }
  39302. int ListBox::getSelectedRow (const int index) const
  39303. {
  39304. return (isPositiveAndBelow (index, selected.size()))
  39305. ? selected [index] : -1;
  39306. }
  39307. bool ListBox::isRowSelected (const int row) const
  39308. {
  39309. return selected.contains (row);
  39310. }
  39311. int ListBox::getLastRowSelected() const
  39312. {
  39313. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39314. }
  39315. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39316. {
  39317. if (isPositiveAndBelow (x, getWidth()))
  39318. {
  39319. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39320. if (isPositiveAndBelow (row, totalItems))
  39321. return row;
  39322. }
  39323. return -1;
  39324. }
  39325. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39326. {
  39327. if (isPositiveAndBelow (x, getWidth()))
  39328. {
  39329. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39330. return jlimit (0, totalItems, row);
  39331. }
  39332. return -1;
  39333. }
  39334. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39335. {
  39336. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39337. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39338. }
  39339. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39340. {
  39341. return viewport->getRowNumberOfComponent (rowComponent);
  39342. }
  39343. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39344. const bool relativeToComponentTopLeft) const throw()
  39345. {
  39346. int y = viewport->getY() + rowHeight * rowNumber;
  39347. if (relativeToComponentTopLeft)
  39348. y -= viewport->getViewPositionY();
  39349. return Rectangle<int> (viewport->getX(), y,
  39350. viewport->getViewedComponent()->getWidth(), rowHeight);
  39351. }
  39352. void ListBox::setVerticalPosition (const double proportion)
  39353. {
  39354. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39355. viewport->setViewPosition (viewport->getViewPositionX(),
  39356. jmax (0, roundToInt (proportion * offscreen)));
  39357. }
  39358. double ListBox::getVerticalPosition() const
  39359. {
  39360. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39361. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39362. : 0;
  39363. }
  39364. int ListBox::getVisibleRowWidth() const throw()
  39365. {
  39366. return viewport->getViewWidth();
  39367. }
  39368. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39369. {
  39370. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39371. }
  39372. bool ListBox::keyPressed (const KeyPress& key)
  39373. {
  39374. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39375. const bool multiple = multipleSelection
  39376. && (lastRowSelected >= 0)
  39377. && (key.getModifiers().isShiftDown()
  39378. || key.getModifiers().isCtrlDown()
  39379. || key.getModifiers().isCommandDown());
  39380. if (key.isKeyCode (KeyPress::upKey))
  39381. {
  39382. if (multiple)
  39383. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39384. else
  39385. selectRow (jmax (0, lastRowSelected - 1));
  39386. }
  39387. else if (key.isKeyCode (KeyPress::returnKey)
  39388. && isRowSelected (lastRowSelected))
  39389. {
  39390. if (model != 0)
  39391. model->returnKeyPressed (lastRowSelected);
  39392. }
  39393. else if (key.isKeyCode (KeyPress::pageUpKey))
  39394. {
  39395. if (multiple)
  39396. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39397. else
  39398. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39399. }
  39400. else if (key.isKeyCode (KeyPress::pageDownKey))
  39401. {
  39402. if (multiple)
  39403. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39404. else
  39405. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39406. }
  39407. else if (key.isKeyCode (KeyPress::homeKey))
  39408. {
  39409. if (multiple && key.getModifiers().isShiftDown())
  39410. selectRangeOfRows (lastRowSelected, 0);
  39411. else
  39412. selectRow (0);
  39413. }
  39414. else if (key.isKeyCode (KeyPress::endKey))
  39415. {
  39416. if (multiple && key.getModifiers().isShiftDown())
  39417. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39418. else
  39419. selectRow (totalItems - 1);
  39420. }
  39421. else if (key.isKeyCode (KeyPress::downKey))
  39422. {
  39423. if (multiple)
  39424. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39425. else
  39426. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39427. }
  39428. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39429. && isRowSelected (lastRowSelected))
  39430. {
  39431. if (model != 0)
  39432. model->deleteKeyPressed (lastRowSelected);
  39433. }
  39434. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39435. {
  39436. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39437. }
  39438. else
  39439. {
  39440. return false;
  39441. }
  39442. return true;
  39443. }
  39444. bool ListBox::keyStateChanged (const bool isKeyDown)
  39445. {
  39446. return isKeyDown
  39447. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39448. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39449. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39450. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39451. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39452. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39453. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39454. }
  39455. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39456. {
  39457. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39458. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39459. }
  39460. void ListBox::mouseMove (const MouseEvent& e)
  39461. {
  39462. if (mouseMoveSelects)
  39463. {
  39464. const MouseEvent e2 (e.getEventRelativeTo (this));
  39465. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39466. }
  39467. }
  39468. void ListBox::mouseExit (const MouseEvent& e)
  39469. {
  39470. mouseMove (e);
  39471. }
  39472. void ListBox::mouseUp (const MouseEvent& e)
  39473. {
  39474. if (e.mouseWasClicked() && model != 0)
  39475. model->backgroundClicked();
  39476. }
  39477. void ListBox::setRowHeight (const int newHeight)
  39478. {
  39479. rowHeight = jmax (1, newHeight);
  39480. viewport->setSingleStepSizes (20, rowHeight);
  39481. updateContent();
  39482. }
  39483. int ListBox::getNumRowsOnScreen() const throw()
  39484. {
  39485. return viewport->getMaximumVisibleHeight() / rowHeight;
  39486. }
  39487. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39488. {
  39489. minimumRowWidth = newMinimumWidth;
  39490. updateContent();
  39491. }
  39492. int ListBox::getVisibleContentWidth() const throw()
  39493. {
  39494. return viewport->getMaximumVisibleWidth();
  39495. }
  39496. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39497. {
  39498. return viewport->getVerticalScrollBar();
  39499. }
  39500. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39501. {
  39502. return viewport->getHorizontalScrollBar();
  39503. }
  39504. void ListBox::colourChanged()
  39505. {
  39506. setOpaque (findColour (backgroundColourId).isOpaque());
  39507. viewport->setOpaque (isOpaque());
  39508. repaint();
  39509. }
  39510. void ListBox::setOutlineThickness (const int outlineThickness_)
  39511. {
  39512. outlineThickness = outlineThickness_;
  39513. resized();
  39514. }
  39515. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39516. {
  39517. if (headerComponent != newHeaderComponent)
  39518. {
  39519. headerComponent = newHeaderComponent;
  39520. addAndMakeVisible (newHeaderComponent);
  39521. ListBox::resized();
  39522. }
  39523. }
  39524. void ListBox::repaintRow (const int rowNumber) throw()
  39525. {
  39526. repaint (getRowPosition (rowNumber, true));
  39527. }
  39528. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39529. {
  39530. Rectangle<int> imageArea;
  39531. const int firstRow = getRowContainingPosition (0, 0);
  39532. int i;
  39533. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39534. {
  39535. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39536. if (rowComp != 0 && isRowSelected (firstRow + i))
  39537. {
  39538. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39539. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39540. imageArea = imageArea.getUnion (rowRect);
  39541. }
  39542. }
  39543. imageArea = imageArea.getIntersection (getLocalBounds());
  39544. imageX = imageArea.getX();
  39545. imageY = imageArea.getY();
  39546. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39547. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39548. {
  39549. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39550. if (rowComp != 0 && isRowSelected (firstRow + i))
  39551. {
  39552. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39553. Graphics g (snapshot);
  39554. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39555. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39556. {
  39557. g.beginTransparencyLayer (0.6f);
  39558. rowComp->paintEntireComponent (g, false);
  39559. g.endTransparencyLayer();
  39560. }
  39561. }
  39562. }
  39563. return snapshot;
  39564. }
  39565. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39566. {
  39567. DragAndDropContainer* const dragContainer
  39568. = DragAndDropContainer::findParentDragContainerFor (this);
  39569. if (dragContainer != 0)
  39570. {
  39571. int x, y;
  39572. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39573. MouseEvent e2 (e.getEventRelativeTo (this));
  39574. const Point<int> p (x - e2.x, y - e2.y);
  39575. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39576. }
  39577. else
  39578. {
  39579. // to be able to do a drag-and-drop operation, the listbox needs to
  39580. // be inside a component which is also a DragAndDropContainer.
  39581. jassertfalse;
  39582. }
  39583. }
  39584. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39585. {
  39586. (void) existingComponentToUpdate;
  39587. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39588. return 0;
  39589. }
  39590. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39591. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39592. void ListBoxModel::backgroundClicked() {}
  39593. void ListBoxModel::selectedRowsChanged (int) {}
  39594. void ListBoxModel::deleteKeyPressed (int) {}
  39595. void ListBoxModel::returnKeyPressed (int) {}
  39596. void ListBoxModel::listWasScrolled() {}
  39597. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39598. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39599. END_JUCE_NAMESPACE
  39600. /*** End of inlined file: juce_ListBox.cpp ***/
  39601. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39602. BEGIN_JUCE_NAMESPACE
  39603. ProgressBar::ProgressBar (double& progress_)
  39604. : progress (progress_),
  39605. displayPercentage (true),
  39606. lastCallbackTime (0)
  39607. {
  39608. currentValue = jlimit (0.0, 1.0, progress);
  39609. }
  39610. ProgressBar::~ProgressBar()
  39611. {
  39612. }
  39613. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39614. {
  39615. displayPercentage = shouldDisplayPercentage;
  39616. repaint();
  39617. }
  39618. void ProgressBar::setTextToDisplay (const String& text)
  39619. {
  39620. displayPercentage = false;
  39621. displayedMessage = text;
  39622. }
  39623. void ProgressBar::lookAndFeelChanged()
  39624. {
  39625. setOpaque (findColour (backgroundColourId).isOpaque());
  39626. }
  39627. void ProgressBar::colourChanged()
  39628. {
  39629. lookAndFeelChanged();
  39630. }
  39631. void ProgressBar::paint (Graphics& g)
  39632. {
  39633. String text;
  39634. if (displayPercentage)
  39635. {
  39636. if (currentValue >= 0 && currentValue <= 1.0)
  39637. text << roundToInt (currentValue * 100.0) << '%';
  39638. }
  39639. else
  39640. {
  39641. text = displayedMessage;
  39642. }
  39643. getLookAndFeel().drawProgressBar (g, *this,
  39644. getWidth(), getHeight(),
  39645. currentValue, text);
  39646. }
  39647. void ProgressBar::visibilityChanged()
  39648. {
  39649. if (isVisible())
  39650. startTimer (30);
  39651. else
  39652. stopTimer();
  39653. }
  39654. void ProgressBar::timerCallback()
  39655. {
  39656. double newProgress = progress;
  39657. const uint32 now = Time::getMillisecondCounter();
  39658. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39659. lastCallbackTime = now;
  39660. if (currentValue != newProgress
  39661. || newProgress < 0 || newProgress >= 1.0
  39662. || currentMessage != displayedMessage)
  39663. {
  39664. if (currentValue < newProgress
  39665. && newProgress >= 0 && newProgress < 1.0
  39666. && currentValue >= 0 && currentValue < 1.0)
  39667. {
  39668. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39669. newProgress);
  39670. }
  39671. currentValue = newProgress;
  39672. currentMessage = displayedMessage;
  39673. repaint();
  39674. }
  39675. }
  39676. END_JUCE_NAMESPACE
  39677. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39678. /*** Start of inlined file: juce_Slider.cpp ***/
  39679. BEGIN_JUCE_NAMESPACE
  39680. class SliderPopupDisplayComponent : public BubbleComponent
  39681. {
  39682. public:
  39683. SliderPopupDisplayComponent (Slider* const owner_)
  39684. : owner (owner_),
  39685. font (15.0f, Font::bold)
  39686. {
  39687. setAlwaysOnTop (true);
  39688. }
  39689. void paintContent (Graphics& g, int w, int h)
  39690. {
  39691. g.setFont (font);
  39692. g.setColour (Colours::black);
  39693. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39694. }
  39695. void getContentSize (int& w, int& h)
  39696. {
  39697. w = font.getStringWidth (text) + 18;
  39698. h = (int) (font.getHeight() * 1.6f);
  39699. }
  39700. void updatePosition (const String& newText)
  39701. {
  39702. if (text != newText)
  39703. {
  39704. text = newText;
  39705. repaint();
  39706. }
  39707. BubbleComponent::setPosition (owner);
  39708. }
  39709. private:
  39710. Slider* owner;
  39711. Font font;
  39712. String text;
  39713. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39714. };
  39715. Slider::Slider (const String& name)
  39716. : Component (name),
  39717. lastCurrentValue (0),
  39718. lastValueMin (0),
  39719. lastValueMax (0),
  39720. minimum (0),
  39721. maximum (10),
  39722. interval (0),
  39723. skewFactor (1.0),
  39724. velocityModeSensitivity (1.0),
  39725. velocityModeOffset (0.0),
  39726. velocityModeThreshold (1),
  39727. rotaryStart (float_Pi * 1.2f),
  39728. rotaryEnd (float_Pi * 2.8f),
  39729. numDecimalPlaces (7),
  39730. sliderRegionStart (0),
  39731. sliderRegionSize (1),
  39732. sliderBeingDragged (-1),
  39733. pixelsForFullDragExtent (250),
  39734. style (LinearHorizontal),
  39735. textBoxPos (TextBoxLeft),
  39736. textBoxWidth (80),
  39737. textBoxHeight (20),
  39738. incDecButtonMode (incDecButtonsNotDraggable),
  39739. editableText (true),
  39740. doubleClickToValue (false),
  39741. isVelocityBased (false),
  39742. userKeyOverridesVelocity (true),
  39743. rotaryStop (true),
  39744. incDecButtonsSideBySide (false),
  39745. sendChangeOnlyOnRelease (false),
  39746. popupDisplayEnabled (false),
  39747. menuEnabled (false),
  39748. menuShown (false),
  39749. scrollWheelEnabled (true),
  39750. snapsToMousePos (true),
  39751. popupDisplay (0),
  39752. parentForPopupDisplay (0)
  39753. {
  39754. setWantsKeyboardFocus (false);
  39755. setRepaintsOnMouseActivity (true);
  39756. lookAndFeelChanged();
  39757. updateText();
  39758. currentValue.addListener (this);
  39759. valueMin.addListener (this);
  39760. valueMax.addListener (this);
  39761. }
  39762. Slider::~Slider()
  39763. {
  39764. currentValue.removeListener (this);
  39765. valueMin.removeListener (this);
  39766. valueMax.removeListener (this);
  39767. popupDisplay = 0;
  39768. }
  39769. void Slider::handleAsyncUpdate()
  39770. {
  39771. cancelPendingUpdate();
  39772. Component::BailOutChecker checker (this);
  39773. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39774. }
  39775. void Slider::sendDragStart()
  39776. {
  39777. startedDragging();
  39778. Component::BailOutChecker checker (this);
  39779. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39780. }
  39781. void Slider::sendDragEnd()
  39782. {
  39783. stoppedDragging();
  39784. sliderBeingDragged = -1;
  39785. Component::BailOutChecker checker (this);
  39786. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39787. }
  39788. void Slider::addListener (SliderListener* const listener)
  39789. {
  39790. listeners.add (listener);
  39791. }
  39792. void Slider::removeListener (SliderListener* const listener)
  39793. {
  39794. listeners.remove (listener);
  39795. }
  39796. void Slider::setSliderStyle (const SliderStyle newStyle)
  39797. {
  39798. if (style != newStyle)
  39799. {
  39800. style = newStyle;
  39801. repaint();
  39802. lookAndFeelChanged();
  39803. }
  39804. }
  39805. void Slider::setRotaryParameters (const float startAngleRadians,
  39806. const float endAngleRadians,
  39807. const bool stopAtEnd)
  39808. {
  39809. // make sure the values are sensible..
  39810. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39811. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39812. jassert (rotaryStart < rotaryEnd);
  39813. rotaryStart = startAngleRadians;
  39814. rotaryEnd = endAngleRadians;
  39815. rotaryStop = stopAtEnd;
  39816. }
  39817. void Slider::setVelocityBasedMode (const bool velBased)
  39818. {
  39819. isVelocityBased = velBased;
  39820. }
  39821. void Slider::setVelocityModeParameters (const double sensitivity,
  39822. const int threshold,
  39823. const double offset,
  39824. const bool userCanPressKeyToSwapMode)
  39825. {
  39826. jassert (threshold >= 0);
  39827. jassert (sensitivity > 0);
  39828. jassert (offset >= 0);
  39829. velocityModeSensitivity = sensitivity;
  39830. velocityModeOffset = offset;
  39831. velocityModeThreshold = threshold;
  39832. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39833. }
  39834. void Slider::setSkewFactor (const double factor)
  39835. {
  39836. skewFactor = factor;
  39837. }
  39838. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39839. {
  39840. if (maximum > minimum)
  39841. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39842. / (maximum - minimum));
  39843. }
  39844. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39845. {
  39846. jassert (distanceForFullScaleDrag > 0);
  39847. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39848. }
  39849. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39850. {
  39851. if (incDecButtonMode != mode)
  39852. {
  39853. incDecButtonMode = mode;
  39854. lookAndFeelChanged();
  39855. }
  39856. }
  39857. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39858. const bool isReadOnly,
  39859. const int textEntryBoxWidth,
  39860. const int textEntryBoxHeight)
  39861. {
  39862. if (textBoxPos != newPosition
  39863. || editableText != (! isReadOnly)
  39864. || textBoxWidth != textEntryBoxWidth
  39865. || textBoxHeight != textEntryBoxHeight)
  39866. {
  39867. textBoxPos = newPosition;
  39868. editableText = ! isReadOnly;
  39869. textBoxWidth = textEntryBoxWidth;
  39870. textBoxHeight = textEntryBoxHeight;
  39871. repaint();
  39872. lookAndFeelChanged();
  39873. }
  39874. }
  39875. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39876. {
  39877. editableText = shouldBeEditable;
  39878. if (valueBox != 0)
  39879. valueBox->setEditable (shouldBeEditable && isEnabled());
  39880. }
  39881. void Slider::showTextBox()
  39882. {
  39883. jassert (editableText); // this should probably be avoided in read-only sliders.
  39884. if (valueBox != 0)
  39885. valueBox->showEditor();
  39886. }
  39887. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39888. {
  39889. if (valueBox != 0)
  39890. {
  39891. valueBox->hideEditor (discardCurrentEditorContents);
  39892. if (discardCurrentEditorContents)
  39893. updateText();
  39894. }
  39895. }
  39896. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39897. {
  39898. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39899. }
  39900. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39901. {
  39902. snapsToMousePos = shouldSnapToMouse;
  39903. }
  39904. void Slider::setPopupDisplayEnabled (const bool enabled,
  39905. Component* const parentComponentToUse)
  39906. {
  39907. popupDisplayEnabled = enabled;
  39908. parentForPopupDisplay = parentComponentToUse;
  39909. }
  39910. void Slider::colourChanged()
  39911. {
  39912. lookAndFeelChanged();
  39913. }
  39914. void Slider::lookAndFeelChanged()
  39915. {
  39916. LookAndFeel& lf = getLookAndFeel();
  39917. if (textBoxPos != NoTextBox)
  39918. {
  39919. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39920. : getTextFromValue (currentValue.getValue()));
  39921. valueBox = 0;
  39922. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39923. valueBox->setWantsKeyboardFocus (false);
  39924. valueBox->setText (previousTextBoxContent, false);
  39925. valueBox->setEditable (editableText && isEnabled());
  39926. valueBox->addListener (this);
  39927. if (style == LinearBar)
  39928. valueBox->addMouseListener (this, false);
  39929. valueBox->setTooltip (getTooltip());
  39930. }
  39931. else
  39932. {
  39933. valueBox = 0;
  39934. }
  39935. if (style == IncDecButtons)
  39936. {
  39937. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39938. incButton->addListener (this);
  39939. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39940. decButton->addListener (this);
  39941. if (incDecButtonMode != incDecButtonsNotDraggable)
  39942. {
  39943. incButton->addMouseListener (this, false);
  39944. decButton->addMouseListener (this, false);
  39945. }
  39946. else
  39947. {
  39948. incButton->setRepeatSpeed (300, 100, 20);
  39949. incButton->addMouseListener (decButton, false);
  39950. decButton->setRepeatSpeed (300, 100, 20);
  39951. decButton->addMouseListener (incButton, false);
  39952. }
  39953. incButton->setTooltip (getTooltip());
  39954. decButton->setTooltip (getTooltip());
  39955. }
  39956. else
  39957. {
  39958. incButton = 0;
  39959. decButton = 0;
  39960. }
  39961. setComponentEffect (lf.getSliderEffect());
  39962. resized();
  39963. repaint();
  39964. }
  39965. void Slider::setRange (const double newMin,
  39966. const double newMax,
  39967. const double newInt)
  39968. {
  39969. if (minimum != newMin
  39970. || maximum != newMax
  39971. || interval != newInt)
  39972. {
  39973. minimum = newMin;
  39974. maximum = newMax;
  39975. interval = newInt;
  39976. // figure out the number of DPs needed to display all values at this
  39977. // interval setting.
  39978. numDecimalPlaces = 7;
  39979. if (newInt != 0)
  39980. {
  39981. int v = abs ((int) (newInt * 10000000));
  39982. while ((v % 10) == 0)
  39983. {
  39984. --numDecimalPlaces;
  39985. v /= 10;
  39986. }
  39987. }
  39988. // keep the current values inside the new range..
  39989. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39990. {
  39991. setValue (getValue(), false, false);
  39992. }
  39993. else
  39994. {
  39995. setMinValue (getMinValue(), false, false);
  39996. setMaxValue (getMaxValue(), false, false);
  39997. }
  39998. updateText();
  39999. }
  40000. }
  40001. void Slider::triggerChangeMessage (const bool synchronous)
  40002. {
  40003. if (synchronous)
  40004. handleAsyncUpdate();
  40005. else
  40006. triggerAsyncUpdate();
  40007. valueChanged();
  40008. }
  40009. void Slider::valueChanged (Value& value)
  40010. {
  40011. if (value.refersToSameSourceAs (currentValue))
  40012. {
  40013. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40014. setValue (currentValue.getValue(), false, false);
  40015. }
  40016. else if (value.refersToSameSourceAs (valueMin))
  40017. setMinValue (valueMin.getValue(), false, false, true);
  40018. else if (value.refersToSameSourceAs (valueMax))
  40019. setMaxValue (valueMax.getValue(), false, false, true);
  40020. }
  40021. double Slider::getValue() const
  40022. {
  40023. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40024. // methods to get the two values.
  40025. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40026. return currentValue.getValue();
  40027. }
  40028. void Slider::setValue (double newValue,
  40029. const bool sendUpdateMessage,
  40030. const bool sendMessageSynchronously)
  40031. {
  40032. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40033. // methods to set the two values.
  40034. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40035. newValue = constrainedValue (newValue);
  40036. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40037. {
  40038. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40039. newValue = jlimit ((double) valueMin.getValue(),
  40040. (double) valueMax.getValue(),
  40041. newValue);
  40042. }
  40043. if (newValue != lastCurrentValue)
  40044. {
  40045. if (valueBox != 0)
  40046. valueBox->hideEditor (true);
  40047. lastCurrentValue = newValue;
  40048. currentValue = newValue;
  40049. updateText();
  40050. repaint();
  40051. if (popupDisplay != 0)
  40052. {
  40053. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40054. ->updatePosition (getTextFromValue (newValue));
  40055. popupDisplay->repaint();
  40056. }
  40057. if (sendUpdateMessage)
  40058. triggerChangeMessage (sendMessageSynchronously);
  40059. }
  40060. }
  40061. double Slider::getMinValue() const
  40062. {
  40063. // The minimum value only applies to sliders that are in two- or three-value mode.
  40064. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40065. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40066. return valueMin.getValue();
  40067. }
  40068. double Slider::getMaxValue() const
  40069. {
  40070. // The maximum value only applies to sliders that are in two- or three-value mode.
  40071. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40072. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40073. return valueMax.getValue();
  40074. }
  40075. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40076. {
  40077. // The minimum value only applies to sliders that are in two- or three-value mode.
  40078. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40079. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40080. newValue = constrainedValue (newValue);
  40081. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40082. {
  40083. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40084. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40085. newValue = jmin ((double) valueMax.getValue(), newValue);
  40086. }
  40087. else
  40088. {
  40089. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40090. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40091. newValue = jmin (lastCurrentValue, newValue);
  40092. }
  40093. if (lastValueMin != newValue)
  40094. {
  40095. lastValueMin = newValue;
  40096. valueMin = newValue;
  40097. repaint();
  40098. if (popupDisplay != 0)
  40099. {
  40100. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40101. ->updatePosition (getTextFromValue (newValue));
  40102. popupDisplay->repaint();
  40103. }
  40104. if (sendUpdateMessage)
  40105. triggerChangeMessage (sendMessageSynchronously);
  40106. }
  40107. }
  40108. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40109. {
  40110. // The maximum value only applies to sliders that are in two- or three-value mode.
  40111. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40112. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40113. newValue = constrainedValue (newValue);
  40114. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40115. {
  40116. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40117. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40118. newValue = jmax ((double) valueMin.getValue(), newValue);
  40119. }
  40120. else
  40121. {
  40122. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40123. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40124. newValue = jmax (lastCurrentValue, newValue);
  40125. }
  40126. if (lastValueMax != newValue)
  40127. {
  40128. lastValueMax = newValue;
  40129. valueMax = newValue;
  40130. repaint();
  40131. if (popupDisplay != 0)
  40132. {
  40133. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40134. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40135. popupDisplay->repaint();
  40136. }
  40137. if (sendUpdateMessage)
  40138. triggerChangeMessage (sendMessageSynchronously);
  40139. }
  40140. }
  40141. void Slider::setMinAndMaxValues (double newMinValue, double newMaxValue, bool sendUpdateMessage, bool sendMessageSynchronously)
  40142. {
  40143. // The maximum value only applies to sliders that are in two- or three-value mode.
  40144. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40145. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40146. if (newMaxValue < newMinValue)
  40147. swapVariables (newMaxValue, newMinValue);
  40148. newMinValue = constrainedValue (newMinValue);
  40149. newMaxValue = constrainedValue (newMaxValue);
  40150. if (lastValueMax != newMaxValue || lastValueMin != newMinValue)
  40151. {
  40152. lastValueMax = newMaxValue;
  40153. lastValueMin = newMinValue;
  40154. valueMin = newMinValue;
  40155. valueMax = newMaxValue;
  40156. repaint();
  40157. if (sendUpdateMessage)
  40158. triggerChangeMessage (sendMessageSynchronously);
  40159. }
  40160. }
  40161. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40162. const double valueToSetOnDoubleClick)
  40163. {
  40164. doubleClickToValue = isDoubleClickEnabled;
  40165. doubleClickReturnValue = valueToSetOnDoubleClick;
  40166. }
  40167. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40168. {
  40169. isEnabled_ = doubleClickToValue;
  40170. return doubleClickReturnValue;
  40171. }
  40172. void Slider::updateText()
  40173. {
  40174. if (valueBox != 0)
  40175. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40176. }
  40177. void Slider::setTextValueSuffix (const String& suffix)
  40178. {
  40179. if (textSuffix != suffix)
  40180. {
  40181. textSuffix = suffix;
  40182. updateText();
  40183. }
  40184. }
  40185. const String Slider::getTextValueSuffix() const
  40186. {
  40187. return textSuffix;
  40188. }
  40189. const String Slider::getTextFromValue (double v)
  40190. {
  40191. if (getNumDecimalPlacesToDisplay() > 0)
  40192. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40193. else
  40194. return String (roundToInt (v)) + getTextValueSuffix();
  40195. }
  40196. double Slider::getValueFromText (const String& text)
  40197. {
  40198. String t (text.trimStart());
  40199. if (t.endsWith (textSuffix))
  40200. t = t.substring (0, t.length() - textSuffix.length());
  40201. while (t.startsWithChar ('+'))
  40202. t = t.substring (1).trimStart();
  40203. return t.initialSectionContainingOnly ("0123456789.,-")
  40204. .getDoubleValue();
  40205. }
  40206. double Slider::proportionOfLengthToValue (double proportion)
  40207. {
  40208. if (skewFactor != 1.0 && proportion > 0.0)
  40209. proportion = exp (log (proportion) / skewFactor);
  40210. return minimum + (maximum - minimum) * proportion;
  40211. }
  40212. double Slider::valueToProportionOfLength (double value)
  40213. {
  40214. const double n = (value - minimum) / (maximum - minimum);
  40215. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40216. }
  40217. double Slider::snapValue (double attemptedValue, const bool)
  40218. {
  40219. return attemptedValue;
  40220. }
  40221. void Slider::startedDragging()
  40222. {
  40223. }
  40224. void Slider::stoppedDragging()
  40225. {
  40226. }
  40227. void Slider::valueChanged()
  40228. {
  40229. }
  40230. void Slider::enablementChanged()
  40231. {
  40232. repaint();
  40233. }
  40234. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40235. {
  40236. menuEnabled = menuEnabled_;
  40237. }
  40238. void Slider::setScrollWheelEnabled (const bool enabled)
  40239. {
  40240. scrollWheelEnabled = enabled;
  40241. }
  40242. void Slider::labelTextChanged (Label* label)
  40243. {
  40244. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40245. if (newValue != (double) currentValue.getValue())
  40246. {
  40247. sendDragStart();
  40248. setValue (newValue, true, true);
  40249. sendDragEnd();
  40250. }
  40251. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40252. }
  40253. void Slider::buttonClicked (Button* button)
  40254. {
  40255. if (style == IncDecButtons)
  40256. {
  40257. sendDragStart();
  40258. if (button == incButton)
  40259. setValue (snapValue (getValue() + interval, false), true, true);
  40260. else if (button == decButton)
  40261. setValue (snapValue (getValue() - interval, false), true, true);
  40262. sendDragEnd();
  40263. }
  40264. }
  40265. double Slider::constrainedValue (double value) const
  40266. {
  40267. if (interval > 0)
  40268. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40269. if (value <= minimum || maximum <= minimum)
  40270. value = minimum;
  40271. else if (value >= maximum)
  40272. value = maximum;
  40273. return value;
  40274. }
  40275. float Slider::getLinearSliderPos (const double value)
  40276. {
  40277. double sliderPosProportional;
  40278. if (maximum > minimum)
  40279. {
  40280. if (value < minimum)
  40281. {
  40282. sliderPosProportional = 0.0;
  40283. }
  40284. else if (value > maximum)
  40285. {
  40286. sliderPosProportional = 1.0;
  40287. }
  40288. else
  40289. {
  40290. sliderPosProportional = valueToProportionOfLength (value);
  40291. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40292. }
  40293. }
  40294. else
  40295. {
  40296. sliderPosProportional = 0.5;
  40297. }
  40298. if (isVertical() || style == IncDecButtons)
  40299. sliderPosProportional = 1.0 - sliderPosProportional;
  40300. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40301. }
  40302. bool Slider::isHorizontal() const
  40303. {
  40304. return style == LinearHorizontal
  40305. || style == LinearBar
  40306. || style == TwoValueHorizontal
  40307. || style == ThreeValueHorizontal;
  40308. }
  40309. bool Slider::isVertical() const
  40310. {
  40311. return style == LinearVertical
  40312. || style == TwoValueVertical
  40313. || style == ThreeValueVertical;
  40314. }
  40315. bool Slider::incDecDragDirectionIsHorizontal() const
  40316. {
  40317. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40318. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40319. }
  40320. float Slider::getPositionOfValue (const double value)
  40321. {
  40322. if (isHorizontal() || isVertical())
  40323. {
  40324. return getLinearSliderPos (value);
  40325. }
  40326. else
  40327. {
  40328. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40329. return 0.0f;
  40330. }
  40331. }
  40332. void Slider::paint (Graphics& g)
  40333. {
  40334. if (style != IncDecButtons)
  40335. {
  40336. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40337. {
  40338. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40339. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40340. getLookAndFeel().drawRotarySlider (g,
  40341. sliderRect.getX(),
  40342. sliderRect.getY(),
  40343. sliderRect.getWidth(),
  40344. sliderRect.getHeight(),
  40345. sliderPos,
  40346. rotaryStart, rotaryEnd,
  40347. *this);
  40348. }
  40349. else
  40350. {
  40351. getLookAndFeel().drawLinearSlider (g,
  40352. sliderRect.getX(),
  40353. sliderRect.getY(),
  40354. sliderRect.getWidth(),
  40355. sliderRect.getHeight(),
  40356. getLinearSliderPos (lastCurrentValue),
  40357. getLinearSliderPos (lastValueMin),
  40358. getLinearSliderPos (lastValueMax),
  40359. style,
  40360. *this);
  40361. }
  40362. if (style == LinearBar && valueBox == 0)
  40363. {
  40364. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40365. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40366. }
  40367. }
  40368. }
  40369. void Slider::resized()
  40370. {
  40371. int minXSpace = 0;
  40372. int minYSpace = 0;
  40373. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40374. minXSpace = 30;
  40375. else
  40376. minYSpace = 15;
  40377. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40378. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40379. if (style == LinearBar)
  40380. {
  40381. if (valueBox != 0)
  40382. valueBox->setBounds (getLocalBounds());
  40383. }
  40384. else
  40385. {
  40386. if (textBoxPos == NoTextBox)
  40387. {
  40388. sliderRect = getLocalBounds();
  40389. }
  40390. else if (textBoxPos == TextBoxLeft)
  40391. {
  40392. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40393. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40394. }
  40395. else if (textBoxPos == TextBoxRight)
  40396. {
  40397. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40398. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40399. }
  40400. else if (textBoxPos == TextBoxAbove)
  40401. {
  40402. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40403. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40404. }
  40405. else if (textBoxPos == TextBoxBelow)
  40406. {
  40407. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40408. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40409. }
  40410. }
  40411. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40412. if (style == LinearBar)
  40413. {
  40414. const int barIndent = 1;
  40415. sliderRegionStart = barIndent;
  40416. sliderRegionSize = getWidth() - barIndent * 2;
  40417. sliderRect.setBounds (sliderRegionStart, barIndent,
  40418. sliderRegionSize, getHeight() - barIndent * 2);
  40419. }
  40420. else if (isHorizontal())
  40421. {
  40422. sliderRegionStart = sliderRect.getX() + indent;
  40423. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40424. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40425. sliderRegionSize, sliderRect.getHeight());
  40426. }
  40427. else if (isVertical())
  40428. {
  40429. sliderRegionStart = sliderRect.getY() + indent;
  40430. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40431. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40432. sliderRect.getWidth(), sliderRegionSize);
  40433. }
  40434. else
  40435. {
  40436. sliderRegionStart = 0;
  40437. sliderRegionSize = 100;
  40438. }
  40439. if (style == IncDecButtons)
  40440. {
  40441. Rectangle<int> buttonRect (sliderRect);
  40442. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40443. buttonRect.expand (-2, 0);
  40444. else
  40445. buttonRect.expand (0, -2);
  40446. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40447. if (incDecButtonsSideBySide)
  40448. {
  40449. decButton->setBounds (buttonRect.getX(),
  40450. buttonRect.getY(),
  40451. buttonRect.getWidth() / 2,
  40452. buttonRect.getHeight());
  40453. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40454. incButton->setBounds (buttonRect.getCentreX(),
  40455. buttonRect.getY(),
  40456. buttonRect.getWidth() / 2,
  40457. buttonRect.getHeight());
  40458. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40459. }
  40460. else
  40461. {
  40462. incButton->setBounds (buttonRect.getX(),
  40463. buttonRect.getY(),
  40464. buttonRect.getWidth(),
  40465. buttonRect.getHeight() / 2);
  40466. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40467. decButton->setBounds (buttonRect.getX(),
  40468. buttonRect.getCentreY(),
  40469. buttonRect.getWidth(),
  40470. buttonRect.getHeight() / 2);
  40471. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40472. }
  40473. }
  40474. }
  40475. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40476. {
  40477. repaint();
  40478. }
  40479. static void sliderMenuCallback (int result, Slider* slider)
  40480. {
  40481. if (slider != 0)
  40482. {
  40483. switch (result)
  40484. {
  40485. case 1: slider->setVelocityBasedMode (! slider->getVelocityBasedMode()); break;
  40486. case 2: slider->setSliderStyle (Slider::Rotary); break;
  40487. case 3: slider->setSliderStyle (Slider::RotaryHorizontalDrag); break;
  40488. case 4: slider->setSliderStyle (Slider::RotaryVerticalDrag); break;
  40489. default: break;
  40490. }
  40491. }
  40492. }
  40493. void Slider::mouseDown (const MouseEvent& e)
  40494. {
  40495. mouseWasHidden = false;
  40496. incDecDragged = false;
  40497. mouseXWhenLastDragged = e.x;
  40498. mouseYWhenLastDragged = e.y;
  40499. mouseDragStartX = e.getMouseDownX();
  40500. mouseDragStartY = e.getMouseDownY();
  40501. if (isEnabled())
  40502. {
  40503. if (e.mods.isPopupMenu() && menuEnabled)
  40504. {
  40505. menuShown = true;
  40506. PopupMenu m;
  40507. m.setLookAndFeel (&getLookAndFeel());
  40508. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40509. m.addSeparator();
  40510. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40511. {
  40512. PopupMenu rotaryMenu;
  40513. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40514. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40515. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40516. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40517. }
  40518. m.showMenuAsync (PopupMenu::Options(),
  40519. ModalCallbackFunction::forComponent (sliderMenuCallback, this));
  40520. }
  40521. else if (maximum > minimum)
  40522. {
  40523. menuShown = false;
  40524. if (valueBox != 0)
  40525. valueBox->hideEditor (true);
  40526. sliderBeingDragged = 0;
  40527. if (style == TwoValueHorizontal
  40528. || style == TwoValueVertical
  40529. || style == ThreeValueHorizontal
  40530. || style == ThreeValueVertical)
  40531. {
  40532. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40533. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40534. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40535. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40536. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40537. {
  40538. if (maxPosDistance <= minPosDistance)
  40539. sliderBeingDragged = 2;
  40540. else
  40541. sliderBeingDragged = 1;
  40542. }
  40543. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40544. {
  40545. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40546. sliderBeingDragged = 1;
  40547. else if (normalPosDistance >= maxPosDistance)
  40548. sliderBeingDragged = 2;
  40549. }
  40550. }
  40551. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40552. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40553. * valueToProportionOfLength (currentValue.getValue());
  40554. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40555. : ((sliderBeingDragged == 1) ? valueMin
  40556. : currentValue)).getValue();
  40557. valueOnMouseDown = valueWhenLastDragged;
  40558. if (popupDisplayEnabled)
  40559. {
  40560. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40561. popupDisplay = popup;
  40562. if (parentForPopupDisplay != 0)
  40563. {
  40564. parentForPopupDisplay->addChildComponent (popup);
  40565. }
  40566. else
  40567. {
  40568. popup->addToDesktop (0);
  40569. }
  40570. popup->setVisible (true);
  40571. }
  40572. sendDragStart();
  40573. mouseDrag (e);
  40574. }
  40575. }
  40576. }
  40577. void Slider::mouseUp (const MouseEvent&)
  40578. {
  40579. if (isEnabled()
  40580. && (! menuShown)
  40581. && (maximum > minimum)
  40582. && (style != IncDecButtons || incDecDragged))
  40583. {
  40584. restoreMouseIfHidden();
  40585. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40586. triggerChangeMessage (false);
  40587. sendDragEnd();
  40588. popupDisplay = 0;
  40589. if (style == IncDecButtons)
  40590. {
  40591. incButton->setState (Button::buttonNormal);
  40592. decButton->setState (Button::buttonNormal);
  40593. }
  40594. }
  40595. }
  40596. void Slider::restoreMouseIfHidden()
  40597. {
  40598. if (mouseWasHidden)
  40599. {
  40600. mouseWasHidden = false;
  40601. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40602. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40603. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40604. : ((sliderBeingDragged == 1) ? getMinValue()
  40605. : (double) currentValue.getValue());
  40606. Point<int> mousePos;
  40607. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40608. {
  40609. mousePos = Desktop::getLastMouseDownPosition();
  40610. if (style == RotaryHorizontalDrag)
  40611. {
  40612. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40613. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40614. }
  40615. else
  40616. {
  40617. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40618. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40619. }
  40620. }
  40621. else
  40622. {
  40623. const int pixelPos = (int) getLinearSliderPos (pos);
  40624. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40625. isVertical() ? pixelPos : (getHeight() / 2)));
  40626. }
  40627. Desktop::setMousePosition (mousePos);
  40628. }
  40629. }
  40630. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40631. {
  40632. if (isEnabled()
  40633. && style != IncDecButtons
  40634. && style != Rotary
  40635. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40636. {
  40637. restoreMouseIfHidden();
  40638. }
  40639. }
  40640. namespace SliderHelpers
  40641. {
  40642. double smallestAngleBetween (double a1, double a2) throw()
  40643. {
  40644. return jmin (std::abs (a1 - a2),
  40645. std::abs (a1 + double_Pi * 2.0 - a2),
  40646. std::abs (a2 + double_Pi * 2.0 - a1));
  40647. }
  40648. }
  40649. void Slider::mouseDrag (const MouseEvent& e)
  40650. {
  40651. if (isEnabled()
  40652. && (! menuShown)
  40653. && (maximum > minimum))
  40654. {
  40655. if (style == Rotary)
  40656. {
  40657. int dx = e.x - sliderRect.getCentreX();
  40658. int dy = e.y - sliderRect.getCentreY();
  40659. if (dx * dx + dy * dy > 25)
  40660. {
  40661. double angle = std::atan2 ((double) dx, (double) -dy);
  40662. while (angle < 0.0)
  40663. angle += double_Pi * 2.0;
  40664. if (rotaryStop && ! e.mouseWasClicked())
  40665. {
  40666. if (std::abs (angle - lastAngle) > double_Pi)
  40667. {
  40668. if (angle >= lastAngle)
  40669. angle -= double_Pi * 2.0;
  40670. else
  40671. angle += double_Pi * 2.0;
  40672. }
  40673. if (angle >= lastAngle)
  40674. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40675. else
  40676. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40677. }
  40678. else
  40679. {
  40680. while (angle < rotaryStart)
  40681. angle += double_Pi * 2.0;
  40682. if (angle > rotaryEnd)
  40683. {
  40684. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40685. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40686. angle = rotaryStart;
  40687. else
  40688. angle = rotaryEnd;
  40689. }
  40690. }
  40691. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40692. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40693. lastAngle = angle;
  40694. }
  40695. }
  40696. else
  40697. {
  40698. if (style == LinearBar && e.mouseWasClicked()
  40699. && valueBox != 0 && valueBox->isEditable())
  40700. return;
  40701. if (style == IncDecButtons && ! incDecDragged)
  40702. {
  40703. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40704. return;
  40705. incDecDragged = true;
  40706. mouseDragStartX = e.x;
  40707. mouseDragStartY = e.y;
  40708. }
  40709. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40710. : false))
  40711. || ((maximum - minimum) / sliderRegionSize < interval))
  40712. {
  40713. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40714. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40715. if (style == RotaryHorizontalDrag
  40716. || style == RotaryVerticalDrag
  40717. || style == IncDecButtons
  40718. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40719. && ! snapsToMousePos))
  40720. {
  40721. const int mouseDiff = (style == RotaryHorizontalDrag
  40722. || style == LinearHorizontal
  40723. || style == LinearBar
  40724. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40725. ? e.x - mouseDragStartX
  40726. : mouseDragStartY - e.y;
  40727. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40728. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40729. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40730. if (style == IncDecButtons)
  40731. {
  40732. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40733. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40734. }
  40735. }
  40736. else
  40737. {
  40738. if (isVertical())
  40739. scaledMousePos = 1.0 - scaledMousePos;
  40740. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40741. }
  40742. }
  40743. else
  40744. {
  40745. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40746. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40747. ? e.x - mouseXWhenLastDragged
  40748. : e.y - mouseYWhenLastDragged;
  40749. const double maxSpeed = jmax (200, sliderRegionSize);
  40750. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40751. if (speed != 0)
  40752. {
  40753. speed = 0.2 * velocityModeSensitivity
  40754. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40755. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40756. / maxSpeed))));
  40757. if (mouseDiff < 0)
  40758. speed = -speed;
  40759. if (isVertical() || style == RotaryVerticalDrag
  40760. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40761. speed = -speed;
  40762. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40763. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40764. e.source.enableUnboundedMouseMovement (true, false);
  40765. mouseWasHidden = true;
  40766. }
  40767. }
  40768. }
  40769. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40770. if (sliderBeingDragged == 0)
  40771. {
  40772. setValue (snapValue (valueWhenLastDragged, true),
  40773. ! sendChangeOnlyOnRelease, true);
  40774. }
  40775. else if (sliderBeingDragged == 1)
  40776. {
  40777. setMinValue (snapValue (valueWhenLastDragged, true),
  40778. ! sendChangeOnlyOnRelease, false, true);
  40779. if (e.mods.isShiftDown())
  40780. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40781. else
  40782. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40783. }
  40784. else
  40785. {
  40786. jassert (sliderBeingDragged == 2);
  40787. setMaxValue (snapValue (valueWhenLastDragged, true),
  40788. ! sendChangeOnlyOnRelease, false, true);
  40789. if (e.mods.isShiftDown())
  40790. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40791. else
  40792. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40793. }
  40794. mouseXWhenLastDragged = e.x;
  40795. mouseYWhenLastDragged = e.y;
  40796. }
  40797. }
  40798. void Slider::mouseDoubleClick (const MouseEvent&)
  40799. {
  40800. if (doubleClickToValue
  40801. && isEnabled()
  40802. && style != IncDecButtons
  40803. && minimum <= doubleClickReturnValue
  40804. && maximum >= doubleClickReturnValue)
  40805. {
  40806. sendDragStart();
  40807. setValue (doubleClickReturnValue, true, true);
  40808. sendDragEnd();
  40809. }
  40810. }
  40811. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40812. {
  40813. if (scrollWheelEnabled && isEnabled()
  40814. && style != TwoValueHorizontal
  40815. && style != TwoValueVertical)
  40816. {
  40817. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40818. {
  40819. if (valueBox != 0)
  40820. valueBox->hideEditor (false);
  40821. const double value = (double) currentValue.getValue();
  40822. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40823. const double currentPos = valueToProportionOfLength (value);
  40824. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40825. double delta = (newValue != value)
  40826. ? jmax (std::abs (newValue - value), interval) : 0;
  40827. if (value > newValue)
  40828. delta = -delta;
  40829. sendDragStart();
  40830. setValue (snapValue (value + delta, false), true, true);
  40831. sendDragEnd();
  40832. }
  40833. }
  40834. else
  40835. {
  40836. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40837. }
  40838. }
  40839. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40840. {
  40841. }
  40842. void SliderListener::sliderDragEnded (Slider*)
  40843. {
  40844. }
  40845. END_JUCE_NAMESPACE
  40846. /*** End of inlined file: juce_Slider.cpp ***/
  40847. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40848. BEGIN_JUCE_NAMESPACE
  40849. class DragOverlayComp : public Component
  40850. {
  40851. public:
  40852. DragOverlayComp (const Image& image_)
  40853. : image (image_)
  40854. {
  40855. image.duplicateIfShared();
  40856. image.multiplyAllAlphas (0.8f);
  40857. setAlwaysOnTop (true);
  40858. }
  40859. void paint (Graphics& g)
  40860. {
  40861. g.drawImageAt (image, 0, 0);
  40862. }
  40863. private:
  40864. Image image;
  40865. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40866. };
  40867. TableHeaderComponent::TableHeaderComponent()
  40868. : columnsChanged (false),
  40869. columnsResized (false),
  40870. sortChanged (false),
  40871. menuActive (true),
  40872. stretchToFit (false),
  40873. columnIdBeingResized (0),
  40874. columnIdBeingDragged (0),
  40875. columnIdUnderMouse (0),
  40876. lastDeliberateWidth (0)
  40877. {
  40878. }
  40879. TableHeaderComponent::~TableHeaderComponent()
  40880. {
  40881. dragOverlayComp = 0;
  40882. }
  40883. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40884. {
  40885. menuActive = hasMenu;
  40886. }
  40887. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40888. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40889. {
  40890. if (onlyCountVisibleColumns)
  40891. {
  40892. int num = 0;
  40893. for (int i = columns.size(); --i >= 0;)
  40894. if (columns.getUnchecked(i)->isVisible())
  40895. ++num;
  40896. return num;
  40897. }
  40898. else
  40899. {
  40900. return columns.size();
  40901. }
  40902. }
  40903. const String TableHeaderComponent::getColumnName (const int columnId) const
  40904. {
  40905. const ColumnInfo* const ci = getInfoForId (columnId);
  40906. return ci != 0 ? ci->name : String::empty;
  40907. }
  40908. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40909. {
  40910. ColumnInfo* const ci = getInfoForId (columnId);
  40911. if (ci != 0 && ci->name != newName)
  40912. {
  40913. ci->name = newName;
  40914. sendColumnsChanged();
  40915. }
  40916. }
  40917. void TableHeaderComponent::addColumn (const String& columnName,
  40918. const int columnId,
  40919. const int width,
  40920. const int minimumWidth,
  40921. const int maximumWidth,
  40922. const int propertyFlags,
  40923. const int insertIndex)
  40924. {
  40925. // can't have a duplicate or null ID!
  40926. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40927. jassert (width > 0);
  40928. ColumnInfo* const ci = new ColumnInfo();
  40929. ci->name = columnName;
  40930. ci->id = columnId;
  40931. ci->width = width;
  40932. ci->lastDeliberateWidth = width;
  40933. ci->minimumWidth = minimumWidth;
  40934. ci->maximumWidth = maximumWidth;
  40935. if (ci->maximumWidth < 0)
  40936. ci->maximumWidth = std::numeric_limits<int>::max();
  40937. jassert (ci->maximumWidth >= ci->minimumWidth);
  40938. ci->propertyFlags = propertyFlags;
  40939. columns.insert (insertIndex, ci);
  40940. sendColumnsChanged();
  40941. }
  40942. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40943. {
  40944. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40945. if (index >= 0)
  40946. {
  40947. columns.remove (index);
  40948. sortChanged = true;
  40949. sendColumnsChanged();
  40950. }
  40951. }
  40952. void TableHeaderComponent::removeAllColumns()
  40953. {
  40954. if (columns.size() > 0)
  40955. {
  40956. columns.clear();
  40957. sendColumnsChanged();
  40958. }
  40959. }
  40960. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40961. {
  40962. const int currentIndex = getIndexOfColumnId (columnId, false);
  40963. newIndex = visibleIndexToTotalIndex (newIndex);
  40964. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40965. {
  40966. columns.move (currentIndex, newIndex);
  40967. sendColumnsChanged();
  40968. }
  40969. }
  40970. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40971. {
  40972. const ColumnInfo* const ci = getInfoForId (columnId);
  40973. return ci != 0 ? ci->width : 0;
  40974. }
  40975. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40976. {
  40977. ColumnInfo* const ci = getInfoForId (columnId);
  40978. if (ci != 0 && ci->width != newWidth)
  40979. {
  40980. const int numColumns = getNumColumns (true);
  40981. ci->lastDeliberateWidth = ci->width
  40982. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40983. if (stretchToFit)
  40984. {
  40985. const int index = getIndexOfColumnId (columnId, true) + 1;
  40986. if (isPositiveAndBelow (index, numColumns))
  40987. {
  40988. const int x = getColumnPosition (index).getX();
  40989. if (lastDeliberateWidth == 0)
  40990. lastDeliberateWidth = getTotalWidth();
  40991. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40992. }
  40993. }
  40994. repaint();
  40995. columnsResized = true;
  40996. triggerAsyncUpdate();
  40997. }
  40998. }
  40999. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41000. {
  41001. int n = 0;
  41002. for (int i = 0; i < columns.size(); ++i)
  41003. {
  41004. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41005. {
  41006. if (columns.getUnchecked(i)->id == columnId)
  41007. return n;
  41008. ++n;
  41009. }
  41010. }
  41011. return -1;
  41012. }
  41013. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41014. {
  41015. if (onlyCountVisibleColumns)
  41016. index = visibleIndexToTotalIndex (index);
  41017. const ColumnInfo* const ci = columns [index];
  41018. return (ci != 0) ? ci->id : 0;
  41019. }
  41020. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41021. {
  41022. int x = 0, width = 0, n = 0;
  41023. for (int i = 0; i < columns.size(); ++i)
  41024. {
  41025. x += width;
  41026. if (columns.getUnchecked(i)->isVisible())
  41027. {
  41028. width = columns.getUnchecked(i)->width;
  41029. if (n++ == index)
  41030. break;
  41031. }
  41032. else
  41033. {
  41034. width = 0;
  41035. }
  41036. }
  41037. return Rectangle<int> (x, 0, width, getHeight());
  41038. }
  41039. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41040. {
  41041. if (xToFind >= 0)
  41042. {
  41043. int x = 0;
  41044. for (int i = 0; i < columns.size(); ++i)
  41045. {
  41046. const ColumnInfo* const ci = columns.getUnchecked(i);
  41047. if (ci->isVisible())
  41048. {
  41049. x += ci->width;
  41050. if (xToFind < x)
  41051. return ci->id;
  41052. }
  41053. }
  41054. }
  41055. return 0;
  41056. }
  41057. int TableHeaderComponent::getTotalWidth() const
  41058. {
  41059. int w = 0;
  41060. for (int i = columns.size(); --i >= 0;)
  41061. if (columns.getUnchecked(i)->isVisible())
  41062. w += columns.getUnchecked(i)->width;
  41063. return w;
  41064. }
  41065. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41066. {
  41067. stretchToFit = shouldStretchToFit;
  41068. lastDeliberateWidth = getTotalWidth();
  41069. resized();
  41070. }
  41071. bool TableHeaderComponent::isStretchToFitActive() const
  41072. {
  41073. return stretchToFit;
  41074. }
  41075. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41076. {
  41077. if (stretchToFit && getWidth() > 0
  41078. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41079. {
  41080. lastDeliberateWidth = targetTotalWidth;
  41081. resizeColumnsToFit (0, targetTotalWidth);
  41082. }
  41083. }
  41084. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41085. {
  41086. targetTotalWidth = jmax (targetTotalWidth, 0);
  41087. StretchableObjectResizer sor;
  41088. int i;
  41089. for (i = firstColumnIndex; i < columns.size(); ++i)
  41090. {
  41091. ColumnInfo* const ci = columns.getUnchecked(i);
  41092. if (ci->isVisible())
  41093. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41094. }
  41095. sor.resizeToFit (targetTotalWidth);
  41096. int visIndex = 0;
  41097. for (i = firstColumnIndex; i < columns.size(); ++i)
  41098. {
  41099. ColumnInfo* const ci = columns.getUnchecked(i);
  41100. if (ci->isVisible())
  41101. {
  41102. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41103. (int) std::floor (sor.getItemSize (visIndex++)));
  41104. if (newWidth != ci->width)
  41105. {
  41106. ci->width = newWidth;
  41107. repaint();
  41108. columnsResized = true;
  41109. triggerAsyncUpdate();
  41110. }
  41111. }
  41112. }
  41113. }
  41114. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41115. {
  41116. ColumnInfo* const ci = getInfoForId (columnId);
  41117. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41118. {
  41119. if (shouldBeVisible)
  41120. ci->propertyFlags |= visible;
  41121. else
  41122. ci->propertyFlags &= ~visible;
  41123. sendColumnsChanged();
  41124. resized();
  41125. }
  41126. }
  41127. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41128. {
  41129. const ColumnInfo* const ci = getInfoForId (columnId);
  41130. return ci != 0 && ci->isVisible();
  41131. }
  41132. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41133. {
  41134. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41135. {
  41136. for (int i = columns.size(); --i >= 0;)
  41137. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41138. ColumnInfo* const ci = getInfoForId (columnId);
  41139. if (ci != 0)
  41140. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41141. reSortTable();
  41142. }
  41143. }
  41144. int TableHeaderComponent::getSortColumnId() const
  41145. {
  41146. for (int i = columns.size(); --i >= 0;)
  41147. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41148. return columns.getUnchecked(i)->id;
  41149. return 0;
  41150. }
  41151. bool TableHeaderComponent::isSortedForwards() const
  41152. {
  41153. for (int i = columns.size(); --i >= 0;)
  41154. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41155. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41156. return true;
  41157. }
  41158. void TableHeaderComponent::reSortTable()
  41159. {
  41160. sortChanged = true;
  41161. repaint();
  41162. triggerAsyncUpdate();
  41163. }
  41164. const String TableHeaderComponent::toString() const
  41165. {
  41166. String s;
  41167. XmlElement doc ("TABLELAYOUT");
  41168. doc.setAttribute ("sortedCol", getSortColumnId());
  41169. doc.setAttribute ("sortForwards", isSortedForwards());
  41170. for (int i = 0; i < columns.size(); ++i)
  41171. {
  41172. const ColumnInfo* const ci = columns.getUnchecked (i);
  41173. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41174. e->setAttribute ("id", ci->id);
  41175. e->setAttribute ("visible", ci->isVisible());
  41176. e->setAttribute ("width", ci->width);
  41177. }
  41178. return doc.createDocument (String::empty, true, false);
  41179. }
  41180. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41181. {
  41182. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41183. int index = 0;
  41184. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41185. {
  41186. forEachXmlChildElement (*storedXml, col)
  41187. {
  41188. const int tabId = col->getIntAttribute ("id");
  41189. ColumnInfo* const ci = getInfoForId (tabId);
  41190. if (ci != 0)
  41191. {
  41192. columns.move (columns.indexOf (ci), index);
  41193. ci->width = col->getIntAttribute ("width");
  41194. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41195. }
  41196. ++index;
  41197. }
  41198. columnsResized = true;
  41199. sendColumnsChanged();
  41200. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41201. storedXml->getBoolAttribute ("sortForwards", true));
  41202. }
  41203. }
  41204. void TableHeaderComponent::addListener (Listener* const newListener)
  41205. {
  41206. listeners.addIfNotAlreadyThere (newListener);
  41207. }
  41208. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41209. {
  41210. listeners.removeValue (listenerToRemove);
  41211. }
  41212. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41213. {
  41214. const ColumnInfo* const ci = getInfoForId (columnId);
  41215. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41216. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41217. }
  41218. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41219. {
  41220. for (int i = 0; i < columns.size(); ++i)
  41221. {
  41222. const ColumnInfo* const ci = columns.getUnchecked(i);
  41223. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41224. menu.addItem (ci->id, ci->name,
  41225. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41226. isColumnVisible (ci->id));
  41227. }
  41228. }
  41229. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41230. {
  41231. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41232. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41233. }
  41234. void TableHeaderComponent::paint (Graphics& g)
  41235. {
  41236. LookAndFeel& lf = getLookAndFeel();
  41237. lf.drawTableHeaderBackground (g, *this);
  41238. const Rectangle<int> clip (g.getClipBounds());
  41239. int x = 0;
  41240. for (int i = 0; i < columns.size(); ++i)
  41241. {
  41242. const ColumnInfo* const ci = columns.getUnchecked(i);
  41243. if (ci->isVisible())
  41244. {
  41245. if (x + ci->width > clip.getX()
  41246. && (ci->id != columnIdBeingDragged
  41247. || dragOverlayComp == 0
  41248. || ! dragOverlayComp->isVisible()))
  41249. {
  41250. Graphics::ScopedSaveState ss (g);
  41251. g.setOrigin (x, 0);
  41252. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41253. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41254. ci->id == columnIdUnderMouse,
  41255. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41256. ci->propertyFlags);
  41257. }
  41258. x += ci->width;
  41259. if (x >= clip.getRight())
  41260. break;
  41261. }
  41262. }
  41263. }
  41264. void TableHeaderComponent::resized()
  41265. {
  41266. }
  41267. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41268. {
  41269. updateColumnUnderMouse (e.x, e.y);
  41270. }
  41271. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41272. {
  41273. updateColumnUnderMouse (e.x, e.y);
  41274. }
  41275. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41276. {
  41277. updateColumnUnderMouse (e.x, e.y);
  41278. }
  41279. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41280. {
  41281. repaint();
  41282. columnIdBeingResized = 0;
  41283. columnIdBeingDragged = 0;
  41284. if (columnIdUnderMouse != 0)
  41285. {
  41286. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41287. if (e.mods.isPopupMenu())
  41288. columnClicked (columnIdUnderMouse, e.mods);
  41289. }
  41290. if (menuActive && e.mods.isPopupMenu())
  41291. showColumnChooserMenu (columnIdUnderMouse);
  41292. }
  41293. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41294. {
  41295. if (columnIdBeingResized == 0
  41296. && columnIdBeingDragged == 0
  41297. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41298. {
  41299. dragOverlayComp = 0;
  41300. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41301. if (columnIdBeingResized != 0)
  41302. {
  41303. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41304. initialColumnWidth = ci->width;
  41305. }
  41306. else
  41307. {
  41308. beginDrag (e);
  41309. }
  41310. }
  41311. if (columnIdBeingResized != 0)
  41312. {
  41313. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41314. if (ci != 0)
  41315. {
  41316. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41317. initialColumnWidth + e.getDistanceFromDragStartX());
  41318. if (stretchToFit)
  41319. {
  41320. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41321. int minWidthOnRight = 0;
  41322. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41323. if (columns.getUnchecked (i)->isVisible())
  41324. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41325. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41326. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41327. }
  41328. setColumnWidth (columnIdBeingResized, w);
  41329. }
  41330. }
  41331. else if (columnIdBeingDragged != 0)
  41332. {
  41333. if (e.y >= -50 && e.y < getHeight() + 50)
  41334. {
  41335. if (dragOverlayComp != 0)
  41336. {
  41337. dragOverlayComp->setVisible (true);
  41338. dragOverlayComp->setBounds (jlimit (0,
  41339. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41340. e.x - draggingColumnOffset),
  41341. 0,
  41342. dragOverlayComp->getWidth(),
  41343. getHeight());
  41344. for (int i = columns.size(); --i >= 0;)
  41345. {
  41346. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41347. int newIndex = currentIndex;
  41348. if (newIndex > 0)
  41349. {
  41350. // if the previous column isn't draggable, we can't move our column
  41351. // past it, because that'd change the undraggable column's position..
  41352. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41353. if ((previous->propertyFlags & draggable) != 0)
  41354. {
  41355. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41356. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41357. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41358. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41359. {
  41360. --newIndex;
  41361. }
  41362. }
  41363. }
  41364. if (newIndex < columns.size() - 1)
  41365. {
  41366. // if the next column isn't draggable, we can't move our column
  41367. // past it, because that'd change the undraggable column's position..
  41368. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41369. if ((nextCol->propertyFlags & draggable) != 0)
  41370. {
  41371. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41372. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41373. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41374. > abs (dragOverlayComp->getRight() - rightOfNext))
  41375. {
  41376. ++newIndex;
  41377. }
  41378. }
  41379. }
  41380. if (newIndex != currentIndex)
  41381. moveColumn (columnIdBeingDragged, newIndex);
  41382. else
  41383. break;
  41384. }
  41385. }
  41386. }
  41387. else
  41388. {
  41389. endDrag (draggingColumnOriginalIndex);
  41390. }
  41391. }
  41392. }
  41393. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41394. {
  41395. if (columnIdBeingDragged == 0)
  41396. {
  41397. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41398. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41399. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41400. {
  41401. columnIdBeingDragged = 0;
  41402. }
  41403. else
  41404. {
  41405. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41406. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41407. const int temp = columnIdBeingDragged;
  41408. columnIdBeingDragged = 0;
  41409. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41410. columnIdBeingDragged = temp;
  41411. dragOverlayComp->setBounds (columnRect);
  41412. for (int i = listeners.size(); --i >= 0;)
  41413. {
  41414. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41415. i = jmin (i, listeners.size() - 1);
  41416. }
  41417. }
  41418. }
  41419. }
  41420. void TableHeaderComponent::endDrag (const int finalIndex)
  41421. {
  41422. if (columnIdBeingDragged != 0)
  41423. {
  41424. moveColumn (columnIdBeingDragged, finalIndex);
  41425. columnIdBeingDragged = 0;
  41426. repaint();
  41427. for (int i = listeners.size(); --i >= 0;)
  41428. {
  41429. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41430. i = jmin (i, listeners.size() - 1);
  41431. }
  41432. }
  41433. }
  41434. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41435. {
  41436. mouseDrag (e);
  41437. for (int i = columns.size(); --i >= 0;)
  41438. if (columns.getUnchecked (i)->isVisible())
  41439. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41440. columnIdBeingResized = 0;
  41441. repaint();
  41442. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41443. updateColumnUnderMouse (e.x, e.y);
  41444. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41445. columnClicked (columnIdUnderMouse, e.mods);
  41446. dragOverlayComp = 0;
  41447. }
  41448. const MouseCursor TableHeaderComponent::getMouseCursor()
  41449. {
  41450. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41451. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41452. return Component::getMouseCursor();
  41453. }
  41454. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41455. {
  41456. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41457. }
  41458. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41459. {
  41460. for (int i = columns.size(); --i >= 0;)
  41461. if (columns.getUnchecked(i)->id == id)
  41462. return columns.getUnchecked(i);
  41463. return 0;
  41464. }
  41465. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41466. {
  41467. int n = 0;
  41468. for (int i = 0; i < columns.size(); ++i)
  41469. {
  41470. if (columns.getUnchecked(i)->isVisible())
  41471. {
  41472. if (n == visibleIndex)
  41473. return i;
  41474. ++n;
  41475. }
  41476. }
  41477. return -1;
  41478. }
  41479. void TableHeaderComponent::sendColumnsChanged()
  41480. {
  41481. if (stretchToFit && lastDeliberateWidth > 0)
  41482. resizeAllColumnsToFit (lastDeliberateWidth);
  41483. repaint();
  41484. columnsChanged = true;
  41485. triggerAsyncUpdate();
  41486. }
  41487. void TableHeaderComponent::handleAsyncUpdate()
  41488. {
  41489. const bool changed = columnsChanged || sortChanged;
  41490. const bool sized = columnsResized || changed;
  41491. const bool sorted = sortChanged;
  41492. columnsChanged = false;
  41493. columnsResized = false;
  41494. sortChanged = false;
  41495. if (sorted)
  41496. {
  41497. for (int i = listeners.size(); --i >= 0;)
  41498. {
  41499. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41500. i = jmin (i, listeners.size() - 1);
  41501. }
  41502. }
  41503. if (changed)
  41504. {
  41505. for (int i = listeners.size(); --i >= 0;)
  41506. {
  41507. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41508. i = jmin (i, listeners.size() - 1);
  41509. }
  41510. }
  41511. if (sized)
  41512. {
  41513. for (int i = listeners.size(); --i >= 0;)
  41514. {
  41515. listeners.getUnchecked(i)->tableColumnsResized (this);
  41516. i = jmin (i, listeners.size() - 1);
  41517. }
  41518. }
  41519. }
  41520. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41521. {
  41522. if (isPositiveAndBelow (mouseX, getWidth()))
  41523. {
  41524. const int draggableDistance = 3;
  41525. int x = 0;
  41526. for (int i = 0; i < columns.size(); ++i)
  41527. {
  41528. const ColumnInfo* const ci = columns.getUnchecked(i);
  41529. if (ci->isVisible())
  41530. {
  41531. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41532. && (ci->propertyFlags & resizable) != 0)
  41533. return ci->id;
  41534. x += ci->width;
  41535. }
  41536. }
  41537. }
  41538. return 0;
  41539. }
  41540. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41541. {
  41542. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41543. ? getColumnIdAtX (x) : 0;
  41544. if (newCol != columnIdUnderMouse)
  41545. {
  41546. columnIdUnderMouse = newCol;
  41547. repaint();
  41548. }
  41549. }
  41550. static void tableHeaderMenuCallback (int result, TableHeaderComponent* tableHeader, int columnIdClicked)
  41551. {
  41552. if (tableHeader != 0 && result != 0)
  41553. tableHeader->reactToMenuItem (result, columnIdClicked);
  41554. }
  41555. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41556. {
  41557. PopupMenu m;
  41558. addMenuItems (m, columnIdClicked);
  41559. if (m.getNumItems() > 0)
  41560. {
  41561. m.setLookAndFeel (&getLookAndFeel());
  41562. m.showMenuAsync (PopupMenu::Options(),
  41563. ModalCallbackFunction::forComponent (tableHeaderMenuCallback, this, columnIdClicked));
  41564. }
  41565. }
  41566. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41567. {
  41568. }
  41569. END_JUCE_NAMESPACE
  41570. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41571. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41572. BEGIN_JUCE_NAMESPACE
  41573. class TableListRowComp : public Component,
  41574. public TooltipClient
  41575. {
  41576. public:
  41577. TableListRowComp (TableListBox& owner_)
  41578. : owner (owner_), row (-1), isSelected (false)
  41579. {
  41580. }
  41581. void paint (Graphics& g)
  41582. {
  41583. TableListBoxModel* const model = owner.getModel();
  41584. if (model != 0)
  41585. {
  41586. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41587. const TableHeaderComponent& header = owner.getHeader();
  41588. const int numColumns = header.getNumColumns (true);
  41589. for (int i = 0; i < numColumns; ++i)
  41590. {
  41591. if (columnComponents[i] == 0)
  41592. {
  41593. const int columnId = header.getColumnIdOfIndex (i, true);
  41594. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41595. Graphics::ScopedSaveState ss (g);
  41596. g.reduceClipRegion (columnRect);
  41597. g.setOrigin (columnRect.getX(), 0);
  41598. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41599. }
  41600. }
  41601. }
  41602. }
  41603. void update (const int newRow, const bool isNowSelected)
  41604. {
  41605. jassert (newRow >= 0);
  41606. if (newRow != row || isNowSelected != isSelected)
  41607. {
  41608. row = newRow;
  41609. isSelected = isNowSelected;
  41610. repaint();
  41611. }
  41612. TableListBoxModel* const model = owner.getModel();
  41613. if (model != 0 && row < owner.getNumRows())
  41614. {
  41615. const Identifier columnProperty ("_tableColumnId");
  41616. const int numColumns = owner.getHeader().getNumColumns (true);
  41617. for (int i = 0; i < numColumns; ++i)
  41618. {
  41619. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41620. Component* comp = columnComponents[i];
  41621. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41622. {
  41623. columnComponents.set (i, 0);
  41624. comp = 0;
  41625. }
  41626. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41627. columnComponents.set (i, comp, false);
  41628. if (comp != 0)
  41629. {
  41630. comp->getProperties().set (columnProperty, columnId);
  41631. addAndMakeVisible (comp);
  41632. resizeCustomComp (i);
  41633. }
  41634. }
  41635. columnComponents.removeRange (numColumns, columnComponents.size());
  41636. }
  41637. else
  41638. {
  41639. columnComponents.clear();
  41640. }
  41641. }
  41642. void resized()
  41643. {
  41644. for (int i = columnComponents.size(); --i >= 0;)
  41645. resizeCustomComp (i);
  41646. }
  41647. void resizeCustomComp (const int index)
  41648. {
  41649. Component* const c = columnComponents.getUnchecked (index);
  41650. if (c != 0)
  41651. c->setBounds (owner.getHeader().getColumnPosition (index)
  41652. .withY (0).withHeight (getHeight()));
  41653. }
  41654. void mouseDown (const MouseEvent& e)
  41655. {
  41656. isDragging = false;
  41657. selectRowOnMouseUp = false;
  41658. if (isEnabled())
  41659. {
  41660. if (! isSelected)
  41661. {
  41662. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  41663. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41664. if (columnId != 0 && owner.getModel() != 0)
  41665. owner.getModel()->cellClicked (row, columnId, e);
  41666. }
  41667. else
  41668. {
  41669. selectRowOnMouseUp = true;
  41670. }
  41671. }
  41672. }
  41673. void mouseDrag (const MouseEvent& e)
  41674. {
  41675. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41676. {
  41677. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41678. if (selectedRows.size() > 0)
  41679. {
  41680. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41681. if (dragDescription.isNotEmpty())
  41682. {
  41683. isDragging = true;
  41684. owner.startDragAndDrop (e, dragDescription);
  41685. }
  41686. }
  41687. }
  41688. }
  41689. void mouseUp (const MouseEvent& e)
  41690. {
  41691. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41692. {
  41693. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  41694. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41695. if (columnId != 0 && owner.getModel() != 0)
  41696. owner.getModel()->cellClicked (row, columnId, e);
  41697. }
  41698. }
  41699. void mouseDoubleClick (const MouseEvent& e)
  41700. {
  41701. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41702. if (columnId != 0 && owner.getModel() != 0)
  41703. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41704. }
  41705. const String getTooltip()
  41706. {
  41707. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41708. if (columnId != 0 && owner.getModel() != 0)
  41709. return owner.getModel()->getCellTooltip (row, columnId);
  41710. return String::empty;
  41711. }
  41712. Component* findChildComponentForColumn (const int columnId) const
  41713. {
  41714. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41715. }
  41716. private:
  41717. TableListBox& owner;
  41718. OwnedArray<Component> columnComponents;
  41719. int row;
  41720. bool isSelected, isDragging, selectRowOnMouseUp;
  41721. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41722. };
  41723. class TableListBoxHeader : public TableHeaderComponent
  41724. {
  41725. public:
  41726. TableListBoxHeader (TableListBox& owner_)
  41727. : owner (owner_)
  41728. {
  41729. }
  41730. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41731. {
  41732. if (owner.isAutoSizeMenuOptionShown())
  41733. {
  41734. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41735. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41736. menu.addSeparator();
  41737. }
  41738. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41739. }
  41740. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41741. {
  41742. switch (menuReturnId)
  41743. {
  41744. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41745. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41746. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41747. }
  41748. }
  41749. private:
  41750. TableListBox& owner;
  41751. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41752. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41753. };
  41754. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41755. : ListBox (name, 0),
  41756. header (0), model (model_),
  41757. autoSizeOptionsShown (true)
  41758. {
  41759. ListBox::model = this;
  41760. setHeader (new TableListBoxHeader (*this));
  41761. }
  41762. TableListBox::~TableListBox()
  41763. {
  41764. header = 0;
  41765. }
  41766. void TableListBox::setModel (TableListBoxModel* const newModel)
  41767. {
  41768. if (model != newModel)
  41769. {
  41770. model = newModel;
  41771. updateContent();
  41772. }
  41773. }
  41774. void TableListBox::setHeader (TableHeaderComponent* newHeader)
  41775. {
  41776. jassert (newHeader != 0); // you need to supply a real header for a table!
  41777. Rectangle<int> newBounds (0, 0, 100, 28);
  41778. if (header != 0)
  41779. newBounds = header->getBounds();
  41780. header = newHeader;
  41781. header->setBounds (newBounds);
  41782. setHeaderComponent (header);
  41783. header->addListener (this);
  41784. }
  41785. int TableListBox::getHeaderHeight() const
  41786. {
  41787. return header->getHeight();
  41788. }
  41789. void TableListBox::setHeaderHeight (const int newHeight)
  41790. {
  41791. header->setSize (header->getWidth(), newHeight);
  41792. resized();
  41793. }
  41794. void TableListBox::autoSizeColumn (const int columnId)
  41795. {
  41796. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41797. if (width > 0)
  41798. header->setColumnWidth (columnId, width);
  41799. }
  41800. void TableListBox::autoSizeAllColumns()
  41801. {
  41802. for (int i = 0; i < header->getNumColumns (true); ++i)
  41803. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41804. }
  41805. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41806. {
  41807. autoSizeOptionsShown = shouldBeShown;
  41808. }
  41809. bool TableListBox::isAutoSizeMenuOptionShown() const
  41810. {
  41811. return autoSizeOptionsShown;
  41812. }
  41813. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41814. const bool relativeToComponentTopLeft) const
  41815. {
  41816. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41817. if (relativeToComponentTopLeft)
  41818. headerCell.translate (header->getX(), 0);
  41819. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41820. .withX (headerCell.getX())
  41821. .withWidth (headerCell.getWidth());
  41822. }
  41823. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41824. {
  41825. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41826. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41827. }
  41828. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41829. {
  41830. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41831. if (scrollbar != 0)
  41832. {
  41833. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41834. double x = scrollbar->getCurrentRangeStart();
  41835. const double w = scrollbar->getCurrentRangeSize();
  41836. if (pos.getX() < x)
  41837. x = pos.getX();
  41838. else if (pos.getRight() > x + w)
  41839. x += jmax (0.0, pos.getRight() - (x + w));
  41840. scrollbar->setCurrentRangeStart (x);
  41841. }
  41842. }
  41843. int TableListBox::getNumRows()
  41844. {
  41845. return model != 0 ? model->getNumRows() : 0;
  41846. }
  41847. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41848. {
  41849. }
  41850. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41851. {
  41852. if (existingComponentToUpdate == 0)
  41853. existingComponentToUpdate = new TableListRowComp (*this);
  41854. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41855. return existingComponentToUpdate;
  41856. }
  41857. void TableListBox::selectedRowsChanged (int row)
  41858. {
  41859. if (model != 0)
  41860. model->selectedRowsChanged (row);
  41861. }
  41862. void TableListBox::deleteKeyPressed (int row)
  41863. {
  41864. if (model != 0)
  41865. model->deleteKeyPressed (row);
  41866. }
  41867. void TableListBox::returnKeyPressed (int row)
  41868. {
  41869. if (model != 0)
  41870. model->returnKeyPressed (row);
  41871. }
  41872. void TableListBox::backgroundClicked()
  41873. {
  41874. if (model != 0)
  41875. model->backgroundClicked();
  41876. }
  41877. void TableListBox::listWasScrolled()
  41878. {
  41879. if (model != 0)
  41880. model->listWasScrolled();
  41881. }
  41882. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41883. {
  41884. setMinimumContentWidth (header->getTotalWidth());
  41885. repaint();
  41886. updateColumnComponents();
  41887. }
  41888. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41889. {
  41890. setMinimumContentWidth (header->getTotalWidth());
  41891. repaint();
  41892. updateColumnComponents();
  41893. }
  41894. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41895. {
  41896. if (model != 0)
  41897. model->sortOrderChanged (header->getSortColumnId(),
  41898. header->isSortedForwards());
  41899. }
  41900. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41901. {
  41902. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41903. repaint();
  41904. }
  41905. void TableListBox::resized()
  41906. {
  41907. ListBox::resized();
  41908. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41909. setMinimumContentWidth (header->getTotalWidth());
  41910. }
  41911. void TableListBox::updateColumnComponents() const
  41912. {
  41913. const int firstRow = getRowContainingPosition (0, 0);
  41914. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41915. {
  41916. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41917. if (rowComp != 0)
  41918. rowComp->resized();
  41919. }
  41920. }
  41921. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  41922. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  41923. void TableListBoxModel::backgroundClicked() {}
  41924. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  41925. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  41926. void TableListBoxModel::selectedRowsChanged (int) {}
  41927. void TableListBoxModel::deleteKeyPressed (int) {}
  41928. void TableListBoxModel::returnKeyPressed (int) {}
  41929. void TableListBoxModel::listWasScrolled() {}
  41930. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  41931. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  41932. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41933. {
  41934. (void) existingComponentToUpdate;
  41935. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41936. return 0;
  41937. }
  41938. END_JUCE_NAMESPACE
  41939. /*** End of inlined file: juce_TableListBox.cpp ***/
  41940. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41941. BEGIN_JUCE_NAMESPACE
  41942. // a word or space that can't be broken down any further
  41943. struct TextAtom
  41944. {
  41945. String atomText;
  41946. float width;
  41947. int numChars;
  41948. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41949. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41950. const String getText (const juce_wchar passwordCharacter) const
  41951. {
  41952. if (passwordCharacter == 0)
  41953. return atomText;
  41954. else
  41955. return String::repeatedString (String::charToString (passwordCharacter),
  41956. atomText.length());
  41957. }
  41958. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41959. {
  41960. if (passwordCharacter == 0)
  41961. return atomText.substring (0, numChars);
  41962. else if (isNewLine())
  41963. return String::empty;
  41964. else
  41965. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41966. }
  41967. };
  41968. // a run of text with a single font and colour
  41969. class TextEditor::UniformTextSection
  41970. {
  41971. public:
  41972. UniformTextSection (const String& text,
  41973. const Font& font_,
  41974. const Colour& colour_,
  41975. const juce_wchar passwordCharacter)
  41976. : font (font_),
  41977. colour (colour_)
  41978. {
  41979. initialiseAtoms (text, passwordCharacter);
  41980. }
  41981. UniformTextSection (const UniformTextSection& other)
  41982. : font (other.font),
  41983. colour (other.colour)
  41984. {
  41985. atoms.ensureStorageAllocated (other.atoms.size());
  41986. for (int i = 0; i < other.atoms.size(); ++i)
  41987. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41988. }
  41989. ~UniformTextSection()
  41990. {
  41991. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41992. }
  41993. void clear()
  41994. {
  41995. for (int i = atoms.size(); --i >= 0;)
  41996. delete getAtom(i);
  41997. atoms.clear();
  41998. }
  41999. int getNumAtoms() const
  42000. {
  42001. return atoms.size();
  42002. }
  42003. TextAtom* getAtom (const int index) const throw()
  42004. {
  42005. return atoms.getUnchecked (index);
  42006. }
  42007. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42008. {
  42009. if (other.atoms.size() > 0)
  42010. {
  42011. TextAtom* const lastAtom = atoms.getLast();
  42012. int i = 0;
  42013. if (lastAtom != 0)
  42014. {
  42015. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42016. {
  42017. TextAtom* const first = other.getAtom(0);
  42018. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42019. {
  42020. lastAtom->atomText += first->atomText;
  42021. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42022. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42023. delete first;
  42024. ++i;
  42025. }
  42026. }
  42027. }
  42028. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42029. while (i < other.atoms.size())
  42030. {
  42031. atoms.add (other.getAtom(i));
  42032. ++i;
  42033. }
  42034. }
  42035. }
  42036. UniformTextSection* split (const int indexToBreakAt,
  42037. const juce_wchar passwordCharacter)
  42038. {
  42039. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42040. font, colour,
  42041. passwordCharacter);
  42042. int index = 0;
  42043. for (int i = 0; i < atoms.size(); ++i)
  42044. {
  42045. TextAtom* const atom = getAtom(i);
  42046. const int nextIndex = index + atom->numChars;
  42047. if (index == indexToBreakAt)
  42048. {
  42049. int j;
  42050. for (j = i; j < atoms.size(); ++j)
  42051. section2->atoms.add (getAtom (j));
  42052. for (j = atoms.size(); --j >= i;)
  42053. atoms.remove (j);
  42054. break;
  42055. }
  42056. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42057. {
  42058. TextAtom* const secondAtom = new TextAtom();
  42059. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42060. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42061. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42062. section2->atoms.add (secondAtom);
  42063. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42064. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42065. atom->numChars = (uint16) (indexToBreakAt - index);
  42066. int j;
  42067. for (j = i + 1; j < atoms.size(); ++j)
  42068. section2->atoms.add (getAtom (j));
  42069. for (j = atoms.size(); --j > i;)
  42070. atoms.remove (j);
  42071. break;
  42072. }
  42073. index = nextIndex;
  42074. }
  42075. return section2;
  42076. }
  42077. void appendAllText (String::Concatenator& concatenator) const
  42078. {
  42079. for (int i = 0; i < atoms.size(); ++i)
  42080. concatenator.append (getAtom(i)->atomText);
  42081. }
  42082. void appendSubstring (String::Concatenator& concatenator,
  42083. const Range<int>& range) const
  42084. {
  42085. int index = 0;
  42086. for (int i = 0; i < atoms.size(); ++i)
  42087. {
  42088. const TextAtom* const atom = getAtom (i);
  42089. const int nextIndex = index + atom->numChars;
  42090. if (range.getStart() < nextIndex)
  42091. {
  42092. if (range.getEnd() <= index)
  42093. break;
  42094. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42095. if (! r.isEmpty())
  42096. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42097. }
  42098. index = nextIndex;
  42099. }
  42100. }
  42101. int getTotalLength() const
  42102. {
  42103. int total = 0;
  42104. for (int i = atoms.size(); --i >= 0;)
  42105. total += getAtom(i)->numChars;
  42106. return total;
  42107. }
  42108. void setFont (const Font& newFont,
  42109. const juce_wchar passwordCharacter)
  42110. {
  42111. if (font != newFont)
  42112. {
  42113. font = newFont;
  42114. for (int i = atoms.size(); --i >= 0;)
  42115. {
  42116. TextAtom* const atom = atoms.getUnchecked(i);
  42117. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42118. }
  42119. }
  42120. }
  42121. Font font;
  42122. Colour colour;
  42123. private:
  42124. Array <TextAtom*> atoms;
  42125. void initialiseAtoms (const String& textToParse,
  42126. const juce_wchar passwordCharacter)
  42127. {
  42128. String::CharPointerType text (textToParse.getCharPointer());
  42129. while (! text.isEmpty())
  42130. {
  42131. int numChars = 0;
  42132. String::CharPointerType start (text);
  42133. // create a whitespace atom unless it starts with non-ws
  42134. if (text.isWhitespace() && *text != '\r' && *text != '\n')
  42135. {
  42136. do
  42137. {
  42138. ++text;
  42139. ++numChars;
  42140. }
  42141. while (text.isWhitespace() && *text != '\r' && *text != '\n');
  42142. }
  42143. else
  42144. {
  42145. if (*text == '\r')
  42146. {
  42147. ++text;
  42148. ++numChars;
  42149. if (*text == '\n')
  42150. {
  42151. ++start;
  42152. ++text;
  42153. }
  42154. }
  42155. else if (*text == '\n')
  42156. {
  42157. ++text;
  42158. ++numChars;
  42159. }
  42160. else
  42161. {
  42162. while (! (text.isEmpty() || text.isWhitespace()))
  42163. {
  42164. ++text;
  42165. ++numChars;
  42166. }
  42167. }
  42168. }
  42169. TextAtom* const atom = new TextAtom();
  42170. atom->atomText = String (start, numChars);
  42171. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42172. atom->numChars = (uint16) numChars;
  42173. atoms.add (atom);
  42174. }
  42175. }
  42176. UniformTextSection& operator= (const UniformTextSection& other);
  42177. JUCE_LEAK_DETECTOR (UniformTextSection);
  42178. };
  42179. class TextEditor::Iterator
  42180. {
  42181. public:
  42182. Iterator (const Array <UniformTextSection*>& sections_,
  42183. const float wordWrapWidth_,
  42184. const juce_wchar passwordCharacter_)
  42185. : indexInText (0),
  42186. lineY (0),
  42187. lineHeight (0),
  42188. maxDescent (0),
  42189. atomX (0),
  42190. atomRight (0),
  42191. atom (0),
  42192. currentSection (0),
  42193. sections (sections_),
  42194. sectionIndex (0),
  42195. atomIndex (0),
  42196. wordWrapWidth (wordWrapWidth_),
  42197. passwordCharacter (passwordCharacter_)
  42198. {
  42199. jassert (wordWrapWidth_ > 0);
  42200. if (sections.size() > 0)
  42201. {
  42202. currentSection = sections.getUnchecked (sectionIndex);
  42203. if (currentSection != 0)
  42204. beginNewLine();
  42205. }
  42206. }
  42207. Iterator (const Iterator& other)
  42208. : indexInText (other.indexInText),
  42209. lineY (other.lineY),
  42210. lineHeight (other.lineHeight),
  42211. maxDescent (other.maxDescent),
  42212. atomX (other.atomX),
  42213. atomRight (other.atomRight),
  42214. atom (other.atom),
  42215. currentSection (other.currentSection),
  42216. sections (other.sections),
  42217. sectionIndex (other.sectionIndex),
  42218. atomIndex (other.atomIndex),
  42219. wordWrapWidth (other.wordWrapWidth),
  42220. passwordCharacter (other.passwordCharacter),
  42221. tempAtom (other.tempAtom)
  42222. {
  42223. }
  42224. bool next()
  42225. {
  42226. if (atom == &tempAtom)
  42227. {
  42228. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42229. if (numRemaining > 0)
  42230. {
  42231. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42232. atomX = 0;
  42233. if (tempAtom.numChars > 0)
  42234. lineY += lineHeight;
  42235. indexInText += tempAtom.numChars;
  42236. GlyphArrangement g;
  42237. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42238. int split;
  42239. for (split = 0; split < g.getNumGlyphs(); ++split)
  42240. if (shouldWrap (g.getGlyph (split).getRight()))
  42241. break;
  42242. if (split > 0 && split <= numRemaining)
  42243. {
  42244. tempAtom.numChars = (uint16) split;
  42245. tempAtom.width = g.getGlyph (split - 1).getRight();
  42246. atomRight = atomX + tempAtom.width;
  42247. return true;
  42248. }
  42249. }
  42250. }
  42251. bool forceNewLine = false;
  42252. if (sectionIndex >= sections.size())
  42253. {
  42254. moveToEndOfLastAtom();
  42255. return false;
  42256. }
  42257. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42258. {
  42259. if (atomIndex >= currentSection->getNumAtoms())
  42260. {
  42261. if (++sectionIndex >= sections.size())
  42262. {
  42263. moveToEndOfLastAtom();
  42264. return false;
  42265. }
  42266. atomIndex = 0;
  42267. currentSection = sections.getUnchecked (sectionIndex);
  42268. }
  42269. else
  42270. {
  42271. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42272. if (! lastAtom->isWhitespace())
  42273. {
  42274. // handle the case where the last atom in a section is actually part of the same
  42275. // word as the first atom of the next section...
  42276. float right = atomRight + lastAtom->width;
  42277. float lineHeight2 = lineHeight;
  42278. float maxDescent2 = maxDescent;
  42279. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42280. {
  42281. const UniformTextSection* const s = sections.getUnchecked (section);
  42282. if (s->getNumAtoms() == 0)
  42283. break;
  42284. const TextAtom* const nextAtom = s->getAtom (0);
  42285. if (nextAtom->isWhitespace())
  42286. break;
  42287. right += nextAtom->width;
  42288. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42289. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42290. if (shouldWrap (right))
  42291. {
  42292. lineHeight = lineHeight2;
  42293. maxDescent = maxDescent2;
  42294. forceNewLine = true;
  42295. break;
  42296. }
  42297. if (s->getNumAtoms() > 1)
  42298. break;
  42299. }
  42300. }
  42301. }
  42302. }
  42303. if (atom != 0)
  42304. {
  42305. atomX = atomRight;
  42306. indexInText += atom->numChars;
  42307. if (atom->isNewLine())
  42308. beginNewLine();
  42309. }
  42310. atom = currentSection->getAtom (atomIndex);
  42311. atomRight = atomX + atom->width;
  42312. ++atomIndex;
  42313. if (shouldWrap (atomRight) || forceNewLine)
  42314. {
  42315. if (atom->isWhitespace())
  42316. {
  42317. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42318. atomRight = jmin (atomRight, wordWrapWidth);
  42319. }
  42320. else
  42321. {
  42322. atomRight = atom->width;
  42323. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42324. {
  42325. tempAtom = *atom;
  42326. tempAtom.width = 0;
  42327. tempAtom.numChars = 0;
  42328. atom = &tempAtom;
  42329. if (atomX > 0)
  42330. beginNewLine();
  42331. return next();
  42332. }
  42333. beginNewLine();
  42334. return true;
  42335. }
  42336. }
  42337. return true;
  42338. }
  42339. void beginNewLine()
  42340. {
  42341. atomX = 0;
  42342. lineY += lineHeight;
  42343. int tempSectionIndex = sectionIndex;
  42344. int tempAtomIndex = atomIndex;
  42345. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42346. lineHeight = section->font.getHeight();
  42347. maxDescent = section->font.getDescent();
  42348. float x = (atom != 0) ? atom->width : 0;
  42349. while (! shouldWrap (x))
  42350. {
  42351. if (tempSectionIndex >= sections.size())
  42352. break;
  42353. bool checkSize = false;
  42354. if (tempAtomIndex >= section->getNumAtoms())
  42355. {
  42356. if (++tempSectionIndex >= sections.size())
  42357. break;
  42358. tempAtomIndex = 0;
  42359. section = sections.getUnchecked (tempSectionIndex);
  42360. checkSize = true;
  42361. }
  42362. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42363. if (nextAtom == 0)
  42364. break;
  42365. x += nextAtom->width;
  42366. if (shouldWrap (x) || nextAtom->isNewLine())
  42367. break;
  42368. if (checkSize)
  42369. {
  42370. lineHeight = jmax (lineHeight, section->font.getHeight());
  42371. maxDescent = jmax (maxDescent, section->font.getDescent());
  42372. }
  42373. ++tempAtomIndex;
  42374. }
  42375. }
  42376. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42377. {
  42378. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42379. {
  42380. if (lastSection != currentSection)
  42381. {
  42382. lastSection = currentSection;
  42383. g.setColour (currentSection->colour);
  42384. g.setFont (currentSection->font);
  42385. }
  42386. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42387. GlyphArrangement ga;
  42388. ga.addLineOfText (currentSection->font,
  42389. atom->getTrimmedText (passwordCharacter),
  42390. atomX,
  42391. (float) roundToInt (lineY + lineHeight - maxDescent));
  42392. ga.draw (g);
  42393. }
  42394. }
  42395. void drawSelection (Graphics& g,
  42396. const Range<int>& selection) const
  42397. {
  42398. const int startX = roundToInt (indexToX (selection.getStart()));
  42399. const int endX = roundToInt (indexToX (selection.getEnd()));
  42400. const int y = roundToInt (lineY);
  42401. const int nextY = roundToInt (lineY + lineHeight);
  42402. g.fillRect (startX, y, endX - startX, nextY - y);
  42403. }
  42404. void drawSelectedText (Graphics& g,
  42405. const Range<int>& selection,
  42406. const Colour& selectedTextColour) const
  42407. {
  42408. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42409. {
  42410. GlyphArrangement ga;
  42411. ga.addLineOfText (currentSection->font,
  42412. atom->getTrimmedText (passwordCharacter),
  42413. atomX,
  42414. (float) roundToInt (lineY + lineHeight - maxDescent));
  42415. if (selection.getEnd() < indexInText + atom->numChars)
  42416. {
  42417. GlyphArrangement ga2 (ga);
  42418. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42419. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42420. g.setColour (currentSection->colour);
  42421. ga2.draw (g);
  42422. }
  42423. if (selection.getStart() > indexInText)
  42424. {
  42425. GlyphArrangement ga2 (ga);
  42426. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42427. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42428. g.setColour (currentSection->colour);
  42429. ga2.draw (g);
  42430. }
  42431. g.setColour (selectedTextColour);
  42432. ga.draw (g);
  42433. }
  42434. }
  42435. float indexToX (const int indexToFind) const
  42436. {
  42437. if (indexToFind <= indexInText)
  42438. return atomX;
  42439. if (indexToFind >= indexInText + atom->numChars)
  42440. return atomRight;
  42441. GlyphArrangement g;
  42442. g.addLineOfText (currentSection->font,
  42443. atom->getText (passwordCharacter),
  42444. atomX, 0.0f);
  42445. if (indexToFind - indexInText >= g.getNumGlyphs())
  42446. return atomRight;
  42447. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42448. }
  42449. int xToIndex (const float xToFind) const
  42450. {
  42451. if (xToFind <= atomX || atom->isNewLine())
  42452. return indexInText;
  42453. if (xToFind >= atomRight)
  42454. return indexInText + atom->numChars;
  42455. GlyphArrangement g;
  42456. g.addLineOfText (currentSection->font,
  42457. atom->getText (passwordCharacter),
  42458. atomX, 0.0f);
  42459. int j;
  42460. for (j = 0; j < g.getNumGlyphs(); ++j)
  42461. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42462. break;
  42463. return indexInText + j;
  42464. }
  42465. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42466. {
  42467. while (next())
  42468. {
  42469. if (indexInText + atom->numChars > index)
  42470. {
  42471. cx = indexToX (index);
  42472. cy = lineY;
  42473. lineHeight_ = lineHeight;
  42474. return true;
  42475. }
  42476. }
  42477. cx = atomX;
  42478. cy = lineY;
  42479. lineHeight_ = lineHeight;
  42480. return false;
  42481. }
  42482. int indexInText;
  42483. float lineY, lineHeight, maxDescent;
  42484. float atomX, atomRight;
  42485. const TextAtom* atom;
  42486. const UniformTextSection* currentSection;
  42487. private:
  42488. const Array <UniformTextSection*>& sections;
  42489. int sectionIndex, atomIndex;
  42490. const float wordWrapWidth;
  42491. const juce_wchar passwordCharacter;
  42492. TextAtom tempAtom;
  42493. Iterator& operator= (const Iterator&);
  42494. void moveToEndOfLastAtom()
  42495. {
  42496. if (atom != 0)
  42497. {
  42498. atomX = atomRight;
  42499. if (atom->isNewLine())
  42500. {
  42501. atomX = 0.0f;
  42502. lineY += lineHeight;
  42503. }
  42504. }
  42505. }
  42506. bool shouldWrap (const float x) const
  42507. {
  42508. return (x - 0.0001f) >= wordWrapWidth;
  42509. }
  42510. JUCE_LEAK_DETECTOR (Iterator);
  42511. };
  42512. class TextEditor::InsertAction : public UndoableAction
  42513. {
  42514. public:
  42515. InsertAction (TextEditor& owner_,
  42516. const String& text_,
  42517. const int insertIndex_,
  42518. const Font& font_,
  42519. const Colour& colour_,
  42520. const int oldCaretPos_,
  42521. const int newCaretPos_)
  42522. : owner (owner_),
  42523. text (text_),
  42524. insertIndex (insertIndex_),
  42525. oldCaretPos (oldCaretPos_),
  42526. newCaretPos (newCaretPos_),
  42527. font (font_),
  42528. colour (colour_)
  42529. {
  42530. }
  42531. bool perform()
  42532. {
  42533. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42534. return true;
  42535. }
  42536. bool undo()
  42537. {
  42538. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42539. return true;
  42540. }
  42541. int getSizeInUnits()
  42542. {
  42543. return text.length() + 16;
  42544. }
  42545. private:
  42546. TextEditor& owner;
  42547. const String text;
  42548. const int insertIndex, oldCaretPos, newCaretPos;
  42549. const Font font;
  42550. const Colour colour;
  42551. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42552. };
  42553. class TextEditor::RemoveAction : public UndoableAction
  42554. {
  42555. public:
  42556. RemoveAction (TextEditor& owner_,
  42557. const Range<int> range_,
  42558. const int oldCaretPos_,
  42559. const int newCaretPos_,
  42560. const Array <UniformTextSection*>& removedSections_)
  42561. : owner (owner_),
  42562. range (range_),
  42563. oldCaretPos (oldCaretPos_),
  42564. newCaretPos (newCaretPos_),
  42565. removedSections (removedSections_)
  42566. {
  42567. }
  42568. ~RemoveAction()
  42569. {
  42570. for (int i = removedSections.size(); --i >= 0;)
  42571. {
  42572. UniformTextSection* const section = removedSections.getUnchecked (i);
  42573. section->clear();
  42574. delete section;
  42575. }
  42576. }
  42577. bool perform()
  42578. {
  42579. owner.remove (range, 0, newCaretPos);
  42580. return true;
  42581. }
  42582. bool undo()
  42583. {
  42584. owner.reinsert (range.getStart(), removedSections);
  42585. owner.moveCursorTo (oldCaretPos, false);
  42586. return true;
  42587. }
  42588. int getSizeInUnits()
  42589. {
  42590. int n = 0;
  42591. for (int i = removedSections.size(); --i >= 0;)
  42592. n += removedSections.getUnchecked (i)->getTotalLength();
  42593. return n + 16;
  42594. }
  42595. private:
  42596. TextEditor& owner;
  42597. const Range<int> range;
  42598. const int oldCaretPos, newCaretPos;
  42599. Array <UniformTextSection*> removedSections;
  42600. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42601. };
  42602. class TextEditor::TextHolderComponent : public Component,
  42603. public Timer,
  42604. public ValueListener
  42605. {
  42606. public:
  42607. TextHolderComponent (TextEditor& owner_)
  42608. : owner (owner_)
  42609. {
  42610. setWantsKeyboardFocus (false);
  42611. setInterceptsMouseClicks (false, true);
  42612. owner.getTextValue().addListener (this);
  42613. }
  42614. ~TextHolderComponent()
  42615. {
  42616. owner.getTextValue().removeListener (this);
  42617. }
  42618. void paint (Graphics& g)
  42619. {
  42620. owner.drawContent (g);
  42621. }
  42622. void timerCallback()
  42623. {
  42624. owner.timerCallbackInt();
  42625. }
  42626. const MouseCursor getMouseCursor()
  42627. {
  42628. return owner.getMouseCursor();
  42629. }
  42630. void valueChanged (Value&)
  42631. {
  42632. owner.textWasChangedByValue();
  42633. }
  42634. private:
  42635. TextEditor& owner;
  42636. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42637. };
  42638. class TextEditorViewport : public Viewport
  42639. {
  42640. public:
  42641. TextEditorViewport (TextEditor& owner_)
  42642. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42643. {
  42644. }
  42645. void visibleAreaChanged (const Rectangle<int>&)
  42646. {
  42647. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42648. // appear and disappear, causing the wrap width to change.
  42649. {
  42650. const float wordWrapWidth = owner.getWordWrapWidth();
  42651. if (wordWrapWidth != lastWordWrapWidth)
  42652. {
  42653. lastWordWrapWidth = wordWrapWidth;
  42654. rentrant = true;
  42655. owner.updateTextHolderSize();
  42656. rentrant = false;
  42657. }
  42658. }
  42659. }
  42660. private:
  42661. TextEditor& owner;
  42662. float lastWordWrapWidth;
  42663. bool rentrant;
  42664. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42665. };
  42666. namespace TextEditorDefs
  42667. {
  42668. const int flashSpeedIntervalMs = 380;
  42669. const int textChangeMessageId = 0x10003001;
  42670. const int returnKeyMessageId = 0x10003002;
  42671. const int escapeKeyMessageId = 0x10003003;
  42672. const int focusLossMessageId = 0x10003004;
  42673. const int maxActionsPerTransaction = 100;
  42674. int getCharacterCategory (const juce_wchar character)
  42675. {
  42676. return CharacterFunctions::isLetterOrDigit (character)
  42677. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42678. }
  42679. }
  42680. TextEditor::TextEditor (const String& name,
  42681. const juce_wchar passwordCharacter_)
  42682. : Component (name),
  42683. borderSize (1, 1, 1, 3),
  42684. readOnly (false),
  42685. multiline (false),
  42686. wordWrap (false),
  42687. returnKeyStartsNewLine (false),
  42688. caretVisible (true),
  42689. popupMenuEnabled (true),
  42690. selectAllTextWhenFocused (false),
  42691. scrollbarVisible (true),
  42692. wasFocused (false),
  42693. caretFlashState (true),
  42694. keepCursorOnScreen (true),
  42695. tabKeyUsed (false),
  42696. menuActive (false),
  42697. valueTextNeedsUpdating (false),
  42698. cursorX (0),
  42699. cursorY (0),
  42700. cursorHeight (0),
  42701. maxTextLength (0),
  42702. leftIndent (4),
  42703. topIndent (4),
  42704. lastTransactionTime (0),
  42705. currentFont (14.0f),
  42706. totalNumChars (0),
  42707. caretPosition (0),
  42708. passwordCharacter (passwordCharacter_),
  42709. dragType (notDragging)
  42710. {
  42711. setOpaque (true);
  42712. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  42713. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42714. viewport->setWantsKeyboardFocus (false);
  42715. viewport->setScrollBarsShown (false, false);
  42716. setMouseCursor (MouseCursor::IBeamCursor);
  42717. setWantsKeyboardFocus (true);
  42718. }
  42719. TextEditor::~TextEditor()
  42720. {
  42721. textValue.referTo (Value());
  42722. clearInternal (0);
  42723. viewport = 0;
  42724. textHolder = 0;
  42725. }
  42726. void TextEditor::newTransaction()
  42727. {
  42728. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42729. undoManager.beginNewTransaction();
  42730. }
  42731. void TextEditor::doUndoRedo (const bool isRedo)
  42732. {
  42733. if (! isReadOnly())
  42734. {
  42735. if (isRedo ? undoManager.redo()
  42736. : undoManager.undo())
  42737. {
  42738. scrollToMakeSureCursorIsVisible();
  42739. repaint();
  42740. textChanged();
  42741. }
  42742. }
  42743. }
  42744. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42745. const bool shouldWordWrap)
  42746. {
  42747. if (multiline != shouldBeMultiLine
  42748. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42749. {
  42750. multiline = shouldBeMultiLine;
  42751. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42752. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42753. scrollbarVisible && multiline);
  42754. viewport->setViewPosition (0, 0);
  42755. resized();
  42756. scrollToMakeSureCursorIsVisible();
  42757. }
  42758. }
  42759. bool TextEditor::isMultiLine() const
  42760. {
  42761. return multiline;
  42762. }
  42763. void TextEditor::setScrollbarsShown (bool shown)
  42764. {
  42765. if (scrollbarVisible != shown)
  42766. {
  42767. scrollbarVisible = shown;
  42768. shown = shown && isMultiLine();
  42769. viewport->setScrollBarsShown (shown, shown);
  42770. }
  42771. }
  42772. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42773. {
  42774. if (readOnly != shouldBeReadOnly)
  42775. {
  42776. readOnly = shouldBeReadOnly;
  42777. enablementChanged();
  42778. }
  42779. }
  42780. bool TextEditor::isReadOnly() const
  42781. {
  42782. return readOnly || ! isEnabled();
  42783. }
  42784. bool TextEditor::isTextInputActive() const
  42785. {
  42786. return ! isReadOnly();
  42787. }
  42788. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42789. {
  42790. returnKeyStartsNewLine = shouldStartNewLine;
  42791. }
  42792. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42793. {
  42794. tabKeyUsed = shouldTabKeyBeUsed;
  42795. }
  42796. void TextEditor::setPopupMenuEnabled (const bool b)
  42797. {
  42798. popupMenuEnabled = b;
  42799. }
  42800. void TextEditor::setSelectAllWhenFocused (const bool b)
  42801. {
  42802. selectAllTextWhenFocused = b;
  42803. }
  42804. const Font TextEditor::getFont() const
  42805. {
  42806. return currentFont;
  42807. }
  42808. void TextEditor::setFont (const Font& newFont)
  42809. {
  42810. currentFont = newFont;
  42811. scrollToMakeSureCursorIsVisible();
  42812. }
  42813. void TextEditor::applyFontToAllText (const Font& newFont)
  42814. {
  42815. currentFont = newFont;
  42816. const Colour overallColour (findColour (textColourId));
  42817. for (int i = sections.size(); --i >= 0;)
  42818. {
  42819. UniformTextSection* const uts = sections.getUnchecked (i);
  42820. uts->setFont (newFont, passwordCharacter);
  42821. uts->colour = overallColour;
  42822. }
  42823. coalesceSimilarSections();
  42824. updateTextHolderSize();
  42825. scrollToMakeSureCursorIsVisible();
  42826. repaint();
  42827. }
  42828. void TextEditor::colourChanged()
  42829. {
  42830. setOpaque (findColour (backgroundColourId).isOpaque());
  42831. repaint();
  42832. }
  42833. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42834. {
  42835. caretVisible = shouldCaretBeVisible;
  42836. if (shouldCaretBeVisible)
  42837. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42838. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42839. : MouseCursor::NormalCursor);
  42840. }
  42841. void TextEditor::setInputRestrictions (const int maxLen,
  42842. const String& chars)
  42843. {
  42844. maxTextLength = jmax (0, maxLen);
  42845. allowedCharacters = chars;
  42846. }
  42847. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42848. {
  42849. textToShowWhenEmpty = text;
  42850. colourForTextWhenEmpty = colourToUse;
  42851. }
  42852. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42853. {
  42854. if (passwordCharacter != newPasswordCharacter)
  42855. {
  42856. passwordCharacter = newPasswordCharacter;
  42857. resized();
  42858. repaint();
  42859. }
  42860. }
  42861. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42862. {
  42863. viewport->setScrollBarThickness (newThicknessPixels);
  42864. }
  42865. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42866. {
  42867. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42868. }
  42869. void TextEditor::clear()
  42870. {
  42871. clearInternal (0);
  42872. updateTextHolderSize();
  42873. undoManager.clearUndoHistory();
  42874. }
  42875. void TextEditor::setText (const String& newText,
  42876. const bool sendTextChangeMessage)
  42877. {
  42878. const int newLength = newText.length();
  42879. if (newLength != getTotalNumChars() || getText() != newText)
  42880. {
  42881. const int oldCursorPos = caretPosition;
  42882. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42883. clearInternal (0);
  42884. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42885. // if you're adding text with line-feeds to a single-line text editor, it
  42886. // ain't gonna look right!
  42887. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42888. if (cursorWasAtEnd && ! isMultiLine())
  42889. moveCursorTo (getTotalNumChars(), false);
  42890. else
  42891. moveCursorTo (oldCursorPos, false);
  42892. if (sendTextChangeMessage)
  42893. textChanged();
  42894. updateTextHolderSize();
  42895. scrollToMakeSureCursorIsVisible();
  42896. undoManager.clearUndoHistory();
  42897. repaint();
  42898. }
  42899. }
  42900. Value& TextEditor::getTextValue()
  42901. {
  42902. if (valueTextNeedsUpdating)
  42903. {
  42904. valueTextNeedsUpdating = false;
  42905. textValue = getText();
  42906. }
  42907. return textValue;
  42908. }
  42909. void TextEditor::textWasChangedByValue()
  42910. {
  42911. if (textValue.getValueSource().getReferenceCount() > 1)
  42912. setText (textValue.getValue());
  42913. }
  42914. void TextEditor::textChanged()
  42915. {
  42916. updateTextHolderSize();
  42917. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42918. if (textValue.getValueSource().getReferenceCount() > 1)
  42919. {
  42920. valueTextNeedsUpdating = false;
  42921. textValue = getText();
  42922. }
  42923. }
  42924. void TextEditor::returnPressed()
  42925. {
  42926. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42927. }
  42928. void TextEditor::escapePressed()
  42929. {
  42930. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42931. }
  42932. void TextEditor::addListener (TextEditorListener* const newListener)
  42933. {
  42934. listeners.add (newListener);
  42935. }
  42936. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42937. {
  42938. listeners.remove (listenerToRemove);
  42939. }
  42940. void TextEditor::timerCallbackInt()
  42941. {
  42942. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42943. if (caretFlashState != newState)
  42944. {
  42945. caretFlashState = newState;
  42946. if (caretFlashState)
  42947. wasFocused = true;
  42948. if (caretVisible
  42949. && hasKeyboardFocus (false)
  42950. && ! isReadOnly())
  42951. {
  42952. repaintCaret();
  42953. }
  42954. }
  42955. const unsigned int now = Time::getApproximateMillisecondCounter();
  42956. if (now > lastTransactionTime + 200)
  42957. newTransaction();
  42958. }
  42959. void TextEditor::repaintCaret()
  42960. {
  42961. if (! findColour (caretColourId).isTransparent())
  42962. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42963. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42964. 4,
  42965. roundToInt (cursorHeight) + 2);
  42966. }
  42967. void TextEditor::repaintText (const Range<int>& range)
  42968. {
  42969. if (! range.isEmpty())
  42970. {
  42971. float x = 0, y = 0, lh = currentFont.getHeight();
  42972. const float wordWrapWidth = getWordWrapWidth();
  42973. if (wordWrapWidth > 0)
  42974. {
  42975. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42976. i.getCharPosition (range.getStart(), x, y, lh);
  42977. const int y1 = (int) y;
  42978. int y2;
  42979. if (range.getEnd() >= getTotalNumChars())
  42980. {
  42981. y2 = textHolder->getHeight();
  42982. }
  42983. else
  42984. {
  42985. i.getCharPosition (range.getEnd(), x, y, lh);
  42986. y2 = (int) (y + lh * 2.0f);
  42987. }
  42988. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42989. }
  42990. }
  42991. }
  42992. void TextEditor::moveCaret (int newCaretPos)
  42993. {
  42994. if (newCaretPos < 0)
  42995. newCaretPos = 0;
  42996. else if (newCaretPos > getTotalNumChars())
  42997. newCaretPos = getTotalNumChars();
  42998. if (newCaretPos != getCaretPosition())
  42999. {
  43000. repaintCaret();
  43001. caretFlashState = true;
  43002. caretPosition = newCaretPos;
  43003. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43004. scrollToMakeSureCursorIsVisible();
  43005. repaintCaret();
  43006. }
  43007. }
  43008. void TextEditor::setCaretPosition (const int newIndex)
  43009. {
  43010. moveCursorTo (newIndex, false);
  43011. }
  43012. int TextEditor::getCaretPosition() const
  43013. {
  43014. return caretPosition;
  43015. }
  43016. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43017. const int desiredCaretY)
  43018. {
  43019. updateCaretPosition();
  43020. int vx = roundToInt (cursorX) - desiredCaretX;
  43021. int vy = roundToInt (cursorY) - desiredCaretY;
  43022. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43023. {
  43024. vx += desiredCaretX - proportionOfWidth (0.2f);
  43025. }
  43026. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43027. {
  43028. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43029. }
  43030. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43031. if (! isMultiLine())
  43032. {
  43033. vy = viewport->getViewPositionY();
  43034. }
  43035. else
  43036. {
  43037. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43038. const int curH = roundToInt (cursorHeight);
  43039. if (desiredCaretY < 0)
  43040. {
  43041. vy = jmax (0, desiredCaretY + vy);
  43042. }
  43043. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43044. {
  43045. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43046. }
  43047. }
  43048. viewport->setViewPosition (vx, vy);
  43049. }
  43050. const Rectangle<int> TextEditor::getCaretRectangle()
  43051. {
  43052. updateCaretPosition();
  43053. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43054. roundToInt (cursorY) - viewport->getY(),
  43055. 1, roundToInt (cursorHeight));
  43056. }
  43057. float TextEditor::getWordWrapWidth() const
  43058. {
  43059. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43060. : 1.0e10f;
  43061. }
  43062. void TextEditor::updateTextHolderSize()
  43063. {
  43064. const float wordWrapWidth = getWordWrapWidth();
  43065. if (wordWrapWidth > 0)
  43066. {
  43067. float maxWidth = 0.0f;
  43068. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43069. while (i.next())
  43070. maxWidth = jmax (maxWidth, i.atomRight);
  43071. const int w = leftIndent + roundToInt (maxWidth);
  43072. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43073. currentFont.getHeight()));
  43074. textHolder->setSize (w + 1, h + 1);
  43075. }
  43076. }
  43077. int TextEditor::getTextWidth() const
  43078. {
  43079. return textHolder->getWidth();
  43080. }
  43081. int TextEditor::getTextHeight() const
  43082. {
  43083. return textHolder->getHeight();
  43084. }
  43085. void TextEditor::setIndents (const int newLeftIndent,
  43086. const int newTopIndent)
  43087. {
  43088. leftIndent = newLeftIndent;
  43089. topIndent = newTopIndent;
  43090. }
  43091. void TextEditor::setBorder (const BorderSize<int>& border)
  43092. {
  43093. borderSize = border;
  43094. resized();
  43095. }
  43096. const BorderSize<int> TextEditor::getBorder() const
  43097. {
  43098. return borderSize;
  43099. }
  43100. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43101. {
  43102. keepCursorOnScreen = shouldScrollToShowCursor;
  43103. }
  43104. void TextEditor::updateCaretPosition()
  43105. {
  43106. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43107. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43108. }
  43109. void TextEditor::scrollToMakeSureCursorIsVisible()
  43110. {
  43111. updateCaretPosition();
  43112. if (keepCursorOnScreen)
  43113. {
  43114. int x = viewport->getViewPositionX();
  43115. int y = viewport->getViewPositionY();
  43116. const int relativeCursorX = roundToInt (cursorX) - x;
  43117. const int relativeCursorY = roundToInt (cursorY) - y;
  43118. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43119. {
  43120. x += relativeCursorX - proportionOfWidth (0.2f);
  43121. }
  43122. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43123. {
  43124. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43125. }
  43126. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43127. if (! isMultiLine())
  43128. {
  43129. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43130. }
  43131. else
  43132. {
  43133. const int curH = roundToInt (cursorHeight);
  43134. if (relativeCursorY < 0)
  43135. {
  43136. y = jmax (0, relativeCursorY + y);
  43137. }
  43138. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43139. {
  43140. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43141. }
  43142. }
  43143. viewport->setViewPosition (x, y);
  43144. }
  43145. }
  43146. void TextEditor::moveCursorTo (const int newPosition,
  43147. const bool isSelecting)
  43148. {
  43149. if (isSelecting)
  43150. {
  43151. moveCaret (newPosition);
  43152. const Range<int> oldSelection (selection);
  43153. if (dragType == notDragging)
  43154. {
  43155. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43156. dragType = draggingSelectionStart;
  43157. else
  43158. dragType = draggingSelectionEnd;
  43159. }
  43160. if (dragType == draggingSelectionStart)
  43161. {
  43162. if (getCaretPosition() >= selection.getEnd())
  43163. dragType = draggingSelectionEnd;
  43164. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43165. }
  43166. else
  43167. {
  43168. if (getCaretPosition() < selection.getStart())
  43169. dragType = draggingSelectionStart;
  43170. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43171. }
  43172. repaintText (selection.getUnionWith (oldSelection));
  43173. }
  43174. else
  43175. {
  43176. dragType = notDragging;
  43177. repaintText (selection);
  43178. moveCaret (newPosition);
  43179. selection = Range<int>::emptyRange (getCaretPosition());
  43180. }
  43181. }
  43182. int TextEditor::getTextIndexAt (const int x,
  43183. const int y)
  43184. {
  43185. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43186. (float) (y + viewport->getViewPositionY() - topIndent));
  43187. }
  43188. void TextEditor::insertTextAtCaret (const String& newText_)
  43189. {
  43190. String newText (newText_);
  43191. if (allowedCharacters.isNotEmpty())
  43192. newText = newText.retainCharacters (allowedCharacters);
  43193. if (! isMultiLine())
  43194. newText = newText.replaceCharacters ("\r\n", " ");
  43195. else
  43196. newText = newText.replace ("\r\n", "\n");
  43197. const int newCaretPos = selection.getStart() + newText.length();
  43198. const int insertIndex = selection.getStart();
  43199. remove (selection, getUndoManager(),
  43200. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43201. if (maxTextLength > 0)
  43202. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43203. if (newText.isNotEmpty())
  43204. insert (newText,
  43205. insertIndex,
  43206. currentFont,
  43207. findColour (textColourId),
  43208. getUndoManager(),
  43209. newCaretPos);
  43210. textChanged();
  43211. }
  43212. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43213. {
  43214. moveCursorTo (newSelection.getStart(), false);
  43215. moveCursorTo (newSelection.getEnd(), true);
  43216. }
  43217. void TextEditor::copy()
  43218. {
  43219. if (passwordCharacter == 0)
  43220. {
  43221. const String selectedText (getHighlightedText());
  43222. if (selectedText.isNotEmpty())
  43223. SystemClipboard::copyTextToClipboard (selectedText);
  43224. }
  43225. }
  43226. void TextEditor::paste()
  43227. {
  43228. if (! isReadOnly())
  43229. {
  43230. const String clip (SystemClipboard::getTextFromClipboard());
  43231. if (clip.isNotEmpty())
  43232. insertTextAtCaret (clip);
  43233. }
  43234. }
  43235. void TextEditor::cut()
  43236. {
  43237. if (! isReadOnly())
  43238. {
  43239. moveCaret (selection.getEnd());
  43240. insertTextAtCaret (String::empty);
  43241. }
  43242. }
  43243. void TextEditor::drawContent (Graphics& g)
  43244. {
  43245. const float wordWrapWidth = getWordWrapWidth();
  43246. if (wordWrapWidth > 0)
  43247. {
  43248. g.setOrigin (leftIndent, topIndent);
  43249. const Rectangle<int> clip (g.getClipBounds());
  43250. Colour selectedTextColour;
  43251. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43252. while (i.lineY + 200.0 < clip.getY() && i.next())
  43253. {}
  43254. if (! selection.isEmpty())
  43255. {
  43256. g.setColour (findColour (highlightColourId)
  43257. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43258. selectedTextColour = findColour (highlightedTextColourId);
  43259. Iterator i2 (i);
  43260. while (i2.next() && i2.lineY < clip.getBottom())
  43261. {
  43262. if (i2.lineY + i2.lineHeight >= clip.getY()
  43263. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43264. {
  43265. i2.drawSelection (g, selection);
  43266. }
  43267. }
  43268. }
  43269. const UniformTextSection* lastSection = 0;
  43270. while (i.next() && i.lineY < clip.getBottom())
  43271. {
  43272. if (i.lineY + i.lineHeight >= clip.getY())
  43273. {
  43274. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43275. {
  43276. i.drawSelectedText (g, selection, selectedTextColour);
  43277. lastSection = 0;
  43278. }
  43279. else
  43280. {
  43281. i.draw (g, lastSection);
  43282. }
  43283. }
  43284. }
  43285. }
  43286. }
  43287. void TextEditor::paint (Graphics& g)
  43288. {
  43289. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43290. }
  43291. void TextEditor::paintOverChildren (Graphics& g)
  43292. {
  43293. if (caretFlashState
  43294. && hasKeyboardFocus (false)
  43295. && caretVisible
  43296. && ! isReadOnly())
  43297. {
  43298. g.setColour (findColour (caretColourId));
  43299. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43300. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43301. 2.0f, cursorHeight);
  43302. }
  43303. if (textToShowWhenEmpty.isNotEmpty()
  43304. && (! hasKeyboardFocus (false))
  43305. && getTotalNumChars() == 0)
  43306. {
  43307. g.setColour (colourForTextWhenEmpty);
  43308. g.setFont (getFont());
  43309. if (isMultiLine())
  43310. {
  43311. g.drawText (textToShowWhenEmpty,
  43312. 0, 0, getWidth(), getHeight(),
  43313. Justification::centred, true);
  43314. }
  43315. else
  43316. {
  43317. g.drawText (textToShowWhenEmpty,
  43318. leftIndent, topIndent,
  43319. viewport->getWidth() - leftIndent,
  43320. viewport->getHeight() - topIndent,
  43321. Justification::centredLeft, true);
  43322. }
  43323. }
  43324. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43325. }
  43326. static void textEditorMenuCallback (int menuResult, TextEditor* editor)
  43327. {
  43328. if (editor != 0 && menuResult != 0)
  43329. editor->performPopupMenuAction (menuResult);
  43330. }
  43331. void TextEditor::mouseDown (const MouseEvent& e)
  43332. {
  43333. beginDragAutoRepeat (100);
  43334. newTransaction();
  43335. if (wasFocused || ! selectAllTextWhenFocused)
  43336. {
  43337. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43338. {
  43339. moveCursorTo (getTextIndexAt (e.x, e.y),
  43340. e.mods.isShiftDown());
  43341. }
  43342. else
  43343. {
  43344. PopupMenu m;
  43345. m.setLookAndFeel (&getLookAndFeel());
  43346. addPopupMenuItems (m, &e);
  43347. m.showMenuAsync (PopupMenu::Options(),
  43348. ModalCallbackFunction::forComponent (textEditorMenuCallback, this));
  43349. }
  43350. }
  43351. }
  43352. void TextEditor::mouseDrag (const MouseEvent& e)
  43353. {
  43354. if (wasFocused || ! selectAllTextWhenFocused)
  43355. {
  43356. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43357. {
  43358. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43359. }
  43360. }
  43361. }
  43362. void TextEditor::mouseUp (const MouseEvent& e)
  43363. {
  43364. newTransaction();
  43365. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43366. if (wasFocused || ! selectAllTextWhenFocused)
  43367. {
  43368. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43369. {
  43370. moveCaret (getTextIndexAt (e.x, e.y));
  43371. }
  43372. }
  43373. wasFocused = true;
  43374. }
  43375. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43376. {
  43377. int tokenEnd = getTextIndexAt (e.x, e.y);
  43378. int tokenStart = tokenEnd;
  43379. if (e.getNumberOfClicks() > 3)
  43380. {
  43381. tokenStart = 0;
  43382. tokenEnd = getTotalNumChars();
  43383. }
  43384. else
  43385. {
  43386. const String t (getText());
  43387. const int totalLength = getTotalNumChars();
  43388. while (tokenEnd < totalLength)
  43389. {
  43390. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43391. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43392. ++tokenEnd;
  43393. else
  43394. break;
  43395. }
  43396. tokenStart = tokenEnd;
  43397. while (tokenStart > 0)
  43398. {
  43399. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43400. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43401. --tokenStart;
  43402. else
  43403. break;
  43404. }
  43405. if (e.getNumberOfClicks() > 2)
  43406. {
  43407. while (tokenEnd < totalLength)
  43408. {
  43409. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43410. ++tokenEnd;
  43411. else
  43412. break;
  43413. }
  43414. while (tokenStart > 0)
  43415. {
  43416. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43417. --tokenStart;
  43418. else
  43419. break;
  43420. }
  43421. }
  43422. }
  43423. moveCursorTo (tokenEnd, false);
  43424. moveCursorTo (tokenStart, true);
  43425. }
  43426. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43427. {
  43428. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43429. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43430. }
  43431. bool TextEditor::keyPressed (const KeyPress& key)
  43432. {
  43433. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43434. return false;
  43435. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43436. if (key.isKeyCode (KeyPress::leftKey)
  43437. || key.isKeyCode (KeyPress::upKey))
  43438. {
  43439. newTransaction();
  43440. int newPos;
  43441. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43442. newPos = indexAtPosition (cursorX, cursorY - 1);
  43443. else if (moveInWholeWordSteps)
  43444. newPos = findWordBreakBefore (getCaretPosition());
  43445. else
  43446. newPos = getCaretPosition() - 1;
  43447. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43448. }
  43449. else if (key.isKeyCode (KeyPress::rightKey)
  43450. || key.isKeyCode (KeyPress::downKey))
  43451. {
  43452. newTransaction();
  43453. int newPos;
  43454. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43455. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43456. else if (moveInWholeWordSteps)
  43457. newPos = findWordBreakAfter (getCaretPosition());
  43458. else
  43459. newPos = getCaretPosition() + 1;
  43460. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43461. }
  43462. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43463. {
  43464. newTransaction();
  43465. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43466. key.getModifiers().isShiftDown());
  43467. }
  43468. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43469. {
  43470. newTransaction();
  43471. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43472. key.getModifiers().isShiftDown());
  43473. }
  43474. else if (key.isKeyCode (KeyPress::homeKey))
  43475. {
  43476. newTransaction();
  43477. if (isMultiLine() && ! moveInWholeWordSteps)
  43478. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43479. key.getModifiers().isShiftDown());
  43480. else
  43481. moveCursorTo (0, key.getModifiers().isShiftDown());
  43482. }
  43483. else if (key.isKeyCode (KeyPress::endKey))
  43484. {
  43485. newTransaction();
  43486. if (isMultiLine() && ! moveInWholeWordSteps)
  43487. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43488. key.getModifiers().isShiftDown());
  43489. else
  43490. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43491. }
  43492. else if (key.isKeyCode (KeyPress::backspaceKey))
  43493. {
  43494. if (moveInWholeWordSteps)
  43495. {
  43496. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43497. }
  43498. else
  43499. {
  43500. if (selection.isEmpty() && selection.getStart() > 0)
  43501. selection.setStart (selection.getEnd() - 1);
  43502. }
  43503. cut();
  43504. }
  43505. else if (key.isKeyCode (KeyPress::deleteKey))
  43506. {
  43507. if (key.getModifiers().isShiftDown())
  43508. copy();
  43509. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43510. selection.setEnd (selection.getStart() + 1);
  43511. cut();
  43512. }
  43513. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43514. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43515. {
  43516. newTransaction();
  43517. copy();
  43518. }
  43519. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43520. {
  43521. newTransaction();
  43522. copy();
  43523. cut();
  43524. }
  43525. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43526. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43527. {
  43528. newTransaction();
  43529. paste();
  43530. }
  43531. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43532. {
  43533. newTransaction();
  43534. doUndoRedo (false);
  43535. }
  43536. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43537. {
  43538. newTransaction();
  43539. doUndoRedo (true);
  43540. }
  43541. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43542. {
  43543. newTransaction();
  43544. moveCursorTo (getTotalNumChars(), false);
  43545. moveCursorTo (0, true);
  43546. }
  43547. else if (key == KeyPress::returnKey)
  43548. {
  43549. newTransaction();
  43550. if (returnKeyStartsNewLine)
  43551. insertTextAtCaret ("\n");
  43552. else
  43553. returnPressed();
  43554. }
  43555. else if (key.isKeyCode (KeyPress::escapeKey))
  43556. {
  43557. newTransaction();
  43558. moveCursorTo (getCaretPosition(), false);
  43559. escapePressed();
  43560. }
  43561. else if (key.getTextCharacter() >= ' '
  43562. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43563. {
  43564. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43565. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43566. }
  43567. else
  43568. {
  43569. return false;
  43570. }
  43571. return true;
  43572. }
  43573. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43574. {
  43575. if (! isKeyDown)
  43576. return false;
  43577. #if JUCE_WINDOWS
  43578. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43579. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43580. #endif
  43581. // (overridden to avoid forwarding key events to the parent)
  43582. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43583. }
  43584. const int baseMenuItemID = 0x7fff0000;
  43585. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43586. {
  43587. const bool writable = ! isReadOnly();
  43588. if (passwordCharacter == 0)
  43589. {
  43590. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43591. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43592. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43593. }
  43594. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43595. m.addSeparator();
  43596. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43597. m.addSeparator();
  43598. if (getUndoManager() != 0)
  43599. {
  43600. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43601. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43602. }
  43603. }
  43604. void TextEditor::performPopupMenuAction (const int menuItemID)
  43605. {
  43606. switch (menuItemID)
  43607. {
  43608. case baseMenuItemID + 1:
  43609. copy();
  43610. cut();
  43611. break;
  43612. case baseMenuItemID + 2:
  43613. copy();
  43614. break;
  43615. case baseMenuItemID + 3:
  43616. paste();
  43617. break;
  43618. case baseMenuItemID + 4:
  43619. cut();
  43620. break;
  43621. case baseMenuItemID + 5:
  43622. moveCursorTo (getTotalNumChars(), false);
  43623. moveCursorTo (0, true);
  43624. break;
  43625. case baseMenuItemID + 6:
  43626. doUndoRedo (false);
  43627. break;
  43628. case baseMenuItemID + 7:
  43629. doUndoRedo (true);
  43630. break;
  43631. default:
  43632. break;
  43633. }
  43634. }
  43635. void TextEditor::focusGained (FocusChangeType)
  43636. {
  43637. newTransaction();
  43638. caretFlashState = true;
  43639. if (selectAllTextWhenFocused)
  43640. {
  43641. moveCursorTo (0, false);
  43642. moveCursorTo (getTotalNumChars(), true);
  43643. }
  43644. repaint();
  43645. if (caretVisible)
  43646. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43647. ComponentPeer* const peer = getPeer();
  43648. if (peer != 0 && ! isReadOnly())
  43649. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43650. }
  43651. void TextEditor::focusLost (FocusChangeType)
  43652. {
  43653. newTransaction();
  43654. wasFocused = false;
  43655. textHolder->stopTimer();
  43656. caretFlashState = false;
  43657. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43658. repaint();
  43659. }
  43660. void TextEditor::resized()
  43661. {
  43662. viewport->setBoundsInset (borderSize);
  43663. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43664. updateTextHolderSize();
  43665. if (! isMultiLine())
  43666. {
  43667. scrollToMakeSureCursorIsVisible();
  43668. }
  43669. else
  43670. {
  43671. updateCaretPosition();
  43672. }
  43673. }
  43674. void TextEditor::handleCommandMessage (const int commandId)
  43675. {
  43676. Component::BailOutChecker checker (this);
  43677. switch (commandId)
  43678. {
  43679. case TextEditorDefs::textChangeMessageId:
  43680. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43681. break;
  43682. case TextEditorDefs::returnKeyMessageId:
  43683. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43684. break;
  43685. case TextEditorDefs::escapeKeyMessageId:
  43686. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43687. break;
  43688. case TextEditorDefs::focusLossMessageId:
  43689. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43690. break;
  43691. default:
  43692. jassertfalse;
  43693. break;
  43694. }
  43695. }
  43696. void TextEditor::enablementChanged()
  43697. {
  43698. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43699. : MouseCursor::IBeamCursor);
  43700. repaint();
  43701. }
  43702. UndoManager* TextEditor::getUndoManager() throw()
  43703. {
  43704. return isReadOnly() ? 0 : &undoManager;
  43705. }
  43706. void TextEditor::clearInternal (UndoManager* const um)
  43707. {
  43708. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43709. }
  43710. void TextEditor::insert (const String& text,
  43711. const int insertIndex,
  43712. const Font& font,
  43713. const Colour& colour,
  43714. UndoManager* const um,
  43715. const int caretPositionToMoveTo)
  43716. {
  43717. if (text.isNotEmpty())
  43718. {
  43719. if (um != 0)
  43720. {
  43721. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43722. newTransaction();
  43723. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43724. caretPosition, caretPositionToMoveTo));
  43725. }
  43726. else
  43727. {
  43728. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43729. // a line gets moved due to word wrap
  43730. int index = 0;
  43731. int nextIndex = 0;
  43732. for (int i = 0; i < sections.size(); ++i)
  43733. {
  43734. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43735. if (insertIndex == index)
  43736. {
  43737. sections.insert (i, new UniformTextSection (text,
  43738. font, colour,
  43739. passwordCharacter));
  43740. break;
  43741. }
  43742. else if (insertIndex > index && insertIndex < nextIndex)
  43743. {
  43744. splitSection (i, insertIndex - index);
  43745. sections.insert (i + 1, new UniformTextSection (text,
  43746. font, colour,
  43747. passwordCharacter));
  43748. break;
  43749. }
  43750. index = nextIndex;
  43751. }
  43752. if (nextIndex == insertIndex)
  43753. sections.add (new UniformTextSection (text,
  43754. font, colour,
  43755. passwordCharacter));
  43756. coalesceSimilarSections();
  43757. totalNumChars = -1;
  43758. valueTextNeedsUpdating = true;
  43759. moveCursorTo (caretPositionToMoveTo, false);
  43760. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43761. }
  43762. }
  43763. }
  43764. void TextEditor::reinsert (const int insertIndex,
  43765. const Array <UniformTextSection*>& sectionsToInsert)
  43766. {
  43767. int index = 0;
  43768. int nextIndex = 0;
  43769. for (int i = 0; i < sections.size(); ++i)
  43770. {
  43771. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43772. if (insertIndex == index)
  43773. {
  43774. for (int j = sectionsToInsert.size(); --j >= 0;)
  43775. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43776. break;
  43777. }
  43778. else if (insertIndex > index && insertIndex < nextIndex)
  43779. {
  43780. splitSection (i, insertIndex - index);
  43781. for (int j = sectionsToInsert.size(); --j >= 0;)
  43782. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43783. break;
  43784. }
  43785. index = nextIndex;
  43786. }
  43787. if (nextIndex == insertIndex)
  43788. {
  43789. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43790. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43791. }
  43792. coalesceSimilarSections();
  43793. totalNumChars = -1;
  43794. valueTextNeedsUpdating = true;
  43795. }
  43796. void TextEditor::remove (const Range<int>& range,
  43797. UndoManager* const um,
  43798. const int caretPositionToMoveTo)
  43799. {
  43800. if (! range.isEmpty())
  43801. {
  43802. int index = 0;
  43803. for (int i = 0; i < sections.size(); ++i)
  43804. {
  43805. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43806. if (range.getStart() > index && range.getStart() < nextIndex)
  43807. {
  43808. splitSection (i, range.getStart() - index);
  43809. --i;
  43810. }
  43811. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43812. {
  43813. splitSection (i, range.getEnd() - index);
  43814. --i;
  43815. }
  43816. else
  43817. {
  43818. index = nextIndex;
  43819. if (index > range.getEnd())
  43820. break;
  43821. }
  43822. }
  43823. index = 0;
  43824. if (um != 0)
  43825. {
  43826. Array <UniformTextSection*> removedSections;
  43827. for (int i = 0; i < sections.size(); ++i)
  43828. {
  43829. if (range.getEnd() <= range.getStart())
  43830. break;
  43831. UniformTextSection* const section = sections.getUnchecked (i);
  43832. const int nextIndex = index + section->getTotalLength();
  43833. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43834. removedSections.add (new UniformTextSection (*section));
  43835. index = nextIndex;
  43836. }
  43837. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43838. newTransaction();
  43839. um->perform (new RemoveAction (*this, range, caretPosition,
  43840. caretPositionToMoveTo, removedSections));
  43841. }
  43842. else
  43843. {
  43844. Range<int> remainingRange (range);
  43845. for (int i = 0; i < sections.size(); ++i)
  43846. {
  43847. UniformTextSection* const section = sections.getUnchecked (i);
  43848. const int nextIndex = index + section->getTotalLength();
  43849. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43850. {
  43851. sections.remove(i);
  43852. section->clear();
  43853. delete section;
  43854. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43855. if (remainingRange.isEmpty())
  43856. break;
  43857. --i;
  43858. }
  43859. else
  43860. {
  43861. index = nextIndex;
  43862. }
  43863. }
  43864. coalesceSimilarSections();
  43865. totalNumChars = -1;
  43866. valueTextNeedsUpdating = true;
  43867. moveCursorTo (caretPositionToMoveTo, false);
  43868. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43869. }
  43870. }
  43871. }
  43872. const String TextEditor::getText() const
  43873. {
  43874. String t;
  43875. t.preallocateStorage (getTotalNumChars());
  43876. String::Concatenator concatenator (t);
  43877. for (int i = 0; i < sections.size(); ++i)
  43878. sections.getUnchecked (i)->appendAllText (concatenator);
  43879. return t;
  43880. }
  43881. const String TextEditor::getTextInRange (const Range<int>& range) const
  43882. {
  43883. String t;
  43884. if (! range.isEmpty())
  43885. {
  43886. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43887. String::Concatenator concatenator (t);
  43888. int index = 0;
  43889. for (int i = 0; i < sections.size(); ++i)
  43890. {
  43891. const UniformTextSection* const s = sections.getUnchecked (i);
  43892. const int nextIndex = index + s->getTotalLength();
  43893. if (range.getStart() < nextIndex)
  43894. {
  43895. if (range.getEnd() <= index)
  43896. break;
  43897. s->appendSubstring (concatenator, range - index);
  43898. }
  43899. index = nextIndex;
  43900. }
  43901. }
  43902. return t;
  43903. }
  43904. const String TextEditor::getHighlightedText() const
  43905. {
  43906. return getTextInRange (selection);
  43907. }
  43908. int TextEditor::getTotalNumChars() const
  43909. {
  43910. if (totalNumChars < 0)
  43911. {
  43912. totalNumChars = 0;
  43913. for (int i = sections.size(); --i >= 0;)
  43914. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43915. }
  43916. return totalNumChars;
  43917. }
  43918. bool TextEditor::isEmpty() const
  43919. {
  43920. return getTotalNumChars() == 0;
  43921. }
  43922. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43923. {
  43924. const float wordWrapWidth = getWordWrapWidth();
  43925. if (wordWrapWidth > 0 && sections.size() > 0)
  43926. {
  43927. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43928. i.getCharPosition (index, cx, cy, lineHeight);
  43929. }
  43930. else
  43931. {
  43932. cx = cy = 0;
  43933. lineHeight = currentFont.getHeight();
  43934. }
  43935. }
  43936. int TextEditor::indexAtPosition (const float x, const float y)
  43937. {
  43938. const float wordWrapWidth = getWordWrapWidth();
  43939. if (wordWrapWidth > 0)
  43940. {
  43941. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43942. while (i.next())
  43943. {
  43944. if (i.lineY + i.lineHeight > y)
  43945. {
  43946. if (i.lineY > y)
  43947. return jmax (0, i.indexInText - 1);
  43948. if (i.atomX >= x)
  43949. return i.indexInText;
  43950. if (x < i.atomRight)
  43951. return i.xToIndex (x);
  43952. }
  43953. }
  43954. }
  43955. return getTotalNumChars();
  43956. }
  43957. int TextEditor::findWordBreakAfter (const int position) const
  43958. {
  43959. const String t (getTextInRange (Range<int> (position, position + 512)));
  43960. const int totalLength = t.length();
  43961. int i = 0;
  43962. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43963. ++i;
  43964. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  43965. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  43966. ++i;
  43967. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43968. ++i;
  43969. return position + i;
  43970. }
  43971. int TextEditor::findWordBreakBefore (const int position) const
  43972. {
  43973. if (position <= 0)
  43974. return 0;
  43975. const int startOfBuffer = jmax (0, position - 512);
  43976. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43977. int i = position - startOfBuffer;
  43978. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43979. --i;
  43980. if (i > 0)
  43981. {
  43982. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  43983. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  43984. --i;
  43985. }
  43986. jassert (startOfBuffer + i >= 0);
  43987. return startOfBuffer + i;
  43988. }
  43989. void TextEditor::splitSection (const int sectionIndex,
  43990. const int charToSplitAt)
  43991. {
  43992. jassert (sections[sectionIndex] != 0);
  43993. sections.insert (sectionIndex + 1,
  43994. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43995. }
  43996. void TextEditor::coalesceSimilarSections()
  43997. {
  43998. for (int i = 0; i < sections.size() - 1; ++i)
  43999. {
  44000. UniformTextSection* const s1 = sections.getUnchecked (i);
  44001. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44002. if (s1->font == s2->font
  44003. && s1->colour == s2->colour)
  44004. {
  44005. s1->append (*s2, passwordCharacter);
  44006. sections.remove (i + 1);
  44007. delete s2;
  44008. --i;
  44009. }
  44010. }
  44011. }
  44012. void TextEditor::Listener::textEditorTextChanged (TextEditor&) {}
  44013. void TextEditor::Listener::textEditorReturnKeyPressed (TextEditor&) {}
  44014. void TextEditor::Listener::textEditorEscapeKeyPressed (TextEditor&) {}
  44015. void TextEditor::Listener::textEditorFocusLost (TextEditor&) {}
  44016. END_JUCE_NAMESPACE
  44017. /*** End of inlined file: juce_TextEditor.cpp ***/
  44018. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44019. BEGIN_JUCE_NAMESPACE
  44020. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44021. class ToolbarSpacerComp : public ToolbarItemComponent
  44022. {
  44023. public:
  44024. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44025. : ToolbarItemComponent (itemId_, String::empty, false),
  44026. fixedSize (fixedSize_),
  44027. drawBar (drawBar_)
  44028. {
  44029. }
  44030. ~ToolbarSpacerComp()
  44031. {
  44032. }
  44033. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44034. int& preferredSize, int& minSize, int& maxSize)
  44035. {
  44036. if (fixedSize <= 0)
  44037. {
  44038. preferredSize = toolbarThickness * 2;
  44039. minSize = 4;
  44040. maxSize = 32768;
  44041. }
  44042. else
  44043. {
  44044. maxSize = roundToInt (toolbarThickness * fixedSize);
  44045. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44046. preferredSize = maxSize;
  44047. if (getEditingMode() == editableOnPalette)
  44048. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44049. }
  44050. return true;
  44051. }
  44052. void paintButtonArea (Graphics&, int, int, bool, bool)
  44053. {
  44054. }
  44055. void contentAreaChanged (const Rectangle<int>&)
  44056. {
  44057. }
  44058. int getResizeOrder() const throw()
  44059. {
  44060. return fixedSize <= 0 ? 0 : 1;
  44061. }
  44062. void paint (Graphics& g)
  44063. {
  44064. const int w = getWidth();
  44065. const int h = getHeight();
  44066. if (drawBar)
  44067. {
  44068. g.setColour (findColour (Toolbar::separatorColourId, true));
  44069. const float thickness = 0.2f;
  44070. if (isToolbarVertical())
  44071. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44072. else
  44073. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44074. }
  44075. if (getEditingMode() != normalMode && ! drawBar)
  44076. {
  44077. g.setColour (findColour (Toolbar::separatorColourId, true));
  44078. const int indentX = jmin (2, (w - 3) / 2);
  44079. const int indentY = jmin (2, (h - 3) / 2);
  44080. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44081. if (fixedSize <= 0)
  44082. {
  44083. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44084. if (isToolbarVertical())
  44085. {
  44086. x1 = w * 0.5f;
  44087. y1 = h * 0.4f;
  44088. x2 = x1;
  44089. y2 = indentX * 2.0f;
  44090. x3 = x1;
  44091. y3 = h * 0.6f;
  44092. x4 = x1;
  44093. y4 = h - y2;
  44094. hw = w * 0.15f;
  44095. hl = w * 0.2f;
  44096. }
  44097. else
  44098. {
  44099. x1 = w * 0.4f;
  44100. y1 = h * 0.5f;
  44101. x2 = indentX * 2.0f;
  44102. y2 = y1;
  44103. x3 = w * 0.6f;
  44104. y3 = y1;
  44105. x4 = w - x2;
  44106. y4 = y1;
  44107. hw = h * 0.15f;
  44108. hl = h * 0.2f;
  44109. }
  44110. Path p;
  44111. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44112. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44113. g.fillPath (p);
  44114. }
  44115. }
  44116. }
  44117. private:
  44118. const float fixedSize;
  44119. const bool drawBar;
  44120. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  44121. };
  44122. class Toolbar::MissingItemsComponent : public PopupMenu::CustomComponent
  44123. {
  44124. public:
  44125. MissingItemsComponent (Toolbar& owner_, const int height_)
  44126. : PopupMenu::CustomComponent (true),
  44127. owner (&owner_),
  44128. height (height_)
  44129. {
  44130. for (int i = owner_.items.size(); --i >= 0;)
  44131. {
  44132. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44133. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44134. {
  44135. oldIndexes.insert (0, i);
  44136. addAndMakeVisible (tc, 0);
  44137. }
  44138. }
  44139. layout (400);
  44140. }
  44141. ~MissingItemsComponent()
  44142. {
  44143. if (owner != 0)
  44144. {
  44145. for (int i = 0; i < getNumChildComponents(); ++i)
  44146. {
  44147. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44148. if (tc != 0)
  44149. {
  44150. tc->setVisible (false);
  44151. const int index = oldIndexes.remove (i);
  44152. owner->addChildComponent (tc, index);
  44153. --i;
  44154. }
  44155. }
  44156. owner->resized();
  44157. }
  44158. }
  44159. void layout (const int preferredWidth)
  44160. {
  44161. const int indent = 8;
  44162. int x = indent;
  44163. int y = indent;
  44164. int maxX = 0;
  44165. for (int i = 0; i < getNumChildComponents(); ++i)
  44166. {
  44167. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44168. if (tc != 0)
  44169. {
  44170. int preferredSize = 1, minSize = 1, maxSize = 1;
  44171. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44172. {
  44173. if (x + preferredSize > preferredWidth && x > indent)
  44174. {
  44175. x = indent;
  44176. y += height;
  44177. }
  44178. tc->setBounds (x, y, preferredSize, height);
  44179. x += preferredSize;
  44180. maxX = jmax (maxX, x);
  44181. }
  44182. }
  44183. }
  44184. setSize (maxX + 8, y + height + 8);
  44185. }
  44186. void getIdealSize (int& idealWidth, int& idealHeight)
  44187. {
  44188. idealWidth = getWidth();
  44189. idealHeight = getHeight();
  44190. }
  44191. private:
  44192. Component::SafePointer<Toolbar> owner;
  44193. const int height;
  44194. Array <int> oldIndexes;
  44195. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44196. };
  44197. Toolbar::Toolbar()
  44198. : vertical (false),
  44199. isEditingActive (false),
  44200. toolbarStyle (Toolbar::iconsOnly)
  44201. {
  44202. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44203. missingItemsButton->setAlwaysOnTop (true);
  44204. missingItemsButton->addListener (this);
  44205. }
  44206. Toolbar::~Toolbar()
  44207. {
  44208. items.clear();
  44209. }
  44210. void Toolbar::setVertical (const bool shouldBeVertical)
  44211. {
  44212. if (vertical != shouldBeVertical)
  44213. {
  44214. vertical = shouldBeVertical;
  44215. resized();
  44216. }
  44217. }
  44218. void Toolbar::clear()
  44219. {
  44220. items.clear();
  44221. resized();
  44222. }
  44223. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44224. {
  44225. if (itemId == ToolbarItemFactory::separatorBarId)
  44226. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44227. else if (itemId == ToolbarItemFactory::spacerId)
  44228. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44229. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44230. return new ToolbarSpacerComp (itemId, 0, false);
  44231. return factory.createItem (itemId);
  44232. }
  44233. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44234. const int itemId,
  44235. const int insertIndex)
  44236. {
  44237. // An ID can't be zero - this might indicate a mistake somewhere?
  44238. jassert (itemId != 0);
  44239. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44240. if (tc != 0)
  44241. {
  44242. #if JUCE_DEBUG
  44243. Array <int> allowedIds;
  44244. factory.getAllToolbarItemIds (allowedIds);
  44245. // If your factory can create an item for a given ID, it must also return
  44246. // that ID from its getAllToolbarItemIds() method!
  44247. jassert (allowedIds.contains (itemId));
  44248. #endif
  44249. items.insert (insertIndex, tc);
  44250. addAndMakeVisible (tc, insertIndex);
  44251. }
  44252. }
  44253. void Toolbar::addItem (ToolbarItemFactory& factory,
  44254. const int itemId,
  44255. const int insertIndex)
  44256. {
  44257. addItemInternal (factory, itemId, insertIndex);
  44258. resized();
  44259. }
  44260. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44261. {
  44262. Array <int> ids;
  44263. factoryToUse.getDefaultItemSet (ids);
  44264. clear();
  44265. for (int i = 0; i < ids.size(); ++i)
  44266. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44267. resized();
  44268. }
  44269. void Toolbar::removeToolbarItem (const int itemIndex)
  44270. {
  44271. items.remove (itemIndex);
  44272. resized();
  44273. }
  44274. int Toolbar::getNumItems() const throw()
  44275. {
  44276. return items.size();
  44277. }
  44278. int Toolbar::getItemId (const int itemIndex) const throw()
  44279. {
  44280. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44281. return tc != 0 ? tc->getItemId() : 0;
  44282. }
  44283. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44284. {
  44285. return items [itemIndex];
  44286. }
  44287. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44288. {
  44289. for (;;)
  44290. {
  44291. index += delta;
  44292. ToolbarItemComponent* const tc = getItemComponent (index);
  44293. if (tc == 0)
  44294. break;
  44295. if (tc->isActive)
  44296. return tc;
  44297. }
  44298. return 0;
  44299. }
  44300. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44301. {
  44302. if (toolbarStyle != newStyle)
  44303. {
  44304. toolbarStyle = newStyle;
  44305. updateAllItemPositions (false);
  44306. }
  44307. }
  44308. const String Toolbar::toString() const
  44309. {
  44310. String s ("TB:");
  44311. for (int i = 0; i < getNumItems(); ++i)
  44312. s << getItemId(i) << ' ';
  44313. return s.trimEnd();
  44314. }
  44315. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44316. const String& savedVersion)
  44317. {
  44318. if (! savedVersion.startsWith ("TB:"))
  44319. return false;
  44320. StringArray tokens;
  44321. tokens.addTokens (savedVersion.substring (3), false);
  44322. clear();
  44323. for (int i = 0; i < tokens.size(); ++i)
  44324. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44325. resized();
  44326. return true;
  44327. }
  44328. void Toolbar::paint (Graphics& g)
  44329. {
  44330. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44331. }
  44332. int Toolbar::getThickness() const throw()
  44333. {
  44334. return vertical ? getWidth() : getHeight();
  44335. }
  44336. int Toolbar::getLength() const throw()
  44337. {
  44338. return vertical ? getHeight() : getWidth();
  44339. }
  44340. void Toolbar::setEditingActive (const bool active)
  44341. {
  44342. if (isEditingActive != active)
  44343. {
  44344. isEditingActive = active;
  44345. updateAllItemPositions (false);
  44346. }
  44347. }
  44348. void Toolbar::resized()
  44349. {
  44350. updateAllItemPositions (false);
  44351. }
  44352. void Toolbar::updateAllItemPositions (const bool animate)
  44353. {
  44354. if (getWidth() > 0 && getHeight() > 0)
  44355. {
  44356. StretchableObjectResizer resizer;
  44357. int i;
  44358. for (i = 0; i < items.size(); ++i)
  44359. {
  44360. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44361. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44362. : ToolbarItemComponent::normalMode);
  44363. tc->setStyle (toolbarStyle);
  44364. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44365. int preferredSize = 1, minSize = 1, maxSize = 1;
  44366. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44367. preferredSize, minSize, maxSize))
  44368. {
  44369. tc->isActive = true;
  44370. resizer.addItem (preferredSize, minSize, maxSize,
  44371. spacer != 0 ? spacer->getResizeOrder() : 2);
  44372. }
  44373. else
  44374. {
  44375. tc->isActive = false;
  44376. tc->setVisible (false);
  44377. }
  44378. }
  44379. resizer.resizeToFit (getLength());
  44380. int totalLength = 0;
  44381. for (i = 0; i < resizer.getNumItems(); ++i)
  44382. totalLength += (int) resizer.getItemSize (i);
  44383. const bool itemsOffTheEnd = totalLength > getLength();
  44384. const int extrasButtonSize = getThickness() / 2;
  44385. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44386. missingItemsButton->setVisible (itemsOffTheEnd);
  44387. missingItemsButton->setEnabled (! isEditingActive);
  44388. if (vertical)
  44389. missingItemsButton->setCentrePosition (getWidth() / 2,
  44390. getHeight() - 4 - extrasButtonSize / 2);
  44391. else
  44392. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44393. getHeight() / 2);
  44394. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44395. : missingItemsButton->getX()) - 4
  44396. : getLength();
  44397. int pos = 0, activeIndex = 0;
  44398. for (i = 0; i < items.size(); ++i)
  44399. {
  44400. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44401. if (tc->isActive)
  44402. {
  44403. const int size = (int) resizer.getItemSize (activeIndex++);
  44404. Rectangle<int> newBounds;
  44405. if (vertical)
  44406. newBounds.setBounds (0, pos, getWidth(), size);
  44407. else
  44408. newBounds.setBounds (pos, 0, size, getHeight());
  44409. if (animate)
  44410. {
  44411. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44412. }
  44413. else
  44414. {
  44415. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44416. tc->setBounds (newBounds);
  44417. }
  44418. pos += size;
  44419. tc->setVisible (pos <= maxLength
  44420. && ((! tc->isBeingDragged)
  44421. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44422. }
  44423. }
  44424. }
  44425. }
  44426. void Toolbar::buttonClicked (Button*)
  44427. {
  44428. jassert (missingItemsButton->isShowing());
  44429. if (missingItemsButton->isShowing())
  44430. {
  44431. PopupMenu m;
  44432. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44433. m.showMenuAsync (PopupMenu::Options().withTargetComponent (missingItemsButton), 0);
  44434. }
  44435. }
  44436. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44437. Component* /*sourceComponent*/)
  44438. {
  44439. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44440. }
  44441. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44442. {
  44443. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44444. if (tc != 0)
  44445. {
  44446. if (! items.contains (tc))
  44447. {
  44448. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44449. {
  44450. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44451. if (palette != 0)
  44452. palette->replaceComponent (tc);
  44453. }
  44454. else
  44455. {
  44456. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44457. }
  44458. items.add (tc);
  44459. addChildComponent (tc);
  44460. updateAllItemPositions (true);
  44461. }
  44462. for (int i = getNumItems(); --i >= 0;)
  44463. {
  44464. const int currentIndex = items.indexOf (tc);
  44465. int newIndex = currentIndex;
  44466. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44467. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44468. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44469. .getComponentDestination (getChildComponent (newIndex)));
  44470. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44471. if (prev != 0)
  44472. {
  44473. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44474. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44475. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44476. {
  44477. newIndex = getIndexOfChildComponent (prev);
  44478. }
  44479. }
  44480. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44481. if (next != 0)
  44482. {
  44483. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44484. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44485. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44486. {
  44487. newIndex = getIndexOfChildComponent (next) + 1;
  44488. }
  44489. }
  44490. if (newIndex == currentIndex)
  44491. break;
  44492. items.removeObject (tc, false);
  44493. removeChildComponent (tc);
  44494. addChildComponent (tc, newIndex);
  44495. items.insert (newIndex, tc);
  44496. updateAllItemPositions (true);
  44497. }
  44498. }
  44499. }
  44500. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44501. {
  44502. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44503. if (tc != 0 && isParentOf (tc))
  44504. {
  44505. items.removeObject (tc, false);
  44506. removeChildComponent (tc);
  44507. updateAllItemPositions (true);
  44508. }
  44509. }
  44510. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44511. {
  44512. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44513. if (tc != 0)
  44514. tc->setState (Button::buttonNormal);
  44515. }
  44516. void Toolbar::mouseDown (const MouseEvent&)
  44517. {
  44518. }
  44519. class ToolbarCustomisationDialog : public DialogWindow
  44520. {
  44521. public:
  44522. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44523. Toolbar* const toolbar_,
  44524. const int optionFlags)
  44525. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44526. toolbar (toolbar_)
  44527. {
  44528. setContentOwned (new CustomiserPanel (factory, toolbar, optionFlags), true);
  44529. setResizable (true, true);
  44530. setResizeLimits (400, 300, 1500, 1000);
  44531. positionNearBar();
  44532. }
  44533. ~ToolbarCustomisationDialog()
  44534. {
  44535. toolbar->setEditingActive (false);
  44536. }
  44537. void closeButtonPressed()
  44538. {
  44539. setVisible (false);
  44540. }
  44541. bool canModalEventBeSentToComponent (const Component* comp)
  44542. {
  44543. return toolbar->isParentOf (comp);
  44544. }
  44545. void positionNearBar()
  44546. {
  44547. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44548. const int tbx = toolbar->getScreenX();
  44549. const int tby = toolbar->getScreenY();
  44550. const int gap = 8;
  44551. int x, y;
  44552. if (toolbar->isVertical())
  44553. {
  44554. y = tby;
  44555. if (tbx > screenSize.getCentreX())
  44556. x = tbx - getWidth() - gap;
  44557. else
  44558. x = tbx + toolbar->getWidth() + gap;
  44559. }
  44560. else
  44561. {
  44562. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44563. if (tby > screenSize.getCentreY())
  44564. y = tby - getHeight() - gap;
  44565. else
  44566. y = tby + toolbar->getHeight() + gap;
  44567. }
  44568. setTopLeftPosition (x, y);
  44569. }
  44570. private:
  44571. Toolbar* const toolbar;
  44572. class CustomiserPanel : public Component,
  44573. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44574. private ButtonListener
  44575. {
  44576. public:
  44577. CustomiserPanel (ToolbarItemFactory& factory_,
  44578. Toolbar* const toolbar_,
  44579. const int optionFlags)
  44580. : factory (factory_),
  44581. toolbar (toolbar_),
  44582. palette (factory_, toolbar_),
  44583. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44584. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44585. defaultButton (TRANS ("Restore to default set of items"))
  44586. {
  44587. addAndMakeVisible (&palette);
  44588. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44589. | Toolbar::allowIconsWithTextChoice
  44590. | Toolbar::allowTextOnlyChoice)) != 0)
  44591. {
  44592. addAndMakeVisible (&styleBox);
  44593. styleBox.setEditableText (false);
  44594. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44595. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44596. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44597. int selectedStyle = 0;
  44598. switch (toolbar_->getStyle())
  44599. {
  44600. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44601. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44602. case Toolbar::textOnly: selectedStyle = 3; break;
  44603. }
  44604. styleBox.setSelectedId (selectedStyle);
  44605. styleBox.addListener (this);
  44606. }
  44607. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44608. {
  44609. addAndMakeVisible (&defaultButton);
  44610. defaultButton.addListener (this);
  44611. }
  44612. addAndMakeVisible (&instructions);
  44613. instructions.setFont (Font (13.0f));
  44614. setSize (500, 300);
  44615. }
  44616. void comboBoxChanged (ComboBox*)
  44617. {
  44618. switch (styleBox.getSelectedId())
  44619. {
  44620. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44621. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44622. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44623. }
  44624. palette.resized(); // to make it update the styles
  44625. }
  44626. void buttonClicked (Button*)
  44627. {
  44628. toolbar->addDefaultItems (factory);
  44629. }
  44630. void paint (Graphics& g)
  44631. {
  44632. Colour background;
  44633. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44634. if (dw != 0)
  44635. background = dw->getBackgroundColour();
  44636. g.setColour (background.contrasting().withAlpha (0.3f));
  44637. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44638. }
  44639. void resized()
  44640. {
  44641. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44642. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44643. defaultButton.changeWidthToFitText (22);
  44644. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44645. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44646. }
  44647. private:
  44648. ToolbarItemFactory& factory;
  44649. Toolbar* const toolbar;
  44650. ToolbarItemPalette palette;
  44651. Label instructions;
  44652. ComboBox styleBox;
  44653. TextButton defaultButton;
  44654. };
  44655. };
  44656. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44657. {
  44658. setEditingActive (true);
  44659. (new ToolbarCustomisationDialog (factory, this, optionFlags))
  44660. ->enterModalState (true, 0, true);
  44661. }
  44662. END_JUCE_NAMESPACE
  44663. /*** End of inlined file: juce_Toolbar.cpp ***/
  44664. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44665. BEGIN_JUCE_NAMESPACE
  44666. ToolbarItemFactory::ToolbarItemFactory()
  44667. {
  44668. }
  44669. ToolbarItemFactory::~ToolbarItemFactory()
  44670. {
  44671. }
  44672. class ItemDragAndDropOverlayComponent : public Component
  44673. {
  44674. public:
  44675. ItemDragAndDropOverlayComponent()
  44676. : isDragging (false)
  44677. {
  44678. setAlwaysOnTop (true);
  44679. setRepaintsOnMouseActivity (true);
  44680. setMouseCursor (MouseCursor::DraggingHandCursor);
  44681. }
  44682. void paint (Graphics& g)
  44683. {
  44684. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44685. if (isMouseOverOrDragging()
  44686. && tc != 0
  44687. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44688. {
  44689. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44690. g.drawRect (0, 0, getWidth(), getHeight(),
  44691. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44692. }
  44693. }
  44694. void mouseDown (const MouseEvent& e)
  44695. {
  44696. isDragging = false;
  44697. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44698. if (tc != 0)
  44699. {
  44700. tc->dragOffsetX = e.x;
  44701. tc->dragOffsetY = e.y;
  44702. }
  44703. }
  44704. void mouseDrag (const MouseEvent& e)
  44705. {
  44706. if (! (isDragging || e.mouseWasClicked()))
  44707. {
  44708. isDragging = true;
  44709. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44710. if (dnd != 0)
  44711. {
  44712. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44713. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44714. if (tc != 0)
  44715. {
  44716. tc->isBeingDragged = true;
  44717. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44718. tc->setVisible (false);
  44719. }
  44720. }
  44721. }
  44722. }
  44723. void mouseUp (const MouseEvent&)
  44724. {
  44725. isDragging = false;
  44726. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44727. if (tc != 0)
  44728. {
  44729. tc->isBeingDragged = false;
  44730. Toolbar* const tb = tc->getToolbar();
  44731. if (tb != 0)
  44732. tb->updateAllItemPositions (true);
  44733. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44734. delete tc;
  44735. }
  44736. }
  44737. void parentSizeChanged()
  44738. {
  44739. setBounds (0, 0, getParentWidth(), getParentHeight());
  44740. }
  44741. private:
  44742. bool isDragging;
  44743. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44744. };
  44745. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44746. const String& labelText,
  44747. const bool isBeingUsedAsAButton_)
  44748. : Button (labelText),
  44749. itemId (itemId_),
  44750. mode (normalMode),
  44751. toolbarStyle (Toolbar::iconsOnly),
  44752. dragOffsetX (0),
  44753. dragOffsetY (0),
  44754. isActive (true),
  44755. isBeingDragged (false),
  44756. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44757. {
  44758. // Your item ID can't be 0!
  44759. jassert (itemId_ != 0);
  44760. }
  44761. ToolbarItemComponent::~ToolbarItemComponent()
  44762. {
  44763. overlayComp = 0;
  44764. }
  44765. Toolbar* ToolbarItemComponent::getToolbar() const
  44766. {
  44767. return dynamic_cast <Toolbar*> (getParentComponent());
  44768. }
  44769. bool ToolbarItemComponent::isToolbarVertical() const
  44770. {
  44771. const Toolbar* const t = getToolbar();
  44772. return t != 0 && t->isVertical();
  44773. }
  44774. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44775. {
  44776. if (toolbarStyle != newStyle)
  44777. {
  44778. toolbarStyle = newStyle;
  44779. repaint();
  44780. resized();
  44781. }
  44782. }
  44783. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44784. {
  44785. if (isBeingUsedAsAButton)
  44786. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44787. over, down, *this);
  44788. if (toolbarStyle != Toolbar::iconsOnly)
  44789. {
  44790. const int indent = contentArea.getX();
  44791. int y = indent;
  44792. int h = getHeight() - indent * 2;
  44793. if (toolbarStyle == Toolbar::iconsWithText)
  44794. {
  44795. y = contentArea.getBottom() + indent / 2;
  44796. h -= contentArea.getHeight();
  44797. }
  44798. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44799. getButtonText(), *this);
  44800. }
  44801. if (! contentArea.isEmpty())
  44802. {
  44803. Graphics::ScopedSaveState ss (g);
  44804. g.reduceClipRegion (contentArea);
  44805. g.setOrigin (contentArea.getX(), contentArea.getY());
  44806. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44807. }
  44808. }
  44809. void ToolbarItemComponent::resized()
  44810. {
  44811. if (toolbarStyle != Toolbar::textOnly)
  44812. {
  44813. const int indent = jmin (proportionOfWidth (0.08f),
  44814. proportionOfHeight (0.08f));
  44815. contentArea = Rectangle<int> (indent, indent,
  44816. getWidth() - indent * 2,
  44817. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44818. : (getHeight() - indent * 2));
  44819. }
  44820. else
  44821. {
  44822. contentArea = Rectangle<int>();
  44823. }
  44824. contentAreaChanged (contentArea);
  44825. }
  44826. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44827. {
  44828. if (mode != newMode)
  44829. {
  44830. mode = newMode;
  44831. repaint();
  44832. if (mode == normalMode)
  44833. {
  44834. overlayComp = 0;
  44835. }
  44836. else if (overlayComp == 0)
  44837. {
  44838. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44839. overlayComp->parentSizeChanged();
  44840. }
  44841. resized();
  44842. }
  44843. }
  44844. END_JUCE_NAMESPACE
  44845. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44846. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44847. BEGIN_JUCE_NAMESPACE
  44848. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44849. Toolbar* const toolbar_)
  44850. : factory (factory_),
  44851. toolbar (toolbar_)
  44852. {
  44853. Component* const itemHolder = new Component();
  44854. viewport.setViewedComponent (itemHolder);
  44855. Array <int> allIds;
  44856. factory.getAllToolbarItemIds (allIds);
  44857. for (int i = 0; i < allIds.size(); ++i)
  44858. addComponent (allIds.getUnchecked (i), -1);
  44859. addAndMakeVisible (&viewport);
  44860. }
  44861. ToolbarItemPalette::~ToolbarItemPalette()
  44862. {
  44863. }
  44864. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44865. {
  44866. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  44867. jassert (tc != 0);
  44868. if (tc != 0)
  44869. {
  44870. items.insert (index, tc);
  44871. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  44872. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44873. }
  44874. }
  44875. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44876. {
  44877. const int index = items.indexOf (comp);
  44878. jassert (index >= 0);
  44879. items.removeObject (comp, false);
  44880. addComponent (comp->getItemId(), index);
  44881. resized();
  44882. }
  44883. void ToolbarItemPalette::resized()
  44884. {
  44885. viewport.setBoundsInset (BorderSize<int> (1));
  44886. Component* const itemHolder = viewport.getViewedComponent();
  44887. const int indent = 8;
  44888. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  44889. const int height = toolbar->getThickness();
  44890. int x = indent;
  44891. int y = indent;
  44892. int maxX = 0;
  44893. for (int i = 0; i < items.size(); ++i)
  44894. {
  44895. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44896. tc->setStyle (toolbar->getStyle());
  44897. int preferredSize = 1, minSize = 1, maxSize = 1;
  44898. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44899. {
  44900. if (x + preferredSize > preferredWidth && x > indent)
  44901. {
  44902. x = indent;
  44903. y += height;
  44904. }
  44905. tc->setBounds (x, y, preferredSize, height);
  44906. x += preferredSize + 8;
  44907. maxX = jmax (maxX, x);
  44908. }
  44909. }
  44910. itemHolder->setSize (maxX, y + height + 8);
  44911. }
  44912. END_JUCE_NAMESPACE
  44913. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44914. /*** Start of inlined file: juce_TreeView.cpp ***/
  44915. BEGIN_JUCE_NAMESPACE
  44916. class TreeViewContentComponent : public Component,
  44917. public TooltipClient
  44918. {
  44919. public:
  44920. TreeViewContentComponent (TreeView& owner_)
  44921. : owner (owner_),
  44922. buttonUnderMouse (0),
  44923. isDragging (false)
  44924. {
  44925. }
  44926. void mouseDown (const MouseEvent& e)
  44927. {
  44928. updateButtonUnderMouse (e);
  44929. isDragging = false;
  44930. needSelectionOnMouseUp = false;
  44931. Rectangle<int> pos;
  44932. TreeViewItem* const item = findItemAt (e.y, pos);
  44933. if (item == 0)
  44934. return;
  44935. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44936. // as selection clicks)
  44937. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44938. {
  44939. if (e.x >= pos.getX() - owner.getIndentSize())
  44940. item->setOpen (! item->isOpen());
  44941. // (clicks to the left of an open/close button are ignored)
  44942. }
  44943. else
  44944. {
  44945. // mouse-down inside the body of the item..
  44946. if (! owner.isMultiSelectEnabled())
  44947. item->setSelected (true, true);
  44948. else if (item->isSelected())
  44949. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44950. else
  44951. selectBasedOnModifiers (item, e.mods);
  44952. if (e.x >= pos.getX())
  44953. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44954. }
  44955. }
  44956. void mouseUp (const MouseEvent& e)
  44957. {
  44958. updateButtonUnderMouse (e);
  44959. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44960. {
  44961. Rectangle<int> pos;
  44962. TreeViewItem* const item = findItemAt (e.y, pos);
  44963. if (item != 0)
  44964. selectBasedOnModifiers (item, e.mods);
  44965. }
  44966. }
  44967. void mouseDoubleClick (const MouseEvent& e)
  44968. {
  44969. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44970. {
  44971. Rectangle<int> pos;
  44972. TreeViewItem* const item = findItemAt (e.y, pos);
  44973. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44974. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44975. }
  44976. }
  44977. void mouseDrag (const MouseEvent& e)
  44978. {
  44979. if (isEnabled()
  44980. && ! (isDragging || e.mouseWasClicked()
  44981. || e.getDistanceFromDragStart() < 5
  44982. || e.mods.isPopupMenu()))
  44983. {
  44984. isDragging = true;
  44985. Rectangle<int> pos;
  44986. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44987. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44988. {
  44989. const String dragDescription (item->getDragSourceDescription());
  44990. if (dragDescription.isNotEmpty())
  44991. {
  44992. DragAndDropContainer* const dragContainer
  44993. = DragAndDropContainer::findParentDragContainerFor (this);
  44994. if (dragContainer != 0)
  44995. {
  44996. pos.setSize (pos.getWidth(), item->itemHeight);
  44997. Image dragImage (Component::createComponentSnapshot (pos, true));
  44998. dragImage.multiplyAllAlphas (0.6f);
  44999. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45000. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45001. }
  45002. else
  45003. {
  45004. // to be able to do a drag-and-drop operation, the treeview needs to
  45005. // be inside a component which is also a DragAndDropContainer.
  45006. jassertfalse;
  45007. }
  45008. }
  45009. }
  45010. }
  45011. }
  45012. void mouseMove (const MouseEvent& e)
  45013. {
  45014. updateButtonUnderMouse (e);
  45015. }
  45016. void mouseExit (const MouseEvent& e)
  45017. {
  45018. updateButtonUnderMouse (e);
  45019. }
  45020. void paint (Graphics& g)
  45021. {
  45022. if (owner.rootItem != 0)
  45023. {
  45024. owner.handleAsyncUpdate();
  45025. if (! owner.rootItemVisible)
  45026. g.setOrigin (0, -owner.rootItem->itemHeight);
  45027. owner.rootItem->paintRecursively (g, getWidth());
  45028. }
  45029. }
  45030. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45031. {
  45032. if (owner.rootItem != 0)
  45033. {
  45034. owner.handleAsyncUpdate();
  45035. if (! owner.rootItemVisible)
  45036. y += owner.rootItem->itemHeight;
  45037. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45038. if (ti != 0)
  45039. itemPosition = ti->getItemPosition (false);
  45040. return ti;
  45041. }
  45042. return 0;
  45043. }
  45044. void updateComponents()
  45045. {
  45046. const int visibleTop = -getY();
  45047. const int visibleBottom = visibleTop + getParentHeight();
  45048. {
  45049. for (int i = items.size(); --i >= 0;)
  45050. items.getUnchecked(i)->shouldKeep = false;
  45051. }
  45052. {
  45053. TreeViewItem* item = owner.rootItem;
  45054. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45055. while (item != 0 && y < visibleBottom)
  45056. {
  45057. y += item->itemHeight;
  45058. if (y >= visibleTop)
  45059. {
  45060. RowItem* const ri = findItem (item->uid);
  45061. if (ri != 0)
  45062. {
  45063. ri->shouldKeep = true;
  45064. }
  45065. else
  45066. {
  45067. Component* const comp = item->createItemComponent();
  45068. if (comp != 0)
  45069. {
  45070. items.add (new RowItem (item, comp, item->uid));
  45071. addAndMakeVisible (comp);
  45072. }
  45073. }
  45074. }
  45075. item = item->getNextVisibleItem (true);
  45076. }
  45077. }
  45078. for (int i = items.size(); --i >= 0;)
  45079. {
  45080. RowItem* const ri = items.getUnchecked(i);
  45081. bool keep = false;
  45082. if (isParentOf (ri->component))
  45083. {
  45084. if (ri->shouldKeep)
  45085. {
  45086. Rectangle<int> pos (ri->item->getItemPosition (false));
  45087. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45088. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45089. {
  45090. keep = true;
  45091. ri->component->setBounds (pos);
  45092. }
  45093. }
  45094. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45095. {
  45096. keep = true;
  45097. ri->component->setSize (0, 0);
  45098. }
  45099. }
  45100. if (! keep)
  45101. items.remove (i);
  45102. }
  45103. }
  45104. void updateButtonUnderMouse (const MouseEvent& e)
  45105. {
  45106. TreeViewItem* newItem = 0;
  45107. if (owner.openCloseButtonsVisible)
  45108. {
  45109. Rectangle<int> pos;
  45110. TreeViewItem* item = findItemAt (e.y, pos);
  45111. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45112. {
  45113. newItem = item;
  45114. if (! newItem->mightContainSubItems())
  45115. newItem = 0;
  45116. }
  45117. }
  45118. if (buttonUnderMouse != newItem)
  45119. {
  45120. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45121. {
  45122. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45123. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45124. }
  45125. buttonUnderMouse = newItem;
  45126. if (buttonUnderMouse != 0)
  45127. {
  45128. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45129. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45130. }
  45131. }
  45132. }
  45133. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45134. {
  45135. return item == buttonUnderMouse;
  45136. }
  45137. void resized()
  45138. {
  45139. owner.itemsChanged();
  45140. }
  45141. const String getTooltip()
  45142. {
  45143. Rectangle<int> pos;
  45144. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45145. if (item != 0)
  45146. return item->getTooltip();
  45147. return owner.getTooltip();
  45148. }
  45149. private:
  45150. TreeView& owner;
  45151. struct RowItem
  45152. {
  45153. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45154. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45155. {
  45156. }
  45157. ~RowItem()
  45158. {
  45159. delete component.get();
  45160. }
  45161. WeakReference<Component> component;
  45162. TreeViewItem* item;
  45163. int uid;
  45164. bool shouldKeep;
  45165. };
  45166. OwnedArray <RowItem> items;
  45167. TreeViewItem* buttonUnderMouse;
  45168. bool isDragging, needSelectionOnMouseUp;
  45169. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45170. {
  45171. TreeViewItem* firstSelected = 0;
  45172. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45173. {
  45174. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45175. jassert (lastSelected != 0);
  45176. int rowStart = firstSelected->getRowNumberInTree();
  45177. int rowEnd = lastSelected->getRowNumberInTree();
  45178. if (rowStart > rowEnd)
  45179. swapVariables (rowStart, rowEnd);
  45180. int ourRow = item->getRowNumberInTree();
  45181. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45182. if (ourRow > otherEnd)
  45183. swapVariables (ourRow, otherEnd);
  45184. for (int i = ourRow; i <= otherEnd; ++i)
  45185. owner.getItemOnRow (i)->setSelected (true, false);
  45186. }
  45187. else
  45188. {
  45189. const bool cmd = modifiers.isCommandDown();
  45190. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45191. }
  45192. }
  45193. bool containsItem (TreeViewItem* const item) const throw()
  45194. {
  45195. for (int i = items.size(); --i >= 0;)
  45196. if (items.getUnchecked(i)->item == item)
  45197. return true;
  45198. return false;
  45199. }
  45200. RowItem* findItem (const int uid) const throw()
  45201. {
  45202. for (int i = items.size(); --i >= 0;)
  45203. {
  45204. RowItem* const ri = items.getUnchecked(i);
  45205. if (ri->uid == uid)
  45206. return ri;
  45207. }
  45208. return 0;
  45209. }
  45210. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45211. {
  45212. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45213. {
  45214. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45215. if (source->isDragging())
  45216. {
  45217. Component* const underMouse = source->getComponentUnderMouse();
  45218. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45219. return true;
  45220. }
  45221. }
  45222. return false;
  45223. }
  45224. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45225. };
  45226. class TreeView::TreeViewport : public Viewport
  45227. {
  45228. public:
  45229. TreeViewport() throw() : lastX (-1) {}
  45230. void updateComponents (const bool triggerResize = false)
  45231. {
  45232. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45233. if (tvc != 0)
  45234. {
  45235. if (triggerResize)
  45236. tvc->resized();
  45237. else
  45238. tvc->updateComponents();
  45239. }
  45240. repaint();
  45241. }
  45242. void visibleAreaChanged (const Rectangle<int>& newVisibleArea)
  45243. {
  45244. const bool hasScrolledSideways = (newVisibleArea.getX() != lastX);
  45245. lastX = newVisibleArea.getX();
  45246. updateComponents (hasScrolledSideways);
  45247. }
  45248. private:
  45249. int lastX;
  45250. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45251. };
  45252. TreeView::TreeView (const String& componentName)
  45253. : Component (componentName),
  45254. rootItem (0),
  45255. indentSize (24),
  45256. defaultOpenness (false),
  45257. needsRecalculating (true),
  45258. rootItemVisible (true),
  45259. multiSelectEnabled (false),
  45260. openCloseButtonsVisible (true)
  45261. {
  45262. addAndMakeVisible (viewport = new TreeViewport());
  45263. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45264. viewport->setWantsKeyboardFocus (false);
  45265. setWantsKeyboardFocus (true);
  45266. }
  45267. TreeView::~TreeView()
  45268. {
  45269. if (rootItem != 0)
  45270. rootItem->setOwnerView (0);
  45271. }
  45272. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45273. {
  45274. if (rootItem != newRootItem)
  45275. {
  45276. if (newRootItem != 0)
  45277. {
  45278. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45279. if (newRootItem->ownerView != 0)
  45280. newRootItem->ownerView->setRootItem (0);
  45281. }
  45282. if (rootItem != 0)
  45283. rootItem->setOwnerView (0);
  45284. rootItem = newRootItem;
  45285. if (newRootItem != 0)
  45286. newRootItem->setOwnerView (this);
  45287. needsRecalculating = true;
  45288. handleAsyncUpdate();
  45289. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45290. {
  45291. rootItem->setOpen (false); // force a re-open
  45292. rootItem->setOpen (true);
  45293. }
  45294. }
  45295. }
  45296. void TreeView::deleteRootItem()
  45297. {
  45298. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45299. setRootItem (0);
  45300. }
  45301. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45302. {
  45303. rootItemVisible = shouldBeVisible;
  45304. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45305. {
  45306. rootItem->setOpen (false); // force a re-open
  45307. rootItem->setOpen (true);
  45308. }
  45309. itemsChanged();
  45310. }
  45311. void TreeView::colourChanged()
  45312. {
  45313. setOpaque (findColour (backgroundColourId).isOpaque());
  45314. repaint();
  45315. }
  45316. void TreeView::setIndentSize (const int newIndentSize)
  45317. {
  45318. if (indentSize != newIndentSize)
  45319. {
  45320. indentSize = newIndentSize;
  45321. resized();
  45322. }
  45323. }
  45324. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45325. {
  45326. if (defaultOpenness != isOpenByDefault)
  45327. {
  45328. defaultOpenness = isOpenByDefault;
  45329. itemsChanged();
  45330. }
  45331. }
  45332. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45333. {
  45334. multiSelectEnabled = canMultiSelect;
  45335. }
  45336. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45337. {
  45338. if (openCloseButtonsVisible != shouldBeVisible)
  45339. {
  45340. openCloseButtonsVisible = shouldBeVisible;
  45341. itemsChanged();
  45342. }
  45343. }
  45344. Viewport* TreeView::getViewport() const throw()
  45345. {
  45346. return viewport;
  45347. }
  45348. void TreeView::clearSelectedItems()
  45349. {
  45350. if (rootItem != 0)
  45351. rootItem->deselectAllRecursively();
  45352. }
  45353. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45354. {
  45355. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45356. }
  45357. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45358. {
  45359. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45360. }
  45361. int TreeView::getNumRowsInTree() const
  45362. {
  45363. if (rootItem != 0)
  45364. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45365. return 0;
  45366. }
  45367. TreeViewItem* TreeView::getItemOnRow (int index) const
  45368. {
  45369. if (! rootItemVisible)
  45370. ++index;
  45371. if (rootItem != 0 && index >= 0)
  45372. return rootItem->getItemOnRow (index);
  45373. return 0;
  45374. }
  45375. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45376. {
  45377. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45378. Rectangle<int> pos;
  45379. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45380. }
  45381. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45382. {
  45383. if (rootItem == 0)
  45384. return 0;
  45385. return rootItem->findItemFromIdentifierString (identifierString);
  45386. }
  45387. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45388. {
  45389. XmlElement* e = 0;
  45390. if (rootItem != 0)
  45391. {
  45392. e = rootItem->getOpennessState();
  45393. if (e != 0 && alsoIncludeScrollPosition)
  45394. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45395. }
  45396. return e;
  45397. }
  45398. void TreeView::restoreOpennessState (const XmlElement& newState)
  45399. {
  45400. if (rootItem != 0)
  45401. {
  45402. rootItem->restoreOpennessState (newState);
  45403. if (newState.hasAttribute ("scrollPos"))
  45404. viewport->setViewPosition (viewport->getViewPositionX(),
  45405. newState.getIntAttribute ("scrollPos"));
  45406. }
  45407. }
  45408. void TreeView::paint (Graphics& g)
  45409. {
  45410. g.fillAll (findColour (backgroundColourId));
  45411. }
  45412. void TreeView::resized()
  45413. {
  45414. viewport->setBounds (getLocalBounds());
  45415. itemsChanged();
  45416. handleAsyncUpdate();
  45417. }
  45418. void TreeView::enablementChanged()
  45419. {
  45420. repaint();
  45421. }
  45422. void TreeView::moveSelectedRow (int delta)
  45423. {
  45424. if (delta == 0)
  45425. return;
  45426. int rowSelected = 0;
  45427. TreeViewItem* const firstSelected = getSelectedItem (0);
  45428. if (firstSelected != 0)
  45429. rowSelected = firstSelected->getRowNumberInTree();
  45430. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45431. for (;;)
  45432. {
  45433. TreeViewItem* item = getItemOnRow (rowSelected);
  45434. if (item != 0)
  45435. {
  45436. if (! item->canBeSelected())
  45437. {
  45438. // if the row we want to highlight doesn't allow it, try skipping
  45439. // to the next item..
  45440. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45441. rowSelected + (delta < 0 ? -1 : 1));
  45442. if (rowSelected != nextRowToTry)
  45443. {
  45444. rowSelected = nextRowToTry;
  45445. continue;
  45446. }
  45447. else
  45448. {
  45449. break;
  45450. }
  45451. }
  45452. item->setSelected (true, true);
  45453. scrollToKeepItemVisible (item);
  45454. }
  45455. break;
  45456. }
  45457. }
  45458. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45459. {
  45460. if (item != 0 && item->ownerView == this)
  45461. {
  45462. handleAsyncUpdate();
  45463. item = item->getDeepestOpenParentItem();
  45464. int y = item->y;
  45465. int viewTop = viewport->getViewPositionY();
  45466. if (y < viewTop)
  45467. {
  45468. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45469. }
  45470. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45471. {
  45472. viewport->setViewPosition (viewport->getViewPositionX(),
  45473. (y + item->itemHeight) - viewport->getViewHeight());
  45474. }
  45475. }
  45476. }
  45477. bool TreeView::keyPressed (const KeyPress& key)
  45478. {
  45479. if (key.isKeyCode (KeyPress::upKey))
  45480. {
  45481. moveSelectedRow (-1);
  45482. }
  45483. else if (key.isKeyCode (KeyPress::downKey))
  45484. {
  45485. moveSelectedRow (1);
  45486. }
  45487. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45488. {
  45489. if (rootItem != 0)
  45490. {
  45491. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45492. if (key.isKeyCode (KeyPress::pageUpKey))
  45493. rowsOnScreen = -rowsOnScreen;
  45494. moveSelectedRow (rowsOnScreen);
  45495. }
  45496. }
  45497. else if (key.isKeyCode (KeyPress::homeKey))
  45498. {
  45499. moveSelectedRow (-0x3fffffff);
  45500. }
  45501. else if (key.isKeyCode (KeyPress::endKey))
  45502. {
  45503. moveSelectedRow (0x3fffffff);
  45504. }
  45505. else if (key.isKeyCode (KeyPress::returnKey))
  45506. {
  45507. TreeViewItem* const firstSelected = getSelectedItem (0);
  45508. if (firstSelected != 0)
  45509. firstSelected->setOpen (! firstSelected->isOpen());
  45510. }
  45511. else if (key.isKeyCode (KeyPress::leftKey))
  45512. {
  45513. TreeViewItem* const firstSelected = getSelectedItem (0);
  45514. if (firstSelected != 0)
  45515. {
  45516. if (firstSelected->isOpen())
  45517. {
  45518. firstSelected->setOpen (false);
  45519. }
  45520. else
  45521. {
  45522. TreeViewItem* parent = firstSelected->parentItem;
  45523. if ((! rootItemVisible) && parent == rootItem)
  45524. parent = 0;
  45525. if (parent != 0)
  45526. {
  45527. parent->setSelected (true, true);
  45528. scrollToKeepItemVisible (parent);
  45529. }
  45530. }
  45531. }
  45532. }
  45533. else if (key.isKeyCode (KeyPress::rightKey))
  45534. {
  45535. TreeViewItem* const firstSelected = getSelectedItem (0);
  45536. if (firstSelected != 0)
  45537. {
  45538. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45539. moveSelectedRow (1);
  45540. else
  45541. firstSelected->setOpen (true);
  45542. }
  45543. }
  45544. else
  45545. {
  45546. return false;
  45547. }
  45548. return true;
  45549. }
  45550. void TreeView::itemsChanged() throw()
  45551. {
  45552. needsRecalculating = true;
  45553. repaint();
  45554. triggerAsyncUpdate();
  45555. }
  45556. void TreeView::handleAsyncUpdate()
  45557. {
  45558. if (needsRecalculating)
  45559. {
  45560. needsRecalculating = false;
  45561. const ScopedLock sl (nodeAlterationLock);
  45562. if (rootItem != 0)
  45563. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45564. viewport->updateComponents();
  45565. if (rootItem != 0)
  45566. {
  45567. viewport->getViewedComponent()
  45568. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45569. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45570. }
  45571. else
  45572. {
  45573. viewport->getViewedComponent()->setSize (0, 0);
  45574. }
  45575. }
  45576. }
  45577. class TreeView::InsertPointHighlight : public Component
  45578. {
  45579. public:
  45580. InsertPointHighlight()
  45581. : lastItem (0)
  45582. {
  45583. setSize (100, 12);
  45584. setAlwaysOnTop (true);
  45585. setInterceptsMouseClicks (false, false);
  45586. }
  45587. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45588. {
  45589. lastItem = item;
  45590. lastIndex = insertIndex;
  45591. const int offset = getHeight() / 2;
  45592. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45593. }
  45594. void paint (Graphics& g)
  45595. {
  45596. Path p;
  45597. const float h = (float) getHeight();
  45598. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45599. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45600. p.lineTo ((float) getWidth(), h / 2.0f);
  45601. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45602. g.strokePath (p, PathStrokeType (2.0f));
  45603. }
  45604. TreeViewItem* lastItem;
  45605. int lastIndex;
  45606. private:
  45607. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45608. };
  45609. class TreeView::TargetGroupHighlight : public Component
  45610. {
  45611. public:
  45612. TargetGroupHighlight()
  45613. {
  45614. setAlwaysOnTop (true);
  45615. setInterceptsMouseClicks (false, false);
  45616. }
  45617. void setTargetPosition (TreeViewItem* const item) throw()
  45618. {
  45619. Rectangle<int> r (item->getItemPosition (true));
  45620. r.setHeight (item->getItemHeight());
  45621. setBounds (r);
  45622. }
  45623. void paint (Graphics& g)
  45624. {
  45625. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45626. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45627. }
  45628. private:
  45629. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45630. };
  45631. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45632. {
  45633. beginDragAutoRepeat (100);
  45634. if (dragInsertPointHighlight == 0)
  45635. {
  45636. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45637. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45638. }
  45639. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45640. dragTargetGroupHighlight->setTargetPosition (item);
  45641. }
  45642. void TreeView::hideDragHighlight() throw()
  45643. {
  45644. dragInsertPointHighlight = 0;
  45645. dragTargetGroupHighlight = 0;
  45646. }
  45647. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45648. const StringArray& files, const String& sourceDescription,
  45649. Component* sourceComponent) const throw()
  45650. {
  45651. insertIndex = 0;
  45652. TreeViewItem* item = getItemAt (y);
  45653. if (item == 0)
  45654. return 0;
  45655. Rectangle<int> itemPos (item->getItemPosition (true));
  45656. insertIndex = item->getIndexInParent();
  45657. const int oldY = y;
  45658. y = itemPos.getY();
  45659. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45660. {
  45661. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45662. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45663. {
  45664. // Check if we're trying to drag into an empty group item..
  45665. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45666. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45667. {
  45668. insertIndex = 0;
  45669. x = itemPos.getX() + getIndentSize();
  45670. y = itemPos.getBottom();
  45671. return item;
  45672. }
  45673. }
  45674. }
  45675. if (oldY > itemPos.getCentreY())
  45676. {
  45677. y += item->getItemHeight();
  45678. while (item->isLastOfSiblings() && item->parentItem != 0
  45679. && item->parentItem->parentItem != 0)
  45680. {
  45681. if (x > itemPos.getX())
  45682. break;
  45683. item = item->parentItem;
  45684. itemPos = item->getItemPosition (true);
  45685. insertIndex = item->getIndexInParent();
  45686. }
  45687. ++insertIndex;
  45688. }
  45689. x = itemPos.getX();
  45690. return item->parentItem;
  45691. }
  45692. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45693. {
  45694. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45695. int insertIndex;
  45696. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45697. if (item != 0)
  45698. {
  45699. if (scrolled || dragInsertPointHighlight == 0
  45700. || dragInsertPointHighlight->lastItem != item
  45701. || dragInsertPointHighlight->lastIndex != insertIndex)
  45702. {
  45703. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45704. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45705. showDragHighlight (item, insertIndex, x, y);
  45706. else
  45707. hideDragHighlight();
  45708. }
  45709. }
  45710. else
  45711. {
  45712. hideDragHighlight();
  45713. }
  45714. }
  45715. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45716. {
  45717. hideDragHighlight();
  45718. int insertIndex;
  45719. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45720. if (item != 0)
  45721. {
  45722. if (files.size() > 0)
  45723. {
  45724. if (item->isInterestedInFileDrag (files))
  45725. item->filesDropped (files, insertIndex);
  45726. }
  45727. else
  45728. {
  45729. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45730. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45731. }
  45732. }
  45733. }
  45734. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45735. {
  45736. return true;
  45737. }
  45738. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45739. {
  45740. fileDragMove (files, x, y);
  45741. }
  45742. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45743. {
  45744. handleDrag (files, String::empty, 0, x, y);
  45745. }
  45746. void TreeView::fileDragExit (const StringArray&)
  45747. {
  45748. hideDragHighlight();
  45749. }
  45750. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45751. {
  45752. handleDrop (files, String::empty, 0, x, y);
  45753. }
  45754. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45755. {
  45756. return true;
  45757. }
  45758. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45759. {
  45760. itemDragMove (sourceDescription, sourceComponent, x, y);
  45761. }
  45762. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45763. {
  45764. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45765. }
  45766. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45767. {
  45768. hideDragHighlight();
  45769. }
  45770. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45771. {
  45772. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45773. }
  45774. enum TreeViewOpenness
  45775. {
  45776. opennessDefault = 0,
  45777. opennessClosed = 1,
  45778. opennessOpen = 2
  45779. };
  45780. TreeViewItem::TreeViewItem()
  45781. : ownerView (0),
  45782. parentItem (0),
  45783. y (0),
  45784. itemHeight (0),
  45785. totalHeight (0),
  45786. selected (false),
  45787. redrawNeeded (true),
  45788. drawLinesInside (true),
  45789. drawsInLeftMargin (false),
  45790. openness (opennessDefault)
  45791. {
  45792. static int nextUID = 0;
  45793. uid = nextUID++;
  45794. }
  45795. TreeViewItem::~TreeViewItem()
  45796. {
  45797. }
  45798. const String TreeViewItem::getUniqueName() const
  45799. {
  45800. return String::empty;
  45801. }
  45802. void TreeViewItem::itemOpennessChanged (bool)
  45803. {
  45804. }
  45805. int TreeViewItem::getNumSubItems() const throw()
  45806. {
  45807. return subItems.size();
  45808. }
  45809. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45810. {
  45811. return subItems [index];
  45812. }
  45813. void TreeViewItem::clearSubItems()
  45814. {
  45815. if (subItems.size() > 0)
  45816. {
  45817. if (ownerView != 0)
  45818. {
  45819. const ScopedLock sl (ownerView->nodeAlterationLock);
  45820. subItems.clear();
  45821. treeHasChanged();
  45822. }
  45823. else
  45824. {
  45825. subItems.clear();
  45826. }
  45827. }
  45828. }
  45829. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45830. {
  45831. if (newItem != 0)
  45832. {
  45833. newItem->parentItem = this;
  45834. newItem->setOwnerView (ownerView);
  45835. newItem->y = 0;
  45836. newItem->itemHeight = newItem->getItemHeight();
  45837. newItem->totalHeight = 0;
  45838. newItem->itemWidth = newItem->getItemWidth();
  45839. newItem->totalWidth = 0;
  45840. if (ownerView != 0)
  45841. {
  45842. const ScopedLock sl (ownerView->nodeAlterationLock);
  45843. subItems.insert (insertPosition, newItem);
  45844. treeHasChanged();
  45845. if (newItem->isOpen())
  45846. newItem->itemOpennessChanged (true);
  45847. }
  45848. else
  45849. {
  45850. subItems.insert (insertPosition, newItem);
  45851. if (newItem->isOpen())
  45852. newItem->itemOpennessChanged (true);
  45853. }
  45854. }
  45855. }
  45856. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45857. {
  45858. if (ownerView != 0)
  45859. {
  45860. const ScopedLock sl (ownerView->nodeAlterationLock);
  45861. if (isPositiveAndBelow (index, subItems.size()))
  45862. {
  45863. subItems.remove (index, deleteItem);
  45864. treeHasChanged();
  45865. }
  45866. }
  45867. else
  45868. {
  45869. subItems.remove (index, deleteItem);
  45870. }
  45871. }
  45872. bool TreeViewItem::isOpen() const throw()
  45873. {
  45874. if (openness == opennessDefault)
  45875. return ownerView != 0 && ownerView->defaultOpenness;
  45876. else
  45877. return openness == opennessOpen;
  45878. }
  45879. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45880. {
  45881. if (isOpen() != shouldBeOpen)
  45882. {
  45883. openness = shouldBeOpen ? opennessOpen
  45884. : opennessClosed;
  45885. treeHasChanged();
  45886. itemOpennessChanged (isOpen());
  45887. }
  45888. }
  45889. bool TreeViewItem::isSelected() const throw()
  45890. {
  45891. return selected;
  45892. }
  45893. void TreeViewItem::deselectAllRecursively()
  45894. {
  45895. setSelected (false, false);
  45896. for (int i = 0; i < subItems.size(); ++i)
  45897. subItems.getUnchecked(i)->deselectAllRecursively();
  45898. }
  45899. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45900. const bool deselectOtherItemsFirst)
  45901. {
  45902. if (shouldBeSelected && ! canBeSelected())
  45903. return;
  45904. if (deselectOtherItemsFirst)
  45905. getTopLevelItem()->deselectAllRecursively();
  45906. if (shouldBeSelected != selected)
  45907. {
  45908. selected = shouldBeSelected;
  45909. if (ownerView != 0)
  45910. ownerView->repaint();
  45911. itemSelectionChanged (shouldBeSelected);
  45912. }
  45913. }
  45914. void TreeViewItem::paintItem (Graphics&, int, int)
  45915. {
  45916. }
  45917. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45918. {
  45919. ownerView->getLookAndFeel()
  45920. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45921. }
  45922. void TreeViewItem::itemClicked (const MouseEvent&)
  45923. {
  45924. }
  45925. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45926. {
  45927. if (mightContainSubItems())
  45928. setOpen (! isOpen());
  45929. }
  45930. void TreeViewItem::itemSelectionChanged (bool)
  45931. {
  45932. }
  45933. const String TreeViewItem::getTooltip()
  45934. {
  45935. return String::empty;
  45936. }
  45937. const String TreeViewItem::getDragSourceDescription()
  45938. {
  45939. return String::empty;
  45940. }
  45941. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45942. {
  45943. return false;
  45944. }
  45945. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45946. {
  45947. }
  45948. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45949. {
  45950. return false;
  45951. }
  45952. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45953. {
  45954. }
  45955. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45956. {
  45957. const int indentX = getIndentX();
  45958. int width = itemWidth;
  45959. if (ownerView != 0 && width < 0)
  45960. width = ownerView->viewport->getViewWidth() - indentX;
  45961. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45962. if (relativeToTreeViewTopLeft)
  45963. r -= ownerView->viewport->getViewPosition();
  45964. return r;
  45965. }
  45966. void TreeViewItem::treeHasChanged() const throw()
  45967. {
  45968. if (ownerView != 0)
  45969. ownerView->itemsChanged();
  45970. }
  45971. void TreeViewItem::repaintItem() const
  45972. {
  45973. if (ownerView != 0 && areAllParentsOpen())
  45974. {
  45975. Rectangle<int> r (getItemPosition (true));
  45976. r.setLeft (0);
  45977. ownerView->viewport->repaint (r);
  45978. }
  45979. }
  45980. bool TreeViewItem::areAllParentsOpen() const throw()
  45981. {
  45982. return parentItem == 0
  45983. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45984. }
  45985. void TreeViewItem::updatePositions (int newY)
  45986. {
  45987. y = newY;
  45988. itemHeight = getItemHeight();
  45989. totalHeight = itemHeight;
  45990. itemWidth = getItemWidth();
  45991. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45992. if (isOpen())
  45993. {
  45994. newY += totalHeight;
  45995. for (int i = 0; i < subItems.size(); ++i)
  45996. {
  45997. TreeViewItem* const ti = subItems.getUnchecked(i);
  45998. ti->updatePositions (newY);
  45999. newY += ti->totalHeight;
  46000. totalHeight += ti->totalHeight;
  46001. totalWidth = jmax (totalWidth, ti->totalWidth);
  46002. }
  46003. }
  46004. }
  46005. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46006. {
  46007. TreeViewItem* result = this;
  46008. TreeViewItem* item = this;
  46009. while (item->parentItem != 0)
  46010. {
  46011. item = item->parentItem;
  46012. if (! item->isOpen())
  46013. result = item;
  46014. }
  46015. return result;
  46016. }
  46017. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46018. {
  46019. ownerView = newOwner;
  46020. for (int i = subItems.size(); --i >= 0;)
  46021. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46022. }
  46023. int TreeViewItem::getIndentX() const throw()
  46024. {
  46025. const int indentWidth = ownerView->getIndentSize();
  46026. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46027. if (! ownerView->openCloseButtonsVisible)
  46028. x -= indentWidth;
  46029. TreeViewItem* p = parentItem;
  46030. while (p != 0)
  46031. {
  46032. x += indentWidth;
  46033. p = p->parentItem;
  46034. }
  46035. return x;
  46036. }
  46037. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46038. {
  46039. drawsInLeftMargin = canDrawInLeftMargin;
  46040. }
  46041. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46042. {
  46043. jassert (ownerView != 0);
  46044. if (ownerView == 0)
  46045. return;
  46046. const int indent = getIndentX();
  46047. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46048. {
  46049. Graphics::ScopedSaveState ss (g);
  46050. g.setOrigin (indent, 0);
  46051. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46052. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46053. paintItem (g, itemW, itemHeight);
  46054. }
  46055. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46056. const float halfH = itemHeight * 0.5f;
  46057. int depth = 0;
  46058. TreeViewItem* p = parentItem;
  46059. while (p != 0)
  46060. {
  46061. ++depth;
  46062. p = p->parentItem;
  46063. }
  46064. if (! ownerView->rootItemVisible)
  46065. --depth;
  46066. const int indentWidth = ownerView->getIndentSize();
  46067. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46068. {
  46069. float x = (depth + 0.5f) * indentWidth;
  46070. if (depth >= 0)
  46071. {
  46072. if (parentItem != 0 && parentItem->drawLinesInside)
  46073. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46074. if ((parentItem != 0 && parentItem->drawLinesInside)
  46075. || (parentItem == 0 && drawLinesInside))
  46076. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46077. }
  46078. p = parentItem;
  46079. int d = depth;
  46080. while (p != 0 && --d >= 0)
  46081. {
  46082. x -= (float) indentWidth;
  46083. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46084. && ! p->isLastOfSiblings())
  46085. {
  46086. g.drawLine (x, 0, x, (float) itemHeight);
  46087. }
  46088. p = p->parentItem;
  46089. }
  46090. if (mightContainSubItems())
  46091. {
  46092. Graphics::ScopedSaveState ss (g);
  46093. g.setOrigin (depth * indentWidth, 0);
  46094. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46095. paintOpenCloseButton (g, indentWidth, itemHeight,
  46096. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46097. ->isMouseOverButton (this));
  46098. }
  46099. }
  46100. if (isOpen())
  46101. {
  46102. const Rectangle<int> clip (g.getClipBounds());
  46103. for (int i = 0; i < subItems.size(); ++i)
  46104. {
  46105. TreeViewItem* const ti = subItems.getUnchecked(i);
  46106. const int relY = ti->y - y;
  46107. if (relY >= clip.getBottom())
  46108. break;
  46109. if (relY + ti->totalHeight >= clip.getY())
  46110. {
  46111. Graphics::ScopedSaveState ss (g);
  46112. g.setOrigin (0, relY);
  46113. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46114. ti->paintRecursively (g, width);
  46115. }
  46116. }
  46117. }
  46118. }
  46119. bool TreeViewItem::isLastOfSiblings() const throw()
  46120. {
  46121. return parentItem == 0
  46122. || parentItem->subItems.getLast() == this;
  46123. }
  46124. int TreeViewItem::getIndexInParent() const throw()
  46125. {
  46126. return parentItem == 0 ? 0
  46127. : parentItem->subItems.indexOf (this);
  46128. }
  46129. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46130. {
  46131. return parentItem == 0 ? this
  46132. : parentItem->getTopLevelItem();
  46133. }
  46134. int TreeViewItem::getNumRows() const throw()
  46135. {
  46136. int num = 1;
  46137. if (isOpen())
  46138. {
  46139. for (int i = subItems.size(); --i >= 0;)
  46140. num += subItems.getUnchecked(i)->getNumRows();
  46141. }
  46142. return num;
  46143. }
  46144. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46145. {
  46146. if (index == 0)
  46147. return this;
  46148. if (index > 0 && isOpen())
  46149. {
  46150. --index;
  46151. for (int i = 0; i < subItems.size(); ++i)
  46152. {
  46153. TreeViewItem* const item = subItems.getUnchecked(i);
  46154. if (index == 0)
  46155. return item;
  46156. const int numRows = item->getNumRows();
  46157. if (numRows > index)
  46158. return item->getItemOnRow (index);
  46159. index -= numRows;
  46160. }
  46161. }
  46162. return 0;
  46163. }
  46164. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46165. {
  46166. if (isPositiveAndBelow (targetY, totalHeight))
  46167. {
  46168. const int h = itemHeight;
  46169. if (targetY < h)
  46170. return this;
  46171. if (isOpen())
  46172. {
  46173. targetY -= h;
  46174. for (int i = 0; i < subItems.size(); ++i)
  46175. {
  46176. TreeViewItem* const ti = subItems.getUnchecked(i);
  46177. if (targetY < ti->totalHeight)
  46178. return ti->findItemRecursively (targetY);
  46179. targetY -= ti->totalHeight;
  46180. }
  46181. }
  46182. }
  46183. return 0;
  46184. }
  46185. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  46186. {
  46187. int total = isSelected() ? 1 : 0;
  46188. if (depth != 0)
  46189. for (int i = subItems.size(); --i >= 0;)
  46190. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  46191. return total;
  46192. }
  46193. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46194. {
  46195. if (isSelected())
  46196. {
  46197. if (index == 0)
  46198. return this;
  46199. --index;
  46200. }
  46201. if (index >= 0)
  46202. {
  46203. for (int i = 0; i < subItems.size(); ++i)
  46204. {
  46205. TreeViewItem* const item = subItems.getUnchecked(i);
  46206. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46207. if (found != 0)
  46208. return found;
  46209. index -= item->countSelectedItemsRecursively (-1);
  46210. }
  46211. }
  46212. return 0;
  46213. }
  46214. int TreeViewItem::getRowNumberInTree() const throw()
  46215. {
  46216. if (parentItem != 0 && ownerView != 0)
  46217. {
  46218. int n = 1 + parentItem->getRowNumberInTree();
  46219. int ourIndex = parentItem->subItems.indexOf (this);
  46220. jassert (ourIndex >= 0);
  46221. while (--ourIndex >= 0)
  46222. n += parentItem->subItems [ourIndex]->getNumRows();
  46223. if (parentItem->parentItem == 0
  46224. && ! ownerView->rootItemVisible)
  46225. --n;
  46226. return n;
  46227. }
  46228. else
  46229. {
  46230. return 0;
  46231. }
  46232. }
  46233. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46234. {
  46235. drawLinesInside = drawLines;
  46236. }
  46237. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46238. {
  46239. if (recurse && isOpen() && subItems.size() > 0)
  46240. return subItems [0];
  46241. if (parentItem != 0)
  46242. {
  46243. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46244. if (nextIndex >= parentItem->subItems.size())
  46245. return parentItem->getNextVisibleItem (false);
  46246. return parentItem->subItems [nextIndex];
  46247. }
  46248. return 0;
  46249. }
  46250. const String TreeViewItem::getItemIdentifierString() const
  46251. {
  46252. String s;
  46253. if (parentItem != 0)
  46254. s = parentItem->getItemIdentifierString();
  46255. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46256. }
  46257. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46258. {
  46259. const String thisId (getUniqueName());
  46260. if (thisId == identifierString)
  46261. return this;
  46262. if (identifierString.startsWith (thisId + "/"))
  46263. {
  46264. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46265. bool wasOpen = isOpen();
  46266. setOpen (true);
  46267. for (int i = subItems.size(); --i >= 0;)
  46268. {
  46269. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46270. if (item != 0)
  46271. return item;
  46272. }
  46273. setOpen (wasOpen);
  46274. }
  46275. return 0;
  46276. }
  46277. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46278. {
  46279. if (e.hasTagName ("CLOSED"))
  46280. {
  46281. setOpen (false);
  46282. }
  46283. else if (e.hasTagName ("OPEN"))
  46284. {
  46285. setOpen (true);
  46286. forEachXmlChildElement (e, n)
  46287. {
  46288. const String id (n->getStringAttribute ("id"));
  46289. for (int i = 0; i < subItems.size(); ++i)
  46290. {
  46291. TreeViewItem* const ti = subItems.getUnchecked(i);
  46292. if (ti->getUniqueName() == id)
  46293. {
  46294. ti->restoreOpennessState (*n);
  46295. break;
  46296. }
  46297. }
  46298. }
  46299. }
  46300. }
  46301. XmlElement* TreeViewItem::getOpennessState() const throw()
  46302. {
  46303. const String name (getUniqueName());
  46304. if (name.isNotEmpty())
  46305. {
  46306. XmlElement* e;
  46307. if (isOpen())
  46308. {
  46309. e = new XmlElement ("OPEN");
  46310. for (int i = 0; i < subItems.size(); ++i)
  46311. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46312. }
  46313. else
  46314. {
  46315. e = new XmlElement ("CLOSED");
  46316. }
  46317. e->setAttribute ("id", name);
  46318. return e;
  46319. }
  46320. else
  46321. {
  46322. // trying to save the openness for an element that has no name - this won't
  46323. // work because it needs the names to identify what to open.
  46324. jassertfalse;
  46325. }
  46326. return 0;
  46327. }
  46328. TreeViewItem::OpennessRestorer::OpennessRestorer (TreeViewItem& treeViewItem_)
  46329. : treeViewItem (treeViewItem_),
  46330. oldOpenness (treeViewItem_.getOpennessState())
  46331. {
  46332. }
  46333. TreeViewItem::OpennessRestorer::~OpennessRestorer()
  46334. {
  46335. if (oldOpenness != 0)
  46336. treeViewItem.restoreOpennessState (*oldOpenness);
  46337. }
  46338. END_JUCE_NAMESPACE
  46339. /*** End of inlined file: juce_TreeView.cpp ***/
  46340. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46341. BEGIN_JUCE_NAMESPACE
  46342. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46343. : fileList (listToShow)
  46344. {
  46345. }
  46346. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46347. {
  46348. }
  46349. FileBrowserListener::~FileBrowserListener()
  46350. {
  46351. }
  46352. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46353. {
  46354. listeners.add (listener);
  46355. }
  46356. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46357. {
  46358. listeners.remove (listener);
  46359. }
  46360. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46361. {
  46362. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46363. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46364. }
  46365. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46366. {
  46367. if (fileList.getDirectory().exists())
  46368. {
  46369. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46370. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46371. }
  46372. }
  46373. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46374. {
  46375. if (fileList.getDirectory().exists())
  46376. {
  46377. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46378. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46379. }
  46380. }
  46381. END_JUCE_NAMESPACE
  46382. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46383. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46384. BEGIN_JUCE_NAMESPACE
  46385. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46386. TimeSliceThread& thread_)
  46387. : fileFilter (fileFilter_),
  46388. thread (thread_),
  46389. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46390. fileFindHandle (0),
  46391. shouldStop (true)
  46392. {
  46393. }
  46394. DirectoryContentsList::~DirectoryContentsList()
  46395. {
  46396. clear();
  46397. }
  46398. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46399. {
  46400. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46401. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46402. }
  46403. bool DirectoryContentsList::ignoresHiddenFiles() const
  46404. {
  46405. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46406. }
  46407. const File& DirectoryContentsList::getDirectory() const
  46408. {
  46409. return root;
  46410. }
  46411. void DirectoryContentsList::setDirectory (const File& directory,
  46412. const bool includeDirectories,
  46413. const bool includeFiles)
  46414. {
  46415. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46416. if (directory != root)
  46417. {
  46418. clear();
  46419. root = directory;
  46420. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46421. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46422. }
  46423. int newFlags = fileTypeFlags;
  46424. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46425. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46426. setTypeFlags (newFlags);
  46427. }
  46428. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46429. {
  46430. if (fileTypeFlags != newFlags)
  46431. {
  46432. fileTypeFlags = newFlags;
  46433. refresh();
  46434. }
  46435. }
  46436. void DirectoryContentsList::clear()
  46437. {
  46438. shouldStop = true;
  46439. thread.removeTimeSliceClient (this);
  46440. fileFindHandle = 0;
  46441. if (files.size() > 0)
  46442. {
  46443. files.clear();
  46444. changed();
  46445. }
  46446. }
  46447. void DirectoryContentsList::refresh()
  46448. {
  46449. clear();
  46450. if (root.isDirectory())
  46451. {
  46452. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46453. shouldStop = false;
  46454. thread.addTimeSliceClient (this);
  46455. }
  46456. }
  46457. int DirectoryContentsList::getNumFiles() const
  46458. {
  46459. return files.size();
  46460. }
  46461. bool DirectoryContentsList::getFileInfo (const int index,
  46462. FileInfo& result) const
  46463. {
  46464. const ScopedLock sl (fileListLock);
  46465. const FileInfo* const info = files [index];
  46466. if (info != 0)
  46467. {
  46468. result = *info;
  46469. return true;
  46470. }
  46471. return false;
  46472. }
  46473. const File DirectoryContentsList::getFile (const int index) const
  46474. {
  46475. const ScopedLock sl (fileListLock);
  46476. const FileInfo* const info = files [index];
  46477. if (info != 0)
  46478. return root.getChildFile (info->filename);
  46479. return File::nonexistent;
  46480. }
  46481. bool DirectoryContentsList::isStillLoading() const
  46482. {
  46483. return fileFindHandle != 0;
  46484. }
  46485. void DirectoryContentsList::changed()
  46486. {
  46487. sendChangeMessage();
  46488. }
  46489. int DirectoryContentsList::useTimeSlice()
  46490. {
  46491. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46492. bool hasChanged = false;
  46493. for (int i = 100; --i >= 0;)
  46494. {
  46495. if (! checkNextFile (hasChanged))
  46496. {
  46497. if (hasChanged)
  46498. changed();
  46499. return 500;
  46500. }
  46501. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46502. break;
  46503. }
  46504. if (hasChanged)
  46505. changed();
  46506. return 0;
  46507. }
  46508. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46509. {
  46510. if (fileFindHandle != 0)
  46511. {
  46512. bool fileFoundIsDir, isHidden, isReadOnly;
  46513. int64 fileSize;
  46514. Time modTime, creationTime;
  46515. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46516. &modTime, &creationTime, &isReadOnly))
  46517. {
  46518. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46519. fileSize, modTime, creationTime, isReadOnly))
  46520. {
  46521. hasChanged = true;
  46522. }
  46523. return true;
  46524. }
  46525. else
  46526. {
  46527. fileFindHandle = 0;
  46528. }
  46529. }
  46530. return false;
  46531. }
  46532. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46533. const DirectoryContentsList::FileInfo* const second)
  46534. {
  46535. #if JUCE_WINDOWS
  46536. if (first->isDirectory != second->isDirectory)
  46537. return first->isDirectory ? -1 : 1;
  46538. #endif
  46539. return first->filename.compareIgnoreCase (second->filename);
  46540. }
  46541. bool DirectoryContentsList::addFile (const File& file,
  46542. const bool isDir,
  46543. const int64 fileSize,
  46544. const Time& modTime,
  46545. const Time& creationTime,
  46546. const bool isReadOnly)
  46547. {
  46548. if (fileFilter == 0
  46549. || ((! isDir) && fileFilter->isFileSuitable (file))
  46550. || (isDir && fileFilter->isDirectorySuitable (file)))
  46551. {
  46552. ScopedPointer <FileInfo> info (new FileInfo());
  46553. info->filename = file.getFileName();
  46554. info->fileSize = fileSize;
  46555. info->modificationTime = modTime;
  46556. info->creationTime = creationTime;
  46557. info->isDirectory = isDir;
  46558. info->isReadOnly = isReadOnly;
  46559. const ScopedLock sl (fileListLock);
  46560. for (int i = files.size(); --i >= 0;)
  46561. if (files.getUnchecked(i)->filename == info->filename)
  46562. return false;
  46563. files.addSorted (*this, info.release());
  46564. return true;
  46565. }
  46566. return false;
  46567. }
  46568. END_JUCE_NAMESPACE
  46569. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46570. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46571. BEGIN_JUCE_NAMESPACE
  46572. FileBrowserComponent::FileBrowserComponent (int flags_,
  46573. const File& initialFileOrDirectory,
  46574. const FileFilter* fileFilter_,
  46575. FilePreviewComponent* previewComp_)
  46576. : FileFilter (String::empty),
  46577. fileFilter (fileFilter_),
  46578. flags (flags_),
  46579. previewComp (previewComp_),
  46580. currentPathBox ("path"),
  46581. fileLabel ("f", TRANS ("file:")),
  46582. thread ("Juce FileBrowser")
  46583. {
  46584. // You need to specify one or other of the open/save flags..
  46585. jassert ((flags & (saveMode | openMode)) != 0);
  46586. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46587. // You need to specify at least one of these flags..
  46588. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46589. String filename;
  46590. if (initialFileOrDirectory == File::nonexistent)
  46591. {
  46592. currentRoot = File::getCurrentWorkingDirectory();
  46593. }
  46594. else if (initialFileOrDirectory.isDirectory())
  46595. {
  46596. currentRoot = initialFileOrDirectory;
  46597. }
  46598. else
  46599. {
  46600. chosenFiles.add (initialFileOrDirectory);
  46601. currentRoot = initialFileOrDirectory.getParentDirectory();
  46602. filename = initialFileOrDirectory.getFileName();
  46603. }
  46604. fileList = new DirectoryContentsList (this, thread);
  46605. if ((flags & useTreeView) != 0)
  46606. {
  46607. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46608. fileListComponent = tree;
  46609. if ((flags & canSelectMultipleItems) != 0)
  46610. tree->setMultiSelectEnabled (true);
  46611. addAndMakeVisible (tree);
  46612. }
  46613. else
  46614. {
  46615. FileListComponent* const list = new FileListComponent (*fileList);
  46616. fileListComponent = list;
  46617. list->setOutlineThickness (1);
  46618. if ((flags & canSelectMultipleItems) != 0)
  46619. list->setMultipleSelectionEnabled (true);
  46620. addAndMakeVisible (list);
  46621. }
  46622. fileListComponent->addListener (this);
  46623. addAndMakeVisible (&currentPathBox);
  46624. currentPathBox.setEditableText (true);
  46625. StringArray rootNames, rootPaths;
  46626. getRoots (rootNames, rootPaths);
  46627. for (int i = 0; i < rootNames.size(); ++i)
  46628. {
  46629. if (rootNames[i].isEmpty())
  46630. currentPathBox.addSeparator();
  46631. else
  46632. currentPathBox.addItem (rootNames[i], i + 1);
  46633. }
  46634. currentPathBox.addSeparator();
  46635. currentPathBox.addListener (this);
  46636. addAndMakeVisible (&filenameBox);
  46637. filenameBox.setMultiLine (false);
  46638. filenameBox.setSelectAllWhenFocused (true);
  46639. filenameBox.setText (filename, false);
  46640. filenameBox.addListener (this);
  46641. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46642. addAndMakeVisible (&fileLabel);
  46643. fileLabel.attachToComponent (&filenameBox, true);
  46644. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46645. goUpButton->addListener (this);
  46646. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46647. if (previewComp != 0)
  46648. addAndMakeVisible (previewComp);
  46649. setRoot (currentRoot);
  46650. thread.startThread (4);
  46651. }
  46652. FileBrowserComponent::~FileBrowserComponent()
  46653. {
  46654. fileListComponent = 0;
  46655. fileList = 0;
  46656. thread.stopThread (10000);
  46657. }
  46658. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46659. {
  46660. listeners.add (newListener);
  46661. }
  46662. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46663. {
  46664. listeners.remove (listener);
  46665. }
  46666. bool FileBrowserComponent::isSaveMode() const throw()
  46667. {
  46668. return (flags & saveMode) != 0;
  46669. }
  46670. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46671. {
  46672. if (chosenFiles.size() == 0 && currentFileIsValid())
  46673. return 1;
  46674. return chosenFiles.size();
  46675. }
  46676. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46677. {
  46678. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46679. return currentRoot;
  46680. if (! filenameBox.isReadOnly())
  46681. return currentRoot.getChildFile (filenameBox.getText());
  46682. return chosenFiles[index];
  46683. }
  46684. bool FileBrowserComponent::currentFileIsValid() const
  46685. {
  46686. if (isSaveMode())
  46687. return ! getSelectedFile (0).isDirectory();
  46688. else
  46689. return getSelectedFile (0).exists();
  46690. }
  46691. const File FileBrowserComponent::getHighlightedFile() const throw()
  46692. {
  46693. return fileListComponent->getSelectedFile (0);
  46694. }
  46695. void FileBrowserComponent::deselectAllFiles()
  46696. {
  46697. fileListComponent->deselectAllFiles();
  46698. }
  46699. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46700. {
  46701. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46702. }
  46703. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46704. {
  46705. return true;
  46706. }
  46707. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46708. {
  46709. if (f.isDirectory())
  46710. return (flags & canSelectDirectories) != 0
  46711. && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46712. return (flags & canSelectFiles) != 0 && f.exists()
  46713. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46714. }
  46715. const File FileBrowserComponent::getRoot() const
  46716. {
  46717. return currentRoot;
  46718. }
  46719. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46720. {
  46721. if (currentRoot != newRootDirectory)
  46722. {
  46723. fileListComponent->scrollToTop();
  46724. String path (newRootDirectory.getFullPathName());
  46725. if (path.isEmpty())
  46726. path = File::separatorString;
  46727. StringArray rootNames, rootPaths;
  46728. getRoots (rootNames, rootPaths);
  46729. if (! rootPaths.contains (path, true))
  46730. {
  46731. bool alreadyListed = false;
  46732. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46733. {
  46734. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46735. {
  46736. alreadyListed = true;
  46737. break;
  46738. }
  46739. }
  46740. if (! alreadyListed)
  46741. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46742. }
  46743. }
  46744. currentRoot = newRootDirectory;
  46745. fileList->setDirectory (currentRoot, true, true);
  46746. String currentRootName (currentRoot.getFullPathName());
  46747. if (currentRootName.isEmpty())
  46748. currentRootName = File::separatorString;
  46749. currentPathBox.setText (currentRootName, true);
  46750. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46751. && currentRoot.getParentDirectory() != currentRoot);
  46752. }
  46753. void FileBrowserComponent::goUp()
  46754. {
  46755. setRoot (getRoot().getParentDirectory());
  46756. }
  46757. void FileBrowserComponent::refresh()
  46758. {
  46759. fileList->refresh();
  46760. }
  46761. void FileBrowserComponent::setFileFilter (const FileFilter* const newFileFilter)
  46762. {
  46763. if (fileFilter != newFileFilter)
  46764. {
  46765. fileFilter = newFileFilter;
  46766. refresh();
  46767. }
  46768. }
  46769. const String FileBrowserComponent::getActionVerb() const
  46770. {
  46771. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46772. }
  46773. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46774. {
  46775. return previewComp;
  46776. }
  46777. void FileBrowserComponent::resized()
  46778. {
  46779. getLookAndFeel()
  46780. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46781. &currentPathBox, &filenameBox, goUpButton);
  46782. }
  46783. void FileBrowserComponent::sendListenerChangeMessage()
  46784. {
  46785. Component::BailOutChecker checker (this);
  46786. if (previewComp != 0)
  46787. previewComp->selectedFileChanged (getSelectedFile (0));
  46788. // You shouldn't delete the browser when the file gets changed!
  46789. jassert (! checker.shouldBailOut());
  46790. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46791. }
  46792. void FileBrowserComponent::selectionChanged()
  46793. {
  46794. StringArray newFilenames;
  46795. bool resetChosenFiles = true;
  46796. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46797. {
  46798. const File f (fileListComponent->getSelectedFile (i));
  46799. if (isFileOrDirSuitable (f))
  46800. {
  46801. if (resetChosenFiles)
  46802. {
  46803. chosenFiles.clear();
  46804. resetChosenFiles = false;
  46805. }
  46806. chosenFiles.add (f);
  46807. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46808. }
  46809. }
  46810. if (newFilenames.size() > 0)
  46811. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46812. sendListenerChangeMessage();
  46813. }
  46814. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46815. {
  46816. Component::BailOutChecker checker (this);
  46817. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46818. }
  46819. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46820. {
  46821. if (f.isDirectory())
  46822. {
  46823. setRoot (f);
  46824. if ((flags & canSelectDirectories) != 0)
  46825. filenameBox.setText (String::empty);
  46826. }
  46827. else
  46828. {
  46829. Component::BailOutChecker checker (this);
  46830. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46831. }
  46832. }
  46833. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46834. {
  46835. (void) key;
  46836. #if JUCE_LINUX || JUCE_WINDOWS
  46837. if (key.getModifiers().isCommandDown()
  46838. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46839. {
  46840. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46841. fileList->refresh();
  46842. return true;
  46843. }
  46844. #endif
  46845. return false;
  46846. }
  46847. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46848. {
  46849. sendListenerChangeMessage();
  46850. }
  46851. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46852. {
  46853. if (filenameBox.getText().containsChar (File::separator))
  46854. {
  46855. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46856. if (f.isDirectory())
  46857. {
  46858. setRoot (f);
  46859. chosenFiles.clear();
  46860. filenameBox.setText (String::empty);
  46861. }
  46862. else
  46863. {
  46864. setRoot (f.getParentDirectory());
  46865. chosenFiles.clear();
  46866. chosenFiles.add (f);
  46867. filenameBox.setText (f.getFileName());
  46868. }
  46869. }
  46870. else
  46871. {
  46872. fileDoubleClicked (getSelectedFile (0));
  46873. }
  46874. }
  46875. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46876. {
  46877. }
  46878. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46879. {
  46880. if (! isSaveMode())
  46881. selectionChanged();
  46882. }
  46883. void FileBrowserComponent::buttonClicked (Button*)
  46884. {
  46885. goUp();
  46886. }
  46887. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46888. {
  46889. const String newText (currentPathBox.getText().trim().unquoted());
  46890. if (newText.isNotEmpty())
  46891. {
  46892. const int index = currentPathBox.getSelectedId() - 1;
  46893. StringArray rootNames, rootPaths;
  46894. getRoots (rootNames, rootPaths);
  46895. if (rootPaths [index].isNotEmpty())
  46896. {
  46897. setRoot (File (rootPaths [index]));
  46898. }
  46899. else
  46900. {
  46901. File f (newText);
  46902. for (;;)
  46903. {
  46904. if (f.isDirectory())
  46905. {
  46906. setRoot (f);
  46907. break;
  46908. }
  46909. if (f.getParentDirectory() == f)
  46910. break;
  46911. f = f.getParentDirectory();
  46912. }
  46913. }
  46914. }
  46915. }
  46916. void FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46917. {
  46918. #if JUCE_WINDOWS
  46919. Array<File> roots;
  46920. File::findFileSystemRoots (roots);
  46921. rootPaths.clear();
  46922. for (int i = 0; i < roots.size(); ++i)
  46923. {
  46924. const File& drive = roots.getReference(i);
  46925. String name (drive.getFullPathName());
  46926. rootPaths.add (name);
  46927. if (drive.isOnHardDisk())
  46928. {
  46929. String volume (drive.getVolumeLabel());
  46930. if (volume.isEmpty())
  46931. volume = TRANS("Hard Drive");
  46932. name << " [" << volume << ']';
  46933. }
  46934. else if (drive.isOnCDRomDrive())
  46935. {
  46936. name << TRANS(" [CD/DVD drive]");
  46937. }
  46938. rootNames.add (name);
  46939. }
  46940. rootPaths.add (String::empty);
  46941. rootNames.add (String::empty);
  46942. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46943. rootNames.add ("Documents");
  46944. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46945. rootNames.add ("Desktop");
  46946. #endif
  46947. #if JUCE_MAC
  46948. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46949. rootNames.add ("Home folder");
  46950. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46951. rootNames.add ("Documents");
  46952. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46953. rootNames.add ("Desktop");
  46954. rootPaths.add (String::empty);
  46955. rootNames.add (String::empty);
  46956. Array <File> volumes;
  46957. File vol ("/Volumes");
  46958. vol.findChildFiles (volumes, File::findDirectories, false);
  46959. for (int i = 0; i < volumes.size(); ++i)
  46960. {
  46961. const File& volume = volumes.getReference(i);
  46962. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46963. {
  46964. rootPaths.add (volume.getFullPathName());
  46965. rootNames.add (volume.getFileName());
  46966. }
  46967. }
  46968. #endif
  46969. #if JUCE_LINUX
  46970. rootPaths.add ("/");
  46971. rootNames.add ("/");
  46972. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46973. rootNames.add ("Home folder");
  46974. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46975. rootNames.add ("Desktop");
  46976. #endif
  46977. }
  46978. END_JUCE_NAMESPACE
  46979. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46980. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46981. BEGIN_JUCE_NAMESPACE
  46982. FileChooser::FileChooser (const String& chooserBoxTitle,
  46983. const File& currentFileOrDirectory,
  46984. const String& fileFilters,
  46985. const bool useNativeDialogBox_)
  46986. : title (chooserBoxTitle),
  46987. filters (fileFilters),
  46988. startingFile (currentFileOrDirectory),
  46989. useNativeDialogBox (useNativeDialogBox_)
  46990. {
  46991. #if JUCE_LINUX
  46992. useNativeDialogBox = false;
  46993. #endif
  46994. if (! fileFilters.containsNonWhitespaceChars())
  46995. filters = "*";
  46996. }
  46997. FileChooser::~FileChooser()
  46998. {
  46999. }
  47000. #if JUCE_MODAL_LOOPS_PERMITTED
  47001. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47002. {
  47003. return showDialog (false, true, false, false, false, previewComponent);
  47004. }
  47005. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47006. {
  47007. return showDialog (false, true, false, false, true, previewComponent);
  47008. }
  47009. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47010. {
  47011. return showDialog (true, true, false, false, true, previewComponent);
  47012. }
  47013. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47014. {
  47015. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47016. }
  47017. bool FileChooser::browseForDirectory()
  47018. {
  47019. return showDialog (true, false, false, false, false, 0);
  47020. }
  47021. bool FileChooser::showDialog (const bool selectsDirectories,
  47022. const bool selectsFiles,
  47023. const bool isSave,
  47024. const bool warnAboutOverwritingExistingFiles,
  47025. const bool selectMultipleFiles,
  47026. FilePreviewComponent* const previewComponent)
  47027. {
  47028. WeakReference<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47029. results.clear();
  47030. // the preview component needs to be the right size before you pass it in here..
  47031. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47032. && previewComponent->getHeight() > 10));
  47033. #if JUCE_WINDOWS
  47034. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47035. #elif JUCE_MAC
  47036. if (useNativeDialogBox && (previewComponent == 0))
  47037. #else
  47038. if (false)
  47039. #endif
  47040. {
  47041. showPlatformDialog (results, title, startingFile, filters,
  47042. selectsDirectories, selectsFiles, isSave,
  47043. warnAboutOverwritingExistingFiles,
  47044. selectMultipleFiles,
  47045. previewComponent);
  47046. }
  47047. else
  47048. {
  47049. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47050. selectsDirectories ? "*" : String::empty,
  47051. String::empty);
  47052. int flags = isSave ? FileBrowserComponent::saveMode
  47053. : FileBrowserComponent::openMode;
  47054. if (selectsFiles)
  47055. flags |= FileBrowserComponent::canSelectFiles;
  47056. if (selectsDirectories)
  47057. {
  47058. flags |= FileBrowserComponent::canSelectDirectories;
  47059. if (! isSave)
  47060. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47061. }
  47062. if (selectMultipleFiles)
  47063. flags |= FileBrowserComponent::canSelectMultipleItems;
  47064. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47065. FileChooserDialogBox box (title, String::empty,
  47066. browserComponent,
  47067. warnAboutOverwritingExistingFiles,
  47068. browserComponent.findColour (AlertWindow::backgroundColourId));
  47069. if (box.show())
  47070. {
  47071. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47072. results.add (browserComponent.getSelectedFile (i));
  47073. }
  47074. }
  47075. if (previouslyFocused != 0)
  47076. previouslyFocused->grabKeyboardFocus();
  47077. return results.size() > 0;
  47078. }
  47079. #endif
  47080. const File FileChooser::getResult() const
  47081. {
  47082. // if you've used a multiple-file select, you should use the getResults() method
  47083. // to retrieve all the files that were chosen.
  47084. jassert (results.size() <= 1);
  47085. return results.getFirst();
  47086. }
  47087. const Array<File>& FileChooser::getResults() const
  47088. {
  47089. return results;
  47090. }
  47091. FilePreviewComponent::FilePreviewComponent()
  47092. {
  47093. }
  47094. FilePreviewComponent::~FilePreviewComponent()
  47095. {
  47096. }
  47097. END_JUCE_NAMESPACE
  47098. /*** End of inlined file: juce_FileChooser.cpp ***/
  47099. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47100. BEGIN_JUCE_NAMESPACE
  47101. class FileChooserDialogBox::ContentComponent : public Component
  47102. {
  47103. public:
  47104. ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47105. : Component (name),
  47106. chooserComponent (chooserComponent_),
  47107. okButton (chooserComponent_.getActionVerb()),
  47108. cancelButton (TRANS ("Cancel")),
  47109. newFolderButton (TRANS ("New Folder")),
  47110. instructions (instructions_)
  47111. {
  47112. addAndMakeVisible (&chooserComponent);
  47113. addAndMakeVisible (&okButton);
  47114. okButton.addShortcut (KeyPress::returnKey);
  47115. addAndMakeVisible (&cancelButton);
  47116. cancelButton.addShortcut (KeyPress::escapeKey);
  47117. addChildComponent (&newFolderButton);
  47118. setInterceptsMouseClicks (false, true);
  47119. }
  47120. void paint (Graphics& g)
  47121. {
  47122. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47123. text.draw (g);
  47124. }
  47125. void resized()
  47126. {
  47127. const int buttonHeight = 26;
  47128. Rectangle<int> area (getLocalBounds());
  47129. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47130. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47131. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47132. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47133. Rectangle<int> buttonArea (area.reduced (16, 10));
  47134. okButton.changeWidthToFitText (buttonHeight);
  47135. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47136. buttonArea.removeFromRight (16);
  47137. cancelButton.changeWidthToFitText (buttonHeight);
  47138. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47139. newFolderButton.changeWidthToFitText (buttonHeight);
  47140. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47141. }
  47142. FileBrowserComponent& chooserComponent;
  47143. TextButton okButton, cancelButton, newFolderButton;
  47144. private:
  47145. String instructions;
  47146. GlyphArrangement text;
  47147. };
  47148. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47149. const String& instructions,
  47150. FileBrowserComponent& chooserComponent,
  47151. const bool warnAboutOverwritingExistingFiles_,
  47152. const Colour& backgroundColour)
  47153. : ResizableWindow (name, backgroundColour, true),
  47154. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47155. {
  47156. content = new ContentComponent (name, instructions, chooserComponent);
  47157. setContentOwned (content, false);
  47158. setResizable (true, true);
  47159. setResizeLimits (300, 300, 1200, 1000);
  47160. content->okButton.addListener (this);
  47161. content->cancelButton.addListener (this);
  47162. content->newFolderButton.addListener (this);
  47163. content->chooserComponent.addListener (this);
  47164. selectionChanged();
  47165. }
  47166. FileChooserDialogBox::~FileChooserDialogBox()
  47167. {
  47168. content->chooserComponent.removeListener (this);
  47169. }
  47170. #if JUCE_MODAL_LOOPS_PERMITTED
  47171. bool FileChooserDialogBox::show (int w, int h)
  47172. {
  47173. return showAt (-1, -1, w, h);
  47174. }
  47175. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47176. {
  47177. if (w <= 0)
  47178. {
  47179. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47180. if (previewComp != 0)
  47181. w = 400 + previewComp->getWidth();
  47182. else
  47183. w = 600;
  47184. }
  47185. if (h <= 0)
  47186. h = 500;
  47187. if (x < 0 || y < 0)
  47188. centreWithSize (w, h);
  47189. else
  47190. setBounds (x, y, w, h);
  47191. const bool ok = (runModalLoop() != 0);
  47192. setVisible (false);
  47193. return ok;
  47194. }
  47195. #endif
  47196. void FileChooserDialogBox::centreWithDefaultSize (Component* componentToCentreAround)
  47197. {
  47198. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47199. centreAroundComponent (componentToCentreAround,
  47200. previewComp != 0 ? 400 + previewComp->getWidth() : 600,
  47201. 500);
  47202. }
  47203. void FileChooserDialogBox::buttonClicked (Button* button)
  47204. {
  47205. if (button == &(content->okButton))
  47206. {
  47207. okButtonPressed();
  47208. }
  47209. else if (button == &(content->cancelButton))
  47210. {
  47211. closeButtonPressed();
  47212. }
  47213. else if (button == &(content->newFolderButton))
  47214. {
  47215. createNewFolder();
  47216. }
  47217. }
  47218. void FileChooserDialogBox::closeButtonPressed()
  47219. {
  47220. setVisible (false);
  47221. }
  47222. void FileChooserDialogBox::selectionChanged()
  47223. {
  47224. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47225. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  47226. && content->chooserComponent.getRoot().isDirectory());
  47227. }
  47228. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47229. {
  47230. }
  47231. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47232. {
  47233. selectionChanged();
  47234. content->okButton.triggerClick();
  47235. }
  47236. void FileChooserDialogBox::okToOverwriteFileCallback (int result, FileChooserDialogBox* box)
  47237. {
  47238. if (result != 0 && box != 0)
  47239. box->exitModalState (1);
  47240. }
  47241. void FileChooserDialogBox::okButtonPressed()
  47242. {
  47243. if (warnAboutOverwritingExistingFiles
  47244. && content->chooserComponent.isSaveMode()
  47245. && content->chooserComponent.getSelectedFile(0).exists())
  47246. {
  47247. AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47248. TRANS("File already exists"),
  47249. TRANS("There's already a file called:")
  47250. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47251. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47252. TRANS("overwrite"),
  47253. TRANS("cancel"),
  47254. this,
  47255. ModalCallbackFunction::forComponent (okToOverwriteFileCallback, this));
  47256. }
  47257. else
  47258. {
  47259. exitModalState (1);
  47260. }
  47261. }
  47262. void FileChooserDialogBox::createNewFolderCallback (int result, FileChooserDialogBox* box,
  47263. Component::SafePointer<AlertWindow> alert)
  47264. {
  47265. if (result != 0 && alert != 0 && box != 0)
  47266. {
  47267. alert->setVisible (false);
  47268. box->createNewFolderConfirmed (alert->getTextEditorContents ("name"));
  47269. }
  47270. }
  47271. void FileChooserDialogBox::createNewFolder()
  47272. {
  47273. File parent (content->chooserComponent.getRoot());
  47274. if (parent.isDirectory())
  47275. {
  47276. AlertWindow* aw = new AlertWindow (TRANS("New Folder"),
  47277. TRANS("Please enter the name for the folder"),
  47278. AlertWindow::NoIcon, this);
  47279. aw->addTextEditor ("name", String::empty, String::empty, false);
  47280. aw->addButton (TRANS("ok"), 1, KeyPress::returnKey);
  47281. aw->addButton (TRANS("cancel"), KeyPress::escapeKey);
  47282. aw->enterModalState (true,
  47283. ModalCallbackFunction::forComponent (createNewFolderCallback, this,
  47284. Component::SafePointer<AlertWindow> (aw)),
  47285. true);
  47286. }
  47287. }
  47288. void FileChooserDialogBox::createNewFolderConfirmed (const String& nameFromDialog)
  47289. {
  47290. const String name (File::createLegalFileName (nameFromDialog));
  47291. if (! name.isEmpty())
  47292. {
  47293. const File parent (content->chooserComponent.getRoot());
  47294. if (! parent.getChildFile (name).createDirectory())
  47295. {
  47296. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  47297. TRANS ("New Folder"),
  47298. TRANS ("Couldn't create the folder!"));
  47299. }
  47300. content->chooserComponent.refresh();
  47301. }
  47302. }
  47303. END_JUCE_NAMESPACE
  47304. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47305. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47306. BEGIN_JUCE_NAMESPACE
  47307. FileFilter::FileFilter (const String& filterDescription)
  47308. : description (filterDescription)
  47309. {
  47310. }
  47311. FileFilter::~FileFilter()
  47312. {
  47313. }
  47314. const String& FileFilter::getDescription() const throw()
  47315. {
  47316. return description;
  47317. }
  47318. END_JUCE_NAMESPACE
  47319. /*** End of inlined file: juce_FileFilter.cpp ***/
  47320. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47321. BEGIN_JUCE_NAMESPACE
  47322. const Image juce_createIconForFile (const File& file);
  47323. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47324. : ListBox (String::empty, 0),
  47325. DirectoryContentsDisplayComponent (listToShow)
  47326. {
  47327. setModel (this);
  47328. fileList.addChangeListener (this);
  47329. }
  47330. FileListComponent::~FileListComponent()
  47331. {
  47332. fileList.removeChangeListener (this);
  47333. }
  47334. int FileListComponent::getNumSelectedFiles() const
  47335. {
  47336. return getNumSelectedRows();
  47337. }
  47338. const File FileListComponent::getSelectedFile (int index) const
  47339. {
  47340. return fileList.getFile (getSelectedRow (index));
  47341. }
  47342. void FileListComponent::deselectAllFiles()
  47343. {
  47344. deselectAllRows();
  47345. }
  47346. void FileListComponent::scrollToTop()
  47347. {
  47348. getVerticalScrollBar()->setCurrentRangeStart (0);
  47349. }
  47350. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47351. {
  47352. updateContent();
  47353. if (lastDirectory != fileList.getDirectory())
  47354. {
  47355. lastDirectory = fileList.getDirectory();
  47356. deselectAllRows();
  47357. }
  47358. }
  47359. class FileListItemComponent : public Component,
  47360. public TimeSliceClient,
  47361. public AsyncUpdater
  47362. {
  47363. public:
  47364. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47365. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47366. {
  47367. }
  47368. ~FileListItemComponent()
  47369. {
  47370. thread.removeTimeSliceClient (this);
  47371. }
  47372. void paint (Graphics& g)
  47373. {
  47374. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47375. file.getFileName(),
  47376. &icon, fileSize, modTime,
  47377. isDirectory, highlighted,
  47378. index, owner);
  47379. }
  47380. void mouseDown (const MouseEvent& e)
  47381. {
  47382. owner.selectRowsBasedOnModifierKeys (index, e.mods, false);
  47383. owner.sendMouseClickMessage (file, e);
  47384. }
  47385. void mouseDoubleClick (const MouseEvent&)
  47386. {
  47387. owner.sendDoubleClickMessage (file);
  47388. }
  47389. void update (const File& root,
  47390. const DirectoryContentsList::FileInfo* const fileInfo,
  47391. const int index_,
  47392. const bool highlighted_)
  47393. {
  47394. thread.removeTimeSliceClient (this);
  47395. if (highlighted_ != highlighted || index_ != index)
  47396. {
  47397. index = index_;
  47398. highlighted = highlighted_;
  47399. repaint();
  47400. }
  47401. File newFile;
  47402. String newFileSize, newModTime;
  47403. if (fileInfo != 0)
  47404. {
  47405. newFile = root.getChildFile (fileInfo->filename);
  47406. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47407. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47408. }
  47409. if (newFile != file
  47410. || fileSize != newFileSize
  47411. || modTime != newModTime)
  47412. {
  47413. file = newFile;
  47414. fileSize = newFileSize;
  47415. modTime = newModTime;
  47416. icon = Image::null;
  47417. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47418. repaint();
  47419. }
  47420. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47421. {
  47422. updateIcon (true);
  47423. if (! icon.isValid())
  47424. thread.addTimeSliceClient (this);
  47425. }
  47426. }
  47427. int useTimeSlice()
  47428. {
  47429. updateIcon (false);
  47430. return -1;
  47431. }
  47432. void handleAsyncUpdate()
  47433. {
  47434. repaint();
  47435. }
  47436. private:
  47437. FileListComponent& owner;
  47438. TimeSliceThread& thread;
  47439. File file;
  47440. String fileSize, modTime;
  47441. Image icon;
  47442. int index;
  47443. bool highlighted, isDirectory;
  47444. void updateIcon (const bool onlyUpdateIfCached)
  47445. {
  47446. if (icon.isNull())
  47447. {
  47448. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47449. Image im (ImageCache::getFromHashCode (hashCode));
  47450. if (im.isNull() && ! onlyUpdateIfCached)
  47451. {
  47452. im = juce_createIconForFile (file);
  47453. if (im.isValid())
  47454. ImageCache::addImageToCache (im, hashCode);
  47455. }
  47456. if (im.isValid())
  47457. {
  47458. icon = im;
  47459. triggerAsyncUpdate();
  47460. }
  47461. }
  47462. }
  47463. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47464. };
  47465. int FileListComponent::getNumRows()
  47466. {
  47467. return fileList.getNumFiles();
  47468. }
  47469. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47470. {
  47471. }
  47472. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47473. {
  47474. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47475. if (comp == 0)
  47476. {
  47477. delete existingComponentToUpdate;
  47478. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47479. }
  47480. DirectoryContentsList::FileInfo fileInfo;
  47481. if (fileList.getFileInfo (row, fileInfo))
  47482. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47483. else
  47484. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47485. return comp;
  47486. }
  47487. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47488. {
  47489. sendSelectionChangeMessage();
  47490. }
  47491. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47492. {
  47493. }
  47494. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47495. {
  47496. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47497. }
  47498. END_JUCE_NAMESPACE
  47499. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47500. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47501. BEGIN_JUCE_NAMESPACE
  47502. FilenameComponent::FilenameComponent (const String& name,
  47503. const File& currentFile,
  47504. const bool canEditFilename,
  47505. const bool isDirectory,
  47506. const bool isForSaving,
  47507. const String& fileBrowserWildcard,
  47508. const String& enforcedSuffix_,
  47509. const String& textWhenNothingSelected)
  47510. : Component (name),
  47511. maxRecentFiles (30),
  47512. isDir (isDirectory),
  47513. isSaving (isForSaving),
  47514. isFileDragOver (false),
  47515. wildcard (fileBrowserWildcard),
  47516. enforcedSuffix (enforcedSuffix_)
  47517. {
  47518. addAndMakeVisible (&filenameBox);
  47519. filenameBox.setEditableText (canEditFilename);
  47520. filenameBox.addListener (this);
  47521. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47522. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47523. setBrowseButtonText ("...");
  47524. setCurrentFile (currentFile, true);
  47525. }
  47526. FilenameComponent::~FilenameComponent()
  47527. {
  47528. }
  47529. void FilenameComponent::paintOverChildren (Graphics& g)
  47530. {
  47531. if (isFileDragOver)
  47532. {
  47533. g.setColour (Colours::red.withAlpha (0.2f));
  47534. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47535. }
  47536. }
  47537. void FilenameComponent::resized()
  47538. {
  47539. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47540. }
  47541. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47542. {
  47543. browseButtonText = newBrowseButtonText;
  47544. lookAndFeelChanged();
  47545. }
  47546. void FilenameComponent::lookAndFeelChanged()
  47547. {
  47548. browseButton = 0;
  47549. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47550. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47551. resized();
  47552. browseButton->addListener (this);
  47553. }
  47554. void FilenameComponent::setTooltip (const String& newTooltip)
  47555. {
  47556. SettableTooltipClient::setTooltip (newTooltip);
  47557. filenameBox.setTooltip (newTooltip);
  47558. }
  47559. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47560. {
  47561. defaultBrowseFile = newDefaultDirectory;
  47562. }
  47563. void FilenameComponent::buttonClicked (Button*)
  47564. {
  47565. #if JUCE_MODAL_LOOPS_PERMITTED
  47566. FileChooser fc (TRANS("Choose a new file"),
  47567. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47568. : getCurrentFile(),
  47569. wildcard);
  47570. if (isDir ? fc.browseForDirectory()
  47571. : (isSaving ? fc.browseForFileToSave (false)
  47572. : fc.browseForFileToOpen()))
  47573. {
  47574. setCurrentFile (fc.getResult(), true);
  47575. }
  47576. #else
  47577. jassertfalse; // needs rewriting to deal with non-modal environments
  47578. #endif
  47579. }
  47580. void FilenameComponent::comboBoxChanged (ComboBox*)
  47581. {
  47582. setCurrentFile (getCurrentFile(), true);
  47583. }
  47584. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47585. {
  47586. return true;
  47587. }
  47588. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47589. {
  47590. isFileDragOver = false;
  47591. repaint();
  47592. const File f (filenames[0]);
  47593. if (f.exists() && (f.isDirectory() == isDir))
  47594. setCurrentFile (f, true);
  47595. }
  47596. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47597. {
  47598. isFileDragOver = true;
  47599. repaint();
  47600. }
  47601. void FilenameComponent::fileDragExit (const StringArray&)
  47602. {
  47603. isFileDragOver = false;
  47604. repaint();
  47605. }
  47606. const File FilenameComponent::getCurrentFile() const
  47607. {
  47608. File f (filenameBox.getText());
  47609. if (enforcedSuffix.isNotEmpty())
  47610. f = f.withFileExtension (enforcedSuffix);
  47611. return f;
  47612. }
  47613. void FilenameComponent::setCurrentFile (File newFile,
  47614. const bool addToRecentlyUsedList,
  47615. const bool sendChangeNotification)
  47616. {
  47617. if (enforcedSuffix.isNotEmpty())
  47618. newFile = newFile.withFileExtension (enforcedSuffix);
  47619. if (newFile.getFullPathName() != lastFilename)
  47620. {
  47621. lastFilename = newFile.getFullPathName();
  47622. if (addToRecentlyUsedList)
  47623. addRecentlyUsedFile (newFile);
  47624. filenameBox.setText (lastFilename, true);
  47625. if (sendChangeNotification)
  47626. triggerAsyncUpdate();
  47627. }
  47628. }
  47629. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47630. {
  47631. filenameBox.setEditableText (shouldBeEditable);
  47632. }
  47633. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47634. {
  47635. StringArray names;
  47636. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47637. names.add (filenameBox.getItemText (i));
  47638. return names;
  47639. }
  47640. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47641. {
  47642. if (filenames != getRecentlyUsedFilenames())
  47643. {
  47644. filenameBox.clear();
  47645. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47646. filenameBox.addItem (filenames[i], i + 1);
  47647. }
  47648. }
  47649. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47650. {
  47651. maxRecentFiles = jmax (1, newMaximum);
  47652. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47653. }
  47654. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47655. {
  47656. StringArray files (getRecentlyUsedFilenames());
  47657. if (file.getFullPathName().isNotEmpty())
  47658. {
  47659. files.removeString (file.getFullPathName(), true);
  47660. files.insert (0, file.getFullPathName());
  47661. setRecentlyUsedFilenames (files);
  47662. }
  47663. }
  47664. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47665. {
  47666. listeners.add (listener);
  47667. }
  47668. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47669. {
  47670. listeners.remove (listener);
  47671. }
  47672. void FilenameComponent::handleAsyncUpdate()
  47673. {
  47674. Component::BailOutChecker checker (this);
  47675. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47676. }
  47677. END_JUCE_NAMESPACE
  47678. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47679. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47680. BEGIN_JUCE_NAMESPACE
  47681. FileSearchPathListComponent::FileSearchPathListComponent()
  47682. : addButton ("+"),
  47683. removeButton ("-"),
  47684. changeButton (TRANS ("change...")),
  47685. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47686. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47687. {
  47688. listBox.setModel (this);
  47689. addAndMakeVisible (&listBox);
  47690. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47691. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47692. listBox.setOutlineThickness (1);
  47693. addAndMakeVisible (&addButton);
  47694. addButton.addListener (this);
  47695. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47696. addAndMakeVisible (&removeButton);
  47697. removeButton.addListener (this);
  47698. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47699. addAndMakeVisible (&changeButton);
  47700. changeButton.addListener (this);
  47701. addAndMakeVisible (&upButton);
  47702. upButton.addListener (this);
  47703. {
  47704. Path arrowPath;
  47705. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47706. DrawablePath arrowImage;
  47707. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47708. arrowImage.setPath (arrowPath);
  47709. upButton.setImages (&arrowImage);
  47710. }
  47711. addAndMakeVisible (&downButton);
  47712. downButton.addListener (this);
  47713. {
  47714. Path arrowPath;
  47715. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47716. DrawablePath arrowImage;
  47717. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47718. arrowImage.setPath (arrowPath);
  47719. downButton.setImages (&arrowImage);
  47720. }
  47721. updateButtons();
  47722. }
  47723. FileSearchPathListComponent::~FileSearchPathListComponent()
  47724. {
  47725. }
  47726. void FileSearchPathListComponent::updateButtons()
  47727. {
  47728. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47729. removeButton.setEnabled (anythingSelected);
  47730. changeButton.setEnabled (anythingSelected);
  47731. upButton.setEnabled (anythingSelected);
  47732. downButton.setEnabled (anythingSelected);
  47733. }
  47734. void FileSearchPathListComponent::changed()
  47735. {
  47736. listBox.updateContent();
  47737. listBox.repaint();
  47738. updateButtons();
  47739. }
  47740. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47741. {
  47742. if (newPath.toString() != path.toString())
  47743. {
  47744. path = newPath;
  47745. changed();
  47746. }
  47747. }
  47748. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47749. {
  47750. defaultBrowseTarget = newDefaultDirectory;
  47751. }
  47752. int FileSearchPathListComponent::getNumRows()
  47753. {
  47754. return path.getNumPaths();
  47755. }
  47756. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47757. {
  47758. if (rowIsSelected)
  47759. g.fillAll (findColour (TextEditor::highlightColourId));
  47760. g.setColour (findColour (ListBox::textColourId));
  47761. Font f (height * 0.7f);
  47762. f.setHorizontalScale (0.9f);
  47763. g.setFont (f);
  47764. g.drawText (path [rowNumber].getFullPathName(),
  47765. 4, 0, width - 6, height,
  47766. Justification::centredLeft, true);
  47767. }
  47768. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47769. {
  47770. if (isPositiveAndBelow (row, path.getNumPaths()))
  47771. {
  47772. path.remove (row);
  47773. changed();
  47774. }
  47775. }
  47776. void FileSearchPathListComponent::returnKeyPressed (int row)
  47777. {
  47778. #if JUCE_MODAL_LOOPS_PERMITTED
  47779. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47780. if (chooser.browseForDirectory())
  47781. {
  47782. path.remove (row);
  47783. path.add (chooser.getResult(), row);
  47784. changed();
  47785. }
  47786. #endif
  47787. }
  47788. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47789. {
  47790. returnKeyPressed (row);
  47791. }
  47792. void FileSearchPathListComponent::selectedRowsChanged (int)
  47793. {
  47794. updateButtons();
  47795. }
  47796. void FileSearchPathListComponent::paint (Graphics& g)
  47797. {
  47798. g.fillAll (findColour (backgroundColourId));
  47799. }
  47800. void FileSearchPathListComponent::resized()
  47801. {
  47802. const int buttonH = 22;
  47803. const int buttonY = getHeight() - buttonH - 4;
  47804. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47805. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47806. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47807. changeButton.changeWidthToFitText (buttonH);
  47808. downButton.setSize (buttonH * 2, buttonH);
  47809. upButton.setSize (buttonH * 2, buttonH);
  47810. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47811. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47812. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47813. }
  47814. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47815. {
  47816. return true;
  47817. }
  47818. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47819. {
  47820. for (int i = filenames.size(); --i >= 0;)
  47821. {
  47822. const File f (filenames[i]);
  47823. if (f.isDirectory())
  47824. {
  47825. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47826. path.add (f, row);
  47827. changed();
  47828. }
  47829. }
  47830. }
  47831. void FileSearchPathListComponent::buttonClicked (Button* button)
  47832. {
  47833. const int currentRow = listBox.getSelectedRow();
  47834. if (button == &removeButton)
  47835. {
  47836. deleteKeyPressed (currentRow);
  47837. }
  47838. else if (button == &addButton)
  47839. {
  47840. File start (defaultBrowseTarget);
  47841. if (start == File::nonexistent)
  47842. start = path [0];
  47843. if (start == File::nonexistent)
  47844. start = File::getCurrentWorkingDirectory();
  47845. #if JUCE_MODAL_LOOPS_PERMITTED
  47846. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47847. if (chooser.browseForDirectory())
  47848. path.add (chooser.getResult(), currentRow);
  47849. #else
  47850. jassertfalse; // needs rewriting to deal with non-modal environments
  47851. #endif
  47852. }
  47853. else if (button == &changeButton)
  47854. {
  47855. returnKeyPressed (currentRow);
  47856. }
  47857. else if (button == &upButton)
  47858. {
  47859. if (currentRow > 0 && currentRow < path.getNumPaths())
  47860. {
  47861. const File f (path[currentRow]);
  47862. path.remove (currentRow);
  47863. path.add (f, currentRow - 1);
  47864. listBox.selectRow (currentRow - 1);
  47865. }
  47866. }
  47867. else if (button == &downButton)
  47868. {
  47869. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47870. {
  47871. const File f (path[currentRow]);
  47872. path.remove (currentRow);
  47873. path.add (f, currentRow + 1);
  47874. listBox.selectRow (currentRow + 1);
  47875. }
  47876. }
  47877. changed();
  47878. }
  47879. END_JUCE_NAMESPACE
  47880. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47881. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47882. BEGIN_JUCE_NAMESPACE
  47883. const Image juce_createIconForFile (const File& file);
  47884. class FileListTreeItem : public TreeViewItem,
  47885. public TimeSliceClient,
  47886. public AsyncUpdater,
  47887. public ChangeListener
  47888. {
  47889. public:
  47890. FileListTreeItem (FileTreeComponent& owner_,
  47891. DirectoryContentsList* const parentContentsList_,
  47892. const int indexInContentsList_,
  47893. const File& file_,
  47894. TimeSliceThread& thread_)
  47895. : file (file_),
  47896. owner (owner_),
  47897. parentContentsList (parentContentsList_),
  47898. indexInContentsList (indexInContentsList_),
  47899. subContentsList (0),
  47900. canDeleteSubContentsList (false),
  47901. thread (thread_),
  47902. icon (0)
  47903. {
  47904. DirectoryContentsList::FileInfo fileInfo;
  47905. if (parentContentsList_ != 0
  47906. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47907. {
  47908. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47909. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47910. isDirectory = fileInfo.isDirectory;
  47911. }
  47912. else
  47913. {
  47914. isDirectory = true;
  47915. }
  47916. }
  47917. ~FileListTreeItem()
  47918. {
  47919. thread.removeTimeSliceClient (this);
  47920. clearSubItems();
  47921. if (canDeleteSubContentsList)
  47922. delete subContentsList;
  47923. }
  47924. bool mightContainSubItems() { return isDirectory; }
  47925. const String getUniqueName() const { return file.getFullPathName(); }
  47926. int getItemHeight() const { return 22; }
  47927. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47928. void itemOpennessChanged (bool isNowOpen)
  47929. {
  47930. if (isNowOpen)
  47931. {
  47932. clearSubItems();
  47933. isDirectory = file.isDirectory();
  47934. if (isDirectory)
  47935. {
  47936. if (subContentsList == 0)
  47937. {
  47938. jassert (parentContentsList != 0);
  47939. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47940. l->setDirectory (file, true, true);
  47941. setSubContentsList (l);
  47942. canDeleteSubContentsList = true;
  47943. }
  47944. changeListenerCallback (0);
  47945. }
  47946. }
  47947. }
  47948. void setSubContentsList (DirectoryContentsList* newList)
  47949. {
  47950. jassert (subContentsList == 0);
  47951. subContentsList = newList;
  47952. newList->addChangeListener (this);
  47953. }
  47954. void changeListenerCallback (ChangeBroadcaster*)
  47955. {
  47956. clearSubItems();
  47957. if (isOpen() && subContentsList != 0)
  47958. {
  47959. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47960. {
  47961. FileListTreeItem* const item
  47962. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47963. addSubItem (item);
  47964. }
  47965. }
  47966. }
  47967. void paintItem (Graphics& g, int width, int height)
  47968. {
  47969. if (file != File::nonexistent)
  47970. {
  47971. updateIcon (true);
  47972. if (icon.isNull())
  47973. thread.addTimeSliceClient (this);
  47974. }
  47975. owner.getLookAndFeel()
  47976. .drawFileBrowserRow (g, width, height,
  47977. file.getFileName(),
  47978. &icon, fileSize, modTime,
  47979. isDirectory, isSelected(),
  47980. indexInContentsList, owner);
  47981. }
  47982. void itemClicked (const MouseEvent& e)
  47983. {
  47984. owner.sendMouseClickMessage (file, e);
  47985. }
  47986. void itemDoubleClicked (const MouseEvent& e)
  47987. {
  47988. TreeViewItem::itemDoubleClicked (e);
  47989. owner.sendDoubleClickMessage (file);
  47990. }
  47991. void itemSelectionChanged (bool)
  47992. {
  47993. owner.sendSelectionChangeMessage();
  47994. }
  47995. int useTimeSlice()
  47996. {
  47997. updateIcon (false);
  47998. return -1;
  47999. }
  48000. void handleAsyncUpdate()
  48001. {
  48002. owner.repaint();
  48003. }
  48004. const File file;
  48005. private:
  48006. FileTreeComponent& owner;
  48007. DirectoryContentsList* parentContentsList;
  48008. int indexInContentsList;
  48009. DirectoryContentsList* subContentsList;
  48010. bool isDirectory, canDeleteSubContentsList;
  48011. TimeSliceThread& thread;
  48012. Image icon;
  48013. String fileSize;
  48014. String modTime;
  48015. void updateIcon (const bool onlyUpdateIfCached)
  48016. {
  48017. if (icon.isNull())
  48018. {
  48019. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48020. Image im (ImageCache::getFromHashCode (hashCode));
  48021. if (im.isNull() && ! onlyUpdateIfCached)
  48022. {
  48023. im = juce_createIconForFile (file);
  48024. if (im.isValid())
  48025. ImageCache::addImageToCache (im, hashCode);
  48026. }
  48027. if (im.isValid())
  48028. {
  48029. icon = im;
  48030. triggerAsyncUpdate();
  48031. }
  48032. }
  48033. }
  48034. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  48035. };
  48036. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48037. : DirectoryContentsDisplayComponent (listToShow)
  48038. {
  48039. FileListTreeItem* const root
  48040. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48041. listToShow.getTimeSliceThread());
  48042. root->setSubContentsList (&listToShow);
  48043. setRootItemVisible (false);
  48044. setRootItem (root);
  48045. }
  48046. FileTreeComponent::~FileTreeComponent()
  48047. {
  48048. deleteRootItem();
  48049. }
  48050. const File FileTreeComponent::getSelectedFile (const int index) const
  48051. {
  48052. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48053. return item != 0 ? item->file
  48054. : File::nonexistent;
  48055. }
  48056. void FileTreeComponent::deselectAllFiles()
  48057. {
  48058. clearSelectedItems();
  48059. }
  48060. void FileTreeComponent::scrollToTop()
  48061. {
  48062. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48063. }
  48064. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48065. {
  48066. dragAndDropDescription = description;
  48067. }
  48068. END_JUCE_NAMESPACE
  48069. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48070. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48071. BEGIN_JUCE_NAMESPACE
  48072. ImagePreviewComponent::ImagePreviewComponent()
  48073. {
  48074. }
  48075. ImagePreviewComponent::~ImagePreviewComponent()
  48076. {
  48077. }
  48078. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48079. {
  48080. const int availableW = proportionOfWidth (0.97f);
  48081. const int availableH = getHeight() - 13 * 4;
  48082. const double scale = jmin (1.0,
  48083. availableW / (double) w,
  48084. availableH / (double) h);
  48085. w = roundToInt (scale * w);
  48086. h = roundToInt (scale * h);
  48087. }
  48088. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48089. {
  48090. if (fileToLoad != file)
  48091. {
  48092. fileToLoad = file;
  48093. startTimer (100);
  48094. }
  48095. }
  48096. void ImagePreviewComponent::timerCallback()
  48097. {
  48098. stopTimer();
  48099. currentThumbnail = Image::null;
  48100. currentDetails = String::empty;
  48101. repaint();
  48102. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48103. if (in != 0)
  48104. {
  48105. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48106. if (format != 0)
  48107. {
  48108. currentThumbnail = format->decodeImage (*in);
  48109. if (currentThumbnail.isValid())
  48110. {
  48111. int w = currentThumbnail.getWidth();
  48112. int h = currentThumbnail.getHeight();
  48113. currentDetails
  48114. << fileToLoad.getFileName() << "\n"
  48115. << format->getFormatName() << "\n"
  48116. << w << " x " << h << " pixels\n"
  48117. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48118. getThumbSize (w, h);
  48119. currentThumbnail = currentThumbnail.rescaled (w, h);
  48120. }
  48121. }
  48122. }
  48123. }
  48124. void ImagePreviewComponent::paint (Graphics& g)
  48125. {
  48126. if (currentThumbnail.isValid())
  48127. {
  48128. g.setFont (13.0f);
  48129. int w = currentThumbnail.getWidth();
  48130. int h = currentThumbnail.getHeight();
  48131. getThumbSize (w, h);
  48132. const int numLines = 4;
  48133. const int totalH = 13 * numLines + h + 4;
  48134. const int y = (getHeight() - totalH) / 2;
  48135. g.drawImageWithin (currentThumbnail,
  48136. (getWidth() - w) / 2, y, w, h,
  48137. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48138. false);
  48139. g.drawFittedText (currentDetails,
  48140. 0, y + h + 4, getWidth(), 100,
  48141. Justification::centredTop, numLines);
  48142. }
  48143. }
  48144. END_JUCE_NAMESPACE
  48145. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48146. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48147. BEGIN_JUCE_NAMESPACE
  48148. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48149. const String& directoryWildcardPatterns,
  48150. const String& description_)
  48151. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48152. : (description_ + " (" + fileWildcardPatterns + ")"))
  48153. {
  48154. parse (fileWildcardPatterns, fileWildcards);
  48155. parse (directoryWildcardPatterns, directoryWildcards);
  48156. }
  48157. WildcardFileFilter::~WildcardFileFilter()
  48158. {
  48159. }
  48160. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48161. {
  48162. return match (file, fileWildcards);
  48163. }
  48164. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48165. {
  48166. return match (file, directoryWildcards);
  48167. }
  48168. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48169. {
  48170. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48171. result.trim();
  48172. result.removeEmptyStrings();
  48173. // special case for *.*, because people use it to mean "any file", but it
  48174. // would actually ignore files with no extension.
  48175. for (int i = result.size(); --i >= 0;)
  48176. if (result[i] == "*.*")
  48177. result.set (i, "*");
  48178. }
  48179. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48180. {
  48181. const String filename (file.getFileName());
  48182. for (int i = wildcards.size(); --i >= 0;)
  48183. if (filename.matchesWildcard (wildcards[i], true))
  48184. return true;
  48185. return false;
  48186. }
  48187. END_JUCE_NAMESPACE
  48188. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48189. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48190. BEGIN_JUCE_NAMESPACE
  48191. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48192. {
  48193. }
  48194. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48195. {
  48196. }
  48197. namespace KeyboardFocusHelpers
  48198. {
  48199. // This will sort a set of components, so that they are ordered in terms of
  48200. // left-to-right and then top-to-bottom.
  48201. class ScreenPositionComparator
  48202. {
  48203. public:
  48204. ScreenPositionComparator() {}
  48205. static int compareElements (const Component* const first, const Component* const second)
  48206. {
  48207. int explicitOrder1 = first->getExplicitFocusOrder();
  48208. if (explicitOrder1 <= 0)
  48209. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48210. int explicitOrder2 = second->getExplicitFocusOrder();
  48211. if (explicitOrder2 <= 0)
  48212. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48213. if (explicitOrder1 != explicitOrder2)
  48214. return explicitOrder1 - explicitOrder2;
  48215. const int diff = first->getY() - second->getY();
  48216. return (diff == 0) ? first->getX() - second->getX()
  48217. : diff;
  48218. }
  48219. };
  48220. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48221. {
  48222. if (parent->getNumChildComponents() > 0)
  48223. {
  48224. Array <Component*> localComps;
  48225. ScreenPositionComparator comparator;
  48226. int i;
  48227. for (i = parent->getNumChildComponents(); --i >= 0;)
  48228. {
  48229. Component* const c = parent->getChildComponent (i);
  48230. if (c->isVisible() && c->isEnabled())
  48231. localComps.addSorted (comparator, c);
  48232. }
  48233. for (i = 0; i < localComps.size(); ++i)
  48234. {
  48235. Component* const c = localComps.getUnchecked (i);
  48236. if (c->getWantsKeyboardFocus())
  48237. comps.add (c);
  48238. if (! c->isFocusContainer())
  48239. findAllFocusableComponents (c, comps);
  48240. }
  48241. }
  48242. }
  48243. }
  48244. namespace KeyboardFocusHelpers
  48245. {
  48246. Component* getIncrementedComponent (Component* const current, const int delta)
  48247. {
  48248. Component* focusContainer = current->getParentComponent();
  48249. if (focusContainer != 0)
  48250. {
  48251. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48252. focusContainer = focusContainer->getParentComponent();
  48253. if (focusContainer != 0)
  48254. {
  48255. Array <Component*> comps;
  48256. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48257. if (comps.size() > 0)
  48258. {
  48259. const int index = comps.indexOf (current);
  48260. return comps [(index + comps.size() + delta) % comps.size()];
  48261. }
  48262. }
  48263. }
  48264. return 0;
  48265. }
  48266. }
  48267. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48268. {
  48269. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48270. }
  48271. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48272. {
  48273. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48274. }
  48275. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48276. {
  48277. Array <Component*> comps;
  48278. if (parentComponent != 0)
  48279. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48280. return comps.getFirst();
  48281. }
  48282. END_JUCE_NAMESPACE
  48283. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48284. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48285. BEGIN_JUCE_NAMESPACE
  48286. bool KeyListener::keyStateChanged (const bool, Component*)
  48287. {
  48288. return false;
  48289. }
  48290. END_JUCE_NAMESPACE
  48291. /*** End of inlined file: juce_KeyListener.cpp ***/
  48292. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48293. BEGIN_JUCE_NAMESPACE
  48294. // N.B. these two includes are put here deliberately to avoid problems with
  48295. // old GCCs failing on long include paths
  48296. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48297. {
  48298. public:
  48299. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48300. const CommandID commandID_,
  48301. const String& keyName,
  48302. const int keyNum_)
  48303. : Button (keyName),
  48304. owner (owner_),
  48305. commandID (commandID_),
  48306. keyNum (keyNum_)
  48307. {
  48308. setWantsKeyboardFocus (false);
  48309. setTriggeredOnMouseDown (keyNum >= 0);
  48310. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48311. : TRANS("click to change this key-mapping"));
  48312. }
  48313. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48314. {
  48315. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48316. keyNum >= 0 ? getName() : String::empty);
  48317. }
  48318. static void menuCallback (int result, ChangeKeyButton* button)
  48319. {
  48320. if (button != 0)
  48321. {
  48322. switch (result)
  48323. {
  48324. case 1: button->assignNewKey(); break;
  48325. case 2: button->owner.getMappings().removeKeyPress (button->commandID, button->keyNum); break;
  48326. default: break;
  48327. }
  48328. }
  48329. }
  48330. void clicked()
  48331. {
  48332. if (keyNum >= 0)
  48333. {
  48334. // existing key clicked..
  48335. PopupMenu m;
  48336. m.addItem (1, TRANS("change this key-mapping"));
  48337. m.addSeparator();
  48338. m.addItem (2, TRANS("remove this key-mapping"));
  48339. m.showMenuAsync (PopupMenu::Options(),
  48340. ModalCallbackFunction::forComponent (menuCallback, this));
  48341. }
  48342. else
  48343. {
  48344. assignNewKey(); // + button pressed..
  48345. }
  48346. }
  48347. void fitToContent (const int h) throw()
  48348. {
  48349. if (keyNum < 0)
  48350. {
  48351. setSize (h, h);
  48352. }
  48353. else
  48354. {
  48355. Font f (h * 0.6f);
  48356. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48357. }
  48358. }
  48359. class KeyEntryWindow : public AlertWindow
  48360. {
  48361. public:
  48362. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48363. : AlertWindow (TRANS("New key-mapping"),
  48364. TRANS("Please press a key combination now..."),
  48365. AlertWindow::NoIcon),
  48366. owner (owner_)
  48367. {
  48368. addButton (TRANS("Ok"), 1);
  48369. addButton (TRANS("Cancel"), 0);
  48370. // (avoid return + escape keys getting processed by the buttons..)
  48371. for (int i = getNumChildComponents(); --i >= 0;)
  48372. getChildComponent (i)->setWantsKeyboardFocus (false);
  48373. setWantsKeyboardFocus (true);
  48374. grabKeyboardFocus();
  48375. }
  48376. bool keyPressed (const KeyPress& key)
  48377. {
  48378. lastPress = key;
  48379. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48380. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48381. if (previousCommand != 0)
  48382. message << "\n\n" << TRANS("(Currently assigned to \"")
  48383. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48384. setMessage (message);
  48385. return true;
  48386. }
  48387. bool keyStateChanged (bool)
  48388. {
  48389. return true;
  48390. }
  48391. KeyPress lastPress;
  48392. private:
  48393. KeyMappingEditorComponent& owner;
  48394. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48395. };
  48396. static void assignNewKeyCallback (int result, ChangeKeyButton* button, KeyPress newKey)
  48397. {
  48398. if (result != 0 && button != 0)
  48399. button->setNewKey (newKey, true);
  48400. }
  48401. void setNewKey (const KeyPress& newKey, bool dontAskUser)
  48402. {
  48403. if (newKey.isValid())
  48404. {
  48405. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (newKey);
  48406. if (previousCommand == 0 || dontAskUser)
  48407. {
  48408. owner.getMappings().removeKeyPress (newKey);
  48409. if (keyNum >= 0)
  48410. owner.getMappings().removeKeyPress (commandID, keyNum);
  48411. owner.getMappings().addKeyPress (commandID, newKey, keyNum);
  48412. }
  48413. else
  48414. {
  48415. AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48416. TRANS("Change key-mapping"),
  48417. TRANS("This key is already assigned to the command \"")
  48418. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48419. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48420. TRANS("Re-assign"),
  48421. TRANS("Cancel"),
  48422. this,
  48423. ModalCallbackFunction::forComponent (assignNewKeyCallback,
  48424. this, KeyPress (newKey)));
  48425. }
  48426. }
  48427. }
  48428. static void keyChosen (int result, ChangeKeyButton* button)
  48429. {
  48430. if (result != 0 && button != 0 && button->currentKeyEntryWindow != 0)
  48431. {
  48432. button->currentKeyEntryWindow->setVisible (false);
  48433. button->setNewKey (button->currentKeyEntryWindow->lastPress, false);
  48434. }
  48435. button->currentKeyEntryWindow = 0;
  48436. }
  48437. void assignNewKey()
  48438. {
  48439. currentKeyEntryWindow = new KeyEntryWindow (owner);
  48440. currentKeyEntryWindow->enterModalState (true, ModalCallbackFunction::forComponent (keyChosen, this));
  48441. }
  48442. private:
  48443. KeyMappingEditorComponent& owner;
  48444. const CommandID commandID;
  48445. const int keyNum;
  48446. ScopedPointer<KeyEntryWindow> currentKeyEntryWindow;
  48447. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48448. };
  48449. class KeyMappingEditorComponent::ItemComponent : public Component
  48450. {
  48451. public:
  48452. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48453. : owner (owner_), commandID (commandID_)
  48454. {
  48455. setInterceptsMouseClicks (false, true);
  48456. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48457. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48458. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48459. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48460. addKeyPressButton (String::empty, -1, isReadOnly);
  48461. }
  48462. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48463. {
  48464. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48465. keyChangeButtons.add (b);
  48466. b->setEnabled (! isReadOnly);
  48467. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48468. addChildComponent (b);
  48469. }
  48470. void paint (Graphics& g)
  48471. {
  48472. g.setFont (getHeight() * 0.7f);
  48473. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48474. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48475. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48476. Justification::centredLeft, true);
  48477. }
  48478. void resized()
  48479. {
  48480. int x = getWidth() - 4;
  48481. for (int i = keyChangeButtons.size(); --i >= 0;)
  48482. {
  48483. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48484. b->fitToContent (getHeight() - 2);
  48485. b->setTopRightPosition (x, 1);
  48486. x = b->getX() - 5;
  48487. }
  48488. }
  48489. private:
  48490. KeyMappingEditorComponent& owner;
  48491. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48492. const CommandID commandID;
  48493. enum { maxNumAssignments = 3 };
  48494. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48495. };
  48496. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48497. {
  48498. public:
  48499. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48500. : owner (owner_), commandID (commandID_)
  48501. {
  48502. }
  48503. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48504. bool mightContainSubItems() { return false; }
  48505. int getItemHeight() const { return 20; }
  48506. Component* createItemComponent()
  48507. {
  48508. return new ItemComponent (owner, commandID);
  48509. }
  48510. private:
  48511. KeyMappingEditorComponent& owner;
  48512. const CommandID commandID;
  48513. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48514. };
  48515. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48516. {
  48517. public:
  48518. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48519. : owner (owner_), categoryName (name)
  48520. {
  48521. }
  48522. const String getUniqueName() const { return categoryName + "_cat"; }
  48523. bool mightContainSubItems() { return true; }
  48524. int getItemHeight() const { return 28; }
  48525. void paintItem (Graphics& g, int width, int height)
  48526. {
  48527. g.setFont (height * 0.6f, Font::bold);
  48528. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48529. g.drawText (categoryName,
  48530. 2, 0, width - 2, height,
  48531. Justification::centredLeft, true);
  48532. }
  48533. void itemOpennessChanged (bool isNowOpen)
  48534. {
  48535. if (isNowOpen)
  48536. {
  48537. if (getNumSubItems() == 0)
  48538. {
  48539. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48540. for (int i = 0; i < commands.size(); ++i)
  48541. {
  48542. if (owner.shouldCommandBeIncluded (commands[i]))
  48543. addSubItem (new MappingItem (owner, commands[i]));
  48544. }
  48545. }
  48546. }
  48547. else
  48548. {
  48549. clearSubItems();
  48550. }
  48551. }
  48552. private:
  48553. KeyMappingEditorComponent& owner;
  48554. String categoryName;
  48555. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48556. };
  48557. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48558. public ChangeListener,
  48559. public ButtonListener
  48560. {
  48561. public:
  48562. TopLevelItem (KeyMappingEditorComponent& owner_)
  48563. : owner (owner_)
  48564. {
  48565. setLinesDrawnForSubItems (false);
  48566. owner.getMappings().addChangeListener (this);
  48567. }
  48568. ~TopLevelItem()
  48569. {
  48570. owner.getMappings().removeChangeListener (this);
  48571. }
  48572. bool mightContainSubItems() { return true; }
  48573. const String getUniqueName() const { return "keys"; }
  48574. void changeListenerCallback (ChangeBroadcaster*)
  48575. {
  48576. const OpennessRestorer openness (*this);
  48577. clearSubItems();
  48578. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48579. for (int i = 0; i < categories.size(); ++i)
  48580. {
  48581. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48582. int count = 0;
  48583. for (int j = 0; j < commands.size(); ++j)
  48584. if (owner.shouldCommandBeIncluded (commands[j]))
  48585. ++count;
  48586. if (count > 0)
  48587. addSubItem (new CategoryItem (owner, categories[i]));
  48588. }
  48589. }
  48590. static void resetToDefaultsCallback (int result, KeyMappingEditorComponent* owner)
  48591. {
  48592. if (result != 0 && owner != 0)
  48593. owner->getMappings().resetToDefaultMappings();
  48594. }
  48595. void buttonClicked (Button*)
  48596. {
  48597. AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48598. TRANS("Reset to defaults"),
  48599. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48600. TRANS("Reset"),
  48601. String::empty,
  48602. &owner,
  48603. ModalCallbackFunction::forComponent (resetToDefaultsCallback, &owner));
  48604. }
  48605. private:
  48606. KeyMappingEditorComponent& owner;
  48607. };
  48608. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48609. const bool showResetToDefaultButton)
  48610. : mappings (mappingManager),
  48611. resetButton (TRANS ("reset to defaults"))
  48612. {
  48613. treeItem = new TopLevelItem (*this);
  48614. if (showResetToDefaultButton)
  48615. {
  48616. addAndMakeVisible (&resetButton);
  48617. resetButton.addListener (treeItem);
  48618. }
  48619. addAndMakeVisible (&tree);
  48620. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48621. tree.setRootItemVisible (false);
  48622. tree.setDefaultOpenness (true);
  48623. tree.setRootItem (treeItem);
  48624. }
  48625. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48626. {
  48627. tree.setRootItem (0);
  48628. }
  48629. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48630. const Colour& textColour)
  48631. {
  48632. setColour (backgroundColourId, mainBackground);
  48633. setColour (textColourId, textColour);
  48634. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48635. }
  48636. void KeyMappingEditorComponent::parentHierarchyChanged()
  48637. {
  48638. treeItem->changeListenerCallback (0);
  48639. }
  48640. void KeyMappingEditorComponent::resized()
  48641. {
  48642. int h = getHeight();
  48643. if (resetButton.isVisible())
  48644. {
  48645. const int buttonHeight = 20;
  48646. h -= buttonHeight + 8;
  48647. int x = getWidth() - 8;
  48648. resetButton.changeWidthToFitText (buttonHeight);
  48649. resetButton.setTopRightPosition (x, h + 6);
  48650. }
  48651. tree.setBounds (0, 0, getWidth(), h);
  48652. }
  48653. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48654. {
  48655. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48656. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48657. }
  48658. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48659. {
  48660. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48661. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48662. }
  48663. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48664. {
  48665. return key.getTextDescription();
  48666. }
  48667. END_JUCE_NAMESPACE
  48668. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48669. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48670. BEGIN_JUCE_NAMESPACE
  48671. KeyPress::KeyPress() throw()
  48672. : keyCode (0),
  48673. mods (0),
  48674. textCharacter (0)
  48675. {
  48676. }
  48677. KeyPress::KeyPress (const int keyCode_,
  48678. const ModifierKeys& mods_,
  48679. const juce_wchar textCharacter_) throw()
  48680. : keyCode (keyCode_),
  48681. mods (mods_),
  48682. textCharacter (textCharacter_)
  48683. {
  48684. }
  48685. KeyPress::KeyPress (const int keyCode_) throw()
  48686. : keyCode (keyCode_),
  48687. textCharacter (0)
  48688. {
  48689. }
  48690. KeyPress::KeyPress (const KeyPress& other) throw()
  48691. : keyCode (other.keyCode),
  48692. mods (other.mods),
  48693. textCharacter (other.textCharacter)
  48694. {
  48695. }
  48696. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48697. {
  48698. keyCode = other.keyCode;
  48699. mods = other.mods;
  48700. textCharacter = other.textCharacter;
  48701. return *this;
  48702. }
  48703. bool KeyPress::operator== (const KeyPress& other) const throw()
  48704. {
  48705. return mods.getRawFlags() == other.mods.getRawFlags()
  48706. && (textCharacter == other.textCharacter
  48707. || textCharacter == 0
  48708. || other.textCharacter == 0)
  48709. && (keyCode == other.keyCode
  48710. || (keyCode < 256
  48711. && other.keyCode < 256
  48712. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48713. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48714. }
  48715. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48716. {
  48717. return ! operator== (other);
  48718. }
  48719. bool KeyPress::isCurrentlyDown() const
  48720. {
  48721. return isKeyCurrentlyDown (keyCode)
  48722. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48723. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48724. }
  48725. namespace KeyPressHelpers
  48726. {
  48727. struct KeyNameAndCode
  48728. {
  48729. const char* name;
  48730. int code;
  48731. };
  48732. const KeyNameAndCode translations[] =
  48733. {
  48734. { "spacebar", KeyPress::spaceKey },
  48735. { "return", KeyPress::returnKey },
  48736. { "escape", KeyPress::escapeKey },
  48737. { "backspace", KeyPress::backspaceKey },
  48738. { "cursor left", KeyPress::leftKey },
  48739. { "cursor right", KeyPress::rightKey },
  48740. { "cursor up", KeyPress::upKey },
  48741. { "cursor down", KeyPress::downKey },
  48742. { "page up", KeyPress::pageUpKey },
  48743. { "page down", KeyPress::pageDownKey },
  48744. { "home", KeyPress::homeKey },
  48745. { "end", KeyPress::endKey },
  48746. { "delete", KeyPress::deleteKey },
  48747. { "insert", KeyPress::insertKey },
  48748. { "tab", KeyPress::tabKey },
  48749. { "play", KeyPress::playKey },
  48750. { "stop", KeyPress::stopKey },
  48751. { "fast forward", KeyPress::fastForwardKey },
  48752. { "rewind", KeyPress::rewindKey }
  48753. };
  48754. const String numberPadPrefix() { return "numpad "; }
  48755. }
  48756. const KeyPress KeyPress::createFromDescription (const String& desc)
  48757. {
  48758. int modifiers = 0;
  48759. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48760. || desc.containsWholeWordIgnoreCase ("control")
  48761. || desc.containsWholeWordIgnoreCase ("ctl"))
  48762. modifiers |= ModifierKeys::ctrlModifier;
  48763. if (desc.containsWholeWordIgnoreCase ("shift")
  48764. || desc.containsWholeWordIgnoreCase ("shft"))
  48765. modifiers |= ModifierKeys::shiftModifier;
  48766. if (desc.containsWholeWordIgnoreCase ("alt")
  48767. || desc.containsWholeWordIgnoreCase ("option"))
  48768. modifiers |= ModifierKeys::altModifier;
  48769. if (desc.containsWholeWordIgnoreCase ("command")
  48770. || desc.containsWholeWordIgnoreCase ("cmd"))
  48771. modifiers |= ModifierKeys::commandModifier;
  48772. int key = 0;
  48773. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48774. {
  48775. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48776. {
  48777. key = KeyPressHelpers::translations[i].code;
  48778. break;
  48779. }
  48780. }
  48781. if (key == 0)
  48782. {
  48783. // see if it's a numpad key..
  48784. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48785. {
  48786. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48787. if (lastChar >= '0' && lastChar <= '9')
  48788. key = numberPad0 + lastChar - '0';
  48789. else if (lastChar == '+')
  48790. key = numberPadAdd;
  48791. else if (lastChar == '-')
  48792. key = numberPadSubtract;
  48793. else if (lastChar == '*')
  48794. key = numberPadMultiply;
  48795. else if (lastChar == '/')
  48796. key = numberPadDivide;
  48797. else if (lastChar == '.')
  48798. key = numberPadDecimalPoint;
  48799. else if (lastChar == '=')
  48800. key = numberPadEquals;
  48801. else if (desc.endsWith ("separator"))
  48802. key = numberPadSeparator;
  48803. else if (desc.endsWith ("delete"))
  48804. key = numberPadDelete;
  48805. }
  48806. if (key == 0)
  48807. {
  48808. // see if it's a function key..
  48809. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48810. for (int i = 1; i <= 12; ++i)
  48811. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48812. key = F1Key + i - 1;
  48813. if (key == 0)
  48814. {
  48815. // give up and use the hex code..
  48816. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48817. .toLowerCase()
  48818. .retainCharacters ("0123456789abcdef")
  48819. .getHexValue32();
  48820. if (hexCode > 0)
  48821. key = hexCode;
  48822. else
  48823. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48824. }
  48825. }
  48826. }
  48827. return KeyPress (key, ModifierKeys (modifiers), 0);
  48828. }
  48829. const String KeyPress::getTextDescription() const
  48830. {
  48831. String desc;
  48832. if (keyCode > 0)
  48833. {
  48834. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48835. // want to store it as being a slash, not shift+whatever.
  48836. if (textCharacter == '/')
  48837. return "/";
  48838. if (mods.isCtrlDown())
  48839. desc << "ctrl + ";
  48840. if (mods.isShiftDown())
  48841. desc << "shift + ";
  48842. #if JUCE_MAC
  48843. // only do this on the mac, because on Windows ctrl and command are the same,
  48844. // and this would get confusing
  48845. if (mods.isCommandDown())
  48846. desc << "command + ";
  48847. if (mods.isAltDown())
  48848. desc << "option + ";
  48849. #else
  48850. if (mods.isAltDown())
  48851. desc << "alt + ";
  48852. #endif
  48853. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48854. if (keyCode == KeyPressHelpers::translations[i].code)
  48855. return desc + KeyPressHelpers::translations[i].name;
  48856. if (keyCode >= F1Key && keyCode <= F16Key)
  48857. desc << 'F' << (1 + keyCode - F1Key);
  48858. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48859. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48860. else if (keyCode >= 33 && keyCode < 176)
  48861. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48862. else if (keyCode == numberPadAdd)
  48863. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48864. else if (keyCode == numberPadSubtract)
  48865. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48866. else if (keyCode == numberPadMultiply)
  48867. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48868. else if (keyCode == numberPadDivide)
  48869. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48870. else if (keyCode == numberPadSeparator)
  48871. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48872. else if (keyCode == numberPadDecimalPoint)
  48873. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48874. else if (keyCode == numberPadDelete)
  48875. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48876. else
  48877. desc << '#' << String::toHexString (keyCode);
  48878. }
  48879. return desc;
  48880. }
  48881. END_JUCE_NAMESPACE
  48882. /*** End of inlined file: juce_KeyPress.cpp ***/
  48883. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48884. BEGIN_JUCE_NAMESPACE
  48885. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48886. : commandManager (commandManager_)
  48887. {
  48888. // A manager is needed to get the descriptions of commands, and will be called when
  48889. // a command is invoked. So you can't leave this null..
  48890. jassert (commandManager_ != 0);
  48891. Desktop::getInstance().addFocusChangeListener (this);
  48892. }
  48893. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48894. : commandManager (other.commandManager)
  48895. {
  48896. Desktop::getInstance().addFocusChangeListener (this);
  48897. }
  48898. KeyPressMappingSet::~KeyPressMappingSet()
  48899. {
  48900. Desktop::getInstance().removeFocusChangeListener (this);
  48901. }
  48902. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48903. {
  48904. for (int i = 0; i < mappings.size(); ++i)
  48905. if (mappings.getUnchecked(i)->commandID == commandID)
  48906. return mappings.getUnchecked (i)->keypresses;
  48907. return Array <KeyPress> ();
  48908. }
  48909. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48910. const KeyPress& newKeyPress,
  48911. int insertIndex)
  48912. {
  48913. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48914. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48915. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48916. && ! newKeyPress.getModifiers().isShiftDown()));
  48917. if (findCommandForKeyPress (newKeyPress) != commandID)
  48918. {
  48919. removeKeyPress (newKeyPress);
  48920. if (newKeyPress.isValid())
  48921. {
  48922. for (int i = mappings.size(); --i >= 0;)
  48923. {
  48924. if (mappings.getUnchecked(i)->commandID == commandID)
  48925. {
  48926. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48927. sendChangeMessage();
  48928. return;
  48929. }
  48930. }
  48931. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48932. if (ci != 0)
  48933. {
  48934. CommandMapping* const cm = new CommandMapping();
  48935. cm->commandID = commandID;
  48936. cm->keypresses.add (newKeyPress);
  48937. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48938. mappings.add (cm);
  48939. sendChangeMessage();
  48940. }
  48941. }
  48942. }
  48943. }
  48944. void KeyPressMappingSet::resetToDefaultMappings()
  48945. {
  48946. mappings.clear();
  48947. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48948. {
  48949. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48950. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48951. {
  48952. addKeyPress (ci->commandID,
  48953. ci->defaultKeypresses.getReference (j));
  48954. }
  48955. }
  48956. sendChangeMessage();
  48957. }
  48958. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48959. {
  48960. clearAllKeyPresses (commandID);
  48961. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48962. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48963. {
  48964. addKeyPress (ci->commandID,
  48965. ci->defaultKeypresses.getReference (j));
  48966. }
  48967. }
  48968. void KeyPressMappingSet::clearAllKeyPresses()
  48969. {
  48970. if (mappings.size() > 0)
  48971. {
  48972. sendChangeMessage();
  48973. mappings.clear();
  48974. }
  48975. }
  48976. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48977. {
  48978. for (int i = mappings.size(); --i >= 0;)
  48979. {
  48980. if (mappings.getUnchecked(i)->commandID == commandID)
  48981. {
  48982. mappings.remove (i);
  48983. sendChangeMessage();
  48984. }
  48985. }
  48986. }
  48987. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48988. {
  48989. if (keypress.isValid())
  48990. {
  48991. for (int i = mappings.size(); --i >= 0;)
  48992. {
  48993. CommandMapping* const cm = mappings.getUnchecked(i);
  48994. for (int j = cm->keypresses.size(); --j >= 0;)
  48995. {
  48996. if (keypress == cm->keypresses [j])
  48997. {
  48998. cm->keypresses.remove (j);
  48999. sendChangeMessage();
  49000. }
  49001. }
  49002. }
  49003. }
  49004. }
  49005. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49006. {
  49007. for (int i = mappings.size(); --i >= 0;)
  49008. {
  49009. if (mappings.getUnchecked(i)->commandID == commandID)
  49010. {
  49011. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49012. sendChangeMessage();
  49013. break;
  49014. }
  49015. }
  49016. }
  49017. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49018. {
  49019. for (int i = 0; i < mappings.size(); ++i)
  49020. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49021. return mappings.getUnchecked(i)->commandID;
  49022. return 0;
  49023. }
  49024. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49025. {
  49026. for (int i = mappings.size(); --i >= 0;)
  49027. if (mappings.getUnchecked(i)->commandID == commandID)
  49028. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49029. return false;
  49030. }
  49031. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49032. const KeyPress& key,
  49033. const bool isKeyDown,
  49034. const int millisecsSinceKeyPressed,
  49035. Component* const originatingComponent) const
  49036. {
  49037. ApplicationCommandTarget::InvocationInfo info (commandID);
  49038. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49039. info.isKeyDown = isKeyDown;
  49040. info.keyPress = key;
  49041. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49042. info.originatingComponent = originatingComponent;
  49043. commandManager->invoke (info, false);
  49044. }
  49045. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49046. {
  49047. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49048. {
  49049. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49050. {
  49051. // if the XML was created as a set of differences from the default mappings,
  49052. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49053. resetToDefaultMappings();
  49054. }
  49055. else
  49056. {
  49057. // if the XML was created calling createXml (false), then we need to clear all
  49058. // the keys and treat the xml as describing the entire set of mappings.
  49059. clearAllKeyPresses();
  49060. }
  49061. forEachXmlChildElement (xmlVersion, map)
  49062. {
  49063. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49064. if (commandId != 0)
  49065. {
  49066. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49067. if (map->hasTagName ("MAPPING"))
  49068. {
  49069. addKeyPress (commandId, key);
  49070. }
  49071. else if (map->hasTagName ("UNMAPPING"))
  49072. {
  49073. if (containsMapping (commandId, key))
  49074. removeKeyPress (key);
  49075. }
  49076. }
  49077. }
  49078. return true;
  49079. }
  49080. return false;
  49081. }
  49082. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49083. {
  49084. ScopedPointer <KeyPressMappingSet> defaultSet;
  49085. if (saveDifferencesFromDefaultSet)
  49086. {
  49087. defaultSet = new KeyPressMappingSet (commandManager);
  49088. defaultSet->resetToDefaultMappings();
  49089. }
  49090. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49091. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49092. int i;
  49093. for (i = 0; i < mappings.size(); ++i)
  49094. {
  49095. const CommandMapping* const cm = mappings.getUnchecked(i);
  49096. for (int j = 0; j < cm->keypresses.size(); ++j)
  49097. {
  49098. if (defaultSet == 0
  49099. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49100. {
  49101. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49102. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49103. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49104. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49105. }
  49106. }
  49107. }
  49108. if (defaultSet != 0)
  49109. {
  49110. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49111. {
  49112. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49113. for (int j = 0; j < cm->keypresses.size(); ++j)
  49114. {
  49115. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49116. {
  49117. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49118. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49119. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49120. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49121. }
  49122. }
  49123. }
  49124. }
  49125. return doc;
  49126. }
  49127. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49128. Component* originatingComponent)
  49129. {
  49130. bool used = false;
  49131. const CommandID commandID = findCommandForKeyPress (key);
  49132. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49133. if (ci != 0
  49134. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49135. {
  49136. ApplicationCommandInfo info (0);
  49137. if (commandManager->getTargetForCommand (commandID, info) != 0
  49138. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49139. {
  49140. invokeCommand (commandID, key, true, 0, originatingComponent);
  49141. used = true;
  49142. }
  49143. else
  49144. {
  49145. if (originatingComponent != 0)
  49146. originatingComponent->getLookAndFeel().playAlertSound();
  49147. }
  49148. }
  49149. return used;
  49150. }
  49151. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49152. {
  49153. bool used = false;
  49154. const uint32 now = Time::getMillisecondCounter();
  49155. for (int i = mappings.size(); --i >= 0;)
  49156. {
  49157. CommandMapping* const cm = mappings.getUnchecked(i);
  49158. if (cm->wantsKeyUpDownCallbacks)
  49159. {
  49160. for (int j = cm->keypresses.size(); --j >= 0;)
  49161. {
  49162. const KeyPress key (cm->keypresses.getReference (j));
  49163. const bool isDown = key.isCurrentlyDown();
  49164. int keyPressEntryIndex = 0;
  49165. bool wasDown = false;
  49166. for (int k = keysDown.size(); --k >= 0;)
  49167. {
  49168. if (key == keysDown.getUnchecked(k)->key)
  49169. {
  49170. keyPressEntryIndex = k;
  49171. wasDown = true;
  49172. used = true;
  49173. break;
  49174. }
  49175. }
  49176. if (isDown != wasDown)
  49177. {
  49178. int millisecs = 0;
  49179. if (isDown)
  49180. {
  49181. KeyPressTime* const k = new KeyPressTime();
  49182. k->key = key;
  49183. k->timeWhenPressed = now;
  49184. keysDown.add (k);
  49185. }
  49186. else
  49187. {
  49188. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49189. if (now > pressTime)
  49190. millisecs = now - pressTime;
  49191. keysDown.remove (keyPressEntryIndex);
  49192. }
  49193. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49194. used = true;
  49195. }
  49196. }
  49197. }
  49198. }
  49199. return used;
  49200. }
  49201. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49202. {
  49203. if (focusedComponent != 0)
  49204. focusedComponent->keyStateChanged (false);
  49205. }
  49206. END_JUCE_NAMESPACE
  49207. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49208. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49209. BEGIN_JUCE_NAMESPACE
  49210. ModifierKeys::ModifierKeys (const int flags_) throw()
  49211. : flags (flags_)
  49212. {
  49213. }
  49214. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49215. : flags (other.flags)
  49216. {
  49217. }
  49218. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49219. {
  49220. flags = other.flags;
  49221. return *this;
  49222. }
  49223. ModifierKeys ModifierKeys::currentModifiers;
  49224. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49225. {
  49226. return currentModifiers;
  49227. }
  49228. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49229. {
  49230. int num = 0;
  49231. if (isLeftButtonDown()) ++num;
  49232. if (isRightButtonDown()) ++num;
  49233. if (isMiddleButtonDown()) ++num;
  49234. return num;
  49235. }
  49236. END_JUCE_NAMESPACE
  49237. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49238. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49239. BEGIN_JUCE_NAMESPACE
  49240. class ComponentAnimator::AnimationTask
  49241. {
  49242. public:
  49243. AnimationTask (Component* const comp)
  49244. : component (comp)
  49245. {
  49246. }
  49247. void reset (const Rectangle<int>& finalBounds,
  49248. float finalAlpha,
  49249. int millisecondsToSpendMoving,
  49250. bool useProxyComponent,
  49251. double startSpeed_, double endSpeed_)
  49252. {
  49253. msElapsed = 0;
  49254. msTotal = jmax (1, millisecondsToSpendMoving);
  49255. lastProgress = 0;
  49256. destination = finalBounds;
  49257. destAlpha = finalAlpha;
  49258. isMoving = (finalBounds != component->getBounds());
  49259. isChangingAlpha = (finalAlpha != component->getAlpha());
  49260. left = component->getX();
  49261. top = component->getY();
  49262. right = component->getRight();
  49263. bottom = component->getBottom();
  49264. alpha = component->getAlpha();
  49265. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49266. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49267. midSpeed = invTotalDistance;
  49268. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49269. if (useProxyComponent)
  49270. proxy = new ProxyComponent (*component);
  49271. else
  49272. proxy = 0;
  49273. component->setVisible (! useProxyComponent);
  49274. }
  49275. bool useTimeslice (const int elapsed)
  49276. {
  49277. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49278. : static_cast <Component*> (component);
  49279. if (c != 0)
  49280. {
  49281. msElapsed += elapsed;
  49282. double newProgress = msElapsed / (double) msTotal;
  49283. if (newProgress >= 0 && newProgress < 1.0)
  49284. {
  49285. newProgress = timeToDistance (newProgress);
  49286. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49287. jassert (newProgress >= lastProgress);
  49288. lastProgress = newProgress;
  49289. if (delta < 1.0)
  49290. {
  49291. bool stillBusy = false;
  49292. if (isMoving)
  49293. {
  49294. left += (destination.getX() - left) * delta;
  49295. top += (destination.getY() - top) * delta;
  49296. right += (destination.getRight() - right) * delta;
  49297. bottom += (destination.getBottom() - bottom) * delta;
  49298. const Rectangle<int> newBounds (roundToInt (left),
  49299. roundToInt (top),
  49300. roundToInt (right - left),
  49301. roundToInt (bottom - top));
  49302. if (newBounds != destination)
  49303. {
  49304. c->setBounds (newBounds);
  49305. stillBusy = true;
  49306. }
  49307. }
  49308. if (isChangingAlpha)
  49309. {
  49310. alpha += (destAlpha - alpha) * delta;
  49311. c->setAlpha ((float) alpha);
  49312. stillBusy = true;
  49313. }
  49314. if (stillBusy)
  49315. return true;
  49316. }
  49317. }
  49318. }
  49319. moveToFinalDestination();
  49320. return false;
  49321. }
  49322. void moveToFinalDestination()
  49323. {
  49324. if (component != 0)
  49325. {
  49326. component->setAlpha ((float) destAlpha);
  49327. component->setBounds (destination);
  49328. }
  49329. }
  49330. class ProxyComponent : public Component
  49331. {
  49332. public:
  49333. ProxyComponent (Component& component)
  49334. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49335. {
  49336. setBounds (component.getBounds());
  49337. setAlpha (component.getAlpha());
  49338. setInterceptsMouseClicks (false, false);
  49339. Component* const parent = component.getParentComponent();
  49340. if (parent != 0)
  49341. parent->addAndMakeVisible (this);
  49342. else if (component.isOnDesktop() && component.getPeer() != 0)
  49343. addToDesktop (component.getPeer()->getStyleFlags());
  49344. else
  49345. jassertfalse; // seem to be trying to animate a component that's not visible..
  49346. setVisible (true);
  49347. toBehind (&component);
  49348. }
  49349. void paint (Graphics& g)
  49350. {
  49351. g.setOpacity (1.0f);
  49352. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49353. 0, 0, image.getWidth(), image.getHeight());
  49354. }
  49355. private:
  49356. Image image;
  49357. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49358. };
  49359. WeakReference<Component> component;
  49360. ScopedPointer<Component> proxy;
  49361. Rectangle<int> destination;
  49362. double destAlpha;
  49363. int msElapsed, msTotal;
  49364. double startSpeed, midSpeed, endSpeed, lastProgress;
  49365. double left, top, right, bottom, alpha;
  49366. bool isMoving, isChangingAlpha;
  49367. private:
  49368. double timeToDistance (const double time) const throw()
  49369. {
  49370. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49371. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49372. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49373. }
  49374. };
  49375. ComponentAnimator::ComponentAnimator()
  49376. : lastTime (0)
  49377. {
  49378. }
  49379. ComponentAnimator::~ComponentAnimator()
  49380. {
  49381. }
  49382. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49383. {
  49384. for (int i = tasks.size(); --i >= 0;)
  49385. if (component == tasks.getUnchecked(i)->component.get())
  49386. return tasks.getUnchecked(i);
  49387. return 0;
  49388. }
  49389. void ComponentAnimator::animateComponent (Component* const component,
  49390. const Rectangle<int>& finalBounds,
  49391. const float finalAlpha,
  49392. const int millisecondsToSpendMoving,
  49393. const bool useProxyComponent,
  49394. const double startSpeed,
  49395. const double endSpeed)
  49396. {
  49397. // the speeds must be 0 or greater!
  49398. jassert (startSpeed >= 0 && endSpeed >= 0)
  49399. if (component != 0)
  49400. {
  49401. AnimationTask* at = findTaskFor (component);
  49402. if (at == 0)
  49403. {
  49404. at = new AnimationTask (component);
  49405. tasks.add (at);
  49406. sendChangeMessage();
  49407. }
  49408. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49409. useProxyComponent, startSpeed, endSpeed);
  49410. if (! isTimerRunning())
  49411. {
  49412. lastTime = Time::getMillisecondCounter();
  49413. startTimer (1000 / 50);
  49414. }
  49415. }
  49416. }
  49417. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49418. {
  49419. if (component != 0)
  49420. {
  49421. if (component->isShowing() && millisecondsToTake > 0)
  49422. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49423. component->setVisible (false);
  49424. }
  49425. }
  49426. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49427. {
  49428. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49429. {
  49430. component->setAlpha (0.0f);
  49431. component->setVisible (true);
  49432. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49433. }
  49434. }
  49435. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49436. {
  49437. if (tasks.size() > 0)
  49438. {
  49439. if (moveComponentsToTheirFinalPositions)
  49440. for (int i = tasks.size(); --i >= 0;)
  49441. tasks.getUnchecked(i)->moveToFinalDestination();
  49442. tasks.clear();
  49443. sendChangeMessage();
  49444. }
  49445. }
  49446. void ComponentAnimator::cancelAnimation (Component* const component,
  49447. const bool moveComponentToItsFinalPosition)
  49448. {
  49449. AnimationTask* const at = findTaskFor (component);
  49450. if (at != 0)
  49451. {
  49452. if (moveComponentToItsFinalPosition)
  49453. at->moveToFinalDestination();
  49454. tasks.removeObject (at);
  49455. sendChangeMessage();
  49456. }
  49457. }
  49458. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49459. {
  49460. jassert (component != 0);
  49461. AnimationTask* const at = findTaskFor (component);
  49462. if (at != 0)
  49463. return at->destination;
  49464. return component->getBounds();
  49465. }
  49466. bool ComponentAnimator::isAnimating (Component* component) const
  49467. {
  49468. return findTaskFor (component) != 0;
  49469. }
  49470. void ComponentAnimator::timerCallback()
  49471. {
  49472. const uint32 timeNow = Time::getMillisecondCounter();
  49473. if (lastTime == 0 || lastTime == timeNow)
  49474. lastTime = timeNow;
  49475. const int elapsed = timeNow - lastTime;
  49476. for (int i = tasks.size(); --i >= 0;)
  49477. {
  49478. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49479. {
  49480. tasks.remove (i);
  49481. sendChangeMessage();
  49482. }
  49483. }
  49484. lastTime = timeNow;
  49485. if (tasks.size() == 0)
  49486. stopTimer();
  49487. }
  49488. END_JUCE_NAMESPACE
  49489. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49490. /*** Start of inlined file: juce_ComponentBuilder.cpp ***/
  49491. BEGIN_JUCE_NAMESPACE
  49492. namespace ComponentBuilderHelpers
  49493. {
  49494. const String getStateId (const ValueTree& state)
  49495. {
  49496. return state [ComponentBuilder::idProperty].toString();
  49497. }
  49498. Component* findComponentWithID (OwnedArray<Component>& components, const String& compId)
  49499. {
  49500. jassert (compId.isNotEmpty());
  49501. for (int i = components.size(); --i >= 0;)
  49502. {
  49503. Component* const c = components.getUnchecked (i);
  49504. if (c->getComponentID() == compId)
  49505. return components.removeAndReturn (i);
  49506. }
  49507. return 0;
  49508. }
  49509. Component* findComponentWithID (Component* const c, const String& compId)
  49510. {
  49511. jassert (compId.isNotEmpty());
  49512. if (c->getComponentID() == compId)
  49513. return c;
  49514. for (int i = c->getNumChildComponents(); --i >= 0;)
  49515. {
  49516. Component* const child = findComponentWithID (c->getChildComponent (i), compId);
  49517. if (child != 0)
  49518. return child;
  49519. }
  49520. return 0;
  49521. }
  49522. Component* createNewComponent (ComponentBuilder::TypeHandler& type,
  49523. const ValueTree& state, Component* parent)
  49524. {
  49525. Component* const c = type.addNewComponentFromState (state, parent);
  49526. jassert (c != 0 && c->getParentComponent() == parent);
  49527. c->setComponentID (getStateId (state));
  49528. return c;
  49529. }
  49530. void updateComponent (ComponentBuilder& builder, const ValueTree& state)
  49531. {
  49532. Component* topLevelComp = builder.getManagedComponent();
  49533. if (topLevelComp != 0)
  49534. {
  49535. ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state);
  49536. const String uid (getStateId (state));
  49537. if (type == 0 || uid.isEmpty())
  49538. {
  49539. // ..handle the case where a child of the actual state node has changed.
  49540. if (state.getParent().isValid())
  49541. updateComponent (builder, state.getParent());
  49542. }
  49543. else
  49544. {
  49545. Component* const changedComp = findComponentWithID (topLevelComp, uid);
  49546. if (changedComp != 0)
  49547. type->updateComponentFromState (changedComp, state);
  49548. }
  49549. }
  49550. }
  49551. }
  49552. const Identifier ComponentBuilder::idProperty ("id");
  49553. ComponentBuilder::ComponentBuilder (const ValueTree& state_)
  49554. : state (state_), imageProvider (0)
  49555. {
  49556. state.addListener (this);
  49557. }
  49558. ComponentBuilder::~ComponentBuilder()
  49559. {
  49560. state.removeListener (this);
  49561. #if JUCE_DEBUG
  49562. // Don't delete the managed component!! The builder owns that component, and will delete
  49563. // it automatically when it gets deleted.
  49564. jassert (componentRef.get() == static_cast <Component*> (component));
  49565. #endif
  49566. }
  49567. Component* ComponentBuilder::getManagedComponent()
  49568. {
  49569. if (component == 0)
  49570. {
  49571. component = createComponent();
  49572. #if JUCE_DEBUG
  49573. componentRef = component;
  49574. #endif
  49575. }
  49576. return component;
  49577. }
  49578. Component* ComponentBuilder::createComponent()
  49579. {
  49580. jassert (types.size() > 0); // You need to register all the necessary types before you can load a component!
  49581. TypeHandler* const type = getHandlerForState (state);
  49582. jassert (type != 0); // trying to create a component from an unknown type of ValueTree
  49583. return type != 0 ? ComponentBuilderHelpers::createNewComponent (*type, state, 0) : 0;
  49584. }
  49585. void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type)
  49586. {
  49587. jassert (type != 0);
  49588. // Don't try to move your types around! Once a type has been added to a builder, the
  49589. // builder owns it, and you should leave it alone!
  49590. jassert (type->builder == 0);
  49591. types.add (type);
  49592. type->builder = this;
  49593. }
  49594. ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const
  49595. {
  49596. const Identifier targetType (s.getType());
  49597. for (int i = 0; i < types.size(); ++i)
  49598. {
  49599. TypeHandler* const t = types.getUnchecked(i);
  49600. if (t->getType() == targetType)
  49601. return t;
  49602. }
  49603. return 0;
  49604. }
  49605. int ComponentBuilder::getNumHandlers() const throw()
  49606. {
  49607. return types.size();
  49608. }
  49609. ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const throw()
  49610. {
  49611. return types [index];
  49612. }
  49613. void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) throw()
  49614. {
  49615. imageProvider = newImageProvider;
  49616. }
  49617. ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const throw()
  49618. {
  49619. return imageProvider;
  49620. }
  49621. void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  49622. {
  49623. ComponentBuilderHelpers::updateComponent (*this, tree);
  49624. }
  49625. void ComponentBuilder::valueTreeChildAdded (ValueTree& tree, ValueTree&)
  49626. {
  49627. ComponentBuilderHelpers::updateComponent (*this, tree);
  49628. }
  49629. void ComponentBuilder::valueTreeChildRemoved (ValueTree& tree, ValueTree&)
  49630. {
  49631. ComponentBuilderHelpers::updateComponent (*this, tree);
  49632. }
  49633. void ComponentBuilder::valueTreeChildOrderChanged (ValueTree& tree)
  49634. {
  49635. ComponentBuilderHelpers::updateComponent (*this, tree);
  49636. }
  49637. void ComponentBuilder::valueTreeParentChanged (ValueTree& tree)
  49638. {
  49639. ComponentBuilderHelpers::updateComponent (*this, tree);
  49640. }
  49641. ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType_)
  49642. : builder (0), valueTreeType (valueTreeType_)
  49643. {
  49644. }
  49645. ComponentBuilder::TypeHandler::~TypeHandler()
  49646. {
  49647. }
  49648. ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const throw()
  49649. {
  49650. // A type handler needs to be registered with a ComponentBuilder before using it!
  49651. jassert (builder != 0);
  49652. return builder;
  49653. }
  49654. void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
  49655. {
  49656. using namespace ComponentBuilderHelpers;
  49657. const int numExistingChildComps = parent.getNumChildComponents();
  49658. Array <Component*> componentsInOrder;
  49659. componentsInOrder.ensureStorageAllocated (numExistingChildComps);
  49660. {
  49661. OwnedArray<Component> existingComponents;
  49662. existingComponents.ensureStorageAllocated (numExistingChildComps);
  49663. int i;
  49664. for (i = 0; i < numExistingChildComps; ++i)
  49665. existingComponents.add (parent.getChildComponent (i));
  49666. const int newNumChildren = children.getNumChildren();
  49667. for (i = 0; i < newNumChildren; ++i)
  49668. {
  49669. const ValueTree childState (children.getChild (i));
  49670. ComponentBuilder::TypeHandler* const type = getHandlerForState (childState);
  49671. jassert (type != 0);
  49672. if (type != 0)
  49673. {
  49674. Component* c = findComponentWithID (existingComponents, getStateId (childState));
  49675. if (c == 0)
  49676. c = createNewComponent (*type, childState, &parent);
  49677. componentsInOrder.add (c);
  49678. }
  49679. }
  49680. // (remaining unused items in existingComponents get deleted here as it goes out of scope)
  49681. }
  49682. // Make sure the z-order is correct..
  49683. if (componentsInOrder.size() > 0)
  49684. {
  49685. componentsInOrder.getLast()->toFront (false);
  49686. for (int i = componentsInOrder.size() - 1; --i >= 0;)
  49687. componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
  49688. }
  49689. }
  49690. END_JUCE_NAMESPACE
  49691. /*** End of inlined file: juce_ComponentBuilder.cpp ***/
  49692. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49693. BEGIN_JUCE_NAMESPACE
  49694. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49695. : minW (0),
  49696. maxW (0x3fffffff),
  49697. minH (0),
  49698. maxH (0x3fffffff),
  49699. minOffTop (0),
  49700. minOffLeft (0),
  49701. minOffBottom (0),
  49702. minOffRight (0),
  49703. aspectRatio (0.0)
  49704. {
  49705. }
  49706. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49707. {
  49708. }
  49709. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49710. {
  49711. minW = minimumWidth;
  49712. }
  49713. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49714. {
  49715. maxW = maximumWidth;
  49716. }
  49717. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49718. {
  49719. minH = minimumHeight;
  49720. }
  49721. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49722. {
  49723. maxH = maximumHeight;
  49724. }
  49725. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49726. {
  49727. jassert (maxW >= minimumWidth);
  49728. jassert (maxH >= minimumHeight);
  49729. jassert (minimumWidth > 0 && minimumHeight > 0);
  49730. minW = minimumWidth;
  49731. minH = minimumHeight;
  49732. if (minW > maxW)
  49733. maxW = minW;
  49734. if (minH > maxH)
  49735. maxH = minH;
  49736. }
  49737. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49738. {
  49739. jassert (maximumWidth >= minW);
  49740. jassert (maximumHeight >= minH);
  49741. jassert (maximumWidth > 0 && maximumHeight > 0);
  49742. maxW = jmax (minW, maximumWidth);
  49743. maxH = jmax (minH, maximumHeight);
  49744. }
  49745. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49746. const int minimumHeight,
  49747. const int maximumWidth,
  49748. const int maximumHeight) throw()
  49749. {
  49750. jassert (maximumWidth >= minimumWidth);
  49751. jassert (maximumHeight >= minimumHeight);
  49752. jassert (maximumWidth > 0 && maximumHeight > 0);
  49753. jassert (minimumWidth > 0 && minimumHeight > 0);
  49754. minW = jmax (0, minimumWidth);
  49755. minH = jmax (0, minimumHeight);
  49756. maxW = jmax (minW, maximumWidth);
  49757. maxH = jmax (minH, maximumHeight);
  49758. }
  49759. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49760. const int minimumWhenOffTheLeft,
  49761. const int minimumWhenOffTheBottom,
  49762. const int minimumWhenOffTheRight) throw()
  49763. {
  49764. minOffTop = minimumWhenOffTheTop;
  49765. minOffLeft = minimumWhenOffTheLeft;
  49766. minOffBottom = minimumWhenOffTheBottom;
  49767. minOffRight = minimumWhenOffTheRight;
  49768. }
  49769. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49770. {
  49771. aspectRatio = jmax (0.0, widthOverHeight);
  49772. }
  49773. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49774. {
  49775. return aspectRatio;
  49776. }
  49777. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49778. const Rectangle<int>& targetBounds,
  49779. const bool isStretchingTop,
  49780. const bool isStretchingLeft,
  49781. const bool isStretchingBottom,
  49782. const bool isStretchingRight)
  49783. {
  49784. jassert (component != 0);
  49785. Rectangle<int> limits, bounds (targetBounds);
  49786. BorderSize<int> border;
  49787. Component* const parent = component->getParentComponent();
  49788. if (parent == 0)
  49789. {
  49790. ComponentPeer* peer = component->getPeer();
  49791. if (peer != 0)
  49792. border = peer->getFrameSize();
  49793. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49794. }
  49795. else
  49796. {
  49797. limits.setSize (parent->getWidth(), parent->getHeight());
  49798. }
  49799. border.addTo (bounds);
  49800. checkBounds (bounds,
  49801. border.addedTo (component->getBounds()), limits,
  49802. isStretchingTop, isStretchingLeft,
  49803. isStretchingBottom, isStretchingRight);
  49804. border.subtractFrom (bounds);
  49805. applyBoundsToComponent (component, bounds);
  49806. }
  49807. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49808. {
  49809. setBoundsForComponent (component, component->getBounds(),
  49810. false, false, false, false);
  49811. }
  49812. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49813. const Rectangle<int>& bounds)
  49814. {
  49815. Component::Positioner* const positioner = component->getPositioner();
  49816. if (positioner != 0)
  49817. positioner->applyNewBounds (bounds);
  49818. else
  49819. component->setBounds (bounds);
  49820. }
  49821. void ComponentBoundsConstrainer::resizeStart()
  49822. {
  49823. }
  49824. void ComponentBoundsConstrainer::resizeEnd()
  49825. {
  49826. }
  49827. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49828. const Rectangle<int>& old,
  49829. const Rectangle<int>& limits,
  49830. const bool isStretchingTop,
  49831. const bool isStretchingLeft,
  49832. const bool isStretchingBottom,
  49833. const bool isStretchingRight)
  49834. {
  49835. // constrain the size if it's being stretched..
  49836. if (isStretchingLeft)
  49837. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49838. if (isStretchingRight)
  49839. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49840. if (isStretchingTop)
  49841. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49842. if (isStretchingBottom)
  49843. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49844. if (bounds.isEmpty())
  49845. return;
  49846. if (minOffTop > 0)
  49847. {
  49848. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49849. if (bounds.getY() < limit)
  49850. {
  49851. if (isStretchingTop)
  49852. bounds.setTop (limits.getY());
  49853. else
  49854. bounds.setY (limit);
  49855. }
  49856. }
  49857. if (minOffLeft > 0)
  49858. {
  49859. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49860. if (bounds.getX() < limit)
  49861. {
  49862. if (isStretchingLeft)
  49863. bounds.setLeft (limits.getX());
  49864. else
  49865. bounds.setX (limit);
  49866. }
  49867. }
  49868. if (minOffBottom > 0)
  49869. {
  49870. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49871. if (bounds.getY() > limit)
  49872. {
  49873. if (isStretchingBottom)
  49874. bounds.setBottom (limits.getBottom());
  49875. else
  49876. bounds.setY (limit);
  49877. }
  49878. }
  49879. if (minOffRight > 0)
  49880. {
  49881. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49882. if (bounds.getX() > limit)
  49883. {
  49884. if (isStretchingRight)
  49885. bounds.setRight (limits.getRight());
  49886. else
  49887. bounds.setX (limit);
  49888. }
  49889. }
  49890. // constrain the aspect ratio if one has been specified..
  49891. if (aspectRatio > 0.0)
  49892. {
  49893. bool adjustWidth;
  49894. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49895. {
  49896. adjustWidth = true;
  49897. }
  49898. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49899. {
  49900. adjustWidth = false;
  49901. }
  49902. else
  49903. {
  49904. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49905. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49906. adjustWidth = (oldRatio > newRatio);
  49907. }
  49908. if (adjustWidth)
  49909. {
  49910. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49911. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49912. {
  49913. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49914. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49915. }
  49916. }
  49917. else
  49918. {
  49919. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49920. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49921. {
  49922. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49923. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49924. }
  49925. }
  49926. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49927. {
  49928. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49929. }
  49930. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49931. {
  49932. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49933. }
  49934. else
  49935. {
  49936. if (isStretchingLeft)
  49937. bounds.setX (old.getRight() - bounds.getWidth());
  49938. if (isStretchingTop)
  49939. bounds.setY (old.getBottom() - bounds.getHeight());
  49940. }
  49941. }
  49942. jassert (! bounds.isEmpty());
  49943. }
  49944. END_JUCE_NAMESPACE
  49945. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49946. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49947. BEGIN_JUCE_NAMESPACE
  49948. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49949. : component (component_),
  49950. lastPeer (0),
  49951. reentrant (false),
  49952. wasShowing (component_->isShowing())
  49953. {
  49954. jassert (component != 0); // can't use this with a null pointer..
  49955. component->addComponentListener (this);
  49956. registerWithParentComps();
  49957. }
  49958. ComponentMovementWatcher::~ComponentMovementWatcher()
  49959. {
  49960. if (component != 0)
  49961. component->removeComponentListener (this);
  49962. unregister();
  49963. }
  49964. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49965. {
  49966. if (component != 0 && ! reentrant)
  49967. {
  49968. const ScopedValueSetter<bool> setter (reentrant, true);
  49969. ComponentPeer* const peer = component->getPeer();
  49970. if (peer != lastPeer)
  49971. {
  49972. componentPeerChanged();
  49973. if (component == 0)
  49974. return;
  49975. lastPeer = peer;
  49976. }
  49977. unregister();
  49978. registerWithParentComps();
  49979. componentMovedOrResized (*component, true, true);
  49980. if (component != 0)
  49981. componentVisibilityChanged (*component);
  49982. }
  49983. }
  49984. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49985. {
  49986. if (component != 0)
  49987. {
  49988. if (wasMoved)
  49989. {
  49990. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49991. wasMoved = lastBounds.getPosition() != pos;
  49992. lastBounds.setPosition (pos);
  49993. }
  49994. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49995. lastBounds.setSize (component->getWidth(), component->getHeight());
  49996. if (wasMoved || wasResized)
  49997. componentMovedOrResized (wasMoved, wasResized);
  49998. }
  49999. }
  50000. void ComponentMovementWatcher::componentBeingDeleted (Component& comp)
  50001. {
  50002. registeredParentComps.removeValue (&comp);
  50003. if (component == &comp)
  50004. unregister();
  50005. }
  50006. void ComponentMovementWatcher::componentVisibilityChanged (Component&)
  50007. {
  50008. if (component != 0)
  50009. {
  50010. const bool isShowingNow = component->isShowing();
  50011. if (wasShowing != isShowingNow)
  50012. {
  50013. wasShowing = isShowingNow;
  50014. componentVisibilityChanged();
  50015. }
  50016. }
  50017. }
  50018. void ComponentMovementWatcher::registerWithParentComps()
  50019. {
  50020. Component* p = component->getParentComponent();
  50021. while (p != 0)
  50022. {
  50023. p->addComponentListener (this);
  50024. registeredParentComps.add (p);
  50025. p = p->getParentComponent();
  50026. }
  50027. }
  50028. void ComponentMovementWatcher::unregister()
  50029. {
  50030. for (int i = registeredParentComps.size(); --i >= 0;)
  50031. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  50032. registeredParentComps.clear();
  50033. }
  50034. END_JUCE_NAMESPACE
  50035. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  50036. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  50037. BEGIN_JUCE_NAMESPACE
  50038. GroupComponent::GroupComponent (const String& componentName,
  50039. const String& labelText)
  50040. : Component (componentName),
  50041. text (labelText),
  50042. justification (Justification::left)
  50043. {
  50044. setInterceptsMouseClicks (false, true);
  50045. }
  50046. GroupComponent::~GroupComponent()
  50047. {
  50048. }
  50049. void GroupComponent::setText (const String& newText)
  50050. {
  50051. if (text != newText)
  50052. {
  50053. text = newText;
  50054. repaint();
  50055. }
  50056. }
  50057. const String GroupComponent::getText() const
  50058. {
  50059. return text;
  50060. }
  50061. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  50062. {
  50063. if (justification != newJustification)
  50064. {
  50065. justification = newJustification;
  50066. repaint();
  50067. }
  50068. }
  50069. void GroupComponent::paint (Graphics& g)
  50070. {
  50071. getLookAndFeel()
  50072. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  50073. text, justification,
  50074. *this);
  50075. }
  50076. void GroupComponent::enablementChanged()
  50077. {
  50078. repaint();
  50079. }
  50080. void GroupComponent::colourChanged()
  50081. {
  50082. repaint();
  50083. }
  50084. END_JUCE_NAMESPACE
  50085. /*** End of inlined file: juce_GroupComponent.cpp ***/
  50086. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50087. BEGIN_JUCE_NAMESPACE
  50088. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50089. : DocumentWindow (String::empty, backgroundColour,
  50090. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50091. {
  50092. }
  50093. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50094. {
  50095. }
  50096. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50097. {
  50098. MultiDocumentPanel* const owner = getOwner();
  50099. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50100. if (owner != 0)
  50101. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50102. }
  50103. void MultiDocumentPanelWindow::closeButtonPressed()
  50104. {
  50105. MultiDocumentPanel* const owner = getOwner();
  50106. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50107. if (owner != 0)
  50108. owner->closeDocument (getContentComponent(), true);
  50109. }
  50110. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50111. {
  50112. DocumentWindow::activeWindowStatusChanged();
  50113. updateOrder();
  50114. }
  50115. void MultiDocumentPanelWindow::broughtToFront()
  50116. {
  50117. DocumentWindow::broughtToFront();
  50118. updateOrder();
  50119. }
  50120. void MultiDocumentPanelWindow::updateOrder()
  50121. {
  50122. MultiDocumentPanel* const owner = getOwner();
  50123. if (owner != 0)
  50124. owner->updateOrder();
  50125. }
  50126. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50127. {
  50128. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50129. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50130. }
  50131. class MDITabbedComponentInternal : public TabbedComponent
  50132. {
  50133. public:
  50134. MDITabbedComponentInternal()
  50135. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50136. {
  50137. }
  50138. ~MDITabbedComponentInternal()
  50139. {
  50140. }
  50141. void currentTabChanged (int, const String&)
  50142. {
  50143. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50144. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50145. if (owner != 0)
  50146. owner->updateOrder();
  50147. }
  50148. };
  50149. MultiDocumentPanel::MultiDocumentPanel()
  50150. : mode (MaximisedWindowsWithTabs),
  50151. backgroundColour (Colours::lightblue),
  50152. maximumNumDocuments (0),
  50153. numDocsBeforeTabsUsed (0)
  50154. {
  50155. setOpaque (true);
  50156. }
  50157. MultiDocumentPanel::~MultiDocumentPanel()
  50158. {
  50159. closeAllDocuments (false);
  50160. }
  50161. namespace MultiDocHelpers
  50162. {
  50163. bool shouldDeleteComp (Component* const c)
  50164. {
  50165. return c->getProperties() ["mdiDocumentDelete_"];
  50166. }
  50167. }
  50168. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50169. {
  50170. while (components.size() > 0)
  50171. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50172. return false;
  50173. return true;
  50174. }
  50175. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50176. {
  50177. return new MultiDocumentPanelWindow (backgroundColour);
  50178. }
  50179. void MultiDocumentPanel::addWindow (Component* component)
  50180. {
  50181. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50182. dw->setResizable (true, false);
  50183. dw->setContentNonOwned (component, true);
  50184. dw->setName (component->getName());
  50185. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50186. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50187. int x = 4;
  50188. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50189. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50190. x += 16;
  50191. dw->setTopLeftPosition (x, x);
  50192. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50193. if (pos.toString().isNotEmpty())
  50194. dw->restoreWindowStateFromString (pos.toString());
  50195. addAndMakeVisible (dw);
  50196. dw->toFront (true);
  50197. }
  50198. bool MultiDocumentPanel::addDocument (Component* const component,
  50199. const Colour& docColour,
  50200. const bool deleteWhenRemoved)
  50201. {
  50202. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50203. // with a frame-within-a-frame! Just pass in the bare content component.
  50204. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50205. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50206. return false;
  50207. components.add (component);
  50208. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50209. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50210. component->addComponentListener (this);
  50211. if (mode == FloatingWindows)
  50212. {
  50213. if (isFullscreenWhenOneDocument())
  50214. {
  50215. if (components.size() == 1)
  50216. {
  50217. addAndMakeVisible (component);
  50218. }
  50219. else
  50220. {
  50221. if (components.size() == 2)
  50222. addWindow (components.getFirst());
  50223. addWindow (component);
  50224. }
  50225. }
  50226. else
  50227. {
  50228. addWindow (component);
  50229. }
  50230. }
  50231. else
  50232. {
  50233. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50234. {
  50235. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50236. Array <Component*> temp (components);
  50237. for (int i = 0; i < temp.size(); ++i)
  50238. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50239. resized();
  50240. }
  50241. else
  50242. {
  50243. if (tabComponent != 0)
  50244. tabComponent->addTab (component->getName(), docColour, component, false);
  50245. else
  50246. addAndMakeVisible (component);
  50247. }
  50248. setActiveDocument (component);
  50249. }
  50250. resized();
  50251. activeDocumentChanged();
  50252. return true;
  50253. }
  50254. bool MultiDocumentPanel::closeDocument (Component* component,
  50255. const bool checkItsOkToCloseFirst)
  50256. {
  50257. if (components.contains (component))
  50258. {
  50259. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50260. return false;
  50261. component->removeComponentListener (this);
  50262. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50263. component->getProperties().remove ("mdiDocumentDelete_");
  50264. component->getProperties().remove ("mdiDocumentBkg_");
  50265. if (mode == FloatingWindows)
  50266. {
  50267. for (int i = getNumChildComponents(); --i >= 0;)
  50268. {
  50269. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50270. if (dw != 0 && dw->getContentComponent() == component)
  50271. {
  50272. ScopedPointer<MultiDocumentPanelWindow> (dw)->clearContentComponent();
  50273. break;
  50274. }
  50275. }
  50276. if (shouldDelete)
  50277. delete component;
  50278. components.removeValue (component);
  50279. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50280. {
  50281. for (int i = getNumChildComponents(); --i >= 0;)
  50282. {
  50283. ScopedPointer<MultiDocumentPanelWindow> dw (dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i)));
  50284. if (dw != 0)
  50285. dw->clearContentComponent();
  50286. }
  50287. addAndMakeVisible (components.getFirst());
  50288. }
  50289. }
  50290. else
  50291. {
  50292. jassert (components.indexOf (component) >= 0);
  50293. if (tabComponent != 0)
  50294. {
  50295. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50296. if (tabComponent->getTabContentComponent (i) == component)
  50297. tabComponent->removeTab (i);
  50298. }
  50299. else
  50300. {
  50301. removeChildComponent (component);
  50302. }
  50303. if (shouldDelete)
  50304. delete component;
  50305. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50306. tabComponent = 0;
  50307. components.removeValue (component);
  50308. if (components.size() > 0 && tabComponent == 0)
  50309. addAndMakeVisible (components.getFirst());
  50310. }
  50311. resized();
  50312. activeDocumentChanged();
  50313. }
  50314. else
  50315. {
  50316. jassertfalse;
  50317. }
  50318. return true;
  50319. }
  50320. int MultiDocumentPanel::getNumDocuments() const throw()
  50321. {
  50322. return components.size();
  50323. }
  50324. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50325. {
  50326. return components [index];
  50327. }
  50328. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50329. {
  50330. if (mode == FloatingWindows)
  50331. {
  50332. for (int i = getNumChildComponents(); --i >= 0;)
  50333. {
  50334. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50335. if (dw != 0 && dw->isActiveWindow())
  50336. return dw->getContentComponent();
  50337. }
  50338. }
  50339. return components.getLast();
  50340. }
  50341. void MultiDocumentPanel::setActiveDocument (Component* component)
  50342. {
  50343. if (mode == FloatingWindows)
  50344. {
  50345. component = getContainerComp (component);
  50346. if (component != 0)
  50347. component->toFront (true);
  50348. }
  50349. else if (tabComponent != 0)
  50350. {
  50351. jassert (components.indexOf (component) >= 0);
  50352. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50353. {
  50354. if (tabComponent->getTabContentComponent (i) == component)
  50355. {
  50356. tabComponent->setCurrentTabIndex (i);
  50357. break;
  50358. }
  50359. }
  50360. }
  50361. else
  50362. {
  50363. component->grabKeyboardFocus();
  50364. }
  50365. }
  50366. void MultiDocumentPanel::activeDocumentChanged()
  50367. {
  50368. }
  50369. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50370. {
  50371. maximumNumDocuments = newNumber;
  50372. }
  50373. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50374. {
  50375. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50376. }
  50377. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50378. {
  50379. return numDocsBeforeTabsUsed != 0;
  50380. }
  50381. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50382. {
  50383. if (mode != newLayoutMode)
  50384. {
  50385. mode = newLayoutMode;
  50386. if (mode == FloatingWindows)
  50387. {
  50388. tabComponent = 0;
  50389. }
  50390. else
  50391. {
  50392. for (int i = getNumChildComponents(); --i >= 0;)
  50393. {
  50394. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50395. if (dw != 0)
  50396. {
  50397. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50398. dw->clearContentComponent();
  50399. delete dw;
  50400. }
  50401. }
  50402. }
  50403. resized();
  50404. const Array <Component*> tempComps (components);
  50405. components.clear();
  50406. for (int i = 0; i < tempComps.size(); ++i)
  50407. {
  50408. Component* const c = tempComps.getUnchecked(i);
  50409. addDocument (c,
  50410. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50411. MultiDocHelpers::shouldDeleteComp (c));
  50412. }
  50413. }
  50414. }
  50415. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50416. {
  50417. if (backgroundColour != newBackgroundColour)
  50418. {
  50419. backgroundColour = newBackgroundColour;
  50420. setOpaque (newBackgroundColour.isOpaque());
  50421. repaint();
  50422. }
  50423. }
  50424. void MultiDocumentPanel::paint (Graphics& g)
  50425. {
  50426. g.fillAll (backgroundColour);
  50427. }
  50428. void MultiDocumentPanel::resized()
  50429. {
  50430. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50431. {
  50432. for (int i = getNumChildComponents(); --i >= 0;)
  50433. getChildComponent (i)->setBounds (getLocalBounds());
  50434. }
  50435. setWantsKeyboardFocus (components.size() == 0);
  50436. }
  50437. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50438. {
  50439. if (mode == FloatingWindows)
  50440. {
  50441. for (int i = 0; i < getNumChildComponents(); ++i)
  50442. {
  50443. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50444. if (dw != 0 && dw->getContentComponent() == c)
  50445. {
  50446. c = dw;
  50447. break;
  50448. }
  50449. }
  50450. }
  50451. return c;
  50452. }
  50453. void MultiDocumentPanel::componentNameChanged (Component&)
  50454. {
  50455. if (mode == FloatingWindows)
  50456. {
  50457. for (int i = 0; i < getNumChildComponents(); ++i)
  50458. {
  50459. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50460. if (dw != 0)
  50461. dw->setName (dw->getContentComponent()->getName());
  50462. }
  50463. }
  50464. else if (tabComponent != 0)
  50465. {
  50466. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50467. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50468. }
  50469. }
  50470. void MultiDocumentPanel::updateOrder()
  50471. {
  50472. const Array <Component*> oldList (components);
  50473. if (mode == FloatingWindows)
  50474. {
  50475. components.clear();
  50476. for (int i = 0; i < getNumChildComponents(); ++i)
  50477. {
  50478. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50479. if (dw != 0)
  50480. components.add (dw->getContentComponent());
  50481. }
  50482. }
  50483. else
  50484. {
  50485. if (tabComponent != 0)
  50486. {
  50487. Component* const current = tabComponent->getCurrentContentComponent();
  50488. if (current != 0)
  50489. {
  50490. components.removeValue (current);
  50491. components.add (current);
  50492. }
  50493. }
  50494. }
  50495. if (components != oldList)
  50496. activeDocumentChanged();
  50497. }
  50498. END_JUCE_NAMESPACE
  50499. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50500. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50501. BEGIN_JUCE_NAMESPACE
  50502. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50503. : zone (zoneFlags)
  50504. {}
  50505. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50506. : zone (other.zone)
  50507. {}
  50508. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50509. {
  50510. zone = other.zone;
  50511. return *this;
  50512. }
  50513. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50514. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50515. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50516. const BorderSize<int>& border,
  50517. const Point<int>& position)
  50518. {
  50519. int z = 0;
  50520. if (totalSize.contains (position)
  50521. && ! border.subtractedFrom (totalSize).contains (position))
  50522. {
  50523. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50524. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50525. z |= left;
  50526. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50527. z |= right;
  50528. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50529. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50530. z |= top;
  50531. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50532. z |= bottom;
  50533. }
  50534. return Zone (z);
  50535. }
  50536. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50537. {
  50538. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50539. switch (zone)
  50540. {
  50541. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50542. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50543. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50544. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50545. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50546. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50547. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50548. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50549. default: break;
  50550. }
  50551. return mc;
  50552. }
  50553. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50554. ComponentBoundsConstrainer* const constrainer_)
  50555. : component (componentToResize),
  50556. constrainer (constrainer_),
  50557. borderSize (5),
  50558. mouseZone (0)
  50559. {
  50560. }
  50561. ResizableBorderComponent::~ResizableBorderComponent()
  50562. {
  50563. }
  50564. void ResizableBorderComponent::paint (Graphics& g)
  50565. {
  50566. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50567. }
  50568. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50569. {
  50570. updateMouseZone (e);
  50571. }
  50572. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50573. {
  50574. updateMouseZone (e);
  50575. }
  50576. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50577. {
  50578. if (component == 0)
  50579. {
  50580. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50581. return;
  50582. }
  50583. updateMouseZone (e);
  50584. originalBounds = component->getBounds();
  50585. if (constrainer != 0)
  50586. constrainer->resizeStart();
  50587. }
  50588. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50589. {
  50590. if (component == 0)
  50591. {
  50592. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50593. return;
  50594. }
  50595. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50596. if (constrainer != 0)
  50597. {
  50598. constrainer->setBoundsForComponent (component, bounds,
  50599. mouseZone.isDraggingTopEdge(),
  50600. mouseZone.isDraggingLeftEdge(),
  50601. mouseZone.isDraggingBottomEdge(),
  50602. mouseZone.isDraggingRightEdge());
  50603. }
  50604. else
  50605. {
  50606. Component::Positioner* const positioner = component->getPositioner();
  50607. if (positioner != 0)
  50608. positioner->applyNewBounds (bounds);
  50609. else
  50610. component->setBounds (bounds);
  50611. }
  50612. }
  50613. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50614. {
  50615. if (constrainer != 0)
  50616. constrainer->resizeEnd();
  50617. }
  50618. bool ResizableBorderComponent::hitTest (int x, int y)
  50619. {
  50620. return x < borderSize.getLeft()
  50621. || x >= getWidth() - borderSize.getRight()
  50622. || y < borderSize.getTop()
  50623. || y >= getHeight() - borderSize.getBottom();
  50624. }
  50625. void ResizableBorderComponent::setBorderThickness (const BorderSize<int>& newBorderSize)
  50626. {
  50627. if (borderSize != newBorderSize)
  50628. {
  50629. borderSize = newBorderSize;
  50630. repaint();
  50631. }
  50632. }
  50633. const BorderSize<int> ResizableBorderComponent::getBorderThickness() const
  50634. {
  50635. return borderSize;
  50636. }
  50637. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50638. {
  50639. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50640. if (mouseZone != newZone)
  50641. {
  50642. mouseZone = newZone;
  50643. setMouseCursor (newZone.getMouseCursor());
  50644. }
  50645. }
  50646. END_JUCE_NAMESPACE
  50647. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50648. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50649. BEGIN_JUCE_NAMESPACE
  50650. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50651. ComponentBoundsConstrainer* const constrainer_)
  50652. : component (componentToResize),
  50653. constrainer (constrainer_)
  50654. {
  50655. setRepaintsOnMouseActivity (true);
  50656. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50657. }
  50658. ResizableCornerComponent::~ResizableCornerComponent()
  50659. {
  50660. }
  50661. void ResizableCornerComponent::paint (Graphics& g)
  50662. {
  50663. getLookAndFeel()
  50664. .drawCornerResizer (g, getWidth(), getHeight(),
  50665. isMouseOverOrDragging(),
  50666. isMouseButtonDown());
  50667. }
  50668. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50669. {
  50670. if (component == 0)
  50671. {
  50672. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50673. return;
  50674. }
  50675. originalBounds = component->getBounds();
  50676. if (constrainer != 0)
  50677. constrainer->resizeStart();
  50678. }
  50679. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50680. {
  50681. if (component == 0)
  50682. {
  50683. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50684. return;
  50685. }
  50686. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50687. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50688. if (constrainer != 0)
  50689. {
  50690. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50691. }
  50692. else
  50693. {
  50694. Component::Positioner* const positioner = component->getPositioner();
  50695. if (positioner != 0)
  50696. positioner->applyNewBounds (r);
  50697. else
  50698. component->setBounds (r);
  50699. }
  50700. }
  50701. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50702. {
  50703. if (constrainer != 0)
  50704. constrainer->resizeStart();
  50705. }
  50706. bool ResizableCornerComponent::hitTest (int x, int y)
  50707. {
  50708. if (getWidth() <= 0)
  50709. return false;
  50710. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50711. return y >= yAtX - getHeight() / 4;
  50712. }
  50713. END_JUCE_NAMESPACE
  50714. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50715. /*** Start of inlined file: juce_ResizableEdgeComponent.cpp ***/
  50716. BEGIN_JUCE_NAMESPACE
  50717. ResizableEdgeComponent::ResizableEdgeComponent (Component* const componentToResize,
  50718. ComponentBoundsConstrainer* const constrainer_,
  50719. Edge edge_)
  50720. : component (componentToResize),
  50721. constrainer (constrainer_),
  50722. edge (edge_)
  50723. {
  50724. setRepaintsOnMouseActivity (true);
  50725. setMouseCursor (MouseCursor (isVertical() ? MouseCursor::LeftRightResizeCursor
  50726. : MouseCursor::UpDownResizeCursor));
  50727. }
  50728. ResizableEdgeComponent::~ResizableEdgeComponent()
  50729. {
  50730. }
  50731. bool ResizableEdgeComponent::isVertical() const throw()
  50732. {
  50733. return edge == leftEdge || edge == rightEdge;
  50734. }
  50735. void ResizableEdgeComponent::paint (Graphics& g)
  50736. {
  50737. getLookAndFeel().drawStretchableLayoutResizerBar (g, getWidth(), getHeight(), isVertical(),
  50738. isMouseOver(), isMouseButtonDown());
  50739. }
  50740. void ResizableEdgeComponent::mouseDown (const MouseEvent&)
  50741. {
  50742. if (component == 0)
  50743. {
  50744. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50745. return;
  50746. }
  50747. originalBounds = component->getBounds();
  50748. if (constrainer != 0)
  50749. constrainer->resizeStart();
  50750. }
  50751. void ResizableEdgeComponent::mouseDrag (const MouseEvent& e)
  50752. {
  50753. if (component == 0)
  50754. {
  50755. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50756. return;
  50757. }
  50758. Rectangle<int> bounds (originalBounds);
  50759. switch (edge)
  50760. {
  50761. case leftEdge: bounds.setLeft (jmin (bounds.getRight(), bounds.getX() + e.getDistanceFromDragStartX())); break;
  50762. case rightEdge: bounds.setWidth (jmax (0, bounds.getWidth() + e.getDistanceFromDragStartX())); break;
  50763. case topEdge: bounds.setTop (jmin (bounds.getBottom(), bounds.getY() + e.getDistanceFromDragStartY())); break;
  50764. case bottomEdge: bounds.setHeight (jmax (0, bounds.getHeight() + e.getDistanceFromDragStartY())); break;
  50765. default: jassertfalse; break;
  50766. }
  50767. if (constrainer != 0)
  50768. {
  50769. constrainer->setBoundsForComponent (component, bounds,
  50770. edge == topEdge,
  50771. edge == leftEdge,
  50772. edge == bottomEdge,
  50773. edge == rightEdge);
  50774. }
  50775. else
  50776. {
  50777. Component::Positioner* const positioner = component->getPositioner();
  50778. if (positioner != 0)
  50779. positioner->applyNewBounds (bounds);
  50780. else
  50781. component->setBounds (bounds);
  50782. }
  50783. }
  50784. void ResizableEdgeComponent::mouseUp (const MouseEvent&)
  50785. {
  50786. if (constrainer != 0)
  50787. constrainer->resizeEnd();
  50788. }
  50789. END_JUCE_NAMESPACE
  50790. /*** End of inlined file: juce_ResizableEdgeComponent.cpp ***/
  50791. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50792. BEGIN_JUCE_NAMESPACE
  50793. class ScrollBar::ScrollbarButton : public Button
  50794. {
  50795. public:
  50796. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50797. : Button (String::empty),
  50798. direction (direction_),
  50799. owner (owner_)
  50800. {
  50801. setWantsKeyboardFocus (false);
  50802. }
  50803. void paintButton (Graphics& g, bool over, bool down)
  50804. {
  50805. getLookAndFeel()
  50806. .drawScrollbarButton (g, owner,
  50807. getWidth(), getHeight(),
  50808. direction,
  50809. owner.isVertical(),
  50810. over, down);
  50811. }
  50812. void clicked()
  50813. {
  50814. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50815. }
  50816. int direction;
  50817. private:
  50818. ScrollBar& owner;
  50819. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50820. };
  50821. ScrollBar::ScrollBar (const bool vertical_,
  50822. const bool buttonsAreVisible)
  50823. : totalRange (0.0, 1.0),
  50824. visibleRange (0.0, 0.1),
  50825. singleStepSize (0.1),
  50826. thumbAreaStart (0),
  50827. thumbAreaSize (0),
  50828. thumbStart (0),
  50829. thumbSize (0),
  50830. initialDelayInMillisecs (100),
  50831. repeatDelayInMillisecs (50),
  50832. minimumDelayInMillisecs (10),
  50833. vertical (vertical_),
  50834. isDraggingThumb (false),
  50835. autohides (true)
  50836. {
  50837. setButtonVisibility (buttonsAreVisible);
  50838. setRepaintsOnMouseActivity (true);
  50839. setFocusContainer (true);
  50840. }
  50841. ScrollBar::~ScrollBar()
  50842. {
  50843. upButton = 0;
  50844. downButton = 0;
  50845. }
  50846. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50847. {
  50848. if (totalRange != newRangeLimit)
  50849. {
  50850. totalRange = newRangeLimit;
  50851. setCurrentRange (visibleRange);
  50852. updateThumbPosition();
  50853. }
  50854. }
  50855. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50856. {
  50857. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50858. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50859. }
  50860. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50861. {
  50862. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50863. if (visibleRange != constrainedRange)
  50864. {
  50865. visibleRange = constrainedRange;
  50866. updateThumbPosition();
  50867. triggerAsyncUpdate();
  50868. }
  50869. }
  50870. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50871. {
  50872. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50873. }
  50874. void ScrollBar::setCurrentRangeStart (const double newStart)
  50875. {
  50876. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50877. }
  50878. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50879. {
  50880. singleStepSize = newSingleStepSize;
  50881. }
  50882. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50883. {
  50884. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50885. }
  50886. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50887. {
  50888. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50889. }
  50890. void ScrollBar::scrollToTop()
  50891. {
  50892. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50893. }
  50894. void ScrollBar::scrollToBottom()
  50895. {
  50896. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50897. }
  50898. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50899. const int repeatDelayInMillisecs_,
  50900. const int minimumDelayInMillisecs_)
  50901. {
  50902. initialDelayInMillisecs = initialDelayInMillisecs_;
  50903. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50904. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50905. if (upButton != 0)
  50906. {
  50907. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50908. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50909. }
  50910. }
  50911. void ScrollBar::addListener (Listener* const listener)
  50912. {
  50913. listeners.add (listener);
  50914. }
  50915. void ScrollBar::removeListener (Listener* const listener)
  50916. {
  50917. listeners.remove (listener);
  50918. }
  50919. void ScrollBar::handleAsyncUpdate()
  50920. {
  50921. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50922. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50923. }
  50924. void ScrollBar::updateThumbPosition()
  50925. {
  50926. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50927. : thumbAreaSize);
  50928. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50929. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50930. if (newThumbSize > thumbAreaSize)
  50931. newThumbSize = thumbAreaSize;
  50932. int newThumbStart = thumbAreaStart;
  50933. if (totalRange.getLength() > visibleRange.getLength())
  50934. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50935. / (totalRange.getLength() - visibleRange.getLength()));
  50936. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50937. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50938. {
  50939. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50940. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50941. if (vertical)
  50942. repaint (0, repaintStart, getWidth(), repaintSize);
  50943. else
  50944. repaint (repaintStart, 0, repaintSize, getHeight());
  50945. thumbStart = newThumbStart;
  50946. thumbSize = newThumbSize;
  50947. }
  50948. }
  50949. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50950. {
  50951. if (vertical != shouldBeVertical)
  50952. {
  50953. vertical = shouldBeVertical;
  50954. if (upButton != 0)
  50955. {
  50956. upButton->direction = vertical ? 0 : 3;
  50957. downButton->direction = vertical ? 2 : 1;
  50958. }
  50959. updateThumbPosition();
  50960. }
  50961. }
  50962. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50963. {
  50964. upButton = 0;
  50965. downButton = 0;
  50966. if (buttonsAreVisible)
  50967. {
  50968. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50969. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50970. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50971. }
  50972. updateThumbPosition();
  50973. }
  50974. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50975. {
  50976. autohides = shouldHideWhenFullRange;
  50977. updateThumbPosition();
  50978. }
  50979. bool ScrollBar::autoHides() const throw()
  50980. {
  50981. return autohides;
  50982. }
  50983. void ScrollBar::paint (Graphics& g)
  50984. {
  50985. if (thumbAreaSize > 0)
  50986. {
  50987. LookAndFeel& lf = getLookAndFeel();
  50988. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50989. ? thumbSize : 0;
  50990. if (vertical)
  50991. {
  50992. lf.drawScrollbar (g, *this,
  50993. 0, thumbAreaStart,
  50994. getWidth(), thumbAreaSize,
  50995. vertical,
  50996. thumbStart, thumb,
  50997. isMouseOver(), isMouseButtonDown());
  50998. }
  50999. else
  51000. {
  51001. lf.drawScrollbar (g, *this,
  51002. thumbAreaStart, 0,
  51003. thumbAreaSize, getHeight(),
  51004. vertical,
  51005. thumbStart, thumb,
  51006. isMouseOver(), isMouseButtonDown());
  51007. }
  51008. }
  51009. }
  51010. void ScrollBar::lookAndFeelChanged()
  51011. {
  51012. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  51013. }
  51014. void ScrollBar::resized()
  51015. {
  51016. const int length = ((vertical) ? getHeight() : getWidth());
  51017. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  51018. : 0;
  51019. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  51020. {
  51021. thumbAreaStart = length >> 1;
  51022. thumbAreaSize = 0;
  51023. }
  51024. else
  51025. {
  51026. thumbAreaStart = buttonSize;
  51027. thumbAreaSize = length - (buttonSize << 1);
  51028. }
  51029. if (upButton != 0)
  51030. {
  51031. if (vertical)
  51032. {
  51033. upButton->setBounds (0, 0, getWidth(), buttonSize);
  51034. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  51035. }
  51036. else
  51037. {
  51038. upButton->setBounds (0, 0, buttonSize, getHeight());
  51039. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  51040. }
  51041. }
  51042. updateThumbPosition();
  51043. }
  51044. void ScrollBar::mouseDown (const MouseEvent& e)
  51045. {
  51046. isDraggingThumb = false;
  51047. lastMousePos = vertical ? e.y : e.x;
  51048. dragStartMousePos = lastMousePos;
  51049. dragStartRange = visibleRange.getStart();
  51050. if (dragStartMousePos < thumbStart)
  51051. {
  51052. moveScrollbarInPages (-1);
  51053. startTimer (400);
  51054. }
  51055. else if (dragStartMousePos >= thumbStart + thumbSize)
  51056. {
  51057. moveScrollbarInPages (1);
  51058. startTimer (400);
  51059. }
  51060. else
  51061. {
  51062. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  51063. && (thumbAreaSize > thumbSize);
  51064. }
  51065. }
  51066. void ScrollBar::mouseDrag (const MouseEvent& e)
  51067. {
  51068. const int mousePos = vertical ? e.y : e.x;
  51069. if (isDraggingThumb && lastMousePos != mousePos)
  51070. {
  51071. const int deltaPixels = mousePos - dragStartMousePos;
  51072. setCurrentRangeStart (dragStartRange
  51073. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  51074. / (thumbAreaSize - thumbSize));
  51075. }
  51076. lastMousePos = mousePos;
  51077. }
  51078. void ScrollBar::mouseUp (const MouseEvent&)
  51079. {
  51080. isDraggingThumb = false;
  51081. stopTimer();
  51082. repaint();
  51083. }
  51084. void ScrollBar::mouseWheelMove (const MouseEvent&,
  51085. float wheelIncrementX,
  51086. float wheelIncrementY)
  51087. {
  51088. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  51089. if (increment < 0)
  51090. increment = jmin (increment * 10.0f, -1.0f);
  51091. else if (increment > 0)
  51092. increment = jmax (increment * 10.0f, 1.0f);
  51093. setCurrentRange (visibleRange - singleStepSize * increment);
  51094. }
  51095. void ScrollBar::timerCallback()
  51096. {
  51097. if (isMouseButtonDown())
  51098. {
  51099. startTimer (40);
  51100. if (lastMousePos < thumbStart)
  51101. setCurrentRange (visibleRange - visibleRange.getLength());
  51102. else if (lastMousePos > thumbStart + thumbSize)
  51103. setCurrentRangeStart (visibleRange.getEnd());
  51104. }
  51105. else
  51106. {
  51107. stopTimer();
  51108. }
  51109. }
  51110. bool ScrollBar::keyPressed (const KeyPress& key)
  51111. {
  51112. if (! isVisible())
  51113. return false;
  51114. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  51115. moveScrollbarInSteps (-1);
  51116. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  51117. moveScrollbarInSteps (1);
  51118. else if (key.isKeyCode (KeyPress::pageUpKey))
  51119. moveScrollbarInPages (-1);
  51120. else if (key.isKeyCode (KeyPress::pageDownKey))
  51121. moveScrollbarInPages (1);
  51122. else if (key.isKeyCode (KeyPress::homeKey))
  51123. scrollToTop();
  51124. else if (key.isKeyCode (KeyPress::endKey))
  51125. scrollToBottom();
  51126. else
  51127. return false;
  51128. return true;
  51129. }
  51130. END_JUCE_NAMESPACE
  51131. /*** End of inlined file: juce_ScrollBar.cpp ***/
  51132. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  51133. BEGIN_JUCE_NAMESPACE
  51134. StretchableLayoutManager::StretchableLayoutManager()
  51135. : totalSize (0)
  51136. {
  51137. }
  51138. StretchableLayoutManager::~StretchableLayoutManager()
  51139. {
  51140. }
  51141. void StretchableLayoutManager::clearAllItems()
  51142. {
  51143. items.clear();
  51144. totalSize = 0;
  51145. }
  51146. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  51147. const double minimumSize,
  51148. const double maximumSize,
  51149. const double preferredSize)
  51150. {
  51151. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  51152. if (layout == 0)
  51153. {
  51154. layout = new ItemLayoutProperties();
  51155. layout->itemIndex = itemIndex;
  51156. int i;
  51157. for (i = 0; i < items.size(); ++i)
  51158. if (items.getUnchecked (i)->itemIndex > itemIndex)
  51159. break;
  51160. items.insert (i, layout);
  51161. }
  51162. layout->minSize = minimumSize;
  51163. layout->maxSize = maximumSize;
  51164. layout->preferredSize = preferredSize;
  51165. layout->currentSize = 0;
  51166. }
  51167. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51168. double& minimumSize,
  51169. double& maximumSize,
  51170. double& preferredSize) const
  51171. {
  51172. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51173. if (layout != 0)
  51174. {
  51175. minimumSize = layout->minSize;
  51176. maximumSize = layout->maxSize;
  51177. preferredSize = layout->preferredSize;
  51178. return true;
  51179. }
  51180. return false;
  51181. }
  51182. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51183. {
  51184. totalSize = newTotalSize;
  51185. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51186. }
  51187. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51188. {
  51189. int pos = 0;
  51190. for (int i = 0; i < itemIndex; ++i)
  51191. {
  51192. const ItemLayoutProperties* const layout = getInfoFor (i);
  51193. if (layout != 0)
  51194. pos += layout->currentSize;
  51195. }
  51196. return pos;
  51197. }
  51198. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51199. {
  51200. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51201. if (layout != 0)
  51202. return layout->currentSize;
  51203. return 0;
  51204. }
  51205. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51206. {
  51207. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51208. if (layout != 0)
  51209. return -layout->currentSize / (double) totalSize;
  51210. return 0;
  51211. }
  51212. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51213. int newPosition)
  51214. {
  51215. for (int i = items.size(); --i >= 0;)
  51216. {
  51217. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51218. if (layout->itemIndex == itemIndex)
  51219. {
  51220. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51221. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51222. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51223. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51224. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51225. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51226. endPos += layout->currentSize;
  51227. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51228. updatePrefSizesToMatchCurrentPositions();
  51229. break;
  51230. }
  51231. }
  51232. }
  51233. void StretchableLayoutManager::layOutComponents (Component** const components,
  51234. int numComponents,
  51235. int x, int y, int w, int h,
  51236. const bool vertically,
  51237. const bool resizeOtherDimension)
  51238. {
  51239. setTotalSize (vertically ? h : w);
  51240. int pos = vertically ? y : x;
  51241. for (int i = 0; i < numComponents; ++i)
  51242. {
  51243. const ItemLayoutProperties* const layout = getInfoFor (i);
  51244. if (layout != 0)
  51245. {
  51246. Component* const c = components[i];
  51247. if (c != 0)
  51248. {
  51249. if (i == numComponents - 1)
  51250. {
  51251. // if it's the last item, crop it to exactly fit the available space..
  51252. if (resizeOtherDimension)
  51253. {
  51254. if (vertically)
  51255. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51256. else
  51257. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51258. }
  51259. else
  51260. {
  51261. if (vertically)
  51262. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51263. else
  51264. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51265. }
  51266. }
  51267. else
  51268. {
  51269. if (resizeOtherDimension)
  51270. {
  51271. if (vertically)
  51272. c->setBounds (x, pos, w, layout->currentSize);
  51273. else
  51274. c->setBounds (pos, y, layout->currentSize, h);
  51275. }
  51276. else
  51277. {
  51278. if (vertically)
  51279. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51280. else
  51281. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51282. }
  51283. }
  51284. }
  51285. pos += layout->currentSize;
  51286. }
  51287. }
  51288. }
  51289. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51290. {
  51291. for (int i = items.size(); --i >= 0;)
  51292. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51293. return items.getUnchecked(i);
  51294. return 0;
  51295. }
  51296. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51297. const int endIndex,
  51298. const int availableSpace,
  51299. int startPos)
  51300. {
  51301. // calculate the total sizes
  51302. int i;
  51303. double totalIdealSize = 0.0;
  51304. int totalMinimums = 0;
  51305. for (i = startIndex; i < endIndex; ++i)
  51306. {
  51307. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51308. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51309. totalMinimums += layout->currentSize;
  51310. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51311. }
  51312. if (totalIdealSize <= 0)
  51313. totalIdealSize = 1.0;
  51314. // now calc the best sizes..
  51315. int extraSpace = availableSpace - totalMinimums;
  51316. while (extraSpace > 0)
  51317. {
  51318. int numWantingMoreSpace = 0;
  51319. int numHavingTakenExtraSpace = 0;
  51320. // first figure out how many comps want a slice of the extra space..
  51321. for (i = startIndex; i < endIndex; ++i)
  51322. {
  51323. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51324. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51325. const int bestSize = jlimit (layout->currentSize,
  51326. jmax (layout->currentSize,
  51327. sizeToRealSize (layout->maxSize, totalSize)),
  51328. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51329. if (bestSize > layout->currentSize)
  51330. ++numWantingMoreSpace;
  51331. }
  51332. // ..share out the extra space..
  51333. for (i = startIndex; i < endIndex; ++i)
  51334. {
  51335. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51336. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51337. int bestSize = jlimit (layout->currentSize,
  51338. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51339. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51340. const int extraWanted = bestSize - layout->currentSize;
  51341. if (extraWanted > 0)
  51342. {
  51343. const int extraAllowed = jmin (extraWanted,
  51344. extraSpace / jmax (1, numWantingMoreSpace));
  51345. if (extraAllowed > 0)
  51346. {
  51347. ++numHavingTakenExtraSpace;
  51348. --numWantingMoreSpace;
  51349. layout->currentSize += extraAllowed;
  51350. extraSpace -= extraAllowed;
  51351. }
  51352. }
  51353. }
  51354. if (numHavingTakenExtraSpace <= 0)
  51355. break;
  51356. }
  51357. // ..and calculate the end position
  51358. for (i = startIndex; i < endIndex; ++i)
  51359. {
  51360. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51361. startPos += layout->currentSize;
  51362. }
  51363. return startPos;
  51364. }
  51365. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51366. const int endIndex) const
  51367. {
  51368. int totalMinimums = 0;
  51369. for (int i = startIndex; i < endIndex; ++i)
  51370. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51371. return totalMinimums;
  51372. }
  51373. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51374. {
  51375. int totalMaximums = 0;
  51376. for (int i = startIndex; i < endIndex; ++i)
  51377. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51378. return totalMaximums;
  51379. }
  51380. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51381. {
  51382. for (int i = 0; i < items.size(); ++i)
  51383. {
  51384. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51385. layout->preferredSize
  51386. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51387. : getItemCurrentAbsoluteSize (i);
  51388. }
  51389. }
  51390. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51391. {
  51392. if (size < 0)
  51393. size *= -totalSpace;
  51394. return roundToInt (size);
  51395. }
  51396. END_JUCE_NAMESPACE
  51397. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51398. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51399. BEGIN_JUCE_NAMESPACE
  51400. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51401. const int itemIndex_,
  51402. const bool isVertical_)
  51403. : layout (layout_),
  51404. itemIndex (itemIndex_),
  51405. isVertical (isVertical_)
  51406. {
  51407. setRepaintsOnMouseActivity (true);
  51408. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51409. : MouseCursor::UpDownResizeCursor));
  51410. }
  51411. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51412. {
  51413. }
  51414. void StretchableLayoutResizerBar::paint (Graphics& g)
  51415. {
  51416. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51417. getWidth(), getHeight(),
  51418. isVertical,
  51419. isMouseOver(),
  51420. isMouseButtonDown());
  51421. }
  51422. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51423. {
  51424. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51425. }
  51426. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51427. {
  51428. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51429. : e.getDistanceFromDragStartY());
  51430. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51431. {
  51432. layout->setItemPosition (itemIndex, desiredPos);
  51433. hasBeenMoved();
  51434. }
  51435. }
  51436. void StretchableLayoutResizerBar::hasBeenMoved()
  51437. {
  51438. if (getParentComponent() != 0)
  51439. getParentComponent()->resized();
  51440. }
  51441. END_JUCE_NAMESPACE
  51442. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51443. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51444. BEGIN_JUCE_NAMESPACE
  51445. StretchableObjectResizer::StretchableObjectResizer()
  51446. {
  51447. }
  51448. StretchableObjectResizer::~StretchableObjectResizer()
  51449. {
  51450. }
  51451. void StretchableObjectResizer::addItem (const double size,
  51452. const double minSize, const double maxSize,
  51453. const int order)
  51454. {
  51455. // the order must be >= 0 but less than the maximum integer value.
  51456. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51457. Item* const item = new Item();
  51458. item->size = size;
  51459. item->minSize = minSize;
  51460. item->maxSize = maxSize;
  51461. item->order = order;
  51462. items.add (item);
  51463. }
  51464. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51465. {
  51466. const Item* const it = items [index];
  51467. return it != 0 ? it->size : 0;
  51468. }
  51469. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51470. {
  51471. int order = 0;
  51472. for (;;)
  51473. {
  51474. double currentSize = 0;
  51475. double minSize = 0;
  51476. double maxSize = 0;
  51477. int nextHighestOrder = std::numeric_limits<int>::max();
  51478. for (int i = 0; i < items.size(); ++i)
  51479. {
  51480. const Item* const it = items.getUnchecked(i);
  51481. currentSize += it->size;
  51482. if (it->order <= order)
  51483. {
  51484. minSize += it->minSize;
  51485. maxSize += it->maxSize;
  51486. }
  51487. else
  51488. {
  51489. minSize += it->size;
  51490. maxSize += it->size;
  51491. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51492. }
  51493. }
  51494. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51495. if (thisIterationTarget >= currentSize)
  51496. {
  51497. const double availableExtraSpace = maxSize - currentSize;
  51498. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51499. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51500. for (int i = 0; i < items.size(); ++i)
  51501. {
  51502. Item* const it = items.getUnchecked(i);
  51503. if (it->order <= order)
  51504. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51505. }
  51506. }
  51507. else
  51508. {
  51509. const double amountOfSlack = currentSize - minSize;
  51510. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51511. const double scale = targetAmountOfSlack / amountOfSlack;
  51512. for (int i = 0; i < items.size(); ++i)
  51513. {
  51514. Item* const it = items.getUnchecked(i);
  51515. if (it->order <= order)
  51516. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51517. }
  51518. }
  51519. if (nextHighestOrder < std::numeric_limits<int>::max())
  51520. order = nextHighestOrder;
  51521. else
  51522. break;
  51523. }
  51524. }
  51525. END_JUCE_NAMESPACE
  51526. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51527. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51528. BEGIN_JUCE_NAMESPACE
  51529. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51530. : Button (name),
  51531. owner (owner_),
  51532. overlapPixels (0)
  51533. {
  51534. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51535. setComponentEffect (&shadow);
  51536. setWantsKeyboardFocus (false);
  51537. }
  51538. TabBarButton::~TabBarButton()
  51539. {
  51540. }
  51541. int TabBarButton::getIndex() const
  51542. {
  51543. return owner.indexOfTabButton (this);
  51544. }
  51545. void TabBarButton::paintButton (Graphics& g,
  51546. bool isMouseOverButton,
  51547. bool isButtonDown)
  51548. {
  51549. const Rectangle<int> area (getActiveArea());
  51550. g.setOrigin (area.getX(), area.getY());
  51551. getLookAndFeel()
  51552. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51553. owner.getTabBackgroundColour (getIndex()),
  51554. getIndex(), getButtonText(), *this,
  51555. owner.getOrientation(),
  51556. isMouseOverButton, isButtonDown,
  51557. getToggleState());
  51558. }
  51559. void TabBarButton::clicked (const ModifierKeys& mods)
  51560. {
  51561. if (mods.isPopupMenu())
  51562. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51563. else
  51564. owner.setCurrentTabIndex (getIndex());
  51565. }
  51566. bool TabBarButton::hitTest (int mx, int my)
  51567. {
  51568. const Rectangle<int> area (getActiveArea());
  51569. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51570. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51571. {
  51572. if (isPositiveAndBelow (mx, getWidth())
  51573. && my >= area.getY() + overlapPixels
  51574. && my < area.getBottom() - overlapPixels)
  51575. return true;
  51576. }
  51577. else
  51578. {
  51579. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51580. && isPositiveAndBelow (my, getHeight()))
  51581. return true;
  51582. }
  51583. Path p;
  51584. getLookAndFeel()
  51585. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51586. owner.getOrientation(), false, false, getToggleState());
  51587. return p.contains ((float) (mx - area.getX()),
  51588. (float) (my - area.getY()));
  51589. }
  51590. int TabBarButton::getBestTabLength (const int depth)
  51591. {
  51592. return jlimit (depth * 2,
  51593. depth * 7,
  51594. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51595. }
  51596. const Rectangle<int> TabBarButton::getActiveArea()
  51597. {
  51598. Rectangle<int> r (getLocalBounds());
  51599. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51600. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51601. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51602. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51603. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51604. return r;
  51605. }
  51606. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51607. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51608. {
  51609. public:
  51610. BehindFrontTabComp (TabbedButtonBar& owner_)
  51611. : owner (owner_)
  51612. {
  51613. setInterceptsMouseClicks (false, false);
  51614. }
  51615. void paint (Graphics& g)
  51616. {
  51617. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51618. owner, owner.getOrientation());
  51619. }
  51620. void enablementChanged()
  51621. {
  51622. repaint();
  51623. }
  51624. void buttonClicked (Button*)
  51625. {
  51626. owner.showExtraItemsMenu();
  51627. }
  51628. private:
  51629. TabbedButtonBar& owner;
  51630. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51631. };
  51632. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51633. : orientation (orientation_),
  51634. minimumScale (0.7),
  51635. currentTabIndex (-1)
  51636. {
  51637. setInterceptsMouseClicks (false, true);
  51638. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51639. setFocusContainer (true);
  51640. }
  51641. TabbedButtonBar::~TabbedButtonBar()
  51642. {
  51643. tabs.clear();
  51644. extraTabsButton = 0;
  51645. }
  51646. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51647. {
  51648. orientation = newOrientation;
  51649. for (int i = getNumChildComponents(); --i >= 0;)
  51650. getChildComponent (i)->resized();
  51651. resized();
  51652. }
  51653. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51654. {
  51655. return new TabBarButton (name, *this);
  51656. }
  51657. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51658. {
  51659. minimumScale = newMinimumScale;
  51660. resized();
  51661. }
  51662. void TabbedButtonBar::clearTabs()
  51663. {
  51664. tabs.clear();
  51665. extraTabsButton = 0;
  51666. setCurrentTabIndex (-1);
  51667. }
  51668. void TabbedButtonBar::addTab (const String& tabName,
  51669. const Colour& tabBackgroundColour,
  51670. int insertIndex)
  51671. {
  51672. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51673. if (tabName.isNotEmpty())
  51674. {
  51675. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51676. insertIndex = tabs.size();
  51677. TabInfo* newTab = new TabInfo();
  51678. newTab->name = tabName;
  51679. newTab->colour = tabBackgroundColour;
  51680. newTab->component = createTabButton (tabName, insertIndex);
  51681. jassert (newTab->component != 0);
  51682. tabs.insert (insertIndex, newTab);
  51683. addAndMakeVisible (newTab->component, insertIndex);
  51684. resized();
  51685. if (currentTabIndex < 0)
  51686. setCurrentTabIndex (0);
  51687. }
  51688. }
  51689. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51690. {
  51691. TabInfo* const tab = tabs [tabIndex];
  51692. if (tab != 0 && tab->name != newName)
  51693. {
  51694. tab->name = newName;
  51695. tab->component->setButtonText (newName);
  51696. resized();
  51697. }
  51698. }
  51699. void TabbedButtonBar::removeTab (const int tabIndex)
  51700. {
  51701. if (tabs [tabIndex] != 0)
  51702. {
  51703. const int oldTabIndex = currentTabIndex;
  51704. if (currentTabIndex == tabIndex)
  51705. currentTabIndex = -1;
  51706. tabs.remove (tabIndex);
  51707. resized();
  51708. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51709. }
  51710. }
  51711. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51712. {
  51713. tabs.move (currentIndex, newIndex);
  51714. resized();
  51715. }
  51716. int TabbedButtonBar::getNumTabs() const
  51717. {
  51718. return tabs.size();
  51719. }
  51720. const String TabbedButtonBar::getCurrentTabName() const
  51721. {
  51722. TabInfo* tab = tabs [currentTabIndex];
  51723. return tab == 0 ? String::empty : tab->name;
  51724. }
  51725. const StringArray TabbedButtonBar::getTabNames() const
  51726. {
  51727. StringArray names;
  51728. for (int i = 0; i < tabs.size(); ++i)
  51729. names.add (tabs.getUnchecked(i)->name);
  51730. return names;
  51731. }
  51732. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51733. {
  51734. if (currentTabIndex != newIndex)
  51735. {
  51736. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51737. newIndex = -1;
  51738. currentTabIndex = newIndex;
  51739. for (int i = 0; i < tabs.size(); ++i)
  51740. {
  51741. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51742. tb->setToggleState (i == newIndex, false);
  51743. }
  51744. resized();
  51745. if (sendChangeMessage_)
  51746. sendChangeMessage();
  51747. currentTabChanged (newIndex, getCurrentTabName());
  51748. }
  51749. }
  51750. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51751. {
  51752. TabInfo* const tab = tabs[index];
  51753. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51754. }
  51755. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51756. {
  51757. for (int i = tabs.size(); --i >= 0;)
  51758. if (tabs.getUnchecked(i)->component == button)
  51759. return i;
  51760. return -1;
  51761. }
  51762. void TabbedButtonBar::lookAndFeelChanged()
  51763. {
  51764. extraTabsButton = 0;
  51765. resized();
  51766. }
  51767. void TabbedButtonBar::resized()
  51768. {
  51769. int depth = getWidth();
  51770. int length = getHeight();
  51771. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51772. swapVariables (depth, length);
  51773. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51774. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51775. int i, totalLength = overlap;
  51776. int numVisibleButtons = tabs.size();
  51777. for (i = 0; i < tabs.size(); ++i)
  51778. {
  51779. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51780. totalLength += tb->getBestTabLength (depth) - overlap;
  51781. tb->overlapPixels = overlap / 2;
  51782. }
  51783. double scale = 1.0;
  51784. if (totalLength > length)
  51785. scale = jmax (minimumScale, length / (double) totalLength);
  51786. const bool isTooBig = totalLength * scale > length;
  51787. int tabsButtonPos = 0;
  51788. if (isTooBig)
  51789. {
  51790. if (extraTabsButton == 0)
  51791. {
  51792. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51793. extraTabsButton->addListener (behindFrontTab);
  51794. extraTabsButton->setAlwaysOnTop (true);
  51795. extraTabsButton->setTriggeredOnMouseDown (true);
  51796. }
  51797. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51798. extraTabsButton->setSize (buttonSize, buttonSize);
  51799. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51800. {
  51801. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51802. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51803. }
  51804. else
  51805. {
  51806. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51807. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51808. }
  51809. totalLength = 0;
  51810. for (i = 0; i < tabs.size(); ++i)
  51811. {
  51812. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51813. const int newLength = totalLength + tb->getBestTabLength (depth);
  51814. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51815. {
  51816. totalLength += overlap;
  51817. break;
  51818. }
  51819. numVisibleButtons = i + 1;
  51820. totalLength = newLength - overlap;
  51821. }
  51822. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51823. }
  51824. else
  51825. {
  51826. extraTabsButton = 0;
  51827. }
  51828. int pos = 0;
  51829. TabBarButton* frontTab = 0;
  51830. for (i = 0; i < tabs.size(); ++i)
  51831. {
  51832. TabBarButton* const tb = getTabButton (i);
  51833. if (tb != 0)
  51834. {
  51835. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51836. if (i < numVisibleButtons)
  51837. {
  51838. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51839. tb->setBounds (pos, 0, bestLength, getHeight());
  51840. else
  51841. tb->setBounds (0, pos, getWidth(), bestLength);
  51842. tb->toBack();
  51843. if (i == currentTabIndex)
  51844. frontTab = tb;
  51845. tb->setVisible (true);
  51846. }
  51847. else
  51848. {
  51849. tb->setVisible (false);
  51850. }
  51851. pos += bestLength - overlap;
  51852. }
  51853. }
  51854. behindFrontTab->setBounds (getLocalBounds());
  51855. if (frontTab != 0)
  51856. {
  51857. frontTab->toFront (false);
  51858. behindFrontTab->toBehind (frontTab);
  51859. }
  51860. }
  51861. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51862. {
  51863. TabInfo* const tab = tabs [tabIndex];
  51864. return tab == 0 ? Colours::white : tab->colour;
  51865. }
  51866. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51867. {
  51868. TabInfo* const tab = tabs [tabIndex];
  51869. if (tab != 0 && tab->colour != newColour)
  51870. {
  51871. tab->colour = newColour;
  51872. repaint();
  51873. }
  51874. }
  51875. void TabbedButtonBar::extraItemsMenuCallback (int result, TabbedButtonBar* bar)
  51876. {
  51877. if (bar != 0 && result > 0)
  51878. bar->setCurrentTabIndex (result - 1);
  51879. }
  51880. void TabbedButtonBar::showExtraItemsMenu()
  51881. {
  51882. PopupMenu m;
  51883. for (int i = 0; i < tabs.size(); ++i)
  51884. {
  51885. const TabInfo* const tab = tabs.getUnchecked(i);
  51886. if (! tab->component->isVisible())
  51887. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51888. }
  51889. m.showMenuAsync (PopupMenu::Options().withTargetComponent (extraTabsButton),
  51890. ModalCallbackFunction::forComponent (extraItemsMenuCallback, this));
  51891. }
  51892. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51893. {
  51894. }
  51895. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51896. {
  51897. }
  51898. END_JUCE_NAMESPACE
  51899. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51900. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51901. BEGIN_JUCE_NAMESPACE
  51902. namespace TabbedComponentHelpers
  51903. {
  51904. const Identifier deleteComponentId ("deleteByTabComp_");
  51905. void deleteIfNecessary (Component* const comp)
  51906. {
  51907. if (comp != 0 && (bool) comp->getProperties() [deleteComponentId])
  51908. delete comp;
  51909. }
  51910. const Rectangle<int> getTabArea (Rectangle<int>& content, BorderSize<int>& outline,
  51911. const TabbedButtonBar::Orientation orientation, const int tabDepth)
  51912. {
  51913. switch (orientation)
  51914. {
  51915. case TabbedButtonBar::TabsAtTop: outline.setTop (0); return content.removeFromTop (tabDepth);
  51916. case TabbedButtonBar::TabsAtBottom: outline.setBottom (0); return content.removeFromBottom (tabDepth);
  51917. case TabbedButtonBar::TabsAtLeft: outline.setLeft (0); return content.removeFromLeft (tabDepth);
  51918. case TabbedButtonBar::TabsAtRight: outline.setRight (0); return content.removeFromRight (tabDepth);
  51919. default: jassertfalse; break;
  51920. }
  51921. return Rectangle<int>();
  51922. }
  51923. }
  51924. class TabbedComponent::ButtonBar : public TabbedButtonBar
  51925. {
  51926. public:
  51927. ButtonBar (TabbedComponent& owner_, const TabbedButtonBar::Orientation orientation_)
  51928. : TabbedButtonBar (orientation_),
  51929. owner (owner_)
  51930. {
  51931. }
  51932. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51933. {
  51934. owner.changeCallback (newCurrentTabIndex, newTabName);
  51935. }
  51936. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51937. {
  51938. owner.popupMenuClickOnTab (tabIndex, tabName);
  51939. }
  51940. const Colour getTabBackgroundColour (const int tabIndex)
  51941. {
  51942. return owner.tabs->getTabBackgroundColour (tabIndex);
  51943. }
  51944. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51945. {
  51946. return owner.createTabButton (tabName, tabIndex);
  51947. }
  51948. private:
  51949. TabbedComponent& owner;
  51950. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonBar);
  51951. };
  51952. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51953. : tabDepth (30),
  51954. outlineThickness (1),
  51955. edgeIndent (0)
  51956. {
  51957. addAndMakeVisible (tabs = new ButtonBar (*this, orientation));
  51958. }
  51959. TabbedComponent::~TabbedComponent()
  51960. {
  51961. clearTabs();
  51962. tabs = 0;
  51963. }
  51964. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51965. {
  51966. tabs->setOrientation (orientation);
  51967. resized();
  51968. }
  51969. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51970. {
  51971. return tabs->getOrientation();
  51972. }
  51973. void TabbedComponent::setTabBarDepth (const int newDepth)
  51974. {
  51975. if (tabDepth != newDepth)
  51976. {
  51977. tabDepth = newDepth;
  51978. resized();
  51979. }
  51980. }
  51981. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51982. {
  51983. return new TabBarButton (tabName, *tabs);
  51984. }
  51985. void TabbedComponent::clearTabs()
  51986. {
  51987. if (panelComponent != 0)
  51988. {
  51989. panelComponent->setVisible (false);
  51990. removeChildComponent (panelComponent);
  51991. panelComponent = 0;
  51992. }
  51993. tabs->clearTabs();
  51994. for (int i = contentComponents.size(); --i >= 0;)
  51995. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (i));
  51996. contentComponents.clear();
  51997. }
  51998. void TabbedComponent::addTab (const String& tabName,
  51999. const Colour& tabBackgroundColour,
  52000. Component* const contentComponent,
  52001. const bool deleteComponentWhenNotNeeded,
  52002. const int insertIndex)
  52003. {
  52004. contentComponents.insert (insertIndex, WeakReference<Component> (contentComponent));
  52005. if (deleteComponentWhenNotNeeded && contentComponent != 0)
  52006. contentComponent->getProperties().set (TabbedComponentHelpers::deleteComponentId, true);
  52007. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  52008. }
  52009. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  52010. {
  52011. tabs->setTabName (tabIndex, newName);
  52012. }
  52013. void TabbedComponent::removeTab (const int tabIndex)
  52014. {
  52015. if (isPositiveAndBelow (tabIndex, contentComponents.size()))
  52016. {
  52017. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (tabIndex));
  52018. contentComponents.remove (tabIndex);
  52019. tabs->removeTab (tabIndex);
  52020. }
  52021. }
  52022. int TabbedComponent::getNumTabs() const
  52023. {
  52024. return tabs->getNumTabs();
  52025. }
  52026. const StringArray TabbedComponent::getTabNames() const
  52027. {
  52028. return tabs->getTabNames();
  52029. }
  52030. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  52031. {
  52032. return contentComponents [tabIndex];
  52033. }
  52034. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  52035. {
  52036. return tabs->getTabBackgroundColour (tabIndex);
  52037. }
  52038. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  52039. {
  52040. tabs->setTabBackgroundColour (tabIndex, newColour);
  52041. if (getCurrentTabIndex() == tabIndex)
  52042. repaint();
  52043. }
  52044. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  52045. {
  52046. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  52047. }
  52048. int TabbedComponent::getCurrentTabIndex() const
  52049. {
  52050. return tabs->getCurrentTabIndex();
  52051. }
  52052. const String TabbedComponent::getCurrentTabName() const
  52053. {
  52054. return tabs->getCurrentTabName();
  52055. }
  52056. void TabbedComponent::setOutline (const int thickness)
  52057. {
  52058. outlineThickness = thickness;
  52059. resized();
  52060. repaint();
  52061. }
  52062. void TabbedComponent::setIndent (const int indentThickness)
  52063. {
  52064. edgeIndent = indentThickness;
  52065. resized();
  52066. repaint();
  52067. }
  52068. void TabbedComponent::paint (Graphics& g)
  52069. {
  52070. g.fillAll (findColour (backgroundColourId));
  52071. Rectangle<int> content (getLocalBounds());
  52072. BorderSize<int> outline (outlineThickness);
  52073. TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth);
  52074. g.reduceClipRegion (content);
  52075. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  52076. if (outlineThickness > 0)
  52077. {
  52078. RectangleList rl (content);
  52079. rl.subtract (outline.subtractedFrom (content));
  52080. g.reduceClipRegion (rl);
  52081. g.fillAll (findColour (outlineColourId));
  52082. }
  52083. }
  52084. void TabbedComponent::resized()
  52085. {
  52086. Rectangle<int> content (getLocalBounds());
  52087. BorderSize<int> outline (outlineThickness);
  52088. tabs->setBounds (TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth));
  52089. content = BorderSize<int> (edgeIndent).subtractedFrom (outline.subtractedFrom (content));
  52090. for (int i = contentComponents.size(); --i >= 0;)
  52091. if (contentComponents.getReference (i) != 0)
  52092. contentComponents.getReference (i)->setBounds (content);
  52093. }
  52094. void TabbedComponent::lookAndFeelChanged()
  52095. {
  52096. for (int i = contentComponents.size(); --i >= 0;)
  52097. if (contentComponents.getReference (i) != 0)
  52098. contentComponents.getReference (i)->lookAndFeelChanged();
  52099. }
  52100. void TabbedComponent::changeCallback (const int newCurrentTabIndex, const String& newTabName)
  52101. {
  52102. if (panelComponent != 0)
  52103. {
  52104. panelComponent->setVisible (false);
  52105. removeChildComponent (panelComponent);
  52106. panelComponent = 0;
  52107. }
  52108. if (getCurrentTabIndex() >= 0)
  52109. {
  52110. panelComponent = getTabContentComponent (getCurrentTabIndex());
  52111. if (panelComponent != 0)
  52112. {
  52113. // do these ops as two stages instead of addAndMakeVisible() so that the
  52114. // component has always got a parent when it gets the visibilityChanged() callback
  52115. addChildComponent (panelComponent);
  52116. panelComponent->setVisible (true);
  52117. panelComponent->toFront (true);
  52118. }
  52119. repaint();
  52120. }
  52121. resized();
  52122. currentTabChanged (newCurrentTabIndex, newTabName);
  52123. }
  52124. void TabbedComponent::currentTabChanged (const int, const String&) {}
  52125. void TabbedComponent::popupMenuClickOnTab (const int, const String&) {}
  52126. END_JUCE_NAMESPACE
  52127. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52128. /*** Start of inlined file: juce_Viewport.cpp ***/
  52129. BEGIN_JUCE_NAMESPACE
  52130. Viewport::Viewport (const String& componentName)
  52131. : Component (componentName),
  52132. scrollBarThickness (0),
  52133. singleStepX (16),
  52134. singleStepY (16),
  52135. showHScrollbar (true),
  52136. showVScrollbar (true),
  52137. verticalScrollBar (true),
  52138. horizontalScrollBar (false)
  52139. {
  52140. // content holder is used to clip the contents so they don't overlap the scrollbars
  52141. addAndMakeVisible (&contentHolder);
  52142. contentHolder.setInterceptsMouseClicks (false, true);
  52143. addChildComponent (&verticalScrollBar);
  52144. addChildComponent (&horizontalScrollBar);
  52145. verticalScrollBar.addListener (this);
  52146. horizontalScrollBar.addListener (this);
  52147. setInterceptsMouseClicks (false, true);
  52148. setWantsKeyboardFocus (true);
  52149. }
  52150. Viewport::~Viewport()
  52151. {
  52152. deleteContentComp();
  52153. }
  52154. void Viewport::visibleAreaChanged (const Rectangle<int>&)
  52155. {
  52156. }
  52157. void Viewport::deleteContentComp()
  52158. {
  52159. // This sets the content comp to a null pointer before deleting the old one, in case
  52160. // anything tries to use the old one while it's in mid-deletion..
  52161. ScopedPointer<Component> oldCompDeleter (contentComp);
  52162. contentComp = 0;
  52163. }
  52164. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52165. {
  52166. if (contentComp.get() != newViewedComponent)
  52167. {
  52168. deleteContentComp();
  52169. contentComp = newViewedComponent;
  52170. if (contentComp != 0)
  52171. {
  52172. contentHolder.addAndMakeVisible (contentComp);
  52173. setViewPosition (0, 0);
  52174. contentComp->addComponentListener (this);
  52175. }
  52176. updateVisibleArea();
  52177. }
  52178. }
  52179. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  52180. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  52181. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52182. {
  52183. if (contentComp != 0)
  52184. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52185. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52186. }
  52187. void Viewport::setViewPosition (const Point<int>& newPosition)
  52188. {
  52189. setViewPosition (newPosition.getX(), newPosition.getY());
  52190. }
  52191. void Viewport::setViewPositionProportionately (const double x, const double y)
  52192. {
  52193. if (contentComp != 0)
  52194. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52195. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52196. }
  52197. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52198. {
  52199. if (contentComp != 0)
  52200. {
  52201. int dx = 0, dy = 0;
  52202. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52203. {
  52204. if (mouseX < activeBorderThickness)
  52205. dx = activeBorderThickness - mouseX;
  52206. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52207. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52208. if (dx < 0)
  52209. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52210. else
  52211. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52212. }
  52213. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52214. {
  52215. if (mouseY < activeBorderThickness)
  52216. dy = activeBorderThickness - mouseY;
  52217. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52218. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52219. if (dy < 0)
  52220. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52221. else
  52222. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52223. }
  52224. if (dx != 0 || dy != 0)
  52225. {
  52226. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52227. contentComp->getY() + dy);
  52228. return true;
  52229. }
  52230. }
  52231. return false;
  52232. }
  52233. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52234. {
  52235. updateVisibleArea();
  52236. }
  52237. void Viewport::resized()
  52238. {
  52239. updateVisibleArea();
  52240. }
  52241. void Viewport::updateVisibleArea()
  52242. {
  52243. const int scrollbarWidth = getScrollBarThickness();
  52244. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52245. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52246. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52247. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52248. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52249. Rectangle<int> contentArea (getLocalBounds());
  52250. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52251. {
  52252. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52253. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52254. if (vBarVisible)
  52255. contentArea.setWidth (getWidth() - scrollbarWidth);
  52256. if (hBarVisible)
  52257. contentArea.setHeight (getHeight() - scrollbarWidth);
  52258. if (! contentArea.contains (contentComp->getBounds()))
  52259. {
  52260. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52261. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52262. }
  52263. }
  52264. if (vBarVisible)
  52265. contentArea.setWidth (getWidth() - scrollbarWidth);
  52266. if (hBarVisible)
  52267. contentArea.setHeight (getHeight() - scrollbarWidth);
  52268. contentHolder.setBounds (contentArea);
  52269. Rectangle<int> contentBounds;
  52270. if (contentComp != 0)
  52271. contentBounds = contentHolder.getLocalArea (contentComp, contentComp->getLocalBounds());
  52272. Point<int> visibleOrigin (-contentBounds.getPosition());
  52273. if (hBarVisible)
  52274. {
  52275. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52276. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52277. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52278. horizontalScrollBar.setSingleStepSize (singleStepX);
  52279. horizontalScrollBar.cancelPendingUpdate();
  52280. }
  52281. else if (canShowHBar)
  52282. {
  52283. visibleOrigin.setX (0);
  52284. }
  52285. if (vBarVisible)
  52286. {
  52287. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52288. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52289. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52290. verticalScrollBar.setSingleStepSize (singleStepY);
  52291. verticalScrollBar.cancelPendingUpdate();
  52292. }
  52293. else if (canShowVBar)
  52294. {
  52295. visibleOrigin.setY (0);
  52296. }
  52297. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52298. horizontalScrollBar.setVisible (hBarVisible);
  52299. verticalScrollBar.setVisible (vBarVisible);
  52300. setViewPosition (visibleOrigin);
  52301. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52302. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52303. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52304. if (lastVisibleArea != visibleArea)
  52305. {
  52306. lastVisibleArea = visibleArea;
  52307. visibleAreaChanged (visibleArea);
  52308. }
  52309. horizontalScrollBar.handleUpdateNowIfNeeded();
  52310. verticalScrollBar.handleUpdateNowIfNeeded();
  52311. }
  52312. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52313. {
  52314. if (singleStepX != stepX || singleStepY != stepY)
  52315. {
  52316. singleStepX = stepX;
  52317. singleStepY = stepY;
  52318. updateVisibleArea();
  52319. }
  52320. }
  52321. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52322. const bool showHorizontalScrollbarIfNeeded)
  52323. {
  52324. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52325. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52326. {
  52327. showVScrollbar = showVerticalScrollbarIfNeeded;
  52328. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52329. updateVisibleArea();
  52330. }
  52331. }
  52332. void Viewport::setScrollBarThickness (const int thickness)
  52333. {
  52334. if (scrollBarThickness != thickness)
  52335. {
  52336. scrollBarThickness = thickness;
  52337. updateVisibleArea();
  52338. }
  52339. }
  52340. int Viewport::getScrollBarThickness() const
  52341. {
  52342. return scrollBarThickness > 0 ? scrollBarThickness
  52343. : getLookAndFeel().getDefaultScrollbarWidth();
  52344. }
  52345. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52346. {
  52347. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52348. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52349. }
  52350. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52351. {
  52352. const int newRangeStartInt = roundToInt (newRangeStart);
  52353. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52354. {
  52355. setViewPosition (newRangeStartInt, getViewPositionY());
  52356. }
  52357. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52358. {
  52359. setViewPosition (getViewPositionX(), newRangeStartInt);
  52360. }
  52361. }
  52362. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52363. {
  52364. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52365. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52366. }
  52367. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52368. {
  52369. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52370. {
  52371. const bool hasVertBar = verticalScrollBar.isVisible();
  52372. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52373. if (hasHorzBar || hasVertBar)
  52374. {
  52375. if (wheelIncrementX != 0)
  52376. {
  52377. wheelIncrementX *= 14.0f * singleStepX;
  52378. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52379. : jmax (wheelIncrementX, 1.0f);
  52380. }
  52381. if (wheelIncrementY != 0)
  52382. {
  52383. wheelIncrementY *= 14.0f * singleStepY;
  52384. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52385. : jmax (wheelIncrementY, 1.0f);
  52386. }
  52387. Point<int> pos (getViewPosition());
  52388. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52389. {
  52390. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52391. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52392. }
  52393. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52394. {
  52395. if (wheelIncrementX == 0 && ! hasVertBar)
  52396. wheelIncrementX = wheelIncrementY;
  52397. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52398. }
  52399. else if (hasVertBar && wheelIncrementY != 0)
  52400. {
  52401. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52402. }
  52403. if (pos != getViewPosition())
  52404. {
  52405. setViewPosition (pos);
  52406. return true;
  52407. }
  52408. }
  52409. }
  52410. return false;
  52411. }
  52412. bool Viewport::keyPressed (const KeyPress& key)
  52413. {
  52414. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52415. || key.isKeyCode (KeyPress::downKey)
  52416. || key.isKeyCode (KeyPress::pageUpKey)
  52417. || key.isKeyCode (KeyPress::pageDownKey)
  52418. || key.isKeyCode (KeyPress::homeKey)
  52419. || key.isKeyCode (KeyPress::endKey);
  52420. if (verticalScrollBar.isVisible() && isUpDownKey)
  52421. return verticalScrollBar.keyPressed (key);
  52422. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52423. || key.isKeyCode (KeyPress::rightKey);
  52424. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52425. return horizontalScrollBar.keyPressed (key);
  52426. return false;
  52427. }
  52428. END_JUCE_NAMESPACE
  52429. /*** End of inlined file: juce_Viewport.cpp ***/
  52430. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52431. BEGIN_JUCE_NAMESPACE
  52432. namespace LookAndFeelHelpers
  52433. {
  52434. void createRoundedPath (Path& p,
  52435. const float x, const float y,
  52436. const float w, const float h,
  52437. const float cs,
  52438. const bool curveTopLeft, const bool curveTopRight,
  52439. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52440. {
  52441. const float cs2 = 2.0f * cs;
  52442. if (curveTopLeft)
  52443. {
  52444. p.startNewSubPath (x, y + cs);
  52445. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52446. }
  52447. else
  52448. {
  52449. p.startNewSubPath (x, y);
  52450. }
  52451. if (curveTopRight)
  52452. {
  52453. p.lineTo (x + w - cs, y);
  52454. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52455. }
  52456. else
  52457. {
  52458. p.lineTo (x + w, y);
  52459. }
  52460. if (curveBottomRight)
  52461. {
  52462. p.lineTo (x + w, y + h - cs);
  52463. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52464. }
  52465. else
  52466. {
  52467. p.lineTo (x + w, y + h);
  52468. }
  52469. if (curveBottomLeft)
  52470. {
  52471. p.lineTo (x + cs, y + h);
  52472. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52473. }
  52474. else
  52475. {
  52476. p.lineTo (x, y + h);
  52477. }
  52478. p.closeSubPath();
  52479. }
  52480. const Colour createBaseColour (const Colour& buttonColour,
  52481. const bool hasKeyboardFocus,
  52482. const bool isMouseOverButton,
  52483. const bool isButtonDown) throw()
  52484. {
  52485. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52486. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52487. if (isButtonDown)
  52488. return baseColour.contrasting (0.2f);
  52489. else if (isMouseOverButton)
  52490. return baseColour.contrasting (0.1f);
  52491. return baseColour;
  52492. }
  52493. const TextLayout layoutTooltipText (const String& text) throw()
  52494. {
  52495. const float tooltipFontSize = 12.0f;
  52496. const int maxToolTipWidth = 400;
  52497. const Font f (tooltipFontSize, Font::bold);
  52498. TextLayout tl (text, f);
  52499. tl.layout (maxToolTipWidth, Justification::left, true);
  52500. return tl;
  52501. }
  52502. LookAndFeel* defaultLF = 0;
  52503. LookAndFeel* currentDefaultLF = 0;
  52504. }
  52505. LookAndFeel::LookAndFeel()
  52506. {
  52507. /* if this fails it means you're trying to create a LookAndFeel object before
  52508. the static Colours have been initialised. That ain't gonna work. It probably
  52509. means that you're using a static LookAndFeel object and that your compiler has
  52510. decided to intialise it before the Colours class.
  52511. */
  52512. jassert (Colours::white == Colour (0xffffffff));
  52513. // set up the standard set of colours..
  52514. const int textButtonColour = 0xffbbbbff;
  52515. const int textHighlightColour = 0x401111ee;
  52516. const int standardOutlineColour = 0xb2808080;
  52517. static const int standardColours[] =
  52518. {
  52519. TextButton::buttonColourId, textButtonColour,
  52520. TextButton::buttonOnColourId, 0xff4444ff,
  52521. TextButton::textColourOnId, 0xff000000,
  52522. TextButton::textColourOffId, 0xff000000,
  52523. ComboBox::buttonColourId, 0xffbbbbff,
  52524. ComboBox::outlineColourId, standardOutlineColour,
  52525. ToggleButton::textColourId, 0xff000000,
  52526. TextEditor::backgroundColourId, 0xffffffff,
  52527. TextEditor::textColourId, 0xff000000,
  52528. TextEditor::highlightColourId, textHighlightColour,
  52529. TextEditor::highlightedTextColourId, 0xff000000,
  52530. TextEditor::caretColourId, 0xff000000,
  52531. TextEditor::outlineColourId, 0x00000000,
  52532. TextEditor::focusedOutlineColourId, textButtonColour,
  52533. TextEditor::shadowColourId, 0x38000000,
  52534. Label::backgroundColourId, 0x00000000,
  52535. Label::textColourId, 0xff000000,
  52536. Label::outlineColourId, 0x00000000,
  52537. ScrollBar::backgroundColourId, 0x00000000,
  52538. ScrollBar::thumbColourId, 0xffffffff,
  52539. TreeView::linesColourId, 0x4c000000,
  52540. TreeView::backgroundColourId, 0x00000000,
  52541. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52542. PopupMenu::backgroundColourId, 0xffffffff,
  52543. PopupMenu::textColourId, 0xff000000,
  52544. PopupMenu::headerTextColourId, 0xff000000,
  52545. PopupMenu::highlightedTextColourId, 0xffffffff,
  52546. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52547. ComboBox::textColourId, 0xff000000,
  52548. ComboBox::backgroundColourId, 0xffffffff,
  52549. ComboBox::arrowColourId, 0x99000000,
  52550. ListBox::backgroundColourId, 0xffffffff,
  52551. ListBox::outlineColourId, standardOutlineColour,
  52552. ListBox::textColourId, 0xff000000,
  52553. Slider::backgroundColourId, 0x00000000,
  52554. Slider::thumbColourId, textButtonColour,
  52555. Slider::trackColourId, 0x7fffffff,
  52556. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52557. Slider::rotarySliderOutlineColourId, 0x66000000,
  52558. Slider::textBoxTextColourId, 0xff000000,
  52559. Slider::textBoxBackgroundColourId, 0xffffffff,
  52560. Slider::textBoxHighlightColourId, textHighlightColour,
  52561. Slider::textBoxOutlineColourId, standardOutlineColour,
  52562. ResizableWindow::backgroundColourId, 0xff777777,
  52563. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52564. AlertWindow::backgroundColourId, 0xffededed,
  52565. AlertWindow::textColourId, 0xff000000,
  52566. AlertWindow::outlineColourId, 0xff666666,
  52567. ProgressBar::backgroundColourId, 0xffeeeeee,
  52568. ProgressBar::foregroundColourId, 0xffaaaaee,
  52569. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52570. TooltipWindow::textColourId, 0xff000000,
  52571. TooltipWindow::outlineColourId, 0x4c000000,
  52572. TabbedComponent::backgroundColourId, 0x00000000,
  52573. TabbedComponent::outlineColourId, 0xff777777,
  52574. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52575. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52576. Toolbar::backgroundColourId, 0xfff6f8f9,
  52577. Toolbar::separatorColourId, 0x4c000000,
  52578. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52579. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52580. Toolbar::labelTextColourId, 0xff000000,
  52581. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52582. HyperlinkButton::textColourId, 0xcc1111ee,
  52583. GroupComponent::outlineColourId, 0x66000000,
  52584. GroupComponent::textColourId, 0xff000000,
  52585. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52586. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52587. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52588. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52589. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52590. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52591. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52592. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52593. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52594. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52595. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52596. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52597. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52598. CodeEditorComponent::caretColourId, 0xff000000,
  52599. CodeEditorComponent::highlightColourId, textHighlightColour,
  52600. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52601. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52602. ColourSelector::labelTextColourId, 0xff000000,
  52603. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52604. KeyMappingEditorComponent::textColourId, 0xff000000,
  52605. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52606. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52607. DrawableButton::textColourId, 0xff000000,
  52608. };
  52609. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52610. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52611. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52612. if (defaultSansName.isEmpty())
  52613. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52614. defaultSans = defaultSansName;
  52615. defaultSerif = defaultSerifName;
  52616. defaultFixed = defaultFixedName;
  52617. Font::setFallbackFontName (defaultFallback);
  52618. }
  52619. LookAndFeel::~LookAndFeel()
  52620. {
  52621. if (this == LookAndFeelHelpers::currentDefaultLF)
  52622. setDefaultLookAndFeel (0);
  52623. }
  52624. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52625. {
  52626. const int index = colourIds.indexOf (colourId);
  52627. if (index >= 0)
  52628. return colours [index];
  52629. jassertfalse;
  52630. return Colours::black;
  52631. }
  52632. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52633. {
  52634. const int index = colourIds.indexOf (colourId);
  52635. if (index >= 0)
  52636. {
  52637. colours.set (index, colour);
  52638. }
  52639. else
  52640. {
  52641. colourIds.add (colourId);
  52642. colours.add (colour);
  52643. }
  52644. }
  52645. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52646. {
  52647. return colourIds.contains (colourId);
  52648. }
  52649. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52650. {
  52651. // if this happens, your app hasn't initialised itself properly.. if you're
  52652. // trying to hack your own main() function, have a look at
  52653. // JUCEApplication::initialiseForGUI()
  52654. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52655. return *LookAndFeelHelpers::currentDefaultLF;
  52656. }
  52657. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52658. {
  52659. using namespace LookAndFeelHelpers;
  52660. if (newDefaultLookAndFeel == 0)
  52661. {
  52662. if (defaultLF == 0)
  52663. defaultLF = new LookAndFeel();
  52664. newDefaultLookAndFeel = defaultLF;
  52665. }
  52666. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52667. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52668. {
  52669. Component* const c = Desktop::getInstance().getComponent (i);
  52670. if (c != 0)
  52671. c->sendLookAndFeelChange();
  52672. }
  52673. }
  52674. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52675. {
  52676. using namespace LookAndFeelHelpers;
  52677. if (currentDefaultLF == defaultLF)
  52678. currentDefaultLF = 0;
  52679. deleteAndZero (defaultLF);
  52680. }
  52681. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52682. {
  52683. String faceName (font.getTypefaceName());
  52684. if (faceName == Font::getDefaultSansSerifFontName())
  52685. faceName = defaultSans;
  52686. else if (faceName == Font::getDefaultSerifFontName())
  52687. faceName = defaultSerif;
  52688. else if (faceName == Font::getDefaultMonospacedFontName())
  52689. faceName = defaultFixed;
  52690. Font f (font);
  52691. f.setTypefaceName (faceName);
  52692. return Typeface::createSystemTypefaceFor (f);
  52693. }
  52694. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52695. {
  52696. defaultSans = newName;
  52697. }
  52698. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52699. {
  52700. return component.getMouseCursor();
  52701. }
  52702. void LookAndFeel::drawButtonBackground (Graphics& g,
  52703. Button& button,
  52704. const Colour& backgroundColour,
  52705. bool isMouseOverButton,
  52706. bool isButtonDown)
  52707. {
  52708. const int width = button.getWidth();
  52709. const int height = button.getHeight();
  52710. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52711. const float halfThickness = outlineThickness * 0.5f;
  52712. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52713. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52714. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52715. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52716. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52717. button.hasKeyboardFocus (true),
  52718. isMouseOverButton, isButtonDown)
  52719. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52720. drawGlassLozenge (g,
  52721. indentL,
  52722. indentT,
  52723. width - indentL - indentR,
  52724. height - indentT - indentB,
  52725. baseColour, outlineThickness, -1.0f,
  52726. button.isConnectedOnLeft(),
  52727. button.isConnectedOnRight(),
  52728. button.isConnectedOnTop(),
  52729. button.isConnectedOnBottom());
  52730. }
  52731. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52732. {
  52733. return button.getFont();
  52734. }
  52735. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52736. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52737. {
  52738. Font font (getFontForTextButton (button));
  52739. g.setFont (font);
  52740. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52741. : TextButton::textColourOffId)
  52742. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52743. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52744. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52745. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52746. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52747. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52748. g.drawFittedText (button.getButtonText(),
  52749. leftIndent,
  52750. yIndent,
  52751. button.getWidth() - leftIndent - rightIndent,
  52752. button.getHeight() - yIndent * 2,
  52753. Justification::centred, 2);
  52754. }
  52755. void LookAndFeel::drawTickBox (Graphics& g,
  52756. Component& component,
  52757. float x, float y, float w, float h,
  52758. const bool ticked,
  52759. const bool isEnabled,
  52760. const bool isMouseOverButton,
  52761. const bool isButtonDown)
  52762. {
  52763. const float boxSize = w * 0.7f;
  52764. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52765. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52766. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52767. true, isMouseOverButton, isButtonDown),
  52768. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52769. if (ticked)
  52770. {
  52771. Path tick;
  52772. tick.startNewSubPath (1.5f, 3.0f);
  52773. tick.lineTo (3.0f, 6.0f);
  52774. tick.lineTo (6.0f, 0.0f);
  52775. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52776. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52777. .translated (x, y));
  52778. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52779. }
  52780. }
  52781. void LookAndFeel::drawToggleButton (Graphics& g,
  52782. ToggleButton& button,
  52783. bool isMouseOverButton,
  52784. bool isButtonDown)
  52785. {
  52786. if (button.hasKeyboardFocus (true))
  52787. {
  52788. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52789. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52790. }
  52791. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52792. const float tickWidth = fontSize * 1.1f;
  52793. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52794. tickWidth, tickWidth,
  52795. button.getToggleState(),
  52796. button.isEnabled(),
  52797. isMouseOverButton,
  52798. isButtonDown);
  52799. g.setColour (button.findColour (ToggleButton::textColourId));
  52800. g.setFont (fontSize);
  52801. if (! button.isEnabled())
  52802. g.setOpacity (0.5f);
  52803. const int textX = (int) tickWidth + 5;
  52804. g.drawFittedText (button.getButtonText(),
  52805. textX, 0,
  52806. button.getWidth() - textX - 2, button.getHeight(),
  52807. Justification::centredLeft, 10);
  52808. }
  52809. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52810. {
  52811. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52812. const int tickWidth = jmin (24, button.getHeight());
  52813. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52814. button.getHeight());
  52815. }
  52816. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52817. const String& message,
  52818. const String& button1,
  52819. const String& button2,
  52820. const String& button3,
  52821. AlertWindow::AlertIconType iconType,
  52822. int numButtons,
  52823. Component* associatedComponent)
  52824. {
  52825. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52826. if (numButtons == 1)
  52827. {
  52828. aw->addButton (button1, 0,
  52829. KeyPress (KeyPress::escapeKey, 0, 0),
  52830. KeyPress (KeyPress::returnKey, 0, 0));
  52831. }
  52832. else
  52833. {
  52834. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52835. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52836. if (button1ShortCut == button2ShortCut)
  52837. button2ShortCut = KeyPress();
  52838. if (numButtons == 2)
  52839. {
  52840. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52841. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52842. }
  52843. else if (numButtons == 3)
  52844. {
  52845. aw->addButton (button1, 1, button1ShortCut);
  52846. aw->addButton (button2, 2, button2ShortCut);
  52847. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52848. }
  52849. }
  52850. return aw;
  52851. }
  52852. void LookAndFeel::drawAlertBox (Graphics& g,
  52853. AlertWindow& alert,
  52854. const Rectangle<int>& textArea,
  52855. TextLayout& textLayout)
  52856. {
  52857. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52858. int iconSpaceUsed = 0;
  52859. Justification alignment (Justification::horizontallyCentred);
  52860. const int iconWidth = 80;
  52861. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52862. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52863. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52864. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52865. iconSize, iconSize);
  52866. if (alert.getAlertType() != AlertWindow::NoIcon)
  52867. {
  52868. Path icon;
  52869. uint32 colour;
  52870. char character;
  52871. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52872. {
  52873. colour = 0x55ff5555;
  52874. character = '!';
  52875. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52876. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52877. (float) iconRect.getX(), (float) iconRect.getBottom());
  52878. icon = icon.createPathWithRoundedCorners (5.0f);
  52879. }
  52880. else
  52881. {
  52882. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52883. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52884. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52885. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52886. }
  52887. GlyphArrangement ga;
  52888. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52889. String::charToString (character),
  52890. (float) iconRect.getX(), (float) iconRect.getY(),
  52891. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52892. Justification::centred, false);
  52893. ga.createPath (icon);
  52894. icon.setUsingNonZeroWinding (false);
  52895. g.setColour (Colour (colour));
  52896. g.fillPath (icon);
  52897. iconSpaceUsed = iconWidth;
  52898. alignment = Justification::left;
  52899. }
  52900. g.setColour (alert.findColour (AlertWindow::textColourId));
  52901. textLayout.drawWithin (g,
  52902. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52903. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52904. alignment.getFlags() | Justification::top);
  52905. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52906. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52907. }
  52908. int LookAndFeel::getAlertBoxWindowFlags()
  52909. {
  52910. return ComponentPeer::windowAppearsOnTaskbar
  52911. | ComponentPeer::windowHasDropShadow;
  52912. }
  52913. int LookAndFeel::getAlertWindowButtonHeight()
  52914. {
  52915. return 28;
  52916. }
  52917. const Font LookAndFeel::getAlertWindowMessageFont()
  52918. {
  52919. return Font (15.0f);
  52920. }
  52921. const Font LookAndFeel::getAlertWindowFont()
  52922. {
  52923. return Font (12.0f);
  52924. }
  52925. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52926. int width, int height,
  52927. double progress, const String& textToShow)
  52928. {
  52929. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52930. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52931. g.fillAll (background);
  52932. if (progress >= 0.0f && progress < 1.0f)
  52933. {
  52934. drawGlassLozenge (g, 1.0f, 1.0f,
  52935. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52936. (float) (height - 2),
  52937. foreground,
  52938. 0.5f, 0.0f,
  52939. true, true, true, true);
  52940. }
  52941. else
  52942. {
  52943. // spinning bar..
  52944. g.setColour (foreground);
  52945. const int stripeWidth = height * 2;
  52946. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52947. Path p;
  52948. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52949. p.addQuadrilateral (x, 0.0f,
  52950. x + stripeWidth * 0.5f, 0.0f,
  52951. x, (float) height,
  52952. x - stripeWidth * 0.5f, (float) height);
  52953. Image im (Image::ARGB, width, height, true);
  52954. {
  52955. Graphics g2 (im);
  52956. drawGlassLozenge (g2, 1.0f, 1.0f,
  52957. (float) (width - 2),
  52958. (float) (height - 2),
  52959. foreground,
  52960. 0.5f, 0.0f,
  52961. true, true, true, true);
  52962. }
  52963. g.setTiledImageFill (im, 0, 0, 0.85f);
  52964. g.fillPath (p);
  52965. }
  52966. if (textToShow.isNotEmpty())
  52967. {
  52968. g.setColour (Colour::contrasting (background, foreground));
  52969. g.setFont (height * 0.6f);
  52970. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52971. }
  52972. }
  52973. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52974. {
  52975. const float radius = jmin (w, h) * 0.4f;
  52976. const float thickness = radius * 0.15f;
  52977. Path p;
  52978. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52979. radius * 0.6f, thickness,
  52980. thickness * 0.5f);
  52981. const float cx = x + w * 0.5f;
  52982. const float cy = y + h * 0.5f;
  52983. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52984. for (int i = 0; i < 12; ++i)
  52985. {
  52986. const int n = (i + 12 - animationIndex) % 12;
  52987. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52988. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52989. .translated (cx, cy));
  52990. }
  52991. }
  52992. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52993. ScrollBar& scrollbar,
  52994. int width, int height,
  52995. int buttonDirection,
  52996. bool /*isScrollbarVertical*/,
  52997. bool /*isMouseOverButton*/,
  52998. bool isButtonDown)
  52999. {
  53000. Path p;
  53001. if (buttonDirection == 0)
  53002. p.addTriangle (width * 0.5f, height * 0.2f,
  53003. width * 0.1f, height * 0.7f,
  53004. width * 0.9f, height * 0.7f);
  53005. else if (buttonDirection == 1)
  53006. p.addTriangle (width * 0.8f, height * 0.5f,
  53007. width * 0.3f, height * 0.1f,
  53008. width * 0.3f, height * 0.9f);
  53009. else if (buttonDirection == 2)
  53010. p.addTriangle (width * 0.5f, height * 0.8f,
  53011. width * 0.1f, height * 0.3f,
  53012. width * 0.9f, height * 0.3f);
  53013. else if (buttonDirection == 3)
  53014. p.addTriangle (width * 0.2f, height * 0.5f,
  53015. width * 0.7f, height * 0.1f,
  53016. width * 0.7f, height * 0.9f);
  53017. if (isButtonDown)
  53018. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  53019. else
  53020. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  53021. g.fillPath (p);
  53022. g.setColour (Colour (0x80000000));
  53023. g.strokePath (p, PathStrokeType (0.5f));
  53024. }
  53025. void LookAndFeel::drawScrollbar (Graphics& g,
  53026. ScrollBar& scrollbar,
  53027. int x, int y,
  53028. int width, int height,
  53029. bool isScrollbarVertical,
  53030. int thumbStartPosition,
  53031. int thumbSize,
  53032. bool /*isMouseOver*/,
  53033. bool /*isMouseDown*/)
  53034. {
  53035. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  53036. Path slotPath, thumbPath;
  53037. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  53038. const float slotIndentx2 = slotIndent * 2.0f;
  53039. const float thumbIndent = slotIndent + 1.0f;
  53040. const float thumbIndentx2 = thumbIndent * 2.0f;
  53041. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  53042. if (isScrollbarVertical)
  53043. {
  53044. slotPath.addRoundedRectangle (x + slotIndent,
  53045. y + slotIndent,
  53046. width - slotIndentx2,
  53047. height - slotIndentx2,
  53048. (width - slotIndentx2) * 0.5f);
  53049. if (thumbSize > 0)
  53050. thumbPath.addRoundedRectangle (x + thumbIndent,
  53051. thumbStartPosition + thumbIndent,
  53052. width - thumbIndentx2,
  53053. thumbSize - thumbIndentx2,
  53054. (width - thumbIndentx2) * 0.5f);
  53055. gx1 = (float) x;
  53056. gx2 = x + width * 0.7f;
  53057. }
  53058. else
  53059. {
  53060. slotPath.addRoundedRectangle (x + slotIndent,
  53061. y + slotIndent,
  53062. width - slotIndentx2,
  53063. height - slotIndentx2,
  53064. (height - slotIndentx2) * 0.5f);
  53065. if (thumbSize > 0)
  53066. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  53067. y + thumbIndent,
  53068. thumbSize - thumbIndentx2,
  53069. height - thumbIndentx2,
  53070. (height - thumbIndentx2) * 0.5f);
  53071. gy1 = (float) y;
  53072. gy2 = y + height * 0.7f;
  53073. }
  53074. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  53075. Colour trackColour1, trackColour2;
  53076. if (scrollbar.isColourSpecified (ScrollBar::trackColourId))
  53077. {
  53078. trackColour1 = trackColour2 = scrollbar.findColour (ScrollBar::trackColourId);
  53079. }
  53080. else
  53081. {
  53082. trackColour1 = thumbColour.overlaidWith (Colour (0x44000000));
  53083. trackColour2 = thumbColour.overlaidWith (Colour (0x19000000));
  53084. }
  53085. g.setGradientFill (ColourGradient (trackColour1, gx1, gy1,
  53086. trackColour2, gx2, gy2, false));
  53087. g.fillPath (slotPath);
  53088. if (isScrollbarVertical)
  53089. {
  53090. gx1 = x + width * 0.6f;
  53091. gx2 = (float) x + width;
  53092. }
  53093. else
  53094. {
  53095. gy1 = y + height * 0.6f;
  53096. gy2 = (float) y + height;
  53097. }
  53098. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  53099. Colour (0x19000000), gx2, gy2, false));
  53100. g.fillPath (slotPath);
  53101. g.setColour (thumbColour);
  53102. g.fillPath (thumbPath);
  53103. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  53104. Colours::transparentBlack, gx2, gy2, false));
  53105. g.saveState();
  53106. if (isScrollbarVertical)
  53107. g.reduceClipRegion (x + width / 2, y, width, height);
  53108. else
  53109. g.reduceClipRegion (x, y + height / 2, width, height);
  53110. g.fillPath (thumbPath);
  53111. g.restoreState();
  53112. g.setColour (Colour (0x4c000000));
  53113. g.strokePath (thumbPath, PathStrokeType (0.4f));
  53114. }
  53115. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  53116. {
  53117. return 0;
  53118. }
  53119. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  53120. {
  53121. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  53122. }
  53123. int LookAndFeel::getDefaultScrollbarWidth()
  53124. {
  53125. return 18;
  53126. }
  53127. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  53128. {
  53129. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  53130. : scrollbar.getHeight());
  53131. }
  53132. const Path LookAndFeel::getTickShape (const float height)
  53133. {
  53134. static const unsigned char tickShapeData[] =
  53135. {
  53136. 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,
  53137. 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,
  53138. 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,
  53139. 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,
  53140. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  53141. };
  53142. Path p;
  53143. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  53144. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53145. return p;
  53146. }
  53147. const Path LookAndFeel::getCrossShape (const float height)
  53148. {
  53149. static const unsigned char crossShapeData[] =
  53150. {
  53151. 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,
  53152. 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,
  53153. 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,
  53154. 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,
  53155. 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,
  53156. 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,
  53157. 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
  53158. };
  53159. Path p;
  53160. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  53161. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53162. return p;
  53163. }
  53164. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  53165. {
  53166. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  53167. x += (w - boxSize) >> 1;
  53168. y += (h - boxSize) >> 1;
  53169. w = boxSize;
  53170. h = boxSize;
  53171. g.setColour (Colour (0xe5ffffff));
  53172. g.fillRect (x, y, w, h);
  53173. g.setColour (Colour (0x80000000));
  53174. g.drawRect (x, y, w, h);
  53175. const float size = boxSize / 2 + 1.0f;
  53176. const float centre = (float) (boxSize / 2);
  53177. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53178. if (isPlus)
  53179. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53180. }
  53181. void LookAndFeel::drawBubble (Graphics& g,
  53182. float tipX, float tipY,
  53183. float boxX, float boxY,
  53184. float boxW, float boxH)
  53185. {
  53186. int side = 0;
  53187. if (tipX < boxX)
  53188. side = 1;
  53189. else if (tipX > boxX + boxW)
  53190. side = 3;
  53191. else if (tipY > boxY + boxH)
  53192. side = 2;
  53193. const float indent = 2.0f;
  53194. Path p;
  53195. p.addBubble (boxX + indent,
  53196. boxY + indent,
  53197. boxW - indent * 2.0f,
  53198. boxH - indent * 2.0f,
  53199. 5.0f,
  53200. tipX, tipY,
  53201. side,
  53202. 0.5f,
  53203. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53204. //xxx need to take comp as param for colour
  53205. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53206. g.fillPath (p);
  53207. //xxx as above
  53208. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53209. g.strokePath (p, PathStrokeType (1.33f));
  53210. }
  53211. const Font LookAndFeel::getPopupMenuFont()
  53212. {
  53213. return Font (17.0f);
  53214. }
  53215. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53216. const bool isSeparator,
  53217. int standardMenuItemHeight,
  53218. int& idealWidth,
  53219. int& idealHeight)
  53220. {
  53221. if (isSeparator)
  53222. {
  53223. idealWidth = 50;
  53224. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53225. }
  53226. else
  53227. {
  53228. Font font (getPopupMenuFont());
  53229. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53230. font.setHeight (standardMenuItemHeight / 1.3f);
  53231. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53232. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53233. }
  53234. }
  53235. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53236. {
  53237. const Colour background (findColour (PopupMenu::backgroundColourId));
  53238. g.fillAll (background);
  53239. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53240. for (int i = 0; i < height; i += 3)
  53241. g.fillRect (0, i, width, 1);
  53242. #if ! JUCE_MAC
  53243. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53244. g.drawRect (0, 0, width, height);
  53245. #endif
  53246. }
  53247. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53248. int width, int height,
  53249. bool isScrollUpArrow)
  53250. {
  53251. const Colour background (findColour (PopupMenu::backgroundColourId));
  53252. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53253. background.withAlpha (0.0f),
  53254. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53255. false));
  53256. g.fillRect (1, 1, width - 2, height - 2);
  53257. const float hw = width * 0.5f;
  53258. const float arrowW = height * 0.3f;
  53259. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53260. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53261. Path p;
  53262. p.addTriangle (hw - arrowW, y1,
  53263. hw + arrowW, y1,
  53264. hw, y2);
  53265. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53266. g.fillPath (p);
  53267. }
  53268. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53269. int width, int height,
  53270. const bool isSeparator,
  53271. const bool isActive,
  53272. const bool isHighlighted,
  53273. const bool isTicked,
  53274. const bool hasSubMenu,
  53275. const String& text,
  53276. const String& shortcutKeyText,
  53277. Image* image,
  53278. const Colour* const textColourToUse)
  53279. {
  53280. const float halfH = height * 0.5f;
  53281. if (isSeparator)
  53282. {
  53283. const float separatorIndent = 5.5f;
  53284. g.setColour (Colour (0x33000000));
  53285. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53286. g.setColour (Colour (0x66ffffff));
  53287. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53288. }
  53289. else
  53290. {
  53291. Colour textColour (findColour (PopupMenu::textColourId));
  53292. if (textColourToUse != 0)
  53293. textColour = *textColourToUse;
  53294. if (isHighlighted)
  53295. {
  53296. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53297. g.fillRect (1, 1, width - 2, height - 2);
  53298. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53299. }
  53300. else
  53301. {
  53302. g.setColour (textColour);
  53303. }
  53304. if (! isActive)
  53305. g.setOpacity (0.3f);
  53306. Font font (getPopupMenuFont());
  53307. if (font.getHeight() > height / 1.3f)
  53308. font.setHeight (height / 1.3f);
  53309. g.setFont (font);
  53310. const int leftBorder = (height * 5) / 4;
  53311. const int rightBorder = 4;
  53312. if (image != 0)
  53313. {
  53314. g.drawImageWithin (*image,
  53315. 2, 1, leftBorder - 4, height - 2,
  53316. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53317. }
  53318. else if (isTicked)
  53319. {
  53320. const Path tick (getTickShape (1.0f));
  53321. const float th = font.getAscent();
  53322. const float ty = halfH - th * 0.5f;
  53323. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53324. th, true));
  53325. }
  53326. g.drawFittedText (text,
  53327. leftBorder, 0,
  53328. width - (leftBorder + rightBorder), height,
  53329. Justification::centredLeft, 1);
  53330. if (shortcutKeyText.isNotEmpty())
  53331. {
  53332. Font f2 (font);
  53333. f2.setHeight (f2.getHeight() * 0.75f);
  53334. f2.setHorizontalScale (0.95f);
  53335. g.setFont (f2);
  53336. g.drawText (shortcutKeyText,
  53337. leftBorder,
  53338. 0,
  53339. width - (leftBorder + rightBorder + 4),
  53340. height,
  53341. Justification::centredRight,
  53342. true);
  53343. }
  53344. if (hasSubMenu)
  53345. {
  53346. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53347. const float x = width - height * 0.6f;
  53348. Path p;
  53349. p.addTriangle (x, halfH - arrowH * 0.5f,
  53350. x, halfH + arrowH * 0.5f,
  53351. x + arrowH * 0.6f, halfH);
  53352. g.fillPath (p);
  53353. }
  53354. }
  53355. }
  53356. int LookAndFeel::getMenuWindowFlags()
  53357. {
  53358. return ComponentPeer::windowHasDropShadow;
  53359. }
  53360. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53361. bool, MenuBarComponent& menuBar)
  53362. {
  53363. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53364. if (menuBar.isEnabled())
  53365. {
  53366. drawShinyButtonShape (g,
  53367. -4.0f, 0.0f,
  53368. width + 8.0f, (float) height,
  53369. 0.0f,
  53370. baseColour,
  53371. 0.4f,
  53372. true, true, true, true);
  53373. }
  53374. else
  53375. {
  53376. g.fillAll (baseColour);
  53377. }
  53378. }
  53379. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53380. {
  53381. return Font (menuBar.getHeight() * 0.7f);
  53382. }
  53383. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53384. {
  53385. return getMenuBarFont (menuBar, itemIndex, itemText)
  53386. .getStringWidth (itemText) + menuBar.getHeight();
  53387. }
  53388. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53389. int width, int height,
  53390. int itemIndex,
  53391. const String& itemText,
  53392. bool isMouseOverItem,
  53393. bool isMenuOpen,
  53394. bool /*isMouseOverBar*/,
  53395. MenuBarComponent& menuBar)
  53396. {
  53397. if (! menuBar.isEnabled())
  53398. {
  53399. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53400. .withMultipliedAlpha (0.5f));
  53401. }
  53402. else if (isMenuOpen || isMouseOverItem)
  53403. {
  53404. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53405. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53406. }
  53407. else
  53408. {
  53409. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53410. }
  53411. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53412. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53413. }
  53414. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53415. TextEditor& textEditor)
  53416. {
  53417. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53418. }
  53419. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53420. {
  53421. if (textEditor.isEnabled())
  53422. {
  53423. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53424. {
  53425. const int border = 2;
  53426. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53427. g.drawRect (0, 0, width, height, border);
  53428. g.setOpacity (1.0f);
  53429. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53430. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53431. }
  53432. else
  53433. {
  53434. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53435. g.drawRect (0, 0, width, height);
  53436. g.setOpacity (1.0f);
  53437. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53438. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53439. }
  53440. }
  53441. }
  53442. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53443. const bool isButtonDown,
  53444. int buttonX, int buttonY,
  53445. int buttonW, int buttonH,
  53446. ComboBox& box)
  53447. {
  53448. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53449. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53450. {
  53451. g.setColour (box.findColour (TextButton::buttonColourId));
  53452. g.drawRect (0, 0, width, height, 2);
  53453. }
  53454. else
  53455. {
  53456. g.setColour (box.findColour (ComboBox::outlineColourId));
  53457. g.drawRect (0, 0, width, height);
  53458. }
  53459. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53460. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53461. box.hasKeyboardFocus (true),
  53462. false, isButtonDown)
  53463. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53464. drawGlassLozenge (g,
  53465. buttonX + outlineThickness, buttonY + outlineThickness,
  53466. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53467. baseColour, outlineThickness, -1.0f,
  53468. true, true, true, true);
  53469. if (box.isEnabled())
  53470. {
  53471. const float arrowX = 0.3f;
  53472. const float arrowH = 0.2f;
  53473. Path p;
  53474. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53475. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53476. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53477. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53478. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53479. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53480. g.setColour (box.findColour (ComboBox::arrowColourId));
  53481. g.fillPath (p);
  53482. }
  53483. }
  53484. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53485. {
  53486. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53487. }
  53488. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53489. {
  53490. return new Label (String::empty, String::empty);
  53491. }
  53492. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53493. {
  53494. label.setBounds (1, 1,
  53495. box.getWidth() + 3 - box.getHeight(),
  53496. box.getHeight() - 2);
  53497. label.setFont (getComboBoxFont (box));
  53498. }
  53499. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53500. {
  53501. g.fillAll (label.findColour (Label::backgroundColourId));
  53502. if (! label.isBeingEdited())
  53503. {
  53504. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53505. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53506. g.setFont (label.getFont());
  53507. g.drawFittedText (label.getText(),
  53508. label.getHorizontalBorderSize(),
  53509. label.getVerticalBorderSize(),
  53510. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53511. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53512. label.getJustificationType(),
  53513. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53514. label.getMinimumHorizontalScale());
  53515. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53516. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53517. }
  53518. else if (label.isEnabled())
  53519. {
  53520. g.setColour (label.findColour (Label::outlineColourId));
  53521. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53522. }
  53523. }
  53524. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53525. int x, int y,
  53526. int width, int height,
  53527. float /*sliderPos*/,
  53528. float /*minSliderPos*/,
  53529. float /*maxSliderPos*/,
  53530. const Slider::SliderStyle /*style*/,
  53531. Slider& slider)
  53532. {
  53533. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53534. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53535. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53536. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53537. Path indent;
  53538. if (slider.isHorizontal())
  53539. {
  53540. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53541. const float ih = sliderRadius;
  53542. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53543. gradCol2, 0.0f, iy + ih, false));
  53544. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53545. width + sliderRadius, ih,
  53546. 5.0f);
  53547. g.fillPath (indent);
  53548. }
  53549. else
  53550. {
  53551. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53552. const float iw = sliderRadius;
  53553. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53554. gradCol2, ix + iw, 0.0f, false));
  53555. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53556. iw, height + sliderRadius,
  53557. 5.0f);
  53558. g.fillPath (indent);
  53559. }
  53560. g.setColour (Colour (0x4c000000));
  53561. g.strokePath (indent, PathStrokeType (0.5f));
  53562. }
  53563. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53564. int x, int y,
  53565. int width, int height,
  53566. float sliderPos,
  53567. float minSliderPos,
  53568. float maxSliderPos,
  53569. const Slider::SliderStyle style,
  53570. Slider& slider)
  53571. {
  53572. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53573. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53574. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53575. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53576. slider.isMouseButtonDown() && slider.isEnabled()));
  53577. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53578. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53579. {
  53580. float kx, ky;
  53581. if (style == Slider::LinearVertical)
  53582. {
  53583. kx = x + width * 0.5f;
  53584. ky = sliderPos;
  53585. }
  53586. else
  53587. {
  53588. kx = sliderPos;
  53589. ky = y + height * 0.5f;
  53590. }
  53591. drawGlassSphere (g,
  53592. kx - sliderRadius,
  53593. ky - sliderRadius,
  53594. sliderRadius * 2.0f,
  53595. knobColour, outlineThickness);
  53596. }
  53597. else
  53598. {
  53599. if (style == Slider::ThreeValueVertical)
  53600. {
  53601. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53602. sliderPos - sliderRadius,
  53603. sliderRadius * 2.0f,
  53604. knobColour, outlineThickness);
  53605. }
  53606. else if (style == Slider::ThreeValueHorizontal)
  53607. {
  53608. drawGlassSphere (g,sliderPos - sliderRadius,
  53609. y + height * 0.5f - sliderRadius,
  53610. sliderRadius * 2.0f,
  53611. knobColour, outlineThickness);
  53612. }
  53613. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53614. {
  53615. const float sr = jmin (sliderRadius, width * 0.4f);
  53616. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53617. minSliderPos - sliderRadius,
  53618. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53619. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53620. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53621. }
  53622. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53623. {
  53624. const float sr = jmin (sliderRadius, height * 0.4f);
  53625. drawGlassPointer (g, minSliderPos - sr,
  53626. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53627. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53628. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53629. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53630. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53631. }
  53632. }
  53633. }
  53634. void LookAndFeel::drawLinearSlider (Graphics& g,
  53635. int x, int y,
  53636. int width, int height,
  53637. float sliderPos,
  53638. float minSliderPos,
  53639. float maxSliderPos,
  53640. const Slider::SliderStyle style,
  53641. Slider& slider)
  53642. {
  53643. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53644. if (style == Slider::LinearBar)
  53645. {
  53646. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53647. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53648. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53649. false, isMouseOver,
  53650. isMouseOver || slider.isMouseButtonDown()));
  53651. drawShinyButtonShape (g,
  53652. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53653. baseColour,
  53654. slider.isEnabled() ? 0.9f : 0.3f,
  53655. true, true, true, true);
  53656. }
  53657. else
  53658. {
  53659. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53660. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53661. }
  53662. }
  53663. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53664. {
  53665. return jmin (7,
  53666. slider.getHeight() / 2,
  53667. slider.getWidth() / 2) + 2;
  53668. }
  53669. void LookAndFeel::drawRotarySlider (Graphics& g,
  53670. int x, int y,
  53671. int width, int height,
  53672. float sliderPos,
  53673. const float rotaryStartAngle,
  53674. const float rotaryEndAngle,
  53675. Slider& slider)
  53676. {
  53677. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53678. const float centreX = x + width * 0.5f;
  53679. const float centreY = y + height * 0.5f;
  53680. const float rx = centreX - radius;
  53681. const float ry = centreY - radius;
  53682. const float rw = radius * 2.0f;
  53683. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53684. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53685. if (radius > 12.0f)
  53686. {
  53687. if (slider.isEnabled())
  53688. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53689. else
  53690. g.setColour (Colour (0x80808080));
  53691. const float thickness = 0.7f;
  53692. {
  53693. Path filledArc;
  53694. filledArc.addPieSegment (rx, ry, rw, rw,
  53695. rotaryStartAngle,
  53696. angle,
  53697. thickness);
  53698. g.fillPath (filledArc);
  53699. }
  53700. if (thickness > 0)
  53701. {
  53702. const float innerRadius = radius * 0.2f;
  53703. Path p;
  53704. p.addTriangle (-innerRadius, 0.0f,
  53705. 0.0f, -radius * thickness * 1.1f,
  53706. innerRadius, 0.0f);
  53707. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53708. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53709. }
  53710. if (slider.isEnabled())
  53711. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53712. else
  53713. g.setColour (Colour (0x80808080));
  53714. Path outlineArc;
  53715. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53716. outlineArc.closeSubPath();
  53717. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53718. }
  53719. else
  53720. {
  53721. if (slider.isEnabled())
  53722. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53723. else
  53724. g.setColour (Colour (0x80808080));
  53725. Path p;
  53726. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53727. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53728. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53729. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53730. }
  53731. }
  53732. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53733. {
  53734. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53735. }
  53736. class SliderLabelComp : public Label
  53737. {
  53738. public:
  53739. SliderLabelComp() : Label (String::empty, String::empty) {}
  53740. ~SliderLabelComp() {}
  53741. void mouseWheelMove (const MouseEvent&, float, float) {}
  53742. };
  53743. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53744. {
  53745. Label* const l = new SliderLabelComp();
  53746. l->setJustificationType (Justification::centred);
  53747. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53748. l->setColour (Label::backgroundColourId,
  53749. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53750. : slider.findColour (Slider::textBoxBackgroundColourId));
  53751. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53752. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53753. l->setColour (TextEditor::backgroundColourId,
  53754. slider.findColour (Slider::textBoxBackgroundColourId)
  53755. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53756. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53757. return l;
  53758. }
  53759. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53760. {
  53761. return 0;
  53762. }
  53763. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53764. {
  53765. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53766. width = tl.getWidth() + 14;
  53767. height = tl.getHeight() + 6;
  53768. }
  53769. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53770. {
  53771. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53772. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53773. g.setColour (findColour (TooltipWindow::outlineColourId));
  53774. g.drawRect (0, 0, width, height, 1);
  53775. #endif
  53776. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53777. g.setColour (findColour (TooltipWindow::textColourId));
  53778. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53779. }
  53780. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53781. {
  53782. return new TextButton (text, TRANS("click to browse for a different file"));
  53783. }
  53784. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53785. ComboBox* filenameBox,
  53786. Button* browseButton)
  53787. {
  53788. browseButton->setSize (80, filenameComp.getHeight());
  53789. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53790. if (tb != 0)
  53791. tb->changeWidthToFitText();
  53792. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53793. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53794. }
  53795. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53796. int imageX, int imageY, int imageW, int imageH,
  53797. const Colour& overlayColour,
  53798. float imageOpacity,
  53799. ImageButton& button)
  53800. {
  53801. if (! button.isEnabled())
  53802. imageOpacity *= 0.3f;
  53803. if (! overlayColour.isOpaque())
  53804. {
  53805. g.setOpacity (imageOpacity);
  53806. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53807. 0, 0, image->getWidth(), image->getHeight(), false);
  53808. }
  53809. if (! overlayColour.isTransparent())
  53810. {
  53811. g.setColour (overlayColour);
  53812. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53813. 0, 0, image->getWidth(), image->getHeight(), true);
  53814. }
  53815. }
  53816. void LookAndFeel::drawCornerResizer (Graphics& g,
  53817. int w, int h,
  53818. bool /*isMouseOver*/,
  53819. bool /*isMouseDragging*/)
  53820. {
  53821. const float lineThickness = jmin (w, h) * 0.075f;
  53822. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53823. {
  53824. g.setColour (Colours::lightgrey);
  53825. g.drawLine (w * i,
  53826. h + 1.0f,
  53827. w + 1.0f,
  53828. h * i,
  53829. lineThickness);
  53830. g.setColour (Colours::darkgrey);
  53831. g.drawLine (w * i + lineThickness,
  53832. h + 1.0f,
  53833. w + 1.0f,
  53834. h * i + lineThickness,
  53835. lineThickness);
  53836. }
  53837. }
  53838. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize<int>& border)
  53839. {
  53840. if (! border.isEmpty())
  53841. {
  53842. const Rectangle<int> fullSize (0, 0, w, h);
  53843. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53844. g.saveState();
  53845. g.excludeClipRegion (centreArea);
  53846. g.setColour (Colour (0x50000000));
  53847. g.drawRect (fullSize);
  53848. g.setColour (Colour (0x19000000));
  53849. g.drawRect (centreArea.expanded (1, 1));
  53850. g.restoreState();
  53851. }
  53852. }
  53853. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53854. const BorderSize<int>& /*border*/, ResizableWindow& window)
  53855. {
  53856. g.fillAll (window.getBackgroundColour());
  53857. }
  53858. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53859. const BorderSize<int>& /*border*/, ResizableWindow&)
  53860. {
  53861. }
  53862. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53863. Graphics& g, int w, int h,
  53864. int titleSpaceX, int titleSpaceW,
  53865. const Image* icon,
  53866. bool drawTitleTextOnLeft)
  53867. {
  53868. const bool isActive = window.isActiveWindow();
  53869. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53870. 0.0f, 0.0f,
  53871. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53872. 0.0f, (float) h, false));
  53873. g.fillAll();
  53874. Font font (h * 0.65f, Font::bold);
  53875. g.setFont (font);
  53876. int textW = font.getStringWidth (window.getName());
  53877. int iconW = 0;
  53878. int iconH = 0;
  53879. if (icon != 0)
  53880. {
  53881. iconH = (int) font.getHeight();
  53882. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53883. }
  53884. textW = jmin (titleSpaceW, textW + iconW);
  53885. int textX = drawTitleTextOnLeft ? titleSpaceX
  53886. : jmax (titleSpaceX, (w - textW) / 2);
  53887. if (textX + textW > titleSpaceX + titleSpaceW)
  53888. textX = titleSpaceX + titleSpaceW - textW;
  53889. if (icon != 0)
  53890. {
  53891. g.setOpacity (isActive ? 1.0f : 0.6f);
  53892. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53893. RectanglePlacement::centred, false);
  53894. textX += iconW;
  53895. textW -= iconW;
  53896. }
  53897. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53898. g.setColour (findColour (DocumentWindow::textColourId));
  53899. else
  53900. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53901. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53902. }
  53903. class GlassWindowButton : public Button
  53904. {
  53905. public:
  53906. GlassWindowButton (const String& name, const Colour& col,
  53907. const Path& normalShape_,
  53908. const Path& toggledShape_) throw()
  53909. : Button (name),
  53910. colour (col),
  53911. normalShape (normalShape_),
  53912. toggledShape (toggledShape_)
  53913. {
  53914. }
  53915. ~GlassWindowButton()
  53916. {
  53917. }
  53918. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53919. {
  53920. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53921. if (! isEnabled())
  53922. alpha *= 0.5f;
  53923. float x = 0, y = 0, diam;
  53924. if (getWidth() < getHeight())
  53925. {
  53926. diam = (float) getWidth();
  53927. y = (getHeight() - getWidth()) * 0.5f;
  53928. }
  53929. else
  53930. {
  53931. diam = (float) getHeight();
  53932. y = (getWidth() - getHeight()) * 0.5f;
  53933. }
  53934. x += diam * 0.05f;
  53935. y += diam * 0.05f;
  53936. diam *= 0.9f;
  53937. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53938. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53939. g.fillEllipse (x, y, diam, diam);
  53940. x += 2.0f;
  53941. y += 2.0f;
  53942. diam -= 4.0f;
  53943. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53944. Path& p = getToggleState() ? toggledShape : normalShape;
  53945. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53946. diam * 0.4f, diam * 0.4f, true));
  53947. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53948. g.fillPath (p, t);
  53949. }
  53950. private:
  53951. Colour colour;
  53952. Path normalShape, toggledShape;
  53953. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53954. };
  53955. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53956. {
  53957. Path shape;
  53958. const float crossThickness = 0.25f;
  53959. if (buttonType == DocumentWindow::closeButton)
  53960. {
  53961. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53962. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53963. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53964. }
  53965. else if (buttonType == DocumentWindow::minimiseButton)
  53966. {
  53967. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53968. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53969. }
  53970. else if (buttonType == DocumentWindow::maximiseButton)
  53971. {
  53972. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53973. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53974. Path fullscreenShape;
  53975. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53976. fullscreenShape.lineTo (0.0f, 100.0f);
  53977. fullscreenShape.lineTo (0.0f, 0.0f);
  53978. fullscreenShape.lineTo (100.0f, 0.0f);
  53979. fullscreenShape.lineTo (100.0f, 45.0f);
  53980. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53981. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53982. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53983. }
  53984. jassertfalse;
  53985. return 0;
  53986. }
  53987. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53988. int titleBarX,
  53989. int titleBarY,
  53990. int titleBarW,
  53991. int titleBarH,
  53992. Button* minimiseButton,
  53993. Button* maximiseButton,
  53994. Button* closeButton,
  53995. bool positionTitleBarButtonsOnLeft)
  53996. {
  53997. const int buttonW = titleBarH - titleBarH / 8;
  53998. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53999. : titleBarX + titleBarW - buttonW - buttonW / 4;
  54000. if (closeButton != 0)
  54001. {
  54002. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54003. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  54004. }
  54005. if (positionTitleBarButtonsOnLeft)
  54006. swapVariables (minimiseButton, maximiseButton);
  54007. if (maximiseButton != 0)
  54008. {
  54009. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54010. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54011. }
  54012. if (minimiseButton != 0)
  54013. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54014. }
  54015. int LookAndFeel::getDefaultMenuBarHeight()
  54016. {
  54017. return 24;
  54018. }
  54019. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  54020. {
  54021. return new DropShadower (0.4f, 1, 5, 10);
  54022. }
  54023. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  54024. int w, int h,
  54025. bool /*isVerticalBar*/,
  54026. bool isMouseOver,
  54027. bool isMouseDragging)
  54028. {
  54029. float alpha = 0.5f;
  54030. if (isMouseOver || isMouseDragging)
  54031. {
  54032. g.fillAll (Colour (0x190000ff));
  54033. alpha = 1.0f;
  54034. }
  54035. const float cx = w * 0.5f;
  54036. const float cy = h * 0.5f;
  54037. const float cr = jmin (w, h) * 0.4f;
  54038. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  54039. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  54040. true));
  54041. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  54042. }
  54043. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  54044. const String& text,
  54045. const Justification& position,
  54046. GroupComponent& group)
  54047. {
  54048. const float textH = 15.0f;
  54049. const float indent = 3.0f;
  54050. const float textEdgeGap = 4.0f;
  54051. float cs = 5.0f;
  54052. Font f (textH);
  54053. Path p;
  54054. float x = indent;
  54055. float y = f.getAscent() - 3.0f;
  54056. float w = jmax (0.0f, width - x * 2.0f);
  54057. float h = jmax (0.0f, height - y - indent);
  54058. cs = jmin (cs, w * 0.5f, h * 0.5f);
  54059. const float cs2 = 2.0f * cs;
  54060. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  54061. float textX = cs + textEdgeGap;
  54062. if (position.testFlags (Justification::horizontallyCentred))
  54063. textX = cs + (w - cs2 - textW) * 0.5f;
  54064. else if (position.testFlags (Justification::right))
  54065. textX = w - cs - textW - textEdgeGap;
  54066. p.startNewSubPath (x + textX + textW, y);
  54067. p.lineTo (x + w - cs, y);
  54068. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  54069. p.lineTo (x + w, y + h - cs);
  54070. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54071. p.lineTo (x + cs, y + h);
  54072. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54073. p.lineTo (x, y + cs);
  54074. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54075. p.lineTo (x + textX, y);
  54076. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  54077. g.setColour (group.findColour (GroupComponent::outlineColourId)
  54078. .withMultipliedAlpha (alpha));
  54079. g.strokePath (p, PathStrokeType (2.0f));
  54080. g.setColour (group.findColour (GroupComponent::textColourId)
  54081. .withMultipliedAlpha (alpha));
  54082. g.setFont (f);
  54083. g.drawText (text,
  54084. roundToInt (x + textX), 0,
  54085. roundToInt (textW),
  54086. roundToInt (textH),
  54087. Justification::centred, true);
  54088. }
  54089. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  54090. {
  54091. return 1 + tabDepth / 3;
  54092. }
  54093. int LookAndFeel::getTabButtonSpaceAroundImage()
  54094. {
  54095. return 4;
  54096. }
  54097. void LookAndFeel::createTabButtonShape (Path& p,
  54098. int width, int height,
  54099. int /*tabIndex*/,
  54100. const String& /*text*/,
  54101. Button& /*button*/,
  54102. TabbedButtonBar::Orientation orientation,
  54103. const bool /*isMouseOver*/,
  54104. const bool /*isMouseDown*/,
  54105. const bool /*isFrontTab*/)
  54106. {
  54107. const float w = (float) width;
  54108. const float h = (float) height;
  54109. float length = w;
  54110. float depth = h;
  54111. if (orientation == TabbedButtonBar::TabsAtLeft
  54112. || orientation == TabbedButtonBar::TabsAtRight)
  54113. {
  54114. swapVariables (length, depth);
  54115. }
  54116. const float indent = (float) getTabButtonOverlap ((int) depth);
  54117. const float overhang = 4.0f;
  54118. if (orientation == TabbedButtonBar::TabsAtLeft)
  54119. {
  54120. p.startNewSubPath (w, 0.0f);
  54121. p.lineTo (0.0f, indent);
  54122. p.lineTo (0.0f, h - indent);
  54123. p.lineTo (w, h);
  54124. p.lineTo (w + overhang, h + overhang);
  54125. p.lineTo (w + overhang, -overhang);
  54126. }
  54127. else if (orientation == TabbedButtonBar::TabsAtRight)
  54128. {
  54129. p.startNewSubPath (0.0f, 0.0f);
  54130. p.lineTo (w, indent);
  54131. p.lineTo (w, h - indent);
  54132. p.lineTo (0.0f, h);
  54133. p.lineTo (-overhang, h + overhang);
  54134. p.lineTo (-overhang, -overhang);
  54135. }
  54136. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54137. {
  54138. p.startNewSubPath (0.0f, 0.0f);
  54139. p.lineTo (indent, h);
  54140. p.lineTo (w - indent, h);
  54141. p.lineTo (w, 0.0f);
  54142. p.lineTo (w + overhang, -overhang);
  54143. p.lineTo (-overhang, -overhang);
  54144. }
  54145. else
  54146. {
  54147. p.startNewSubPath (0.0f, h);
  54148. p.lineTo (indent, 0.0f);
  54149. p.lineTo (w - indent, 0.0f);
  54150. p.lineTo (w, h);
  54151. p.lineTo (w + overhang, h + overhang);
  54152. p.lineTo (-overhang, h + overhang);
  54153. }
  54154. p.closeSubPath();
  54155. p = p.createPathWithRoundedCorners (3.0f);
  54156. }
  54157. void LookAndFeel::fillTabButtonShape (Graphics& g,
  54158. const Path& path,
  54159. const Colour& preferredColour,
  54160. int /*tabIndex*/,
  54161. const String& /*text*/,
  54162. Button& button,
  54163. TabbedButtonBar::Orientation /*orientation*/,
  54164. const bool /*isMouseOver*/,
  54165. const bool /*isMouseDown*/,
  54166. const bool isFrontTab)
  54167. {
  54168. g.setColour (isFrontTab ? preferredColour
  54169. : preferredColour.withMultipliedAlpha (0.9f));
  54170. g.fillPath (path);
  54171. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54172. : TabbedButtonBar::tabOutlineColourId, false)
  54173. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54174. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54175. }
  54176. void LookAndFeel::drawTabButtonText (Graphics& g,
  54177. int x, int y, int w, int h,
  54178. const Colour& preferredBackgroundColour,
  54179. int /*tabIndex*/,
  54180. const String& text,
  54181. Button& button,
  54182. TabbedButtonBar::Orientation orientation,
  54183. const bool isMouseOver,
  54184. const bool isMouseDown,
  54185. const bool isFrontTab)
  54186. {
  54187. int length = w;
  54188. int depth = h;
  54189. if (orientation == TabbedButtonBar::TabsAtLeft
  54190. || orientation == TabbedButtonBar::TabsAtRight)
  54191. {
  54192. swapVariables (length, depth);
  54193. }
  54194. Font font (depth * 0.6f);
  54195. font.setUnderline (button.hasKeyboardFocus (false));
  54196. GlyphArrangement textLayout;
  54197. textLayout.addFittedText (font, text.trim(),
  54198. 0.0f, 0.0f, (float) length, (float) depth,
  54199. Justification::centred,
  54200. jmax (1, depth / 12));
  54201. AffineTransform transform;
  54202. if (orientation == TabbedButtonBar::TabsAtLeft)
  54203. {
  54204. transform = transform.rotated (float_Pi * -0.5f)
  54205. .translated ((float) x, (float) (y + h));
  54206. }
  54207. else if (orientation == TabbedButtonBar::TabsAtRight)
  54208. {
  54209. transform = transform.rotated (float_Pi * 0.5f)
  54210. .translated ((float) (x + w), (float) y);
  54211. }
  54212. else
  54213. {
  54214. transform = transform.translated ((float) x, (float) y);
  54215. }
  54216. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54217. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54218. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54219. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54220. else
  54221. g.setColour (preferredBackgroundColour.contrasting());
  54222. if (! (isMouseOver || isMouseDown))
  54223. g.setOpacity (0.8f);
  54224. if (! button.isEnabled())
  54225. g.setOpacity (0.3f);
  54226. textLayout.draw (g, transform);
  54227. }
  54228. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54229. const String& text,
  54230. int tabDepth,
  54231. Button&)
  54232. {
  54233. Font f (tabDepth * 0.6f);
  54234. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54235. }
  54236. void LookAndFeel::drawTabButton (Graphics& g,
  54237. int w, int h,
  54238. const Colour& preferredColour,
  54239. int tabIndex,
  54240. const String& text,
  54241. Button& button,
  54242. TabbedButtonBar::Orientation orientation,
  54243. const bool isMouseOver,
  54244. const bool isMouseDown,
  54245. const bool isFrontTab)
  54246. {
  54247. int length = w;
  54248. int depth = h;
  54249. if (orientation == TabbedButtonBar::TabsAtLeft
  54250. || orientation == TabbedButtonBar::TabsAtRight)
  54251. {
  54252. swapVariables (length, depth);
  54253. }
  54254. Path tabShape;
  54255. createTabButtonShape (tabShape, w, h,
  54256. tabIndex, text, button, orientation,
  54257. isMouseOver, isMouseDown, isFrontTab);
  54258. fillTabButtonShape (g, tabShape, preferredColour,
  54259. tabIndex, text, button, orientation,
  54260. isMouseOver, isMouseDown, isFrontTab);
  54261. const int indent = getTabButtonOverlap (depth);
  54262. int x = 0, y = 0;
  54263. if (orientation == TabbedButtonBar::TabsAtLeft
  54264. || orientation == TabbedButtonBar::TabsAtRight)
  54265. {
  54266. y += indent;
  54267. h -= indent * 2;
  54268. }
  54269. else
  54270. {
  54271. x += indent;
  54272. w -= indent * 2;
  54273. }
  54274. drawTabButtonText (g, x, y, w, h, preferredColour,
  54275. tabIndex, text, button, orientation,
  54276. isMouseOver, isMouseDown, isFrontTab);
  54277. }
  54278. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54279. int w, int h,
  54280. TabbedButtonBar& tabBar,
  54281. TabbedButtonBar::Orientation orientation)
  54282. {
  54283. const float shadowSize = 0.2f;
  54284. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54285. Rectangle<int> shadowRect;
  54286. if (orientation == TabbedButtonBar::TabsAtLeft)
  54287. {
  54288. x1 = (float) w;
  54289. x2 = w * (1.0f - shadowSize);
  54290. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54291. }
  54292. else if (orientation == TabbedButtonBar::TabsAtRight)
  54293. {
  54294. x2 = w * shadowSize;
  54295. shadowRect.setBounds (0, 0, (int) x2, h);
  54296. }
  54297. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54298. {
  54299. y2 = h * shadowSize;
  54300. shadowRect.setBounds (0, 0, w, (int) y2);
  54301. }
  54302. else
  54303. {
  54304. y1 = (float) h;
  54305. y2 = h * (1.0f - shadowSize);
  54306. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54307. }
  54308. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54309. Colours::transparentBlack, x2, y2, false));
  54310. shadowRect.expand (2, 2);
  54311. g.fillRect (shadowRect);
  54312. g.setColour (Colour (0x80000000));
  54313. if (orientation == TabbedButtonBar::TabsAtLeft)
  54314. {
  54315. g.fillRect (w - 1, 0, 1, h);
  54316. }
  54317. else if (orientation == TabbedButtonBar::TabsAtRight)
  54318. {
  54319. g.fillRect (0, 0, 1, h);
  54320. }
  54321. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54322. {
  54323. g.fillRect (0, 0, w, 1);
  54324. }
  54325. else
  54326. {
  54327. g.fillRect (0, h - 1, w, 1);
  54328. }
  54329. }
  54330. Button* LookAndFeel::createTabBarExtrasButton()
  54331. {
  54332. const float thickness = 7.0f;
  54333. const float indent = 22.0f;
  54334. Path p;
  54335. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54336. DrawablePath ellipse;
  54337. ellipse.setPath (p);
  54338. ellipse.setFill (Colour (0x99ffffff));
  54339. p.clear();
  54340. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54341. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54342. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54343. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54344. p.setUsingNonZeroWinding (false);
  54345. DrawablePath dp;
  54346. dp.setPath (p);
  54347. dp.setFill (Colour (0x59000000));
  54348. DrawableComposite normalImage;
  54349. normalImage.addAndMakeVisible (ellipse.createCopy());
  54350. normalImage.addAndMakeVisible (dp.createCopy());
  54351. dp.setFill (Colour (0xcc000000));
  54352. DrawableComposite overImage;
  54353. overImage.addAndMakeVisible (ellipse.createCopy());
  54354. overImage.addAndMakeVisible (dp.createCopy());
  54355. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54356. db->setImages (&normalImage, &overImage, 0);
  54357. return db;
  54358. }
  54359. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54360. {
  54361. g.fillAll (Colours::white);
  54362. const int w = header.getWidth();
  54363. const int h = header.getHeight();
  54364. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54365. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54366. false));
  54367. g.fillRect (0, h / 2, w, h);
  54368. g.setColour (Colour (0x33000000));
  54369. g.fillRect (0, h - 1, w, 1);
  54370. for (int i = header.getNumColumns (true); --i >= 0;)
  54371. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54372. }
  54373. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54374. int width, int height,
  54375. bool isMouseOver, bool isMouseDown,
  54376. int columnFlags)
  54377. {
  54378. if (isMouseDown)
  54379. g.fillAll (Colour (0x8899aadd));
  54380. else if (isMouseOver)
  54381. g.fillAll (Colour (0x5599aadd));
  54382. int rightOfText = width - 4;
  54383. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54384. {
  54385. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54386. const float bottom = height - top;
  54387. const float w = height * 0.5f;
  54388. const float x = rightOfText - (w * 1.25f);
  54389. rightOfText = (int) x;
  54390. Path sortArrow;
  54391. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54392. g.setColour (Colour (0x99000000));
  54393. g.fillPath (sortArrow);
  54394. }
  54395. g.setColour (Colours::black);
  54396. g.setFont (height * 0.5f, Font::bold);
  54397. const int textX = 4;
  54398. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54399. }
  54400. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54401. {
  54402. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54403. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54404. background.darker (0.1f),
  54405. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54406. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54407. false));
  54408. g.fillAll();
  54409. }
  54410. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54411. {
  54412. return createTabBarExtrasButton();
  54413. }
  54414. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54415. bool isMouseOver, bool isMouseDown,
  54416. ToolbarItemComponent& component)
  54417. {
  54418. if (isMouseDown)
  54419. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54420. else if (isMouseOver)
  54421. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54422. }
  54423. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54424. const String& text, ToolbarItemComponent& component)
  54425. {
  54426. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54427. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54428. const float fontHeight = jmin (14.0f, height * 0.85f);
  54429. g.setFont (fontHeight);
  54430. g.drawFittedText (text,
  54431. x, y, width, height,
  54432. Justification::centred,
  54433. jmax (1, height / (int) fontHeight));
  54434. }
  54435. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54436. bool isOpen, int width, int height)
  54437. {
  54438. const int buttonSize = (height * 3) / 4;
  54439. const int buttonIndent = (height - buttonSize) / 2;
  54440. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54441. const int textX = buttonIndent * 2 + buttonSize + 2;
  54442. g.setColour (Colours::black);
  54443. g.setFont (height * 0.7f, Font::bold);
  54444. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54445. }
  54446. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54447. PropertyComponent&)
  54448. {
  54449. g.setColour (Colour (0x66ffffff));
  54450. g.fillRect (0, 0, width, height - 1);
  54451. }
  54452. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54453. PropertyComponent& component)
  54454. {
  54455. g.setColour (Colours::black);
  54456. if (! component.isEnabled())
  54457. g.setOpacity (0.6f);
  54458. g.setFont (jmin (height, 24) * 0.65f);
  54459. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54460. g.drawFittedText (component.getName(),
  54461. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54462. Justification::centredLeft, 2);
  54463. }
  54464. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54465. {
  54466. return Rectangle<int> (component.getWidth() / 3, 1,
  54467. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54468. }
  54469. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54470. {
  54471. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54472. {
  54473. Graphics g2 (content);
  54474. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54475. g2.fillPath (path);
  54476. g2.setColour (Colours::white.withAlpha (0.8f));
  54477. g2.strokePath (path, PathStrokeType (2.0f));
  54478. }
  54479. DropShadowEffect shadow;
  54480. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54481. shadow.applyEffect (content, g, 1.0f);
  54482. }
  54483. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54484. const String& instructions,
  54485. GlyphArrangement& text,
  54486. int width)
  54487. {
  54488. text.clear();
  54489. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54490. 8.0f, 22.0f, width - 16.0f,
  54491. Justification::centred);
  54492. text.addJustifiedText (Font (14.0f), instructions,
  54493. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54494. Justification::centred);
  54495. }
  54496. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54497. const String& filename, Image* icon,
  54498. const String& fileSizeDescription,
  54499. const String& fileTimeDescription,
  54500. const bool isDirectory,
  54501. const bool isItemSelected,
  54502. const int /*itemIndex*/,
  54503. DirectoryContentsDisplayComponent&)
  54504. {
  54505. if (isItemSelected)
  54506. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54507. const int x = 32;
  54508. g.setColour (Colours::black);
  54509. if (icon != 0 && icon->isValid())
  54510. {
  54511. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54512. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54513. false);
  54514. }
  54515. else
  54516. {
  54517. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54518. : getDefaultDocumentFileImage();
  54519. if (d != 0)
  54520. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54521. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54522. }
  54523. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54524. g.setFont (height * 0.7f);
  54525. if (width > 450 && ! isDirectory)
  54526. {
  54527. const int sizeX = roundToInt (width * 0.7f);
  54528. const int dateX = roundToInt (width * 0.8f);
  54529. g.drawFittedText (filename,
  54530. x, 0, sizeX - x, height,
  54531. Justification::centredLeft, 1);
  54532. g.setFont (height * 0.5f);
  54533. g.setColour (Colours::darkgrey);
  54534. if (! isDirectory)
  54535. {
  54536. g.drawFittedText (fileSizeDescription,
  54537. sizeX, 0, dateX - sizeX - 8, height,
  54538. Justification::centredRight, 1);
  54539. g.drawFittedText (fileTimeDescription,
  54540. dateX, 0, width - 8 - dateX, height,
  54541. Justification::centredRight, 1);
  54542. }
  54543. }
  54544. else
  54545. {
  54546. g.drawFittedText (filename,
  54547. x, 0, width - x, height,
  54548. Justification::centredLeft, 1);
  54549. }
  54550. }
  54551. Button* LookAndFeel::createFileBrowserGoUpButton()
  54552. {
  54553. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54554. Path arrowPath;
  54555. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54556. DrawablePath arrowImage;
  54557. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54558. arrowImage.setPath (arrowPath);
  54559. goUpButton->setImages (&arrowImage);
  54560. return goUpButton;
  54561. }
  54562. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54563. DirectoryContentsDisplayComponent* fileListComponent,
  54564. FilePreviewComponent* previewComp,
  54565. ComboBox* currentPathBox,
  54566. TextEditor* filenameBox,
  54567. Button* goUpButton)
  54568. {
  54569. const int x = 8;
  54570. int w = browserComp.getWidth() - x - x;
  54571. if (previewComp != 0)
  54572. {
  54573. const int previewWidth = w / 3;
  54574. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54575. w -= previewWidth + 4;
  54576. }
  54577. int y = 4;
  54578. const int controlsHeight = 22;
  54579. const int bottomSectionHeight = controlsHeight + 8;
  54580. const int upButtonWidth = 50;
  54581. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54582. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54583. y += controlsHeight + 4;
  54584. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54585. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54586. y = listAsComp->getBottom() + 4;
  54587. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54588. }
  54589. // Pulls a drawable out of compressed valuetree data..
  54590. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54591. {
  54592. MemoryInputStream m (data, numBytes, false);
  54593. GZIPDecompressorInputStream gz (m);
  54594. ValueTree drawable (ValueTree::readFromStream (gz));
  54595. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54596. }
  54597. const Drawable* LookAndFeel::getDefaultFolderImage()
  54598. {
  54599. if (folderImage == 0)
  54600. {
  54601. static const unsigned char drawableData[] =
  54602. { 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,
  54603. 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,
  54604. 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,
  54605. 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,
  54606. 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,
  54607. 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,
  54608. 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,
  54609. 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,
  54610. 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,
  54611. 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,
  54612. 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,
  54613. 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,
  54614. 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,
  54615. 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,
  54616. 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 };
  54617. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54618. }
  54619. return folderImage;
  54620. }
  54621. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54622. {
  54623. if (documentImage == 0)
  54624. {
  54625. static const unsigned char drawableData[] =
  54626. { 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,
  54627. 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,
  54628. 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,
  54629. 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,
  54630. 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,
  54631. 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,
  54632. 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,
  54633. 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,
  54634. 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,
  54635. 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,
  54636. 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,
  54637. 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,
  54638. 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,
  54639. 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,
  54640. 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,
  54641. 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,
  54642. 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,
  54643. 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,
  54644. 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,
  54645. 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,
  54646. 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,
  54647. 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,
  54648. 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 };
  54649. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54650. }
  54651. return documentImage;
  54652. }
  54653. void LookAndFeel::playAlertSound()
  54654. {
  54655. PlatformUtilities::beep();
  54656. }
  54657. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54658. {
  54659. g.setColour (Colours::white.withAlpha (0.7f));
  54660. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54661. g.setColour (Colours::black.withAlpha (0.2f));
  54662. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54663. const int totalBlocks = 7;
  54664. const int numBlocks = roundToInt (totalBlocks * level);
  54665. const float w = (width - 6.0f) / (float) totalBlocks;
  54666. for (int i = 0; i < totalBlocks; ++i)
  54667. {
  54668. if (i >= numBlocks)
  54669. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54670. else
  54671. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54672. : Colours::red);
  54673. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54674. }
  54675. }
  54676. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54677. {
  54678. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54679. if (keyDescription.isNotEmpty())
  54680. {
  54681. if (button.isEnabled())
  54682. {
  54683. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54684. g.fillAll (textColour.withAlpha (alpha));
  54685. g.setOpacity (0.3f);
  54686. g.drawBevel (0, 0, width, height, 2);
  54687. }
  54688. g.setColour (textColour);
  54689. g.setFont (height * 0.6f);
  54690. g.drawFittedText (keyDescription,
  54691. 3, 0, width - 6, height,
  54692. Justification::centred, 1);
  54693. }
  54694. else
  54695. {
  54696. const float thickness = 7.0f;
  54697. const float indent = 22.0f;
  54698. Path p;
  54699. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54700. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54701. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54702. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54703. p.setUsingNonZeroWinding (false);
  54704. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54705. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54706. }
  54707. if (button.hasKeyboardFocus (false))
  54708. {
  54709. g.setColour (textColour.withAlpha (0.4f));
  54710. g.drawRect (0, 0, width, height);
  54711. }
  54712. }
  54713. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54714. float x, float y, float w, float h,
  54715. float maxCornerSize,
  54716. const Colour& baseColour,
  54717. const float strokeWidth,
  54718. const bool flatOnLeft,
  54719. const bool flatOnRight,
  54720. const bool flatOnTop,
  54721. const bool flatOnBottom) throw()
  54722. {
  54723. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54724. return;
  54725. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54726. Path outline;
  54727. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54728. ! (flatOnLeft || flatOnTop),
  54729. ! (flatOnRight || flatOnTop),
  54730. ! (flatOnLeft || flatOnBottom),
  54731. ! (flatOnRight || flatOnBottom));
  54732. ColourGradient cg (baseColour, 0.0f, y,
  54733. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54734. false);
  54735. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54736. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54737. g.setGradientFill (cg);
  54738. g.fillPath (outline);
  54739. g.setColour (Colour (0x80000000));
  54740. g.strokePath (outline, PathStrokeType (strokeWidth));
  54741. }
  54742. void LookAndFeel::drawGlassSphere (Graphics& g,
  54743. const float x, const float y,
  54744. const float diameter,
  54745. const Colour& colour,
  54746. const float outlineThickness) throw()
  54747. {
  54748. if (diameter <= outlineThickness)
  54749. return;
  54750. Path p;
  54751. p.addEllipse (x, y, diameter, diameter);
  54752. {
  54753. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54754. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54755. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54756. g.setGradientFill (cg);
  54757. g.fillPath (p);
  54758. }
  54759. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54760. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54761. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54762. ColourGradient cg (Colours::transparentBlack,
  54763. x + diameter * 0.5f, y + diameter * 0.5f,
  54764. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54765. x, y + diameter * 0.5f, true);
  54766. cg.addColour (0.7, Colours::transparentBlack);
  54767. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54768. g.setGradientFill (cg);
  54769. g.fillPath (p);
  54770. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54771. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54772. }
  54773. void LookAndFeel::drawGlassPointer (Graphics& g,
  54774. const float x, const float y,
  54775. const float diameter,
  54776. const Colour& colour, const float outlineThickness,
  54777. const int direction) throw()
  54778. {
  54779. if (diameter <= outlineThickness)
  54780. return;
  54781. Path p;
  54782. p.startNewSubPath (x + diameter * 0.5f, y);
  54783. p.lineTo (x + diameter, y + diameter * 0.6f);
  54784. p.lineTo (x + diameter, y + diameter);
  54785. p.lineTo (x, y + diameter);
  54786. p.lineTo (x, y + diameter * 0.6f);
  54787. p.closeSubPath();
  54788. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54789. {
  54790. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54791. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54792. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54793. g.setGradientFill (cg);
  54794. g.fillPath (p);
  54795. }
  54796. ColourGradient cg (Colours::transparentBlack,
  54797. x + diameter * 0.5f, y + diameter * 0.5f,
  54798. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54799. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54800. cg.addColour (0.5, Colours::transparentBlack);
  54801. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54802. g.setGradientFill (cg);
  54803. g.fillPath (p);
  54804. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54805. g.strokePath (p, PathStrokeType (outlineThickness));
  54806. }
  54807. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54808. const float x, const float y,
  54809. const float width, const float height,
  54810. const Colour& colour,
  54811. const float outlineThickness,
  54812. const float cornerSize,
  54813. const bool flatOnLeft,
  54814. const bool flatOnRight,
  54815. const bool flatOnTop,
  54816. const bool flatOnBottom) throw()
  54817. {
  54818. if (width <= outlineThickness || height <= outlineThickness)
  54819. return;
  54820. const int intX = (int) x;
  54821. const int intY = (int) y;
  54822. const int intW = (int) width;
  54823. const int intH = (int) height;
  54824. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54825. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54826. const int intEdge = (int) edgeBlurRadius;
  54827. Path outline;
  54828. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54829. ! (flatOnLeft || flatOnTop),
  54830. ! (flatOnRight || flatOnTop),
  54831. ! (flatOnLeft || flatOnBottom),
  54832. ! (flatOnRight || flatOnBottom));
  54833. {
  54834. ColourGradient cg (colour.darker (0.2f), 0, y,
  54835. colour.darker (0.2f), 0, y + height, false);
  54836. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54837. cg.addColour (0.4, colour);
  54838. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54839. g.setGradientFill (cg);
  54840. g.fillPath (outline);
  54841. }
  54842. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54843. colour.darker (0.2f), x, y + height * 0.5f, true);
  54844. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54845. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54846. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54847. {
  54848. g.saveState();
  54849. g.setGradientFill (cg);
  54850. g.reduceClipRegion (intX, intY, intEdge, intH);
  54851. g.fillPath (outline);
  54852. g.restoreState();
  54853. }
  54854. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54855. {
  54856. cg.point1.setX (x + width - edgeBlurRadius);
  54857. cg.point2.setX (x + width);
  54858. g.saveState();
  54859. g.setGradientFill (cg);
  54860. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54861. g.fillPath (outline);
  54862. g.restoreState();
  54863. }
  54864. {
  54865. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54866. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54867. Path highlight;
  54868. LookAndFeelHelpers::createRoundedPath (highlight,
  54869. x + leftIndent,
  54870. y + cs * 0.1f,
  54871. width - (leftIndent + rightIndent),
  54872. height * 0.4f, cs * 0.4f,
  54873. ! (flatOnLeft || flatOnTop),
  54874. ! (flatOnRight || flatOnTop),
  54875. ! (flatOnLeft || flatOnBottom),
  54876. ! (flatOnRight || flatOnBottom));
  54877. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54878. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54879. g.fillPath (highlight);
  54880. }
  54881. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54882. g.strokePath (outline, PathStrokeType (outlineThickness));
  54883. }
  54884. END_JUCE_NAMESPACE
  54885. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54886. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54887. BEGIN_JUCE_NAMESPACE
  54888. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54889. {
  54890. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54891. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54892. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54893. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54894. setColour (Slider::thumbColourId, Colours::white);
  54895. setColour (Slider::trackColourId, Colour (0x7f000000));
  54896. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54897. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54898. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54899. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54900. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54901. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54902. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54903. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54904. }
  54905. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54906. {
  54907. }
  54908. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54909. Button& button,
  54910. const Colour& backgroundColour,
  54911. bool isMouseOverButton,
  54912. bool isButtonDown)
  54913. {
  54914. const int width = button.getWidth();
  54915. const int height = button.getHeight();
  54916. const float indent = 2.0f;
  54917. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54918. roundToInt (height * 0.4f));
  54919. Path p;
  54920. p.addRoundedRectangle (indent, indent,
  54921. width - indent * 2.0f,
  54922. height - indent * 2.0f,
  54923. (float) cornerSize);
  54924. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54925. if (isMouseOverButton)
  54926. {
  54927. if (isButtonDown)
  54928. bc = bc.brighter();
  54929. else if (bc.getBrightness() > 0.5f)
  54930. bc = bc.darker (0.1f);
  54931. else
  54932. bc = bc.brighter (0.1f);
  54933. }
  54934. g.setColour (bc);
  54935. g.fillPath (p);
  54936. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54937. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54938. }
  54939. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54940. Component& /*component*/,
  54941. float x, float y, float w, float h,
  54942. const bool ticked,
  54943. const bool isEnabled,
  54944. const bool /*isMouseOverButton*/,
  54945. const bool isButtonDown)
  54946. {
  54947. Path box;
  54948. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54949. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54950. : Colours::lightgrey.withAlpha (0.1f));
  54951. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54952. g.fillPath (box, trans);
  54953. g.setColour (Colours::black.withAlpha (0.6f));
  54954. g.strokePath (box, PathStrokeType (0.9f), trans);
  54955. if (ticked)
  54956. {
  54957. Path tick;
  54958. tick.startNewSubPath (1.5f, 3.0f);
  54959. tick.lineTo (3.0f, 6.0f);
  54960. tick.lineTo (6.0f, 0.0f);
  54961. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54962. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54963. }
  54964. }
  54965. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54966. ToggleButton& button,
  54967. bool isMouseOverButton,
  54968. bool isButtonDown)
  54969. {
  54970. if (button.hasKeyboardFocus (true))
  54971. {
  54972. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54973. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54974. }
  54975. const int tickWidth = jmin (20, button.getHeight() - 4);
  54976. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54977. (float) tickWidth, (float) tickWidth,
  54978. button.getToggleState(),
  54979. button.isEnabled(),
  54980. isMouseOverButton,
  54981. isButtonDown);
  54982. g.setColour (button.findColour (ToggleButton::textColourId));
  54983. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54984. if (! button.isEnabled())
  54985. g.setOpacity (0.5f);
  54986. const int textX = tickWidth + 5;
  54987. g.drawFittedText (button.getButtonText(),
  54988. textX, 4,
  54989. button.getWidth() - textX - 2, button.getHeight() - 8,
  54990. Justification::centredLeft, 10);
  54991. }
  54992. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54993. int width, int height,
  54994. double progress, const String& textToShow)
  54995. {
  54996. if (progress < 0 || progress >= 1.0)
  54997. {
  54998. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54999. }
  55000. else
  55001. {
  55002. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  55003. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  55004. g.fillAll (background);
  55005. g.setColour (foreground);
  55006. g.fillRect (1, 1,
  55007. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  55008. height - 2);
  55009. if (textToShow.isNotEmpty())
  55010. {
  55011. g.setColour (Colour::contrasting (background, foreground));
  55012. g.setFont (height * 0.6f);
  55013. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  55014. }
  55015. }
  55016. }
  55017. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  55018. ScrollBar& bar,
  55019. int width, int height,
  55020. int buttonDirection,
  55021. bool isScrollbarVertical,
  55022. bool isMouseOverButton,
  55023. bool isButtonDown)
  55024. {
  55025. if (isScrollbarVertical)
  55026. width -= 2;
  55027. else
  55028. height -= 2;
  55029. Path p;
  55030. if (buttonDirection == 0)
  55031. p.addTriangle (width * 0.5f, height * 0.2f,
  55032. width * 0.1f, height * 0.7f,
  55033. width * 0.9f, height * 0.7f);
  55034. else if (buttonDirection == 1)
  55035. p.addTriangle (width * 0.8f, height * 0.5f,
  55036. width * 0.3f, height * 0.1f,
  55037. width * 0.3f, height * 0.9f);
  55038. else if (buttonDirection == 2)
  55039. p.addTriangle (width * 0.5f, height * 0.8f,
  55040. width * 0.1f, height * 0.3f,
  55041. width * 0.9f, height * 0.3f);
  55042. else if (buttonDirection == 3)
  55043. p.addTriangle (width * 0.2f, height * 0.5f,
  55044. width * 0.7f, height * 0.1f,
  55045. width * 0.7f, height * 0.9f);
  55046. if (isButtonDown)
  55047. g.setColour (Colours::white);
  55048. else if (isMouseOverButton)
  55049. g.setColour (Colours::white.withAlpha (0.7f));
  55050. else
  55051. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  55052. g.fillPath (p);
  55053. g.setColour (Colours::black.withAlpha (0.5f));
  55054. g.strokePath (p, PathStrokeType (0.5f));
  55055. }
  55056. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  55057. ScrollBar& bar,
  55058. int x, int y,
  55059. int width, int height,
  55060. bool isScrollbarVertical,
  55061. int thumbStartPosition,
  55062. int thumbSize,
  55063. bool isMouseOver,
  55064. bool isMouseDown)
  55065. {
  55066. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  55067. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55068. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  55069. if (thumbSize > 0.0f)
  55070. {
  55071. Rectangle<int> thumb;
  55072. if (isScrollbarVertical)
  55073. {
  55074. width -= 2;
  55075. g.fillRect (x + roundToInt (width * 0.35f), y,
  55076. roundToInt (width * 0.3f), height);
  55077. thumb.setBounds (x + 1, thumbStartPosition,
  55078. width - 2, thumbSize);
  55079. }
  55080. else
  55081. {
  55082. height -= 2;
  55083. g.fillRect (x, y + roundToInt (height * 0.35f),
  55084. width, roundToInt (height * 0.3f));
  55085. thumb.setBounds (thumbStartPosition, y + 1,
  55086. thumbSize, height - 2);
  55087. }
  55088. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55089. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  55090. g.fillRect (thumb);
  55091. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  55092. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  55093. if (thumbSize > 16)
  55094. {
  55095. for (int i = 3; --i >= 0;)
  55096. {
  55097. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  55098. g.setColour (Colours::black.withAlpha (0.15f));
  55099. if (isScrollbarVertical)
  55100. {
  55101. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  55102. g.setColour (Colours::white.withAlpha (0.15f));
  55103. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  55104. }
  55105. else
  55106. {
  55107. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  55108. g.setColour (Colours::white.withAlpha (0.15f));
  55109. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  55110. }
  55111. }
  55112. }
  55113. }
  55114. }
  55115. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  55116. {
  55117. return &scrollbarShadow;
  55118. }
  55119. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  55120. {
  55121. g.fillAll (findColour (PopupMenu::backgroundColourId));
  55122. g.setColour (Colours::black.withAlpha (0.6f));
  55123. g.drawRect (0, 0, width, height);
  55124. }
  55125. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  55126. bool, MenuBarComponent& menuBar)
  55127. {
  55128. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  55129. }
  55130. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  55131. {
  55132. if (textEditor.isEnabled())
  55133. {
  55134. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55135. g.drawRect (0, 0, width, height);
  55136. }
  55137. }
  55138. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55139. const bool isButtonDown,
  55140. int buttonX, int buttonY,
  55141. int buttonW, int buttonH,
  55142. ComboBox& box)
  55143. {
  55144. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55145. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55146. : ComboBox::backgroundColourId));
  55147. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55148. g.setColour (box.findColour (ComboBox::outlineColourId));
  55149. g.drawRect (0, 0, width, height);
  55150. const float arrowX = 0.2f;
  55151. const float arrowH = 0.3f;
  55152. if (box.isEnabled())
  55153. {
  55154. Path p;
  55155. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55156. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55157. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55158. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55159. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55160. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55161. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55162. : ComboBox::buttonColourId));
  55163. g.fillPath (p);
  55164. }
  55165. }
  55166. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55167. {
  55168. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55169. f.setHorizontalScale (0.9f);
  55170. return f;
  55171. }
  55172. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55173. {
  55174. Path p;
  55175. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55176. g.setColour (fill);
  55177. g.fillPath (p);
  55178. g.setColour (outline);
  55179. g.strokePath (p, PathStrokeType (0.3f));
  55180. }
  55181. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55182. int x, int y,
  55183. int w, int h,
  55184. float sliderPos,
  55185. float minSliderPos,
  55186. float maxSliderPos,
  55187. const Slider::SliderStyle style,
  55188. Slider& slider)
  55189. {
  55190. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55191. if (style == Slider::LinearBar)
  55192. {
  55193. g.setColour (slider.findColour (Slider::thumbColourId));
  55194. g.fillRect (x, y, (int) sliderPos - x, h);
  55195. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55196. g.drawRect (x, y, (int) sliderPos - x, h);
  55197. }
  55198. else
  55199. {
  55200. g.setColour (slider.findColour (Slider::trackColourId)
  55201. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55202. if (slider.isHorizontal())
  55203. {
  55204. g.fillRect (x, y + roundToInt (h * 0.6f),
  55205. w, roundToInt (h * 0.2f));
  55206. }
  55207. else
  55208. {
  55209. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55210. jmin (4, roundToInt (w * 0.2f)), h);
  55211. }
  55212. float alpha = 0.35f;
  55213. if (slider.isEnabled())
  55214. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55215. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55216. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55217. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55218. {
  55219. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55220. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55221. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55222. fill, outline);
  55223. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55224. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55225. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55226. fill, outline);
  55227. }
  55228. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55229. {
  55230. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55231. minSliderPos - 7.0f, y + h * 0.9f ,
  55232. minSliderPos, y + h * 0.9f,
  55233. fill, outline);
  55234. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55235. maxSliderPos, y + h * 0.9f,
  55236. maxSliderPos + 7.0f, y + h * 0.9f,
  55237. fill, outline);
  55238. }
  55239. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55240. {
  55241. drawTriangle (g, sliderPos, y + h * 0.9f,
  55242. sliderPos - 7.0f, y + h * 0.2f,
  55243. sliderPos + 7.0f, y + h * 0.2f,
  55244. fill, outline);
  55245. }
  55246. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55247. {
  55248. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55249. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55250. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55251. fill, outline);
  55252. }
  55253. }
  55254. }
  55255. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55256. {
  55257. if (isIncrement)
  55258. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55259. else
  55260. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55261. }
  55262. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55263. {
  55264. return &scrollbarShadow;
  55265. }
  55266. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55267. {
  55268. return 8;
  55269. }
  55270. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55271. int w, int h,
  55272. bool isMouseOver,
  55273. bool isMouseDragging)
  55274. {
  55275. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55276. : Colours::darkgrey);
  55277. const float lineThickness = jmin (w, h) * 0.1f;
  55278. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55279. {
  55280. g.drawLine (w * i,
  55281. h + 1.0f,
  55282. w + 1.0f,
  55283. h * i,
  55284. lineThickness);
  55285. }
  55286. }
  55287. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55288. {
  55289. Path shape;
  55290. if (buttonType == DocumentWindow::closeButton)
  55291. {
  55292. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55293. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55294. ShapeButton* const b = new ShapeButton ("close",
  55295. Colour (0x7fff3333),
  55296. Colour (0xd7ff3333),
  55297. Colour (0xf7ff3333));
  55298. b->setShape (shape, true, true, true);
  55299. return b;
  55300. }
  55301. else if (buttonType == DocumentWindow::minimiseButton)
  55302. {
  55303. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55304. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55305. DrawablePath dp;
  55306. dp.setPath (shape);
  55307. dp.setFill (Colours::black.withAlpha (0.3f));
  55308. b->setImages (&dp);
  55309. return b;
  55310. }
  55311. else if (buttonType == DocumentWindow::maximiseButton)
  55312. {
  55313. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55314. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55315. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55316. DrawablePath dp;
  55317. dp.setPath (shape);
  55318. dp.setFill (Colours::black.withAlpha (0.3f));
  55319. b->setImages (&dp);
  55320. return b;
  55321. }
  55322. jassertfalse;
  55323. return 0;
  55324. }
  55325. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55326. int titleBarX,
  55327. int titleBarY,
  55328. int titleBarW,
  55329. int titleBarH,
  55330. Button* minimiseButton,
  55331. Button* maximiseButton,
  55332. Button* closeButton,
  55333. bool positionTitleBarButtonsOnLeft)
  55334. {
  55335. titleBarY += titleBarH / 8;
  55336. titleBarH -= titleBarH / 4;
  55337. const int buttonW = titleBarH;
  55338. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55339. : titleBarX + titleBarW - buttonW - 4;
  55340. if (closeButton != 0)
  55341. {
  55342. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55343. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55344. : -(buttonW + buttonW / 5);
  55345. }
  55346. if (positionTitleBarButtonsOnLeft)
  55347. swapVariables (minimiseButton, maximiseButton);
  55348. if (maximiseButton != 0)
  55349. {
  55350. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55351. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55352. }
  55353. if (minimiseButton != 0)
  55354. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55355. }
  55356. END_JUCE_NAMESPACE
  55357. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55358. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55359. BEGIN_JUCE_NAMESPACE
  55360. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55361. : model (0),
  55362. itemUnderMouse (-1),
  55363. currentPopupIndex (-1),
  55364. topLevelIndexClicked (0),
  55365. lastMouseX (0),
  55366. lastMouseY (0)
  55367. {
  55368. setRepaintsOnMouseActivity (true);
  55369. setWantsKeyboardFocus (false);
  55370. setMouseClickGrabsKeyboardFocus (false);
  55371. setModel (model_);
  55372. }
  55373. MenuBarComponent::~MenuBarComponent()
  55374. {
  55375. setModel (0);
  55376. Desktop::getInstance().removeGlobalMouseListener (this);
  55377. }
  55378. MenuBarModel* MenuBarComponent::getModel() const throw()
  55379. {
  55380. return model;
  55381. }
  55382. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55383. {
  55384. if (model != newModel)
  55385. {
  55386. if (model != 0)
  55387. model->removeListener (this);
  55388. model = newModel;
  55389. if (model != 0)
  55390. model->addListener (this);
  55391. repaint();
  55392. menuBarItemsChanged (0);
  55393. }
  55394. }
  55395. void MenuBarComponent::paint (Graphics& g)
  55396. {
  55397. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55398. getLookAndFeel().drawMenuBarBackground (g,
  55399. getWidth(),
  55400. getHeight(),
  55401. isMouseOverBar,
  55402. *this);
  55403. if (model != 0)
  55404. {
  55405. for (int i = 0; i < menuNames.size(); ++i)
  55406. {
  55407. Graphics::ScopedSaveState ss (g);
  55408. g.setOrigin (xPositions [i], 0);
  55409. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55410. getLookAndFeel().drawMenuBarItem (g,
  55411. xPositions[i + 1] - xPositions[i],
  55412. getHeight(),
  55413. i,
  55414. menuNames[i],
  55415. i == itemUnderMouse,
  55416. i == currentPopupIndex,
  55417. isMouseOverBar,
  55418. *this);
  55419. }
  55420. }
  55421. }
  55422. void MenuBarComponent::resized()
  55423. {
  55424. xPositions.clear();
  55425. int x = 0;
  55426. xPositions.add (x);
  55427. for (int i = 0; i < menuNames.size(); ++i)
  55428. {
  55429. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55430. xPositions.add (x);
  55431. }
  55432. }
  55433. int MenuBarComponent::getItemAt (const int x, const int y)
  55434. {
  55435. for (int i = 0; i < xPositions.size(); ++i)
  55436. if (x >= xPositions[i] && x < xPositions[i + 1])
  55437. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55438. return -1;
  55439. }
  55440. void MenuBarComponent::repaintMenuItem (int index)
  55441. {
  55442. if (isPositiveAndBelow (index, xPositions.size()))
  55443. {
  55444. const int x1 = xPositions [index];
  55445. const int x2 = xPositions [index + 1];
  55446. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55447. }
  55448. }
  55449. void MenuBarComponent::setItemUnderMouse (const int index)
  55450. {
  55451. if (itemUnderMouse != index)
  55452. {
  55453. repaintMenuItem (itemUnderMouse);
  55454. itemUnderMouse = index;
  55455. repaintMenuItem (itemUnderMouse);
  55456. }
  55457. }
  55458. void MenuBarComponent::setOpenItem (int index)
  55459. {
  55460. if (currentPopupIndex != index)
  55461. {
  55462. repaintMenuItem (currentPopupIndex);
  55463. currentPopupIndex = index;
  55464. repaintMenuItem (currentPopupIndex);
  55465. if (index >= 0)
  55466. Desktop::getInstance().addGlobalMouseListener (this);
  55467. else
  55468. Desktop::getInstance().removeGlobalMouseListener (this);
  55469. }
  55470. }
  55471. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55472. {
  55473. setItemUnderMouse (getItemAt (x, y));
  55474. }
  55475. void MenuBarComponent::showMenu (int index)
  55476. {
  55477. if (index != currentPopupIndex)
  55478. {
  55479. PopupMenu::dismissAllActiveMenus();
  55480. menuBarItemsChanged (0);
  55481. setOpenItem (index);
  55482. setItemUnderMouse (index);
  55483. if (index >= 0)
  55484. {
  55485. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55486. menuNames [itemUnderMouse]));
  55487. if (m.lookAndFeel == 0)
  55488. m.setLookAndFeel (&getLookAndFeel());
  55489. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55490. m.showMenuAsync (PopupMenu::Options().withTargetComponent (this)
  55491. .withTargetScreenArea (localAreaToGlobal (itemPos))
  55492. .withMinimumWidth (itemPos.getWidth()),
  55493. ModalCallbackFunction::forComponent (menuBarMenuDismissedCallback, this, index));
  55494. }
  55495. }
  55496. }
  55497. void MenuBarComponent::menuBarMenuDismissedCallback (int result, MenuBarComponent* bar, int topLevelIndex)
  55498. {
  55499. if (bar != 0)
  55500. bar->menuDismissed (topLevelIndex, result);
  55501. }
  55502. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55503. {
  55504. topLevelIndexClicked = topLevelIndex;
  55505. postCommandMessage (itemId);
  55506. }
  55507. void MenuBarComponent::handleCommandMessage (int commandId)
  55508. {
  55509. const Point<int> mousePos (getMouseXYRelative());
  55510. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55511. if (currentPopupIndex == topLevelIndexClicked)
  55512. setOpenItem (-1);
  55513. if (commandId != 0 && model != 0)
  55514. model->menuItemSelected (commandId, topLevelIndexClicked);
  55515. }
  55516. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55517. {
  55518. if (e.eventComponent == this)
  55519. updateItemUnderMouse (e.x, e.y);
  55520. }
  55521. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55522. {
  55523. if (e.eventComponent == this)
  55524. updateItemUnderMouse (e.x, e.y);
  55525. }
  55526. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55527. {
  55528. if (currentPopupIndex < 0)
  55529. {
  55530. const MouseEvent e2 (e.getEventRelativeTo (this));
  55531. updateItemUnderMouse (e2.x, e2.y);
  55532. currentPopupIndex = -2;
  55533. showMenu (itemUnderMouse);
  55534. }
  55535. }
  55536. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55537. {
  55538. const MouseEvent e2 (e.getEventRelativeTo (this));
  55539. const int item = getItemAt (e2.x, e2.y);
  55540. if (item >= 0)
  55541. showMenu (item);
  55542. }
  55543. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55544. {
  55545. const MouseEvent e2 (e.getEventRelativeTo (this));
  55546. updateItemUnderMouse (e2.x, e2.y);
  55547. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55548. {
  55549. setOpenItem (-1);
  55550. PopupMenu::dismissAllActiveMenus();
  55551. }
  55552. }
  55553. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55554. {
  55555. const MouseEvent e2 (e.getEventRelativeTo (this));
  55556. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55557. {
  55558. if (currentPopupIndex >= 0)
  55559. {
  55560. const int item = getItemAt (e2.x, e2.y);
  55561. if (item >= 0)
  55562. showMenu (item);
  55563. }
  55564. else
  55565. {
  55566. updateItemUnderMouse (e2.x, e2.y);
  55567. }
  55568. lastMouseX = e2.x;
  55569. lastMouseY = e2.y;
  55570. }
  55571. }
  55572. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55573. {
  55574. bool used = false;
  55575. const int numMenus = menuNames.size();
  55576. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55577. if (key.isKeyCode (KeyPress::leftKey))
  55578. {
  55579. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55580. used = true;
  55581. }
  55582. else if (key.isKeyCode (KeyPress::rightKey))
  55583. {
  55584. showMenu ((currentIndex + 1) % numMenus);
  55585. used = true;
  55586. }
  55587. return used;
  55588. }
  55589. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55590. {
  55591. StringArray newNames;
  55592. if (model != 0)
  55593. newNames = model->getMenuBarNames();
  55594. if (newNames != menuNames)
  55595. {
  55596. menuNames = newNames;
  55597. repaint();
  55598. resized();
  55599. }
  55600. }
  55601. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55602. const ApplicationCommandTarget::InvocationInfo& info)
  55603. {
  55604. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55605. return;
  55606. for (int i = 0; i < menuNames.size(); ++i)
  55607. {
  55608. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55609. if (menu.containsCommandItem (info.commandID))
  55610. {
  55611. setItemUnderMouse (i);
  55612. startTimer (200);
  55613. break;
  55614. }
  55615. }
  55616. }
  55617. void MenuBarComponent::timerCallback()
  55618. {
  55619. stopTimer();
  55620. const Point<int> mousePos (getMouseXYRelative());
  55621. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55622. }
  55623. END_JUCE_NAMESPACE
  55624. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55625. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55626. BEGIN_JUCE_NAMESPACE
  55627. MenuBarModel::MenuBarModel() throw()
  55628. : manager (0)
  55629. {
  55630. }
  55631. MenuBarModel::~MenuBarModel()
  55632. {
  55633. setApplicationCommandManagerToWatch (0);
  55634. }
  55635. void MenuBarModel::menuItemsChanged()
  55636. {
  55637. triggerAsyncUpdate();
  55638. }
  55639. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55640. {
  55641. if (manager != newManager)
  55642. {
  55643. if (manager != 0)
  55644. manager->removeListener (this);
  55645. manager = newManager;
  55646. if (manager != 0)
  55647. manager->addListener (this);
  55648. }
  55649. }
  55650. void MenuBarModel::addListener (Listener* const newListener) throw()
  55651. {
  55652. listeners.add (newListener);
  55653. }
  55654. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55655. {
  55656. // Trying to remove a listener that isn't on the list!
  55657. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55658. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55659. jassert (listeners.contains (listenerToRemove));
  55660. listeners.remove (listenerToRemove);
  55661. }
  55662. void MenuBarModel::handleAsyncUpdate()
  55663. {
  55664. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55665. }
  55666. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55667. {
  55668. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55669. }
  55670. void MenuBarModel::applicationCommandListChanged()
  55671. {
  55672. menuItemsChanged();
  55673. }
  55674. END_JUCE_NAMESPACE
  55675. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55676. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55677. BEGIN_JUCE_NAMESPACE
  55678. class PopupMenu::Item
  55679. {
  55680. public:
  55681. Item()
  55682. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55683. usesColour (false), customComp (0), commandManager (0)
  55684. {
  55685. }
  55686. Item (const int itemId_,
  55687. const String& text_,
  55688. const bool active_,
  55689. const bool isTicked_,
  55690. const Image& im,
  55691. const Colour& textColour_,
  55692. const bool usesColour_,
  55693. CustomComponent* const customComp_,
  55694. const PopupMenu* const subMenu_,
  55695. ApplicationCommandManager* const commandManager_)
  55696. : itemId (itemId_), text (text_), textColour (textColour_),
  55697. active (active_), isSeparator (false), isTicked (isTicked_),
  55698. usesColour (usesColour_), image (im), customComp (customComp_),
  55699. commandManager (commandManager_)
  55700. {
  55701. if (subMenu_ != 0)
  55702. subMenu = new PopupMenu (*subMenu_);
  55703. if (commandManager_ != 0 && itemId_ != 0)
  55704. {
  55705. String shortcutKey;
  55706. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55707. ->getKeyPressesAssignedToCommand (itemId_));
  55708. for (int i = 0; i < keyPresses.size(); ++i)
  55709. {
  55710. const String key (keyPresses.getReference(i).getTextDescription());
  55711. if (shortcutKey.isNotEmpty())
  55712. shortcutKey << ", ";
  55713. if (key.length() == 1)
  55714. shortcutKey << "shortcut: '" << key << '\'';
  55715. else
  55716. shortcutKey << key;
  55717. }
  55718. shortcutKey = shortcutKey.trim();
  55719. if (shortcutKey.isNotEmpty())
  55720. text << "<end>" << shortcutKey;
  55721. }
  55722. }
  55723. Item (const Item& other)
  55724. : itemId (other.itemId),
  55725. text (other.text),
  55726. textColour (other.textColour),
  55727. active (other.active),
  55728. isSeparator (other.isSeparator),
  55729. isTicked (other.isTicked),
  55730. usesColour (other.usesColour),
  55731. image (other.image),
  55732. customComp (other.customComp),
  55733. commandManager (other.commandManager)
  55734. {
  55735. if (other.subMenu != 0)
  55736. subMenu = new PopupMenu (*(other.subMenu));
  55737. }
  55738. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55739. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55740. const int itemId;
  55741. String text;
  55742. const Colour textColour;
  55743. const bool active, isSeparator, isTicked, usesColour;
  55744. Image image;
  55745. ReferenceCountedObjectPtr <CustomComponent> customComp;
  55746. ScopedPointer <PopupMenu> subMenu;
  55747. ApplicationCommandManager* const commandManager;
  55748. private:
  55749. Item& operator= (const Item&);
  55750. JUCE_LEAK_DETECTOR (Item);
  55751. };
  55752. class PopupMenu::ItemComponent : public Component
  55753. {
  55754. public:
  55755. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight, Component* const parent)
  55756. : itemInfo (itemInfo_),
  55757. isHighlighted (false)
  55758. {
  55759. if (itemInfo.customComp != 0)
  55760. addAndMakeVisible (itemInfo.customComp);
  55761. parent->addAndMakeVisible (this);
  55762. int itemW = 80;
  55763. int itemH = 16;
  55764. getIdealSize (itemW, itemH, standardItemHeight);
  55765. setSize (itemW, jlimit (2, 600, itemH));
  55766. addMouseListener (parent, false);
  55767. }
  55768. ~ItemComponent()
  55769. {
  55770. if (itemInfo.customComp != 0)
  55771. removeChildComponent (itemInfo.customComp);
  55772. }
  55773. void getIdealSize (int& idealWidth, int& idealHeight, const int standardItemHeight)
  55774. {
  55775. if (itemInfo.customComp != 0)
  55776. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55777. else
  55778. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55779. itemInfo.isSeparator,
  55780. standardItemHeight,
  55781. idealWidth, idealHeight);
  55782. }
  55783. void paint (Graphics& g)
  55784. {
  55785. if (itemInfo.customComp == 0)
  55786. {
  55787. String mainText (itemInfo.text);
  55788. String endText;
  55789. const int endIndex = mainText.indexOf ("<end>");
  55790. if (endIndex >= 0)
  55791. {
  55792. endText = mainText.substring (endIndex + 5).trim();
  55793. mainText = mainText.substring (0, endIndex);
  55794. }
  55795. getLookAndFeel()
  55796. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55797. itemInfo.isSeparator,
  55798. itemInfo.active,
  55799. isHighlighted,
  55800. itemInfo.isTicked,
  55801. itemInfo.subMenu != 0,
  55802. mainText, endText,
  55803. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55804. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55805. }
  55806. }
  55807. void resized()
  55808. {
  55809. if (getNumChildComponents() > 0)
  55810. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55811. }
  55812. void setHighlighted (bool shouldBeHighlighted)
  55813. {
  55814. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55815. if (isHighlighted != shouldBeHighlighted)
  55816. {
  55817. isHighlighted = shouldBeHighlighted;
  55818. if (itemInfo.customComp != 0)
  55819. itemInfo.customComp->setHighlighted (shouldBeHighlighted);
  55820. repaint();
  55821. }
  55822. }
  55823. PopupMenu::Item itemInfo;
  55824. private:
  55825. bool isHighlighted;
  55826. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55827. };
  55828. namespace PopupMenuSettings
  55829. {
  55830. const int scrollZone = 24;
  55831. const int borderSize = 2;
  55832. const int timerInterval = 50;
  55833. const int dismissCommandId = 0x6287345f;
  55834. static bool menuWasHiddenBecauseOfAppChange = false;
  55835. }
  55836. class PopupMenu::Window : public Component,
  55837. private Timer
  55838. {
  55839. public:
  55840. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55841. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55842. const int minimumWidth_, const int maximumNumColumns_,
  55843. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55844. ApplicationCommandManager** const managerOfChosenCommand_,
  55845. Component* const componentAttachedTo_)
  55846. : Component ("menu"),
  55847. owner (owner_),
  55848. activeSubMenu (0),
  55849. managerOfChosenCommand (managerOfChosenCommand_),
  55850. componentAttachedTo (componentAttachedTo_),
  55851. componentAttachedToOriginal (componentAttachedTo_),
  55852. minimumWidth (minimumWidth_),
  55853. maximumNumColumns (maximumNumColumns_),
  55854. standardItemHeight (standardItemHeight_),
  55855. isOver (false),
  55856. hasBeenOver (false),
  55857. isDown (false),
  55858. needsToScroll (false),
  55859. dismissOnMouseUp (dismissOnMouseUp_),
  55860. hideOnExit (false),
  55861. disableMouseMoves (false),
  55862. hasAnyJuceCompHadFocus (false),
  55863. numColumns (0),
  55864. contentHeight (0),
  55865. childYOffset (0),
  55866. menuCreationTime (Time::getMillisecondCounter()),
  55867. lastMouseMoveTime (0),
  55868. timeEnteredCurrentChildComp (0),
  55869. scrollAcceleration (1.0)
  55870. {
  55871. lastFocused = lastScroll = menuCreationTime;
  55872. setWantsKeyboardFocus (false);
  55873. setMouseClickGrabsKeyboardFocus (false);
  55874. setAlwaysOnTop (true);
  55875. setLookAndFeel (menu.lookAndFeel);
  55876. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55877. for (int i = 0; i < menu.items.size(); ++i)
  55878. items.add (new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight, this));
  55879. calculateWindowPos (target, alignToRectangle);
  55880. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55881. updateYPositions();
  55882. if (itemIdThatMustBeVisible != 0)
  55883. {
  55884. const int y = target.getY() - windowPos.getY();
  55885. ensureItemIsVisible (itemIdThatMustBeVisible,
  55886. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55887. }
  55888. resizeToBestWindowPos();
  55889. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55890. getActiveWindows().add (this);
  55891. Desktop::getInstance().addGlobalMouseListener (this);
  55892. }
  55893. ~Window()
  55894. {
  55895. getActiveWindows().removeValue (this);
  55896. Desktop::getInstance().removeGlobalMouseListener (this);
  55897. activeSubMenu = 0;
  55898. items.clear();
  55899. }
  55900. static Window* create (const PopupMenu& menu,
  55901. bool dismissOnMouseUp,
  55902. Window* const owner_,
  55903. const Rectangle<int>& target,
  55904. int minimumWidth,
  55905. int maximumNumColumns,
  55906. int standardItemHeight,
  55907. bool alignToRectangle,
  55908. int itemIdThatMustBeVisible,
  55909. ApplicationCommandManager** managerOfChosenCommand,
  55910. Component* componentAttachedTo)
  55911. {
  55912. if (menu.items.size() > 0)
  55913. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55914. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55915. managerOfChosenCommand, componentAttachedTo);
  55916. return 0;
  55917. }
  55918. void paint (Graphics& g)
  55919. {
  55920. if (isOpaque())
  55921. g.fillAll (Colours::white);
  55922. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55923. }
  55924. void paintOverChildren (Graphics& g)
  55925. {
  55926. if (isScrolling())
  55927. {
  55928. LookAndFeel& lf = getLookAndFeel();
  55929. if (isScrollZoneActive (false))
  55930. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55931. if (isScrollZoneActive (true))
  55932. {
  55933. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55934. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55935. }
  55936. }
  55937. }
  55938. bool isScrollZoneActive (bool bottomOne) const
  55939. {
  55940. return isScrolling()
  55941. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55942. : childYOffset > 0);
  55943. }
  55944. // hide this and all sub-comps
  55945. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55946. {
  55947. if (isVisible())
  55948. {
  55949. activeSubMenu = 0;
  55950. currentChild = 0;
  55951. exitModalState (item != 0 ? item->itemId : 0);
  55952. if (makeInvisible)
  55953. setVisible (false);
  55954. if (item != 0
  55955. && item->commandManager != 0
  55956. && item->itemId != 0)
  55957. {
  55958. *managerOfChosenCommand = item->commandManager;
  55959. }
  55960. }
  55961. }
  55962. void dismissMenu (const PopupMenu::Item* const item)
  55963. {
  55964. if (owner != 0)
  55965. {
  55966. owner->dismissMenu (item);
  55967. }
  55968. else
  55969. {
  55970. if (item != 0)
  55971. {
  55972. // need a copy of this on the stack as the one passed in will get deleted during this call
  55973. const PopupMenu::Item mi (*item);
  55974. hide (&mi, false);
  55975. }
  55976. else
  55977. {
  55978. hide (0, false);
  55979. }
  55980. }
  55981. }
  55982. void mouseMove (const MouseEvent&) { timerCallback(); }
  55983. void mouseDown (const MouseEvent&) { timerCallback(); }
  55984. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55985. void mouseUp (const MouseEvent&) { timerCallback(); }
  55986. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55987. {
  55988. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55989. lastMouse = Point<int> (-1, -1);
  55990. }
  55991. bool keyPressed (const KeyPress& key)
  55992. {
  55993. if (key.isKeyCode (KeyPress::downKey))
  55994. {
  55995. selectNextItem (1);
  55996. }
  55997. else if (key.isKeyCode (KeyPress::upKey))
  55998. {
  55999. selectNextItem (-1);
  56000. }
  56001. else if (key.isKeyCode (KeyPress::leftKey))
  56002. {
  56003. if (owner != 0)
  56004. {
  56005. Component::SafePointer<Window> parentWindow (owner);
  56006. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  56007. hide (0, true);
  56008. if (parentWindow != 0)
  56009. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  56010. disableTimerUntilMouseMoves();
  56011. }
  56012. else if (componentAttachedTo != 0)
  56013. {
  56014. componentAttachedTo->keyPressed (key);
  56015. }
  56016. }
  56017. else if (key.isKeyCode (KeyPress::rightKey))
  56018. {
  56019. disableTimerUntilMouseMoves();
  56020. if (showSubMenuFor (currentChild))
  56021. {
  56022. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  56023. activeSubMenu->selectNextItem (1);
  56024. }
  56025. else if (componentAttachedTo != 0)
  56026. {
  56027. componentAttachedTo->keyPressed (key);
  56028. }
  56029. }
  56030. else if (key.isKeyCode (KeyPress::returnKey))
  56031. {
  56032. triggerCurrentlyHighlightedItem();
  56033. }
  56034. else if (key.isKeyCode (KeyPress::escapeKey))
  56035. {
  56036. dismissMenu (0);
  56037. }
  56038. else
  56039. {
  56040. return false;
  56041. }
  56042. return true;
  56043. }
  56044. void inputAttemptWhenModal()
  56045. {
  56046. WeakReference<Component> deletionChecker (this);
  56047. timerCallback();
  56048. if (deletionChecker != 0 && ! isOverAnyMenu())
  56049. {
  56050. if (componentAttachedTo != 0)
  56051. {
  56052. // we want to dismiss the menu, but if we do it synchronously, then
  56053. // the mouse-click will be allowed to pass through. That's good, except
  56054. // when the user clicks on the button that orginally popped the menu up,
  56055. // as they'll expect the menu to go away, and in fact it'll just
  56056. // come back. So only dismiss synchronously if they're not on the original
  56057. // comp that we're attached to.
  56058. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  56059. if (componentAttachedTo->reallyContains (mousePos, true))
  56060. {
  56061. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  56062. return;
  56063. }
  56064. }
  56065. dismissMenu (0);
  56066. }
  56067. }
  56068. void handleCommandMessage (int commandId)
  56069. {
  56070. Component::handleCommandMessage (commandId);
  56071. if (commandId == PopupMenuSettings::dismissCommandId)
  56072. dismissMenu (0);
  56073. }
  56074. void timerCallback()
  56075. {
  56076. if (! isVisible())
  56077. return;
  56078. if (componentAttachedTo != componentAttachedToOriginal)
  56079. {
  56080. dismissMenu (0);
  56081. return;
  56082. }
  56083. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56084. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56085. return;
  56086. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56087. // move rather than a real timer callback
  56088. const Point<int> globalMousePos (Desktop::getMousePosition());
  56089. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  56090. const uint32 now = Time::getMillisecondCounter();
  56091. if (now > timeEnteredCurrentChildComp + 100
  56092. && reallyContains (localMousePos, true)
  56093. && currentChild != 0
  56094. && (! disableMouseMoves)
  56095. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56096. {
  56097. showSubMenuFor (currentChild);
  56098. }
  56099. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56100. {
  56101. highlightItemUnderMouse (globalMousePos, localMousePos);
  56102. }
  56103. bool overScrollArea = false;
  56104. if (isScrolling()
  56105. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  56106. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56107. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56108. {
  56109. if (now > lastScroll + 20)
  56110. {
  56111. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56112. int amount = 0;
  56113. for (int i = 0; i < items.size() && amount == 0; ++i)
  56114. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  56115. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56116. lastScroll = now;
  56117. }
  56118. overScrollArea = true;
  56119. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56120. }
  56121. else
  56122. {
  56123. scrollAcceleration = 1.0;
  56124. }
  56125. const bool wasDown = isDown;
  56126. bool isOverAny = isOverAnyMenu();
  56127. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56128. {
  56129. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56130. isOverAny = isOverAnyMenu();
  56131. }
  56132. if (hideOnExit && hasBeenOver && ! isOverAny)
  56133. {
  56134. hide (0, true);
  56135. }
  56136. else
  56137. {
  56138. isDown = hasBeenOver
  56139. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56140. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56141. bool anyFocused = Process::isForegroundProcess();
  56142. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56143. {
  56144. // because no component at all may have focus, our test here will
  56145. // only be triggered when something has focus and then loses it.
  56146. anyFocused = ! hasAnyJuceCompHadFocus;
  56147. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56148. {
  56149. if (ComponentPeer::getPeer (i)->isFocused())
  56150. {
  56151. anyFocused = true;
  56152. hasAnyJuceCompHadFocus = true;
  56153. break;
  56154. }
  56155. }
  56156. }
  56157. if (! anyFocused)
  56158. {
  56159. if (now > lastFocused + 10)
  56160. {
  56161. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = true;
  56162. dismissMenu (0);
  56163. return; // may have been deleted by the previous call..
  56164. }
  56165. }
  56166. else if (wasDown && now > menuCreationTime + 250
  56167. && ! (isDown || overScrollArea))
  56168. {
  56169. isOver = reallyContains (localMousePos, true);
  56170. if (isOver)
  56171. {
  56172. triggerCurrentlyHighlightedItem();
  56173. }
  56174. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56175. {
  56176. dismissMenu (0);
  56177. }
  56178. return; // may have been deleted by the previous calls..
  56179. }
  56180. else
  56181. {
  56182. lastFocused = now;
  56183. }
  56184. }
  56185. }
  56186. static Array<Window*>& getActiveWindows()
  56187. {
  56188. static Array<Window*> activeMenuWindows;
  56189. return activeMenuWindows;
  56190. }
  56191. private:
  56192. Window* owner;
  56193. OwnedArray <PopupMenu::ItemComponent> items;
  56194. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  56195. ScopedPointer <Window> activeSubMenu;
  56196. ApplicationCommandManager** managerOfChosenCommand;
  56197. WeakReference<Component> componentAttachedTo;
  56198. Component* componentAttachedToOriginal;
  56199. Rectangle<int> windowPos;
  56200. Point<int> lastMouse;
  56201. int minimumWidth, maximumNumColumns, standardItemHeight;
  56202. bool isOver, hasBeenOver, isDown, needsToScroll;
  56203. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56204. int numColumns, contentHeight, childYOffset;
  56205. Array <int> columnWidths;
  56206. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56207. double scrollAcceleration;
  56208. bool overlaps (const Rectangle<int>& r) const
  56209. {
  56210. return r.intersects (getBounds())
  56211. || (owner != 0 && owner->overlaps (r));
  56212. }
  56213. bool isOverAnyMenu() const
  56214. {
  56215. return (owner != 0) ? owner->isOverAnyMenu()
  56216. : isOverChildren();
  56217. }
  56218. bool isOverChildren() const
  56219. {
  56220. return isVisible()
  56221. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56222. }
  56223. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56224. {
  56225. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  56226. isOver = reallyContains (relPos, true);
  56227. if (activeSubMenu != 0)
  56228. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56229. }
  56230. bool treeContains (const Window* const window) const throw()
  56231. {
  56232. const Window* mw = this;
  56233. while (mw->owner != 0)
  56234. mw = mw->owner;
  56235. while (mw != 0)
  56236. {
  56237. if (mw == window)
  56238. return true;
  56239. mw = mw->activeSubMenu;
  56240. }
  56241. return false;
  56242. }
  56243. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56244. {
  56245. const Rectangle<int> mon (Desktop::getInstance()
  56246. .getMonitorAreaContaining (target.getCentre(),
  56247. #if JUCE_MAC
  56248. true));
  56249. #else
  56250. false)); // on windows, don't stop the menu overlapping the taskbar
  56251. #endif
  56252. int x, y, widthToUse, heightToUse;
  56253. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56254. if (alignToRectangle)
  56255. {
  56256. x = target.getX();
  56257. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56258. const int spaceOver = target.getY() - mon.getY();
  56259. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56260. y = target.getBottom();
  56261. else
  56262. y = target.getY() - heightToUse;
  56263. }
  56264. else
  56265. {
  56266. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56267. if (owner != 0)
  56268. {
  56269. if (owner->owner != 0)
  56270. {
  56271. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56272. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56273. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56274. tendTowardsRight = true;
  56275. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56276. tendTowardsRight = false;
  56277. }
  56278. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56279. {
  56280. tendTowardsRight = true;
  56281. }
  56282. }
  56283. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56284. target.getX() - mon.getX()) - 32;
  56285. if (biggestSpace < widthToUse)
  56286. {
  56287. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56288. if (numColumns > 1)
  56289. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56290. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56291. }
  56292. if (tendTowardsRight)
  56293. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56294. else
  56295. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56296. y = target.getY();
  56297. if (target.getCentreY() > mon.getCentreY())
  56298. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56299. }
  56300. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56301. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56302. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56303. // sets this flag if it's big enough to obscure any of its parent menus
  56304. hideOnExit = (owner != 0)
  56305. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56306. }
  56307. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56308. {
  56309. numColumns = 0;
  56310. contentHeight = 0;
  56311. const int maxMenuH = getParentHeight() - 24;
  56312. int totalW;
  56313. do
  56314. {
  56315. ++numColumns;
  56316. totalW = workOutBestSize (maxMenuW);
  56317. if (totalW > maxMenuW)
  56318. {
  56319. numColumns = jmax (1, numColumns - 1);
  56320. totalW = workOutBestSize (maxMenuW); // to update col widths
  56321. break;
  56322. }
  56323. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56324. {
  56325. break;
  56326. }
  56327. } while (numColumns < maximumNumColumns);
  56328. const int actualH = jmin (contentHeight, maxMenuH);
  56329. needsToScroll = contentHeight > actualH;
  56330. width = updateYPositions();
  56331. height = actualH + PopupMenuSettings::borderSize * 2;
  56332. }
  56333. int workOutBestSize (const int maxMenuW)
  56334. {
  56335. int totalW = 0;
  56336. contentHeight = 0;
  56337. int childNum = 0;
  56338. for (int col = 0; col < numColumns; ++col)
  56339. {
  56340. int i, colW = 50, colH = 0;
  56341. const int numChildren = jmin (items.size() - childNum,
  56342. (items.size() + numColumns - 1) / numColumns);
  56343. for (i = numChildren; --i >= 0;)
  56344. {
  56345. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56346. colH += items.getUnchecked (childNum + i)->getHeight();
  56347. }
  56348. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56349. columnWidths.set (col, colW);
  56350. totalW += colW;
  56351. contentHeight = jmax (contentHeight, colH);
  56352. childNum += numChildren;
  56353. }
  56354. if (totalW < minimumWidth)
  56355. {
  56356. totalW = minimumWidth;
  56357. for (int col = 0; col < numColumns; ++col)
  56358. columnWidths.set (0, totalW / numColumns);
  56359. }
  56360. return totalW;
  56361. }
  56362. void ensureItemIsVisible (const int itemId, int wantedY)
  56363. {
  56364. jassert (itemId != 0)
  56365. for (int i = items.size(); --i >= 0;)
  56366. {
  56367. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56368. if (m != 0
  56369. && m->itemInfo.itemId == itemId
  56370. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56371. {
  56372. const int currentY = m->getY();
  56373. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56374. {
  56375. if (wantedY < 0)
  56376. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56377. jmax (PopupMenuSettings::scrollZone,
  56378. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56379. currentY);
  56380. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56381. int deltaY = wantedY - currentY;
  56382. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56383. jmin (windowPos.getHeight(), mon.getHeight()));
  56384. const int newY = jlimit (mon.getY(),
  56385. mon.getBottom() - windowPos.getHeight(),
  56386. windowPos.getY() + deltaY);
  56387. deltaY -= newY - windowPos.getY();
  56388. childYOffset -= deltaY;
  56389. windowPos.setPosition (windowPos.getX(), newY);
  56390. updateYPositions();
  56391. }
  56392. break;
  56393. }
  56394. }
  56395. }
  56396. void resizeToBestWindowPos()
  56397. {
  56398. Rectangle<int> r (windowPos);
  56399. if (childYOffset < 0)
  56400. {
  56401. r.setBounds (r.getX(), r.getY() - childYOffset,
  56402. r.getWidth(), r.getHeight() + childYOffset);
  56403. }
  56404. else if (childYOffset > 0)
  56405. {
  56406. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56407. if (spaceAtBottom > 0)
  56408. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56409. }
  56410. setBounds (r);
  56411. updateYPositions();
  56412. }
  56413. void alterChildYPos (const int delta)
  56414. {
  56415. if (isScrolling())
  56416. {
  56417. childYOffset += delta;
  56418. if (delta < 0)
  56419. {
  56420. childYOffset = jmax (childYOffset, 0);
  56421. }
  56422. else if (delta > 0)
  56423. {
  56424. childYOffset = jmin (childYOffset,
  56425. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56426. }
  56427. updateYPositions();
  56428. }
  56429. else
  56430. {
  56431. childYOffset = 0;
  56432. }
  56433. resizeToBestWindowPos();
  56434. repaint();
  56435. }
  56436. int updateYPositions()
  56437. {
  56438. int x = 0;
  56439. int childNum = 0;
  56440. for (int col = 0; col < numColumns; ++col)
  56441. {
  56442. const int numChildren = jmin (items.size() - childNum,
  56443. (items.size() + numColumns - 1) / numColumns);
  56444. const int colW = columnWidths [col];
  56445. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56446. for (int i = 0; i < numChildren; ++i)
  56447. {
  56448. Component* const c = items.getUnchecked (childNum + i);
  56449. c->setBounds (x, y, colW, c->getHeight());
  56450. y += c->getHeight();
  56451. }
  56452. x += colW;
  56453. childNum += numChildren;
  56454. }
  56455. return x;
  56456. }
  56457. bool isScrolling() const throw()
  56458. {
  56459. return childYOffset != 0 || needsToScroll;
  56460. }
  56461. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56462. {
  56463. if (currentChild != 0)
  56464. currentChild->setHighlighted (false);
  56465. currentChild = child;
  56466. if (currentChild != 0)
  56467. {
  56468. currentChild->setHighlighted (true);
  56469. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56470. }
  56471. }
  56472. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56473. {
  56474. activeSubMenu = 0;
  56475. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56476. {
  56477. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56478. dismissOnMouseUp,
  56479. this,
  56480. childComp->getScreenBounds(),
  56481. 0, maximumNumColumns,
  56482. standardItemHeight,
  56483. false, 0, managerOfChosenCommand,
  56484. componentAttachedTo);
  56485. if (activeSubMenu != 0)
  56486. {
  56487. activeSubMenu->setVisible (true);
  56488. activeSubMenu->enterModalState (false);
  56489. activeSubMenu->toFront (false);
  56490. return true;
  56491. }
  56492. }
  56493. return false;
  56494. }
  56495. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56496. {
  56497. isOver = reallyContains (localMousePos, true);
  56498. if (isOver)
  56499. hasBeenOver = true;
  56500. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56501. {
  56502. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56503. if (disableMouseMoves && isOver)
  56504. disableMouseMoves = false;
  56505. }
  56506. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56507. return;
  56508. bool isMovingTowardsMenu = false;
  56509. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56510. {
  56511. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56512. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56513. // extends from the last mouse pos to the submenu's rectangle..
  56514. float subX = (float) activeSubMenu->getScreenX();
  56515. if (activeSubMenu->getX() > getX())
  56516. {
  56517. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56518. }
  56519. else
  56520. {
  56521. lastMouse += Point<int> (2, 0);
  56522. subX += activeSubMenu->getWidth();
  56523. }
  56524. Path areaTowardsSubMenu;
  56525. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56526. subX, (float) activeSubMenu->getScreenY(),
  56527. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56528. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56529. }
  56530. lastMouse = globalMousePos;
  56531. if (! isMovingTowardsMenu)
  56532. {
  56533. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56534. if (c == this)
  56535. c = 0;
  56536. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56537. if (mic == 0 && c != 0)
  56538. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56539. if (mic != currentChild
  56540. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56541. {
  56542. if (isOver && (c != 0) && (activeSubMenu != 0))
  56543. activeSubMenu->hide (0, true);
  56544. if (! isOver)
  56545. mic = 0;
  56546. setCurrentlyHighlightedChild (mic);
  56547. }
  56548. }
  56549. }
  56550. void triggerCurrentlyHighlightedItem()
  56551. {
  56552. if (currentChild != 0
  56553. && currentChild->itemInfo.canBeTriggered()
  56554. && (currentChild->itemInfo.customComp == 0
  56555. || currentChild->itemInfo.customComp->isTriggeredAutomatically()))
  56556. {
  56557. dismissMenu (&currentChild->itemInfo);
  56558. }
  56559. }
  56560. void selectNextItem (const int delta)
  56561. {
  56562. disableTimerUntilMouseMoves();
  56563. PopupMenu::ItemComponent* mic = 0;
  56564. bool wasLastOne = (currentChild == 0);
  56565. const int numItems = items.size();
  56566. for (int i = 0; i < numItems + 1; ++i)
  56567. {
  56568. int index = (delta > 0) ? i : (numItems - 1 - i);
  56569. index = (index + numItems) % numItems;
  56570. mic = items.getUnchecked (index);
  56571. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56572. && wasLastOne)
  56573. break;
  56574. if (mic == currentChild)
  56575. wasLastOne = true;
  56576. }
  56577. setCurrentlyHighlightedChild (mic);
  56578. }
  56579. void disableTimerUntilMouseMoves()
  56580. {
  56581. disableMouseMoves = true;
  56582. if (owner != 0)
  56583. owner->disableTimerUntilMouseMoves();
  56584. }
  56585. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56586. };
  56587. PopupMenu::PopupMenu()
  56588. : lookAndFeel (0),
  56589. separatorPending (false)
  56590. {
  56591. }
  56592. PopupMenu::PopupMenu (const PopupMenu& other)
  56593. : lookAndFeel (other.lookAndFeel),
  56594. separatorPending (false)
  56595. {
  56596. items.addCopiesOf (other.items);
  56597. }
  56598. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56599. {
  56600. if (this != &other)
  56601. {
  56602. lookAndFeel = other.lookAndFeel;
  56603. clear();
  56604. items.addCopiesOf (other.items);
  56605. }
  56606. return *this;
  56607. }
  56608. PopupMenu::~PopupMenu()
  56609. {
  56610. clear();
  56611. }
  56612. void PopupMenu::clear()
  56613. {
  56614. items.clear();
  56615. separatorPending = false;
  56616. }
  56617. void PopupMenu::addSeparatorIfPending()
  56618. {
  56619. if (separatorPending)
  56620. {
  56621. separatorPending = false;
  56622. if (items.size() > 0)
  56623. items.add (new Item());
  56624. }
  56625. }
  56626. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56627. const bool isActive, const bool isTicked, const Image& iconToUse)
  56628. {
  56629. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56630. // didn't pick anything, so you shouldn't use it as the id
  56631. // for an item..
  56632. addSeparatorIfPending();
  56633. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56634. Colours::black, false, 0, 0, 0));
  56635. }
  56636. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56637. const int commandID,
  56638. const String& displayName)
  56639. {
  56640. jassert (commandManager != 0 && commandID != 0);
  56641. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56642. if (registeredInfo != 0)
  56643. {
  56644. ApplicationCommandInfo info (*registeredInfo);
  56645. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56646. addSeparatorIfPending();
  56647. items.add (new Item (commandID,
  56648. displayName.isNotEmpty() ? displayName
  56649. : info.shortName,
  56650. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56651. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56652. Image::null,
  56653. Colours::black,
  56654. false,
  56655. 0, 0,
  56656. commandManager));
  56657. }
  56658. }
  56659. void PopupMenu::addColouredItem (const int itemResultId,
  56660. const String& itemText,
  56661. const Colour& itemTextColour,
  56662. const bool isActive,
  56663. const bool isTicked,
  56664. const Image& iconToUse)
  56665. {
  56666. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56667. // didn't pick anything, so you shouldn't use it as the id
  56668. // for an item..
  56669. addSeparatorIfPending();
  56670. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56671. itemTextColour, true, 0, 0, 0));
  56672. }
  56673. void PopupMenu::addCustomItem (const int itemResultId, CustomComponent* const customComponent)
  56674. {
  56675. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56676. // didn't pick anything, so you shouldn't use it as the id
  56677. // for an item..
  56678. addSeparatorIfPending();
  56679. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56680. Colours::black, false, customComponent, 0, 0));
  56681. }
  56682. class NormalComponentWrapper : public PopupMenu::CustomComponent
  56683. {
  56684. public:
  56685. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56686. const bool triggerMenuItemAutomaticallyWhenClicked)
  56687. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56688. width (w), height (h)
  56689. {
  56690. addAndMakeVisible (comp);
  56691. }
  56692. void getIdealSize (int& idealWidth, int& idealHeight)
  56693. {
  56694. idealWidth = width;
  56695. idealHeight = height;
  56696. }
  56697. void resized()
  56698. {
  56699. if (getChildComponent(0) != 0)
  56700. getChildComponent(0)->setBounds (getLocalBounds());
  56701. }
  56702. private:
  56703. const int width, height;
  56704. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56705. };
  56706. void PopupMenu::addCustomItem (const int itemResultId,
  56707. Component* customComponent,
  56708. int idealWidth, int idealHeight,
  56709. const bool triggerMenuItemAutomaticallyWhenClicked)
  56710. {
  56711. addCustomItem (itemResultId,
  56712. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56713. triggerMenuItemAutomaticallyWhenClicked));
  56714. }
  56715. void PopupMenu::addSubMenu (const String& subMenuName,
  56716. const PopupMenu& subMenu,
  56717. const bool isActive,
  56718. const Image& iconToUse,
  56719. const bool isTicked)
  56720. {
  56721. addSeparatorIfPending();
  56722. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56723. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56724. }
  56725. void PopupMenu::addSeparator()
  56726. {
  56727. separatorPending = true;
  56728. }
  56729. class HeaderItemComponent : public PopupMenu::CustomComponent
  56730. {
  56731. public:
  56732. HeaderItemComponent (const String& name)
  56733. : PopupMenu::CustomComponent (false)
  56734. {
  56735. setName (name);
  56736. }
  56737. void paint (Graphics& g)
  56738. {
  56739. Font f (getLookAndFeel().getPopupMenuFont());
  56740. f.setBold (true);
  56741. g.setFont (f);
  56742. g.setColour (findColour (PopupMenu::headerTextColourId));
  56743. g.drawFittedText (getName(),
  56744. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56745. Justification::bottomLeft, 1);
  56746. }
  56747. void getIdealSize (int& idealWidth, int& idealHeight)
  56748. {
  56749. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56750. idealHeight += idealHeight / 2;
  56751. idealWidth += idealWidth / 4;
  56752. }
  56753. private:
  56754. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56755. };
  56756. void PopupMenu::addSectionHeader (const String& title)
  56757. {
  56758. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56759. }
  56760. PopupMenu::Options::Options()
  56761. : targetComponent (0),
  56762. visibleItemID (0),
  56763. minWidth (0),
  56764. maxColumns (0),
  56765. standardHeight (0)
  56766. {
  56767. targetArea.setPosition (Desktop::getMousePosition());
  56768. }
  56769. const PopupMenu::Options PopupMenu::Options::withTargetComponent (Component* comp) const
  56770. {
  56771. Options o (*this);
  56772. o.targetComponent = comp;
  56773. if (comp != 0)
  56774. o.targetArea = comp->getScreenBounds();
  56775. return o;
  56776. }
  56777. const PopupMenu::Options PopupMenu::Options::withTargetScreenArea (const Rectangle<int>& area) const
  56778. {
  56779. Options o (*this);
  56780. o.targetArea = area;
  56781. return o;
  56782. }
  56783. const PopupMenu::Options PopupMenu::Options::withMinimumWidth (int w) const
  56784. {
  56785. Options o (*this);
  56786. o.minWidth = w;
  56787. return o;
  56788. }
  56789. const PopupMenu::Options PopupMenu::Options::withMaximumNumColumns (int cols) const
  56790. {
  56791. Options o (*this);
  56792. o.maxColumns = cols;
  56793. return o;
  56794. }
  56795. const PopupMenu::Options PopupMenu::Options::withStandardItemHeight (int height) const
  56796. {
  56797. Options o (*this);
  56798. o.standardHeight = height;
  56799. return o;
  56800. }
  56801. const PopupMenu::Options PopupMenu::Options::withItemThatMustBeVisible (int idOfItemToBeVisible) const
  56802. {
  56803. Options o (*this);
  56804. o.visibleItemID = idOfItemToBeVisible;
  56805. return o;
  56806. }
  56807. Component* PopupMenu::createWindow (const Options& options,
  56808. ApplicationCommandManager** managerOfChosenCommand) const
  56809. {
  56810. return Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56811. 0, options.targetArea, options.minWidth, options.maxColumns > 0 ? options.maxColumns : 7,
  56812. options.standardHeight, ! options.targetArea.isEmpty(), options.visibleItemID,
  56813. managerOfChosenCommand, options.targetComponent);
  56814. }
  56815. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56816. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56817. {
  56818. public:
  56819. PopupMenuCompletionCallback()
  56820. : managerOfChosenCommand (0),
  56821. prevFocused (Component::getCurrentlyFocusedComponent()),
  56822. prevTopLevel (prevFocused != 0 ? prevFocused->getTopLevelComponent() : 0)
  56823. {
  56824. PopupMenuSettings::menuWasHiddenBecauseOfAppChange = false;
  56825. }
  56826. void modalStateFinished (int result)
  56827. {
  56828. if (managerOfChosenCommand != 0 && result != 0)
  56829. {
  56830. ApplicationCommandTarget::InvocationInfo info (result);
  56831. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56832. managerOfChosenCommand->invoke (info, true);
  56833. }
  56834. // (this would be the place to fade out the component, if that's what's required)
  56835. component = 0;
  56836. if (! PopupMenuSettings::menuWasHiddenBecauseOfAppChange)
  56837. {
  56838. if (prevTopLevel != 0)
  56839. prevTopLevel->toFront (true);
  56840. if (prevFocused != 0)
  56841. prevFocused->grabKeyboardFocus();
  56842. }
  56843. }
  56844. ApplicationCommandManager* managerOfChosenCommand;
  56845. ScopedPointer<Component> component;
  56846. WeakReference<Component> prevFocused, prevTopLevel;
  56847. private:
  56848. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56849. };
  56850. int PopupMenu::showWithOptionalCallback (const Options& options, ModalComponentManager::Callback* const userCallback,
  56851. const bool canBeModal)
  56852. {
  56853. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56854. ScopedPointer<PopupMenuCompletionCallback> callback (new PopupMenuCompletionCallback());
  56855. Component* window = createWindow (options, &(callback->managerOfChosenCommand));
  56856. if (window == 0)
  56857. return 0;
  56858. callback->component = window;
  56859. window->enterModalState (false, userCallbackDeleter.release());
  56860. ModalComponentManager::getInstance()->attachCallback (window, callback.release());
  56861. window->toFront (false); // need to do this after making it modal, or it could
  56862. // be stuck behind other comps that are already modal..
  56863. #if JUCE_MODAL_LOOPS_PERMITTED
  56864. return (userCallback == 0 && canBeModal) ? window->runModalLoop() : 0;
  56865. #else
  56866. jassert (userCallback != 0 && canBeModal);
  56867. return 0;
  56868. #endif
  56869. }
  56870. #if JUCE_MODAL_LOOPS_PERMITTED
  56871. int PopupMenu::showMenu (const Options& options)
  56872. {
  56873. return showWithOptionalCallback (options, 0, true);
  56874. }
  56875. #endif
  56876. void PopupMenu::showMenuAsync (const Options& options, ModalComponentManager::Callback* userCallback)
  56877. {
  56878. #if ! JUCE_MODAL_LOOPS_PERMITTED
  56879. jassert (userCallback != 0);
  56880. #endif
  56881. showWithOptionalCallback (options, userCallback, false);
  56882. }
  56883. #if JUCE_MODAL_LOOPS_PERMITTED
  56884. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56885. const int minimumWidth, const int maximumNumColumns,
  56886. const int standardItemHeight,
  56887. ModalComponentManager::Callback* callback)
  56888. {
  56889. return showWithOptionalCallback (Options().withItemThatMustBeVisible (itemIdThatMustBeVisible)
  56890. .withMinimumWidth (minimumWidth)
  56891. .withMaximumNumColumns (maximumNumColumns)
  56892. .withStandardItemHeight (standardItemHeight),
  56893. callback, true);
  56894. }
  56895. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56896. const int itemIdThatMustBeVisible,
  56897. const int minimumWidth, const int maximumNumColumns,
  56898. const int standardItemHeight,
  56899. ModalComponentManager::Callback* callback)
  56900. {
  56901. return showWithOptionalCallback (Options().withTargetScreenArea (screenAreaToAttachTo)
  56902. .withItemThatMustBeVisible (itemIdThatMustBeVisible)
  56903. .withMinimumWidth (minimumWidth)
  56904. .withMaximumNumColumns (maximumNumColumns)
  56905. .withStandardItemHeight (standardItemHeight),
  56906. callback, true);
  56907. }
  56908. int PopupMenu::showAt (Component* componentToAttachTo,
  56909. const int itemIdThatMustBeVisible,
  56910. const int minimumWidth, const int maximumNumColumns,
  56911. const int standardItemHeight,
  56912. ModalComponentManager::Callback* callback)
  56913. {
  56914. Options options (Options().withItemThatMustBeVisible (itemIdThatMustBeVisible)
  56915. .withMinimumWidth (minimumWidth)
  56916. .withMaximumNumColumns (maximumNumColumns)
  56917. .withStandardItemHeight (standardItemHeight));
  56918. if (componentToAttachTo != 0)
  56919. options = options.withTargetComponent (componentToAttachTo);
  56920. return showWithOptionalCallback (options, callback, true);
  56921. }
  56922. #endif
  56923. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56924. {
  56925. const int numWindows = Window::getActiveWindows().size();
  56926. for (int i = numWindows; --i >= 0;)
  56927. {
  56928. Window* const pmw = Window::getActiveWindows()[i];
  56929. if (pmw != 0)
  56930. pmw->dismissMenu (0);
  56931. }
  56932. return numWindows > 0;
  56933. }
  56934. int PopupMenu::getNumItems() const throw()
  56935. {
  56936. int num = 0;
  56937. for (int i = items.size(); --i >= 0;)
  56938. if (! (items.getUnchecked(i))->isSeparator)
  56939. ++num;
  56940. return num;
  56941. }
  56942. bool PopupMenu::containsCommandItem (const int commandID) const
  56943. {
  56944. for (int i = items.size(); --i >= 0;)
  56945. {
  56946. const Item* mi = items.getUnchecked (i);
  56947. if ((mi->itemId == commandID && mi->commandManager != 0)
  56948. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56949. {
  56950. return true;
  56951. }
  56952. }
  56953. return false;
  56954. }
  56955. bool PopupMenu::containsAnyActiveItems() const throw()
  56956. {
  56957. for (int i = items.size(); --i >= 0;)
  56958. {
  56959. const Item* const mi = items.getUnchecked (i);
  56960. if (mi->subMenu != 0)
  56961. {
  56962. if (mi->subMenu->containsAnyActiveItems())
  56963. return true;
  56964. }
  56965. else if (mi->active)
  56966. {
  56967. return true;
  56968. }
  56969. }
  56970. return false;
  56971. }
  56972. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56973. {
  56974. lookAndFeel = newLookAndFeel;
  56975. }
  56976. PopupMenu::CustomComponent::CustomComponent (const bool isTriggeredAutomatically_)
  56977. : isHighlighted (false),
  56978. triggeredAutomatically (isTriggeredAutomatically_)
  56979. {
  56980. }
  56981. PopupMenu::CustomComponent::~CustomComponent()
  56982. {
  56983. }
  56984. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  56985. {
  56986. isHighlighted = shouldBeHighlighted;
  56987. repaint();
  56988. }
  56989. void PopupMenu::CustomComponent::triggerMenuItem()
  56990. {
  56991. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56992. if (mic != 0)
  56993. {
  56994. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56995. if (pmw != 0)
  56996. {
  56997. pmw->dismissMenu (&mic->itemInfo);
  56998. }
  56999. else
  57000. {
  57001. // something must have gone wrong with the component hierarchy if this happens..
  57002. jassertfalse;
  57003. }
  57004. }
  57005. else
  57006. {
  57007. // why isn't this component inside a menu? Not much point triggering the item if
  57008. // there's no menu.
  57009. jassertfalse;
  57010. }
  57011. }
  57012. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  57013. : subMenu (0),
  57014. itemId (0),
  57015. isSeparator (false),
  57016. isTicked (false),
  57017. isEnabled (false),
  57018. isCustomComponent (false),
  57019. isSectionHeader (false),
  57020. customColour (0),
  57021. customImage (0),
  57022. menu (menu_),
  57023. index (0)
  57024. {
  57025. }
  57026. PopupMenu::MenuItemIterator::~MenuItemIterator()
  57027. {
  57028. }
  57029. bool PopupMenu::MenuItemIterator::next()
  57030. {
  57031. if (index >= menu.items.size())
  57032. return false;
  57033. const Item* const item = menu.items.getUnchecked (index);
  57034. ++index;
  57035. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  57036. subMenu = item->subMenu;
  57037. itemId = item->itemId;
  57038. isSeparator = item->isSeparator;
  57039. isTicked = item->isTicked;
  57040. isEnabled = item->active;
  57041. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <CustomComponent*> (item->customComp)) != 0;
  57042. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  57043. customColour = item->usesColour ? &(item->textColour) : 0;
  57044. customImage = item->image;
  57045. commandManager = item->commandManager;
  57046. return true;
  57047. }
  57048. END_JUCE_NAMESPACE
  57049. /*** End of inlined file: juce_PopupMenu.cpp ***/
  57050. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  57051. BEGIN_JUCE_NAMESPACE
  57052. ComponentDragger::ComponentDragger()
  57053. {
  57054. }
  57055. ComponentDragger::~ComponentDragger()
  57056. {
  57057. }
  57058. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  57059. {
  57060. jassert (componentToDrag != 0);
  57061. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  57062. if (componentToDrag != 0)
  57063. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  57064. }
  57065. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  57066. ComponentBoundsConstrainer* const constrainer)
  57067. {
  57068. jassert (componentToDrag != 0);
  57069. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  57070. if (componentToDrag != 0)
  57071. {
  57072. Rectangle<int> bounds (componentToDrag->getBounds());
  57073. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  57074. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  57075. // the current mouse position instead of the one that the event contains...
  57076. if (componentToDrag->isOnDesktop())
  57077. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  57078. else
  57079. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  57080. if (constrainer != 0)
  57081. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  57082. else
  57083. componentToDrag->setBounds (bounds);
  57084. }
  57085. }
  57086. END_JUCE_NAMESPACE
  57087. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  57088. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  57089. BEGIN_JUCE_NAMESPACE
  57090. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  57091. bool juce_performDragDropText (const String& text, bool& shouldStop);
  57092. class DragImageComponent : public Component,
  57093. public Timer
  57094. {
  57095. public:
  57096. DragImageComponent (const Image& im,
  57097. const String& desc,
  57098. Component* const sourceComponent,
  57099. Component* const mouseDragSource_,
  57100. DragAndDropContainer* const o,
  57101. const Point<int>& imageOffset_)
  57102. : image (im),
  57103. source (sourceComponent),
  57104. mouseDragSource (mouseDragSource_),
  57105. owner (o),
  57106. dragDesc (desc),
  57107. imageOffset (imageOffset_),
  57108. hasCheckedForExternalDrag (false),
  57109. drawImage (true)
  57110. {
  57111. setSize (im.getWidth(), im.getHeight());
  57112. if (mouseDragSource == 0)
  57113. mouseDragSource = source;
  57114. mouseDragSource->addMouseListener (this, false);
  57115. startTimer (200);
  57116. setInterceptsMouseClicks (false, false);
  57117. setAlwaysOnTop (true);
  57118. }
  57119. ~DragImageComponent()
  57120. {
  57121. if (owner->dragImageComponent == this)
  57122. owner->dragImageComponent.release();
  57123. if (mouseDragSource != 0)
  57124. {
  57125. mouseDragSource->removeMouseListener (this);
  57126. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57127. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57128. }
  57129. }
  57130. void paint (Graphics& g)
  57131. {
  57132. if (isOpaque())
  57133. g.fillAll (Colours::white);
  57134. if (drawImage)
  57135. {
  57136. g.setOpacity (1.0f);
  57137. g.drawImageAt (image, 0, 0);
  57138. }
  57139. }
  57140. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57141. {
  57142. Component* hit = getParentComponent();
  57143. if (hit == 0)
  57144. {
  57145. hit = Desktop::getInstance().findComponentAt (screenPos);
  57146. }
  57147. else
  57148. {
  57149. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  57150. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57151. }
  57152. // (note: use a local copy of the dragDesc member in case the callback runs
  57153. // a modal loop and deletes this object before the method completes)
  57154. const String dragDescLocal (dragDesc);
  57155. while (hit != 0)
  57156. {
  57157. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57158. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57159. {
  57160. relativePos = hit->getLocalPoint (0, screenPos);
  57161. return ddt;
  57162. }
  57163. hit = hit->getParentComponent();
  57164. }
  57165. return 0;
  57166. }
  57167. void mouseUp (const MouseEvent& e)
  57168. {
  57169. if (e.originalComponent != this)
  57170. {
  57171. if (mouseDragSource != 0)
  57172. mouseDragSource->removeMouseListener (this);
  57173. bool dropAccepted = false;
  57174. DragAndDropTarget* ddt = 0;
  57175. Point<int> relPos;
  57176. if (isVisible())
  57177. {
  57178. setVisible (false);
  57179. ddt = findTarget (e.getScreenPosition(), relPos);
  57180. // fade this component and remove it - it'll be deleted later by the timer callback
  57181. dropAccepted = ddt != 0;
  57182. setVisible (true);
  57183. if (dropAccepted || source == 0)
  57184. {
  57185. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  57186. }
  57187. else
  57188. {
  57189. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  57190. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  57191. Desktop::getInstance().getAnimator().animateComponent (this,
  57192. getBounds() + (target - ourCentre),
  57193. 0.0f, 120,
  57194. true, 1.0, 1.0);
  57195. }
  57196. }
  57197. if (getParentComponent() != 0)
  57198. getParentComponent()->removeChildComponent (this);
  57199. if (dropAccepted && ddt != 0)
  57200. {
  57201. // (note: use a local copy of the dragDesc member in case the callback runs
  57202. // a modal loop and deletes this object before the method completes)
  57203. const String dragDescLocal (dragDesc);
  57204. currentlyOverComp = 0;
  57205. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57206. }
  57207. // careful - this object could now be deleted..
  57208. }
  57209. }
  57210. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57211. {
  57212. // (note: use a local copy of the dragDesc member in case the callback runs
  57213. // a modal loop and deletes this object before it returns)
  57214. const String dragDescLocal (dragDesc);
  57215. Point<int> newPos (screenPos + imageOffset);
  57216. if (getParentComponent() != 0)
  57217. newPos = getParentComponent()->getLocalPoint (0, newPos);
  57218. //if (newX != getX() || newY != getY())
  57219. {
  57220. setTopLeftPosition (newPos.getX(), newPos.getY());
  57221. Point<int> relPos;
  57222. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57223. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57224. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57225. if (ddtComp != currentlyOverComp)
  57226. {
  57227. if (currentlyOverComp != 0 && source != 0
  57228. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57229. {
  57230. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57231. }
  57232. currentlyOverComp = ddtComp;
  57233. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57234. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57235. }
  57236. DragAndDropTarget* target = getCurrentlyOver();
  57237. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57238. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57239. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57240. {
  57241. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57242. {
  57243. hasCheckedForExternalDrag = true;
  57244. StringArray files;
  57245. bool canMoveFiles = false;
  57246. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57247. && files.size() > 0)
  57248. {
  57249. WeakReference<Component> cdw (this);
  57250. setVisible (false);
  57251. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57252. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57253. if (cdw != 0)
  57254. delete this;
  57255. return;
  57256. }
  57257. }
  57258. }
  57259. }
  57260. }
  57261. void mouseDrag (const MouseEvent& e)
  57262. {
  57263. if (e.originalComponent != this)
  57264. updateLocation (true, e.getScreenPosition());
  57265. }
  57266. void timerCallback()
  57267. {
  57268. if (source == 0)
  57269. {
  57270. delete this;
  57271. }
  57272. else if (! isMouseButtonDownAnywhere())
  57273. {
  57274. if (mouseDragSource != 0)
  57275. mouseDragSource->removeMouseListener (this);
  57276. delete this;
  57277. }
  57278. }
  57279. private:
  57280. Image image;
  57281. WeakReference<Component> source;
  57282. WeakReference<Component> mouseDragSource;
  57283. DragAndDropContainer* const owner;
  57284. WeakReference<Component> currentlyOverComp;
  57285. DragAndDropTarget* getCurrentlyOver()
  57286. {
  57287. return dynamic_cast <DragAndDropTarget*> (currentlyOverComp.get());
  57288. }
  57289. String dragDesc;
  57290. const Point<int> imageOffset;
  57291. bool hasCheckedForExternalDrag, drawImage;
  57292. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  57293. };
  57294. DragAndDropContainer::DragAndDropContainer()
  57295. {
  57296. }
  57297. DragAndDropContainer::~DragAndDropContainer()
  57298. {
  57299. dragImageComponent = 0;
  57300. }
  57301. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57302. Component* sourceComponent,
  57303. const Image& dragImage_,
  57304. const bool allowDraggingToExternalWindows,
  57305. const Point<int>* imageOffsetFromMouse)
  57306. {
  57307. Image dragImage (dragImage_);
  57308. if (dragImageComponent == 0)
  57309. {
  57310. Component* const thisComp = dynamic_cast <Component*> (this);
  57311. if (thisComp == 0)
  57312. {
  57313. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57314. return;
  57315. }
  57316. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57317. if (draggingSource == 0 || ! draggingSource->isDragging())
  57318. {
  57319. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57320. return;
  57321. }
  57322. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57323. Point<int> imageOffset;
  57324. if (dragImage.isNull())
  57325. {
  57326. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57327. .convertedToFormat (Image::ARGB);
  57328. dragImage.multiplyAllAlphas (0.6f);
  57329. const int lo = 150;
  57330. const int hi = 400;
  57331. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  57332. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57333. for (int y = dragImage.getHeight(); --y >= 0;)
  57334. {
  57335. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57336. for (int x = dragImage.getWidth(); --x >= 0;)
  57337. {
  57338. const int dx = x - clipped.getX();
  57339. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57340. if (distance > lo)
  57341. {
  57342. const float alpha = (distance > hi) ? 0
  57343. : (hi - distance) / (float) (hi - lo)
  57344. + Random::getSystemRandom().nextFloat() * 0.008f;
  57345. dragImage.multiplyAlphaAt (x, y, alpha);
  57346. }
  57347. }
  57348. }
  57349. imageOffset = -clipped;
  57350. }
  57351. else
  57352. {
  57353. if (imageOffsetFromMouse == 0)
  57354. imageOffset = -dragImage.getBounds().getCentre();
  57355. else
  57356. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57357. }
  57358. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57359. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57360. currentDragDesc = sourceDescription;
  57361. if (allowDraggingToExternalWindows)
  57362. {
  57363. if (! Desktop::canUseSemiTransparentWindows())
  57364. dragImageComponent->setOpaque (true);
  57365. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57366. | ComponentPeer::windowIsTemporary
  57367. | ComponentPeer::windowIgnoresKeyPresses);
  57368. }
  57369. else
  57370. thisComp->addChildComponent (dragImageComponent);
  57371. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57372. dragImageComponent->setVisible (true);
  57373. }
  57374. }
  57375. bool DragAndDropContainer::isDragAndDropActive() const
  57376. {
  57377. return dragImageComponent != 0;
  57378. }
  57379. const String DragAndDropContainer::getCurrentDragDescription() const
  57380. {
  57381. return (dragImageComponent != 0) ? currentDragDesc
  57382. : String::empty;
  57383. }
  57384. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57385. {
  57386. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57387. }
  57388. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57389. {
  57390. return false;
  57391. }
  57392. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57393. {
  57394. }
  57395. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57396. {
  57397. }
  57398. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57399. {
  57400. }
  57401. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57402. {
  57403. return true;
  57404. }
  57405. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57406. {
  57407. }
  57408. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57409. {
  57410. }
  57411. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57412. {
  57413. }
  57414. END_JUCE_NAMESPACE
  57415. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57416. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57417. BEGIN_JUCE_NAMESPACE
  57418. class MouseCursor::SharedCursorHandle
  57419. {
  57420. public:
  57421. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57422. : handle (createStandardMouseCursor (type)),
  57423. refCount (1),
  57424. standardType (type),
  57425. isStandard (true)
  57426. {
  57427. }
  57428. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57429. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57430. refCount (1),
  57431. standardType (MouseCursor::NormalCursor),
  57432. isStandard (false)
  57433. {
  57434. }
  57435. ~SharedCursorHandle()
  57436. {
  57437. deleteMouseCursor (handle, isStandard);
  57438. }
  57439. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57440. {
  57441. const ScopedLock sl (getLock());
  57442. for (int i = 0; i < getCursors().size(); ++i)
  57443. {
  57444. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57445. if (sc->standardType == type)
  57446. return sc->retain();
  57447. }
  57448. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57449. getCursors().add (sc);
  57450. return sc;
  57451. }
  57452. SharedCursorHandle* retain() throw()
  57453. {
  57454. ++refCount;
  57455. return this;
  57456. }
  57457. void release()
  57458. {
  57459. if (--refCount == 0)
  57460. {
  57461. if (isStandard)
  57462. {
  57463. const ScopedLock sl (getLock());
  57464. getCursors().removeValue (this);
  57465. }
  57466. delete this;
  57467. }
  57468. }
  57469. void* getHandle() const throw() { return handle; }
  57470. private:
  57471. void* const handle;
  57472. Atomic <int> refCount;
  57473. const MouseCursor::StandardCursorType standardType;
  57474. const bool isStandard;
  57475. static CriticalSection& getLock()
  57476. {
  57477. static CriticalSection lock;
  57478. return lock;
  57479. }
  57480. static Array <SharedCursorHandle*>& getCursors()
  57481. {
  57482. static Array <SharedCursorHandle*> cursors;
  57483. return cursors;
  57484. }
  57485. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57486. };
  57487. MouseCursor::MouseCursor()
  57488. : cursorHandle (0)
  57489. {
  57490. }
  57491. MouseCursor::MouseCursor (const StandardCursorType type)
  57492. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57493. {
  57494. }
  57495. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57496. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57497. {
  57498. }
  57499. MouseCursor::MouseCursor (const MouseCursor& other)
  57500. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57501. {
  57502. }
  57503. MouseCursor::~MouseCursor()
  57504. {
  57505. if (cursorHandle != 0)
  57506. cursorHandle->release();
  57507. }
  57508. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57509. {
  57510. if (other.cursorHandle != 0)
  57511. other.cursorHandle->retain();
  57512. if (cursorHandle != 0)
  57513. cursorHandle->release();
  57514. cursorHandle = other.cursorHandle;
  57515. return *this;
  57516. }
  57517. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57518. {
  57519. return getHandle() == other.getHandle();
  57520. }
  57521. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57522. {
  57523. return getHandle() != other.getHandle();
  57524. }
  57525. void* MouseCursor::getHandle() const throw()
  57526. {
  57527. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57528. }
  57529. void MouseCursor::showWaitCursor()
  57530. {
  57531. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57532. }
  57533. void MouseCursor::hideWaitCursor()
  57534. {
  57535. Desktop::getInstance().getMainMouseSource().revealCursor();
  57536. }
  57537. END_JUCE_NAMESPACE
  57538. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57539. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57540. BEGIN_JUCE_NAMESPACE
  57541. MouseEvent::MouseEvent (MouseInputSource& source_,
  57542. const Point<int>& position,
  57543. const ModifierKeys& mods_,
  57544. Component* const eventComponent_,
  57545. Component* const originator,
  57546. const Time& eventTime_,
  57547. const Point<int> mouseDownPos_,
  57548. const Time& mouseDownTime_,
  57549. const int numberOfClicks_,
  57550. const bool mouseWasDragged) throw()
  57551. : x (position.getX()),
  57552. y (position.getY()),
  57553. mods (mods_),
  57554. eventComponent (eventComponent_),
  57555. originalComponent (originator),
  57556. eventTime (eventTime_),
  57557. source (source_),
  57558. mouseDownPos (mouseDownPos_),
  57559. mouseDownTime (mouseDownTime_),
  57560. numberOfClicks (numberOfClicks_),
  57561. wasMovedSinceMouseDown (mouseWasDragged)
  57562. {
  57563. }
  57564. MouseEvent::~MouseEvent() throw()
  57565. {
  57566. }
  57567. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57568. {
  57569. if (otherComponent == 0)
  57570. {
  57571. jassertfalse;
  57572. return *this;
  57573. }
  57574. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57575. mods, otherComponent, originalComponent, eventTime,
  57576. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57577. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57578. }
  57579. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57580. {
  57581. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57582. eventTime, mouseDownPos, mouseDownTime,
  57583. numberOfClicks, wasMovedSinceMouseDown);
  57584. }
  57585. bool MouseEvent::mouseWasClicked() const throw()
  57586. {
  57587. return ! wasMovedSinceMouseDown;
  57588. }
  57589. int MouseEvent::getMouseDownX() const throw()
  57590. {
  57591. return mouseDownPos.getX();
  57592. }
  57593. int MouseEvent::getMouseDownY() const throw()
  57594. {
  57595. return mouseDownPos.getY();
  57596. }
  57597. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57598. {
  57599. return mouseDownPos;
  57600. }
  57601. int MouseEvent::getDistanceFromDragStartX() const throw()
  57602. {
  57603. return x - mouseDownPos.getX();
  57604. }
  57605. int MouseEvent::getDistanceFromDragStartY() const throw()
  57606. {
  57607. return y - mouseDownPos.getY();
  57608. }
  57609. int MouseEvent::getDistanceFromDragStart() const throw()
  57610. {
  57611. return mouseDownPos.getDistanceFrom (getPosition());
  57612. }
  57613. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57614. {
  57615. return getPosition() - mouseDownPos;
  57616. }
  57617. int MouseEvent::getLengthOfMousePress() const throw()
  57618. {
  57619. if (mouseDownTime.toMilliseconds() > 0)
  57620. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57621. return 0;
  57622. }
  57623. const Point<int> MouseEvent::getPosition() const throw()
  57624. {
  57625. return Point<int> (x, y);
  57626. }
  57627. int MouseEvent::getScreenX() const
  57628. {
  57629. return getScreenPosition().getX();
  57630. }
  57631. int MouseEvent::getScreenY() const
  57632. {
  57633. return getScreenPosition().getY();
  57634. }
  57635. const Point<int> MouseEvent::getScreenPosition() const
  57636. {
  57637. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57638. }
  57639. int MouseEvent::getMouseDownScreenX() const
  57640. {
  57641. return getMouseDownScreenPosition().getX();
  57642. }
  57643. int MouseEvent::getMouseDownScreenY() const
  57644. {
  57645. return getMouseDownScreenPosition().getY();
  57646. }
  57647. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57648. {
  57649. return eventComponent->localPointToGlobal (mouseDownPos);
  57650. }
  57651. int MouseEvent::doubleClickTimeOutMs = 400;
  57652. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57653. {
  57654. doubleClickTimeOutMs = newTime;
  57655. }
  57656. int MouseEvent::getDoubleClickTimeout() throw()
  57657. {
  57658. return doubleClickTimeOutMs;
  57659. }
  57660. END_JUCE_NAMESPACE
  57661. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57662. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57663. BEGIN_JUCE_NAMESPACE
  57664. class MouseInputSourceInternal : public AsyncUpdater
  57665. {
  57666. public:
  57667. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57668. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57669. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57670. mouseEventCounter (0)
  57671. {
  57672. }
  57673. bool isDragging() const throw()
  57674. {
  57675. return buttonState.isAnyMouseButtonDown();
  57676. }
  57677. Component* getComponentUnderMouse() const
  57678. {
  57679. return static_cast <Component*> (componentUnderMouse);
  57680. }
  57681. const ModifierKeys getCurrentModifiers() const
  57682. {
  57683. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57684. }
  57685. ComponentPeer* getPeer()
  57686. {
  57687. if (! ComponentPeer::isValidPeer (lastPeer))
  57688. lastPeer = 0;
  57689. return lastPeer;
  57690. }
  57691. Component* findComponentAt (const Point<int>& screenPos)
  57692. {
  57693. ComponentPeer* const peer = getPeer();
  57694. if (peer != 0)
  57695. {
  57696. Component* const comp = peer->getComponent();
  57697. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57698. // (the contains() call is needed to test for overlapping desktop windows)
  57699. if (comp->contains (relativePos))
  57700. return comp->getComponentAt (relativePos);
  57701. }
  57702. return 0;
  57703. }
  57704. const Point<int> getScreenPosition() const
  57705. {
  57706. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57707. // value, because that can cause continuity problems.
  57708. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57709. : lastScreenPos);
  57710. }
  57711. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const Time& time)
  57712. {
  57713. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57714. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57715. }
  57716. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const Time& time)
  57717. {
  57718. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57719. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57720. }
  57721. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const Time& time)
  57722. {
  57723. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57724. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57725. }
  57726. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const Time& time)
  57727. {
  57728. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57729. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57730. }
  57731. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const Time& time)
  57732. {
  57733. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57734. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57735. }
  57736. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const Time& time)
  57737. {
  57738. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57739. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57740. }
  57741. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const Time& time, float x, float y)
  57742. {
  57743. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57744. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57745. }
  57746. // (returns true if the button change caused a modal event loop)
  57747. bool setButtons (const Point<int>& screenPos, const Time& time, const ModifierKeys& newButtonState)
  57748. {
  57749. if (buttonState == newButtonState)
  57750. return false;
  57751. setScreenPos (screenPos, time, false);
  57752. // (ignore secondary clicks when there's already a button down)
  57753. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57754. {
  57755. buttonState = newButtonState;
  57756. return false;
  57757. }
  57758. const int lastCounter = mouseEventCounter;
  57759. if (buttonState.isAnyMouseButtonDown())
  57760. {
  57761. Component* const current = getComponentUnderMouse();
  57762. if (current != 0)
  57763. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57764. enableUnboundedMouseMovement (false, false);
  57765. }
  57766. buttonState = newButtonState;
  57767. if (buttonState.isAnyMouseButtonDown())
  57768. {
  57769. Desktop::getInstance().incrementMouseClickCounter();
  57770. Component* const current = getComponentUnderMouse();
  57771. if (current != 0)
  57772. {
  57773. registerMouseDown (screenPos, time, current, buttonState);
  57774. sendMouseDown (current, screenPos, time);
  57775. }
  57776. }
  57777. return lastCounter != mouseEventCounter;
  57778. }
  57779. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const Time& time)
  57780. {
  57781. Component* current = getComponentUnderMouse();
  57782. if (newComponent != current)
  57783. {
  57784. WeakReference<Component> safeNewComp (newComponent);
  57785. const ModifierKeys originalButtonState (buttonState);
  57786. if (current != 0)
  57787. {
  57788. setButtons (screenPos, time, ModifierKeys());
  57789. sendMouseExit (current, screenPos, time);
  57790. buttonState = originalButtonState;
  57791. }
  57792. componentUnderMouse = safeNewComp;
  57793. current = getComponentUnderMouse();
  57794. if (current != 0)
  57795. sendMouseEnter (current, screenPos, time);
  57796. revealCursor (false);
  57797. setButtons (screenPos, time, originalButtonState);
  57798. }
  57799. }
  57800. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const Time& time)
  57801. {
  57802. ModifierKeys::updateCurrentModifiers();
  57803. if (newPeer != lastPeer)
  57804. {
  57805. setComponentUnderMouse (0, screenPos, time);
  57806. lastPeer = newPeer;
  57807. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57808. }
  57809. }
  57810. void setScreenPos (const Point<int>& newScreenPos, const Time& time, const bool forceUpdate)
  57811. {
  57812. if (! isDragging())
  57813. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57814. if (newScreenPos != lastScreenPos || forceUpdate)
  57815. {
  57816. cancelPendingUpdate();
  57817. lastScreenPos = newScreenPos;
  57818. Component* const current = getComponentUnderMouse();
  57819. if (current != 0)
  57820. {
  57821. if (isDragging())
  57822. {
  57823. registerMouseDrag (newScreenPos);
  57824. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57825. if (isUnboundedMouseModeOn)
  57826. handleUnboundedDrag (current);
  57827. }
  57828. else
  57829. {
  57830. sendMouseMove (current, newScreenPos, time);
  57831. }
  57832. }
  57833. revealCursor (false);
  57834. }
  57835. }
  57836. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const Time& time, const ModifierKeys& newMods)
  57837. {
  57838. jassert (newPeer != 0);
  57839. lastTime = time;
  57840. ++mouseEventCounter;
  57841. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57842. if (isDragging() && newMods.isAnyMouseButtonDown())
  57843. {
  57844. setScreenPos (screenPos, time, false);
  57845. }
  57846. else
  57847. {
  57848. setPeer (newPeer, screenPos, time);
  57849. ComponentPeer* peer = getPeer();
  57850. if (peer != 0)
  57851. {
  57852. if (setButtons (screenPos, time, newMods))
  57853. return; // some modal events have been dispatched, so the current event is now out-of-date
  57854. peer = getPeer();
  57855. if (peer != 0)
  57856. setScreenPos (screenPos, time, false);
  57857. }
  57858. }
  57859. }
  57860. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const Time& time, float x, float y)
  57861. {
  57862. jassert (peer != 0);
  57863. lastTime = time;
  57864. ++mouseEventCounter;
  57865. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57866. setPeer (peer, screenPos, time);
  57867. setScreenPos (screenPos, time, false);
  57868. triggerFakeMove();
  57869. if (! isDragging())
  57870. {
  57871. Component* current = getComponentUnderMouse();
  57872. if (current != 0)
  57873. sendMouseWheel (current, screenPos, time, x, y);
  57874. }
  57875. }
  57876. const Time getLastMouseDownTime() const throw()
  57877. {
  57878. return Time (mouseDowns[0].time);
  57879. }
  57880. const Point<int> getLastMouseDownPosition() const throw()
  57881. {
  57882. return mouseDowns[0].position;
  57883. }
  57884. int getNumberOfMultipleClicks() const throw()
  57885. {
  57886. int numClicks = 0;
  57887. if (mouseDowns[0].time != Time())
  57888. {
  57889. if (! mouseMovedSignificantlySincePressed)
  57890. ++numClicks;
  57891. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57892. {
  57893. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57894. ++numClicks;
  57895. else
  57896. break;
  57897. }
  57898. }
  57899. return numClicks;
  57900. }
  57901. bool hasMouseMovedSignificantlySincePressed() const throw()
  57902. {
  57903. return mouseMovedSignificantlySincePressed
  57904. || lastTime > mouseDowns[0].time + RelativeTime::milliseconds (300);
  57905. }
  57906. void triggerFakeMove()
  57907. {
  57908. triggerAsyncUpdate();
  57909. }
  57910. void handleAsyncUpdate()
  57911. {
  57912. setScreenPos (lastScreenPos, jmax (lastTime, Time::getCurrentTime()), true);
  57913. }
  57914. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57915. {
  57916. enable = enable && isDragging();
  57917. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57918. if (enable != isUnboundedMouseModeOn)
  57919. {
  57920. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57921. {
  57922. // when released, return the mouse to within the component's bounds
  57923. Component* current = getComponentUnderMouse();
  57924. if (current != 0)
  57925. Desktop::setMousePosition (current->getScreenBounds()
  57926. .getConstrainedPoint (lastScreenPos));
  57927. }
  57928. isUnboundedMouseModeOn = enable;
  57929. unboundedMouseOffset = Point<int>();
  57930. revealCursor (true);
  57931. }
  57932. }
  57933. void handleUnboundedDrag (Component* current)
  57934. {
  57935. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57936. if (! screenArea.contains (lastScreenPos))
  57937. {
  57938. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57939. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57940. Desktop::setMousePosition (componentCentre);
  57941. }
  57942. else if (isCursorVisibleUntilOffscreen
  57943. && (! unboundedMouseOffset.isOrigin())
  57944. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57945. {
  57946. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57947. unboundedMouseOffset = Point<int>();
  57948. }
  57949. }
  57950. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57951. {
  57952. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57953. {
  57954. cursor = MouseCursor::NoCursor;
  57955. forcedUpdate = true;
  57956. }
  57957. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57958. {
  57959. currentCursorHandle = cursor.getHandle();
  57960. cursor.showInWindow (getPeer());
  57961. }
  57962. }
  57963. void hideCursor()
  57964. {
  57965. showMouseCursor (MouseCursor::NoCursor, true);
  57966. }
  57967. void revealCursor (bool forcedUpdate)
  57968. {
  57969. MouseCursor mc (MouseCursor::NormalCursor);
  57970. Component* current = getComponentUnderMouse();
  57971. if (current != 0)
  57972. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57973. showMouseCursor (mc, forcedUpdate);
  57974. }
  57975. const int index;
  57976. const bool isMouseDevice;
  57977. Point<int> lastScreenPos;
  57978. ModifierKeys buttonState;
  57979. private:
  57980. MouseInputSource& source;
  57981. WeakReference<Component> componentUnderMouse;
  57982. ComponentPeer* lastPeer;
  57983. Point<int> unboundedMouseOffset;
  57984. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57985. void* currentCursorHandle;
  57986. int mouseEventCounter;
  57987. struct RecentMouseDown
  57988. {
  57989. RecentMouseDown() : component (0)
  57990. {
  57991. }
  57992. Point<int> position;
  57993. Time time;
  57994. Component* component;
  57995. ModifierKeys buttons;
  57996. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetweenMs) const
  57997. {
  57998. return time - other.time < RelativeTime::milliseconds (maxTimeBetweenMs)
  57999. && abs (position.getX() - other.position.getX()) < 8
  58000. && abs (position.getY() - other.position.getY()) < 8
  58001. && buttons == other.buttons;;
  58002. }
  58003. };
  58004. RecentMouseDown mouseDowns[4];
  58005. bool mouseMovedSignificantlySincePressed;
  58006. Time lastTime;
  58007. void registerMouseDown (const Point<int>& screenPos, const Time& time,
  58008. Component* const component, const ModifierKeys& modifiers) throw()
  58009. {
  58010. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  58011. mouseDowns[i] = mouseDowns[i - 1];
  58012. mouseDowns[0].position = screenPos;
  58013. mouseDowns[0].time = time;
  58014. mouseDowns[0].component = component;
  58015. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  58016. mouseMovedSignificantlySincePressed = false;
  58017. }
  58018. void registerMouseDrag (const Point<int>& screenPos) throw()
  58019. {
  58020. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  58021. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  58022. }
  58023. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  58024. };
  58025. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  58026. {
  58027. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  58028. }
  58029. MouseInputSource::~MouseInputSource()
  58030. {
  58031. }
  58032. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  58033. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  58034. bool MouseInputSource::canHover() const { return isMouse(); }
  58035. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  58036. int MouseInputSource::getIndex() const { return pimpl->index; }
  58037. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  58038. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  58039. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  58040. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  58041. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  58042. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  58043. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  58044. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  58045. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  58046. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  58047. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  58048. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  58049. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  58050. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  58051. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  58052. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  58053. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  58054. {
  58055. pimpl->handleEvent (peer, positionWithinPeer, Time (time), mods.withOnlyMouseButtons());
  58056. }
  58057. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  58058. {
  58059. pimpl->handleWheel (peer, positionWithinPeer, Time (time), x, y);
  58060. }
  58061. END_JUCE_NAMESPACE
  58062. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  58063. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58064. BEGIN_JUCE_NAMESPACE
  58065. void MouseListener::mouseEnter (const MouseEvent&)
  58066. {
  58067. }
  58068. void MouseListener::mouseExit (const MouseEvent&)
  58069. {
  58070. }
  58071. void MouseListener::mouseDown (const MouseEvent&)
  58072. {
  58073. }
  58074. void MouseListener::mouseUp (const MouseEvent&)
  58075. {
  58076. }
  58077. void MouseListener::mouseDrag (const MouseEvent&)
  58078. {
  58079. }
  58080. void MouseListener::mouseMove (const MouseEvent&)
  58081. {
  58082. }
  58083. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58084. {
  58085. }
  58086. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58087. {
  58088. }
  58089. END_JUCE_NAMESPACE
  58090. /*** End of inlined file: juce_MouseListener.cpp ***/
  58091. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58092. BEGIN_JUCE_NAMESPACE
  58093. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58094. const String& buttonTextWhenTrue,
  58095. const String& buttonTextWhenFalse)
  58096. : PropertyComponent (name),
  58097. onText (buttonTextWhenTrue),
  58098. offText (buttonTextWhenFalse)
  58099. {
  58100. addAndMakeVisible (&button);
  58101. button.setClickingTogglesState (false);
  58102. button.addListener (this);
  58103. }
  58104. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58105. const String& name,
  58106. const String& buttonText)
  58107. : PropertyComponent (name),
  58108. onText (buttonText),
  58109. offText (buttonText)
  58110. {
  58111. addAndMakeVisible (&button);
  58112. button.setClickingTogglesState (false);
  58113. button.setButtonText (buttonText);
  58114. button.getToggleStateValue().referTo (valueToControl);
  58115. button.setClickingTogglesState (true);
  58116. }
  58117. BooleanPropertyComponent::~BooleanPropertyComponent()
  58118. {
  58119. }
  58120. void BooleanPropertyComponent::setState (const bool newState)
  58121. {
  58122. button.setToggleState (newState, true);
  58123. }
  58124. bool BooleanPropertyComponent::getState() const
  58125. {
  58126. return button.getToggleState();
  58127. }
  58128. void BooleanPropertyComponent::paint (Graphics& g)
  58129. {
  58130. PropertyComponent::paint (g);
  58131. g.setColour (Colours::white);
  58132. g.fillRect (button.getBounds());
  58133. g.setColour (findColour (ComboBox::outlineColourId));
  58134. g.drawRect (button.getBounds());
  58135. }
  58136. void BooleanPropertyComponent::refresh()
  58137. {
  58138. button.setToggleState (getState(), false);
  58139. button.setButtonText (button.getToggleState() ? onText : offText);
  58140. }
  58141. void BooleanPropertyComponent::buttonClicked (Button*)
  58142. {
  58143. setState (! getState());
  58144. }
  58145. END_JUCE_NAMESPACE
  58146. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58147. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58148. BEGIN_JUCE_NAMESPACE
  58149. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58150. const bool triggerOnMouseDown)
  58151. : PropertyComponent (name)
  58152. {
  58153. addAndMakeVisible (&button);
  58154. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58155. button.addListener (this);
  58156. }
  58157. ButtonPropertyComponent::~ButtonPropertyComponent()
  58158. {
  58159. }
  58160. void ButtonPropertyComponent::refresh()
  58161. {
  58162. button.setButtonText (getButtonText());
  58163. }
  58164. void ButtonPropertyComponent::buttonClicked (Button*)
  58165. {
  58166. buttonClicked();
  58167. }
  58168. END_JUCE_NAMESPACE
  58169. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58170. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58171. BEGIN_JUCE_NAMESPACE
  58172. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58173. public ValueListener
  58174. {
  58175. public:
  58176. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58177. : sourceValue (sourceValue_),
  58178. mappings (mappings_)
  58179. {
  58180. sourceValue.addListener (this);
  58181. }
  58182. ~RemapperValueSource() {}
  58183. const var getValue() const
  58184. {
  58185. return mappings.indexOf (sourceValue.getValue()) + 1;
  58186. }
  58187. void setValue (const var& newValue)
  58188. {
  58189. const var remappedVal (mappings [(int) newValue - 1]);
  58190. if (remappedVal != sourceValue)
  58191. sourceValue = remappedVal;
  58192. }
  58193. void valueChanged (Value&)
  58194. {
  58195. sendChangeMessage (true);
  58196. }
  58197. protected:
  58198. Value sourceValue;
  58199. Array<var> mappings;
  58200. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  58201. };
  58202. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58203. : PropertyComponent (name),
  58204. isCustomClass (true)
  58205. {
  58206. }
  58207. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58208. const String& name,
  58209. const StringArray& choices_,
  58210. const Array <var>& correspondingValues)
  58211. : PropertyComponent (name),
  58212. choices (choices_),
  58213. isCustomClass (false)
  58214. {
  58215. // The array of corresponding values must contain one value for each of the items in
  58216. // the choices array!
  58217. jassert (correspondingValues.size() == choices.size());
  58218. createComboBox();
  58219. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58220. }
  58221. ChoicePropertyComponent::~ChoicePropertyComponent()
  58222. {
  58223. }
  58224. void ChoicePropertyComponent::createComboBox()
  58225. {
  58226. addAndMakeVisible (&comboBox);
  58227. for (int i = 0; i < choices.size(); ++i)
  58228. {
  58229. if (choices[i].isNotEmpty())
  58230. comboBox.addItem (choices[i], i + 1);
  58231. else
  58232. comboBox.addSeparator();
  58233. }
  58234. comboBox.setEditableText (false);
  58235. }
  58236. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58237. {
  58238. jassertfalse; // you need to override this method in your subclass!
  58239. }
  58240. int ChoicePropertyComponent::getIndex() const
  58241. {
  58242. jassertfalse; // you need to override this method in your subclass!
  58243. return -1;
  58244. }
  58245. const StringArray& ChoicePropertyComponent::getChoices() const
  58246. {
  58247. return choices;
  58248. }
  58249. void ChoicePropertyComponent::refresh()
  58250. {
  58251. if (isCustomClass)
  58252. {
  58253. if (! comboBox.isVisible())
  58254. {
  58255. createComboBox();
  58256. comboBox.addListener (this);
  58257. }
  58258. comboBox.setSelectedId (getIndex() + 1, true);
  58259. }
  58260. }
  58261. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58262. {
  58263. if (isCustomClass)
  58264. {
  58265. const int newIndex = comboBox.getSelectedId() - 1;
  58266. if (newIndex != getIndex())
  58267. setIndex (newIndex);
  58268. }
  58269. }
  58270. END_JUCE_NAMESPACE
  58271. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58272. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58273. BEGIN_JUCE_NAMESPACE
  58274. PropertyComponent::PropertyComponent (const String& name,
  58275. const int preferredHeight_)
  58276. : Component (name),
  58277. preferredHeight (preferredHeight_)
  58278. {
  58279. jassert (name.isNotEmpty());
  58280. }
  58281. PropertyComponent::~PropertyComponent()
  58282. {
  58283. }
  58284. void PropertyComponent::paint (Graphics& g)
  58285. {
  58286. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58287. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58288. }
  58289. void PropertyComponent::resized()
  58290. {
  58291. if (getNumChildComponents() > 0)
  58292. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58293. }
  58294. void PropertyComponent::enablementChanged()
  58295. {
  58296. repaint();
  58297. }
  58298. END_JUCE_NAMESPACE
  58299. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58300. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58301. BEGIN_JUCE_NAMESPACE
  58302. class PropertySectionComponent : public Component
  58303. {
  58304. public:
  58305. PropertySectionComponent (const String& sectionTitle,
  58306. const Array <PropertyComponent*>& newProperties,
  58307. const bool sectionIsOpen_)
  58308. : Component (sectionTitle),
  58309. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58310. sectionIsOpen (sectionIsOpen_)
  58311. {
  58312. propertyComps.addArray (newProperties);
  58313. for (int i = propertyComps.size(); --i >= 0;)
  58314. {
  58315. addAndMakeVisible (propertyComps.getUnchecked(i));
  58316. propertyComps.getUnchecked(i)->refresh();
  58317. }
  58318. }
  58319. ~PropertySectionComponent()
  58320. {
  58321. propertyComps.clear();
  58322. }
  58323. void paint (Graphics& g)
  58324. {
  58325. if (titleHeight > 0)
  58326. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58327. }
  58328. void resized()
  58329. {
  58330. int y = titleHeight;
  58331. for (int i = 0; i < propertyComps.size(); ++i)
  58332. {
  58333. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  58334. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  58335. y = pec->getBottom();
  58336. }
  58337. }
  58338. int getPreferredHeight() const
  58339. {
  58340. int y = titleHeight;
  58341. if (isOpen())
  58342. {
  58343. for (int i = propertyComps.size(); --i >= 0;)
  58344. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  58345. }
  58346. return y;
  58347. }
  58348. void setOpen (const bool open)
  58349. {
  58350. if (sectionIsOpen != open)
  58351. {
  58352. sectionIsOpen = open;
  58353. for (int i = propertyComps.size(); --i >= 0;)
  58354. propertyComps.getUnchecked(i)->setVisible (open);
  58355. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58356. if (pp != 0)
  58357. pp->resized();
  58358. }
  58359. }
  58360. bool isOpen() const
  58361. {
  58362. return sectionIsOpen;
  58363. }
  58364. void refreshAll() const
  58365. {
  58366. for (int i = propertyComps.size(); --i >= 0;)
  58367. propertyComps.getUnchecked (i)->refresh();
  58368. }
  58369. void mouseUp (const MouseEvent& e)
  58370. {
  58371. if (e.getMouseDownX() < titleHeight
  58372. && e.x < titleHeight
  58373. && e.y < titleHeight
  58374. && e.getNumberOfClicks() != 2)
  58375. {
  58376. setOpen (! isOpen());
  58377. }
  58378. }
  58379. void mouseDoubleClick (const MouseEvent& e)
  58380. {
  58381. if (e.y < titleHeight)
  58382. setOpen (! isOpen());
  58383. }
  58384. private:
  58385. OwnedArray <PropertyComponent> propertyComps;
  58386. int titleHeight;
  58387. bool sectionIsOpen;
  58388. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58389. };
  58390. class PropertyPanel::PropertyHolderComponent : public Component
  58391. {
  58392. public:
  58393. PropertyHolderComponent() {}
  58394. void paint (Graphics&) {}
  58395. void updateLayout (int width)
  58396. {
  58397. int y = 0;
  58398. for (int i = 0; i < sections.size(); ++i)
  58399. {
  58400. PropertySectionComponent* const section = sections.getUnchecked(i);
  58401. section->setBounds (0, y, width, section->getPreferredHeight());
  58402. y = section->getBottom();
  58403. }
  58404. setSize (width, y);
  58405. repaint();
  58406. }
  58407. void refreshAll() const
  58408. {
  58409. for (int i = 0; i < sections.size(); ++i)
  58410. sections.getUnchecked(i)->refreshAll();
  58411. }
  58412. void clear()
  58413. {
  58414. sections.clear();
  58415. }
  58416. void addSection (PropertySectionComponent* newSection)
  58417. {
  58418. sections.add (newSection);
  58419. addAndMakeVisible (newSection, 0);
  58420. }
  58421. int getNumSections() const throw() { return sections.size(); }
  58422. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58423. private:
  58424. OwnedArray<PropertySectionComponent> sections;
  58425. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58426. };
  58427. PropertyPanel::PropertyPanel()
  58428. {
  58429. messageWhenEmpty = TRANS("(nothing selected)");
  58430. addAndMakeVisible (&viewport);
  58431. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58432. viewport.setFocusContainer (true);
  58433. }
  58434. PropertyPanel::~PropertyPanel()
  58435. {
  58436. clear();
  58437. }
  58438. void PropertyPanel::paint (Graphics& g)
  58439. {
  58440. if (propertyHolderComponent->getNumSections() == 0)
  58441. {
  58442. g.setColour (Colours::black.withAlpha (0.5f));
  58443. g.setFont (14.0f);
  58444. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58445. Justification::centred, true);
  58446. }
  58447. }
  58448. void PropertyPanel::resized()
  58449. {
  58450. viewport.setBounds (getLocalBounds());
  58451. updatePropHolderLayout();
  58452. }
  58453. void PropertyPanel::clear()
  58454. {
  58455. if (propertyHolderComponent->getNumSections() > 0)
  58456. {
  58457. propertyHolderComponent->clear();
  58458. repaint();
  58459. }
  58460. }
  58461. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58462. {
  58463. if (propertyHolderComponent->getNumSections() == 0)
  58464. repaint();
  58465. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58466. updatePropHolderLayout();
  58467. }
  58468. void PropertyPanel::addSection (const String& sectionTitle,
  58469. const Array <PropertyComponent*>& newProperties,
  58470. const bool shouldBeOpen)
  58471. {
  58472. jassert (sectionTitle.isNotEmpty());
  58473. if (propertyHolderComponent->getNumSections() == 0)
  58474. repaint();
  58475. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58476. updatePropHolderLayout();
  58477. }
  58478. void PropertyPanel::updatePropHolderLayout() const
  58479. {
  58480. const int maxWidth = viewport.getMaximumVisibleWidth();
  58481. propertyHolderComponent->updateLayout (maxWidth);
  58482. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58483. if (maxWidth != newMaxWidth)
  58484. {
  58485. // need to do this twice because of scrollbars changing the size, etc.
  58486. propertyHolderComponent->updateLayout (newMaxWidth);
  58487. }
  58488. }
  58489. void PropertyPanel::refreshAll() const
  58490. {
  58491. propertyHolderComponent->refreshAll();
  58492. }
  58493. const StringArray PropertyPanel::getSectionNames() const
  58494. {
  58495. StringArray s;
  58496. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58497. {
  58498. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58499. if (section->getName().isNotEmpty())
  58500. s.add (section->getName());
  58501. }
  58502. return s;
  58503. }
  58504. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58505. {
  58506. int index = 0;
  58507. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58508. {
  58509. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58510. if (section->getName().isNotEmpty())
  58511. {
  58512. if (index == sectionIndex)
  58513. return section->isOpen();
  58514. ++index;
  58515. }
  58516. }
  58517. return false;
  58518. }
  58519. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58520. {
  58521. int index = 0;
  58522. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58523. {
  58524. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58525. if (section->getName().isNotEmpty())
  58526. {
  58527. if (index == sectionIndex)
  58528. {
  58529. section->setOpen (shouldBeOpen);
  58530. break;
  58531. }
  58532. ++index;
  58533. }
  58534. }
  58535. }
  58536. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58537. {
  58538. int index = 0;
  58539. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58540. {
  58541. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58542. if (section->getName().isNotEmpty())
  58543. {
  58544. if (index == sectionIndex)
  58545. {
  58546. section->setEnabled (shouldBeEnabled);
  58547. break;
  58548. }
  58549. ++index;
  58550. }
  58551. }
  58552. }
  58553. XmlElement* PropertyPanel::getOpennessState() const
  58554. {
  58555. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58556. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58557. const StringArray sections (getSectionNames());
  58558. for (int i = 0; i < sections.size(); ++i)
  58559. {
  58560. if (sections[i].isNotEmpty())
  58561. {
  58562. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58563. e->setAttribute ("name", sections[i]);
  58564. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58565. }
  58566. }
  58567. return xml;
  58568. }
  58569. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58570. {
  58571. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58572. {
  58573. const StringArray sections (getSectionNames());
  58574. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58575. {
  58576. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58577. e->getBoolAttribute ("open"));
  58578. }
  58579. viewport.setViewPosition (viewport.getViewPositionX(),
  58580. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58581. }
  58582. }
  58583. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58584. {
  58585. if (messageWhenEmpty != newMessage)
  58586. {
  58587. messageWhenEmpty = newMessage;
  58588. repaint();
  58589. }
  58590. }
  58591. const String& PropertyPanel::getMessageWhenEmpty() const
  58592. {
  58593. return messageWhenEmpty;
  58594. }
  58595. END_JUCE_NAMESPACE
  58596. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58597. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58598. BEGIN_JUCE_NAMESPACE
  58599. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58600. const double rangeMin,
  58601. const double rangeMax,
  58602. const double interval,
  58603. const double skewFactor)
  58604. : PropertyComponent (name)
  58605. {
  58606. addAndMakeVisible (&slider);
  58607. slider.setRange (rangeMin, rangeMax, interval);
  58608. slider.setSkewFactor (skewFactor);
  58609. slider.setSliderStyle (Slider::LinearBar);
  58610. slider.addListener (this);
  58611. }
  58612. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58613. const String& name,
  58614. const double rangeMin,
  58615. const double rangeMax,
  58616. const double interval,
  58617. const double skewFactor)
  58618. : PropertyComponent (name)
  58619. {
  58620. addAndMakeVisible (&slider);
  58621. slider.setRange (rangeMin, rangeMax, interval);
  58622. slider.setSkewFactor (skewFactor);
  58623. slider.setSliderStyle (Slider::LinearBar);
  58624. slider.getValueObject().referTo (valueToControl);
  58625. }
  58626. SliderPropertyComponent::~SliderPropertyComponent()
  58627. {
  58628. }
  58629. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58630. {
  58631. }
  58632. double SliderPropertyComponent::getValue() const
  58633. {
  58634. return slider.getValue();
  58635. }
  58636. void SliderPropertyComponent::refresh()
  58637. {
  58638. slider.setValue (getValue(), false);
  58639. }
  58640. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58641. {
  58642. if (getValue() != slider.getValue())
  58643. setValue (slider.getValue());
  58644. }
  58645. END_JUCE_NAMESPACE
  58646. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58647. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58648. BEGIN_JUCE_NAMESPACE
  58649. class TextPropLabel : public Label
  58650. {
  58651. public:
  58652. TextPropLabel (TextPropertyComponent& owner_,
  58653. const int maxChars_, const bool isMultiline_)
  58654. : Label (String::empty, String::empty),
  58655. owner (owner_),
  58656. maxChars (maxChars_),
  58657. isMultiline (isMultiline_)
  58658. {
  58659. setEditable (true, true, false);
  58660. setColour (backgroundColourId, Colours::white);
  58661. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58662. }
  58663. TextEditor* createEditorComponent()
  58664. {
  58665. TextEditor* const textEditor = Label::createEditorComponent();
  58666. textEditor->setInputRestrictions (maxChars);
  58667. if (isMultiline)
  58668. {
  58669. textEditor->setMultiLine (true, true);
  58670. textEditor->setReturnKeyStartsNewLine (true);
  58671. }
  58672. return textEditor;
  58673. }
  58674. void textWasEdited()
  58675. {
  58676. owner.textWasEdited();
  58677. }
  58678. private:
  58679. TextPropertyComponent& owner;
  58680. int maxChars;
  58681. bool isMultiline;
  58682. };
  58683. TextPropertyComponent::TextPropertyComponent (const String& name,
  58684. const int maxNumChars,
  58685. const bool isMultiLine)
  58686. : PropertyComponent (name)
  58687. {
  58688. createEditor (maxNumChars, isMultiLine);
  58689. }
  58690. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58691. const String& name,
  58692. const int maxNumChars,
  58693. const bool isMultiLine)
  58694. : PropertyComponent (name)
  58695. {
  58696. createEditor (maxNumChars, isMultiLine);
  58697. textEditor->getTextValue().referTo (valueToControl);
  58698. }
  58699. TextPropertyComponent::~TextPropertyComponent()
  58700. {
  58701. }
  58702. void TextPropertyComponent::setText (const String& newText)
  58703. {
  58704. textEditor->setText (newText, true);
  58705. }
  58706. const String TextPropertyComponent::getText() const
  58707. {
  58708. return textEditor->getText();
  58709. }
  58710. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58711. {
  58712. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58713. if (isMultiLine)
  58714. {
  58715. textEditor->setJustificationType (Justification::topLeft);
  58716. preferredHeight = 120;
  58717. }
  58718. }
  58719. void TextPropertyComponent::refresh()
  58720. {
  58721. textEditor->setText (getText(), false);
  58722. }
  58723. void TextPropertyComponent::textWasEdited()
  58724. {
  58725. const String newText (textEditor->getText());
  58726. if (getText() != newText)
  58727. setText (newText);
  58728. }
  58729. END_JUCE_NAMESPACE
  58730. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58731. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58732. BEGIN_JUCE_NAMESPACE
  58733. class SimpleDeviceManagerInputLevelMeter : public Component,
  58734. public Timer
  58735. {
  58736. public:
  58737. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58738. : manager (manager_),
  58739. level (0)
  58740. {
  58741. startTimer (50);
  58742. manager->enableInputLevelMeasurement (true);
  58743. }
  58744. ~SimpleDeviceManagerInputLevelMeter()
  58745. {
  58746. manager->enableInputLevelMeasurement (false);
  58747. }
  58748. void timerCallback()
  58749. {
  58750. const float newLevel = (float) manager->getCurrentInputLevel();
  58751. if (std::abs (level - newLevel) > 0.005f)
  58752. {
  58753. level = newLevel;
  58754. repaint();
  58755. }
  58756. }
  58757. void paint (Graphics& g)
  58758. {
  58759. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58760. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58761. }
  58762. private:
  58763. AudioDeviceManager* const manager;
  58764. float level;
  58765. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58766. };
  58767. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58768. public ListBoxModel
  58769. {
  58770. public:
  58771. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58772. const String& noItemsMessage_,
  58773. const int minNumber_,
  58774. const int maxNumber_)
  58775. : ListBox (String::empty, 0),
  58776. deviceManager (deviceManager_),
  58777. noItemsMessage (noItemsMessage_),
  58778. minNumber (minNumber_),
  58779. maxNumber (maxNumber_)
  58780. {
  58781. items = MidiInput::getDevices();
  58782. setModel (this);
  58783. setOutlineThickness (1);
  58784. }
  58785. ~MidiInputSelectorComponentListBox()
  58786. {
  58787. }
  58788. int getNumRows()
  58789. {
  58790. return items.size();
  58791. }
  58792. void paintListBoxItem (int row,
  58793. Graphics& g,
  58794. int width, int height,
  58795. bool rowIsSelected)
  58796. {
  58797. if (isPositiveAndBelow (row, items.size()))
  58798. {
  58799. if (rowIsSelected)
  58800. g.fillAll (findColour (TextEditor::highlightColourId)
  58801. .withMultipliedAlpha (0.3f));
  58802. const String item (items [row]);
  58803. bool enabled = deviceManager.isMidiInputEnabled (item);
  58804. const int x = getTickX();
  58805. const float tickW = height * 0.75f;
  58806. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58807. enabled, true, true, false);
  58808. g.setFont (height * 0.6f);
  58809. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58810. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58811. }
  58812. }
  58813. void listBoxItemClicked (int row, const MouseEvent& e)
  58814. {
  58815. selectRow (row);
  58816. if (e.x < getTickX())
  58817. flipEnablement (row);
  58818. }
  58819. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58820. {
  58821. flipEnablement (row);
  58822. }
  58823. void returnKeyPressed (int row)
  58824. {
  58825. flipEnablement (row);
  58826. }
  58827. void paint (Graphics& g)
  58828. {
  58829. ListBox::paint (g);
  58830. if (items.size() == 0)
  58831. {
  58832. g.setColour (Colours::grey);
  58833. g.setFont (13.0f);
  58834. g.drawText (noItemsMessage,
  58835. 0, 0, getWidth(), getHeight() / 2,
  58836. Justification::centred, true);
  58837. }
  58838. }
  58839. int getBestHeight (const int preferredHeight)
  58840. {
  58841. const int extra = getOutlineThickness() * 2;
  58842. return jmax (getRowHeight() * 2 + extra,
  58843. jmin (getRowHeight() * getNumRows() + extra,
  58844. preferredHeight));
  58845. }
  58846. private:
  58847. AudioDeviceManager& deviceManager;
  58848. const String noItemsMessage;
  58849. StringArray items;
  58850. int minNumber, maxNumber;
  58851. void flipEnablement (const int row)
  58852. {
  58853. if (isPositiveAndBelow (row, items.size()))
  58854. {
  58855. const String item (items [row]);
  58856. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58857. }
  58858. }
  58859. int getTickX() const
  58860. {
  58861. return getRowHeight() + 5;
  58862. }
  58863. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58864. };
  58865. class AudioDeviceSettingsPanel : public Component,
  58866. public ChangeListener,
  58867. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58868. public ButtonListener
  58869. {
  58870. public:
  58871. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58872. AudioIODeviceType::DeviceSetupDetails& setup_,
  58873. const bool hideAdvancedOptionsWithButton)
  58874. : type (type_),
  58875. setup (setup_)
  58876. {
  58877. if (hideAdvancedOptionsWithButton)
  58878. {
  58879. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58880. showAdvancedSettingsButton->addListener (this);
  58881. }
  58882. type->scanForDevices();
  58883. setup.manager->addChangeListener (this);
  58884. changeListenerCallback (0);
  58885. }
  58886. ~AudioDeviceSettingsPanel()
  58887. {
  58888. setup.manager->removeChangeListener (this);
  58889. }
  58890. void resized()
  58891. {
  58892. const int lx = proportionOfWidth (0.35f);
  58893. const int w = proportionOfWidth (0.4f);
  58894. const int h = 24;
  58895. const int space = 6;
  58896. const int dh = h + space;
  58897. int y = 0;
  58898. if (outputDeviceDropDown != 0)
  58899. {
  58900. outputDeviceDropDown->setBounds (lx, y, w, h);
  58901. if (testButton != 0)
  58902. testButton->setBounds (proportionOfWidth (0.77f),
  58903. outputDeviceDropDown->getY(),
  58904. proportionOfWidth (0.18f),
  58905. h);
  58906. y += dh;
  58907. }
  58908. if (inputDeviceDropDown != 0)
  58909. {
  58910. inputDeviceDropDown->setBounds (lx, y, w, h);
  58911. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58912. inputDeviceDropDown->getY(),
  58913. proportionOfWidth (0.18f),
  58914. h);
  58915. y += dh;
  58916. }
  58917. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58918. if (outputChanList != 0)
  58919. {
  58920. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58921. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58922. y += bh + space;
  58923. }
  58924. if (inputChanList != 0)
  58925. {
  58926. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58927. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58928. y += bh + space;
  58929. }
  58930. y += space * 2;
  58931. if (showAdvancedSettingsButton != 0)
  58932. {
  58933. showAdvancedSettingsButton->changeWidthToFitText (h);
  58934. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58935. }
  58936. if (sampleRateDropDown != 0)
  58937. {
  58938. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58939. || ! showAdvancedSettingsButton->isVisible());
  58940. sampleRateDropDown->setBounds (lx, y, w, h);
  58941. y += dh;
  58942. }
  58943. if (bufferSizeDropDown != 0)
  58944. {
  58945. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58946. || ! showAdvancedSettingsButton->isVisible());
  58947. bufferSizeDropDown->setBounds (lx, y, w, h);
  58948. y += dh;
  58949. }
  58950. if (showUIButton != 0)
  58951. {
  58952. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58953. || ! showAdvancedSettingsButton->isVisible());
  58954. showUIButton->changeWidthToFitText (h);
  58955. showUIButton->setTopLeftPosition (lx, y);
  58956. }
  58957. }
  58958. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58959. {
  58960. if (comboBoxThatHasChanged == 0)
  58961. return;
  58962. AudioDeviceManager::AudioDeviceSetup config;
  58963. setup.manager->getAudioDeviceSetup (config);
  58964. String error;
  58965. if (comboBoxThatHasChanged == outputDeviceDropDown
  58966. || comboBoxThatHasChanged == inputDeviceDropDown)
  58967. {
  58968. if (outputDeviceDropDown != 0)
  58969. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58970. : outputDeviceDropDown->getText();
  58971. if (inputDeviceDropDown != 0)
  58972. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58973. : inputDeviceDropDown->getText();
  58974. if (! type->hasSeparateInputsAndOutputs())
  58975. config.inputDeviceName = config.outputDeviceName;
  58976. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58977. config.useDefaultInputChannels = true;
  58978. else
  58979. config.useDefaultOutputChannels = true;
  58980. error = setup.manager->setAudioDeviceSetup (config, true);
  58981. showCorrectDeviceName (inputDeviceDropDown, true);
  58982. showCorrectDeviceName (outputDeviceDropDown, false);
  58983. updateControlPanelButton();
  58984. resized();
  58985. }
  58986. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58987. {
  58988. if (sampleRateDropDown->getSelectedId() > 0)
  58989. {
  58990. config.sampleRate = sampleRateDropDown->getSelectedId();
  58991. error = setup.manager->setAudioDeviceSetup (config, true);
  58992. }
  58993. }
  58994. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58995. {
  58996. if (bufferSizeDropDown->getSelectedId() > 0)
  58997. {
  58998. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58999. error = setup.manager->setAudioDeviceSetup (config, true);
  59000. }
  59001. }
  59002. if (error.isNotEmpty())
  59003. {
  59004. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  59005. "Error when trying to open audio device!",
  59006. error);
  59007. }
  59008. }
  59009. void buttonClicked (Button* button)
  59010. {
  59011. if (button == showAdvancedSettingsButton)
  59012. {
  59013. showAdvancedSettingsButton->setVisible (false);
  59014. resized();
  59015. }
  59016. else if (button == showUIButton)
  59017. {
  59018. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  59019. if (device != 0 && device->showControlPanel())
  59020. {
  59021. setup.manager->closeAudioDevice();
  59022. setup.manager->restartLastAudioDevice();
  59023. getTopLevelComponent()->toFront (true);
  59024. }
  59025. }
  59026. else if (button == testButton && testButton != 0)
  59027. {
  59028. setup.manager->playTestSound();
  59029. }
  59030. }
  59031. void updateControlPanelButton()
  59032. {
  59033. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59034. showUIButton = 0;
  59035. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59036. {
  59037. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59038. TRANS ("opens the device's own control panel")));
  59039. showUIButton->addListener (this);
  59040. }
  59041. resized();
  59042. }
  59043. void changeListenerCallback (ChangeBroadcaster*)
  59044. {
  59045. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59046. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59047. {
  59048. if (outputDeviceDropDown == 0)
  59049. {
  59050. outputDeviceDropDown = new ComboBox (String::empty);
  59051. outputDeviceDropDown->addListener (this);
  59052. addAndMakeVisible (outputDeviceDropDown);
  59053. outputDeviceLabel = new Label (String::empty,
  59054. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59055. : TRANS ("device:"));
  59056. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59057. if (setup.maxNumOutputChannels > 0)
  59058. {
  59059. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59060. testButton->addListener (this);
  59061. }
  59062. }
  59063. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59064. }
  59065. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59066. {
  59067. if (inputDeviceDropDown == 0)
  59068. {
  59069. inputDeviceDropDown = new ComboBox (String::empty);
  59070. inputDeviceDropDown->addListener (this);
  59071. addAndMakeVisible (inputDeviceDropDown);
  59072. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59073. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59074. addAndMakeVisible (inputLevelMeter
  59075. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59076. }
  59077. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59078. }
  59079. updateControlPanelButton();
  59080. showCorrectDeviceName (inputDeviceDropDown, true);
  59081. showCorrectDeviceName (outputDeviceDropDown, false);
  59082. if (currentDevice != 0)
  59083. {
  59084. if (setup.maxNumOutputChannels > 0
  59085. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59086. {
  59087. if (outputChanList == 0)
  59088. {
  59089. addAndMakeVisible (outputChanList
  59090. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59091. TRANS ("(no audio output channels found)")));
  59092. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59093. outputChanLabel->attachToComponent (outputChanList, true);
  59094. }
  59095. outputChanList->refresh();
  59096. }
  59097. else
  59098. {
  59099. outputChanLabel = 0;
  59100. outputChanList = 0;
  59101. }
  59102. if (setup.maxNumInputChannels > 0
  59103. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59104. {
  59105. if (inputChanList == 0)
  59106. {
  59107. addAndMakeVisible (inputChanList
  59108. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59109. TRANS ("(no audio input channels found)")));
  59110. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59111. inputChanLabel->attachToComponent (inputChanList, true);
  59112. }
  59113. inputChanList->refresh();
  59114. }
  59115. else
  59116. {
  59117. inputChanLabel = 0;
  59118. inputChanList = 0;
  59119. }
  59120. // sample rate..
  59121. {
  59122. if (sampleRateDropDown == 0)
  59123. {
  59124. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59125. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59126. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59127. }
  59128. else
  59129. {
  59130. sampleRateDropDown->clear();
  59131. sampleRateDropDown->removeListener (this);
  59132. }
  59133. const int numRates = currentDevice->getNumSampleRates();
  59134. for (int i = 0; i < numRates; ++i)
  59135. {
  59136. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59137. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59138. }
  59139. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59140. sampleRateDropDown->addListener (this);
  59141. }
  59142. // buffer size
  59143. {
  59144. if (bufferSizeDropDown == 0)
  59145. {
  59146. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59147. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59148. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59149. }
  59150. else
  59151. {
  59152. bufferSizeDropDown->clear();
  59153. bufferSizeDropDown->removeListener (this);
  59154. }
  59155. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59156. double currentRate = currentDevice->getCurrentSampleRate();
  59157. if (currentRate == 0)
  59158. currentRate = 48000.0;
  59159. for (int i = 0; i < numBufferSizes; ++i)
  59160. {
  59161. const int bs = currentDevice->getBufferSizeSamples (i);
  59162. bufferSizeDropDown->addItem (String (bs)
  59163. + " samples ("
  59164. + String (bs * 1000.0 / currentRate, 1)
  59165. + " ms)",
  59166. bs);
  59167. }
  59168. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59169. bufferSizeDropDown->addListener (this);
  59170. }
  59171. }
  59172. else
  59173. {
  59174. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59175. sampleRateLabel = 0;
  59176. bufferSizeLabel = 0;
  59177. sampleRateDropDown = 0;
  59178. bufferSizeDropDown = 0;
  59179. if (outputDeviceDropDown != 0)
  59180. outputDeviceDropDown->setSelectedId (-1, true);
  59181. if (inputDeviceDropDown != 0)
  59182. inputDeviceDropDown->setSelectedId (-1, true);
  59183. }
  59184. resized();
  59185. setSize (getWidth(), getLowestY() + 4);
  59186. }
  59187. private:
  59188. AudioIODeviceType* const type;
  59189. const AudioIODeviceType::DeviceSetupDetails setup;
  59190. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59191. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59192. ScopedPointer<TextButton> testButton;
  59193. ScopedPointer<Component> inputLevelMeter;
  59194. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59195. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59196. {
  59197. if (box != 0)
  59198. {
  59199. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59200. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59201. box->setSelectedId (index + 1, true);
  59202. if (testButton != 0 && ! isInput)
  59203. testButton->setEnabled (index >= 0);
  59204. }
  59205. }
  59206. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59207. {
  59208. const StringArray devs (type->getDeviceNames (isInputs));
  59209. combo.clear (true);
  59210. for (int i = 0; i < devs.size(); ++i)
  59211. combo.addItem (devs[i], i + 1);
  59212. combo.addItem (TRANS("<< none >>"), -1);
  59213. combo.setSelectedId (-1, true);
  59214. }
  59215. int getLowestY() const
  59216. {
  59217. int y = 0;
  59218. for (int i = getNumChildComponents(); --i >= 0;)
  59219. y = jmax (y, getChildComponent (i)->getBottom());
  59220. return y;
  59221. }
  59222. public:
  59223. class ChannelSelectorListBox : public ListBox,
  59224. public ListBoxModel
  59225. {
  59226. public:
  59227. enum BoxType
  59228. {
  59229. audioInputType,
  59230. audioOutputType
  59231. };
  59232. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59233. const BoxType type_,
  59234. const String& noItemsMessage_)
  59235. : ListBox (String::empty, 0),
  59236. setup (setup_),
  59237. type (type_),
  59238. noItemsMessage (noItemsMessage_)
  59239. {
  59240. refresh();
  59241. setModel (this);
  59242. setOutlineThickness (1);
  59243. }
  59244. ~ChannelSelectorListBox()
  59245. {
  59246. }
  59247. void refresh()
  59248. {
  59249. items.clear();
  59250. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59251. if (currentDevice != 0)
  59252. {
  59253. if (type == audioInputType)
  59254. items = currentDevice->getInputChannelNames();
  59255. else if (type == audioOutputType)
  59256. items = currentDevice->getOutputChannelNames();
  59257. if (setup.useStereoPairs)
  59258. {
  59259. StringArray pairs;
  59260. for (int i = 0; i < items.size(); i += 2)
  59261. {
  59262. const String name (items[i]);
  59263. const String name2 (items[i + 1]);
  59264. String commonBit;
  59265. for (int j = 0; j < name.length(); ++j)
  59266. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59267. commonBit = name.substring (0, j);
  59268. // Make sure we only split the name at a space, because otherwise, things
  59269. // like "input 11" + "input 12" would become "input 11 + 2"
  59270. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59271. commonBit = commonBit.dropLastCharacters (1);
  59272. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59273. }
  59274. items = pairs;
  59275. }
  59276. }
  59277. updateContent();
  59278. repaint();
  59279. }
  59280. int getNumRows()
  59281. {
  59282. return items.size();
  59283. }
  59284. void paintListBoxItem (int row,
  59285. Graphics& g,
  59286. int width, int height,
  59287. bool rowIsSelected)
  59288. {
  59289. if (isPositiveAndBelow (row, items.size()))
  59290. {
  59291. if (rowIsSelected)
  59292. g.fillAll (findColour (TextEditor::highlightColourId)
  59293. .withMultipliedAlpha (0.3f));
  59294. const String item (items [row]);
  59295. bool enabled = false;
  59296. AudioDeviceManager::AudioDeviceSetup config;
  59297. setup.manager->getAudioDeviceSetup (config);
  59298. if (setup.useStereoPairs)
  59299. {
  59300. if (type == audioInputType)
  59301. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59302. else if (type == audioOutputType)
  59303. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59304. }
  59305. else
  59306. {
  59307. if (type == audioInputType)
  59308. enabled = config.inputChannels [row];
  59309. else if (type == audioOutputType)
  59310. enabled = config.outputChannels [row];
  59311. }
  59312. const int x = getTickX();
  59313. const float tickW = height * 0.75f;
  59314. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59315. enabled, true, true, false);
  59316. g.setFont (height * 0.6f);
  59317. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59318. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59319. }
  59320. }
  59321. void listBoxItemClicked (int row, const MouseEvent& e)
  59322. {
  59323. selectRow (row);
  59324. if (e.x < getTickX())
  59325. flipEnablement (row);
  59326. }
  59327. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59328. {
  59329. flipEnablement (row);
  59330. }
  59331. void returnKeyPressed (int row)
  59332. {
  59333. flipEnablement (row);
  59334. }
  59335. void paint (Graphics& g)
  59336. {
  59337. ListBox::paint (g);
  59338. if (items.size() == 0)
  59339. {
  59340. g.setColour (Colours::grey);
  59341. g.setFont (13.0f);
  59342. g.drawText (noItemsMessage,
  59343. 0, 0, getWidth(), getHeight() / 2,
  59344. Justification::centred, true);
  59345. }
  59346. }
  59347. int getBestHeight (int maxHeight)
  59348. {
  59349. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59350. getNumRows())
  59351. + getOutlineThickness() * 2;
  59352. }
  59353. private:
  59354. const AudioIODeviceType::DeviceSetupDetails setup;
  59355. const BoxType type;
  59356. const String noItemsMessage;
  59357. StringArray items;
  59358. void flipEnablement (const int row)
  59359. {
  59360. jassert (type == audioInputType || type == audioOutputType);
  59361. if (isPositiveAndBelow (row, items.size()))
  59362. {
  59363. AudioDeviceManager::AudioDeviceSetup config;
  59364. setup.manager->getAudioDeviceSetup (config);
  59365. if (setup.useStereoPairs)
  59366. {
  59367. BigInteger bits;
  59368. BigInteger& original = (type == audioInputType ? config.inputChannels
  59369. : config.outputChannels);
  59370. int i;
  59371. for (i = 0; i < 256; i += 2)
  59372. bits.setBit (i / 2, original [i] || original [i + 1]);
  59373. if (type == audioInputType)
  59374. {
  59375. config.useDefaultInputChannels = false;
  59376. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59377. }
  59378. else
  59379. {
  59380. config.useDefaultOutputChannels = false;
  59381. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59382. }
  59383. for (i = 0; i < 256; ++i)
  59384. original.setBit (i, bits [i / 2]);
  59385. }
  59386. else
  59387. {
  59388. if (type == audioInputType)
  59389. {
  59390. config.useDefaultInputChannels = false;
  59391. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59392. }
  59393. else
  59394. {
  59395. config.useDefaultOutputChannels = false;
  59396. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59397. }
  59398. }
  59399. String error (setup.manager->setAudioDeviceSetup (config, true));
  59400. if (! error.isEmpty())
  59401. {
  59402. //xxx
  59403. }
  59404. }
  59405. }
  59406. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59407. {
  59408. const int numActive = chans.countNumberOfSetBits();
  59409. if (chans [index])
  59410. {
  59411. if (numActive > minNumber)
  59412. chans.setBit (index, false);
  59413. }
  59414. else
  59415. {
  59416. if (numActive >= maxNumber)
  59417. {
  59418. const int firstActiveChan = chans.findNextSetBit();
  59419. chans.setBit (index > firstActiveChan
  59420. ? firstActiveChan : chans.getHighestBit(),
  59421. false);
  59422. }
  59423. chans.setBit (index, true);
  59424. }
  59425. }
  59426. int getTickX() const
  59427. {
  59428. return getRowHeight() + 5;
  59429. }
  59430. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59431. };
  59432. private:
  59433. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59434. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59435. };
  59436. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59437. const int minInputChannels_,
  59438. const int maxInputChannels_,
  59439. const int minOutputChannels_,
  59440. const int maxOutputChannels_,
  59441. const bool showMidiInputOptions,
  59442. const bool showMidiOutputSelector,
  59443. const bool showChannelsAsStereoPairs_,
  59444. const bool hideAdvancedOptionsWithButton_)
  59445. : deviceManager (deviceManager_),
  59446. deviceTypeDropDown (0),
  59447. deviceTypeDropDownLabel (0),
  59448. minOutputChannels (minOutputChannels_),
  59449. maxOutputChannels (maxOutputChannels_),
  59450. minInputChannels (minInputChannels_),
  59451. maxInputChannels (maxInputChannels_),
  59452. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59453. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59454. {
  59455. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59456. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59457. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59458. {
  59459. deviceTypeDropDown = new ComboBox (String::empty);
  59460. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59461. {
  59462. deviceTypeDropDown
  59463. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59464. i + 1);
  59465. }
  59466. addAndMakeVisible (deviceTypeDropDown);
  59467. deviceTypeDropDown->addListener (this);
  59468. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59469. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59470. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59471. }
  59472. if (showMidiInputOptions)
  59473. {
  59474. addAndMakeVisible (midiInputsList
  59475. = new MidiInputSelectorComponentListBox (deviceManager,
  59476. TRANS("(no midi inputs available)"),
  59477. 0, 0));
  59478. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59479. midiInputsLabel->setJustificationType (Justification::topRight);
  59480. midiInputsLabel->attachToComponent (midiInputsList, true);
  59481. }
  59482. else
  59483. {
  59484. midiInputsList = 0;
  59485. midiInputsLabel = 0;
  59486. }
  59487. if (showMidiOutputSelector)
  59488. {
  59489. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59490. midiOutputSelector->addListener (this);
  59491. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59492. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59493. }
  59494. else
  59495. {
  59496. midiOutputSelector = 0;
  59497. midiOutputLabel = 0;
  59498. }
  59499. deviceManager_.addChangeListener (this);
  59500. changeListenerCallback (0);
  59501. }
  59502. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59503. {
  59504. deviceManager.removeChangeListener (this);
  59505. }
  59506. void AudioDeviceSelectorComponent::resized()
  59507. {
  59508. const int lx = proportionOfWidth (0.35f);
  59509. const int w = proportionOfWidth (0.4f);
  59510. const int h = 24;
  59511. const int space = 6;
  59512. const int dh = h + space;
  59513. int y = 15;
  59514. if (deviceTypeDropDown != 0)
  59515. {
  59516. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59517. y += dh + space * 2;
  59518. }
  59519. if (audioDeviceSettingsComp != 0)
  59520. {
  59521. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59522. y += audioDeviceSettingsComp->getHeight() + space;
  59523. }
  59524. if (midiInputsList != 0)
  59525. {
  59526. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59527. midiInputsList->setBounds (lx, y, w, bh);
  59528. y += bh + space;
  59529. }
  59530. if (midiOutputSelector != 0)
  59531. midiOutputSelector->setBounds (lx, y, w, h);
  59532. }
  59533. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59534. {
  59535. if (child == audioDeviceSettingsComp)
  59536. resized();
  59537. }
  59538. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59539. {
  59540. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59541. if (device != 0 && device->hasControlPanel())
  59542. {
  59543. if (device->showControlPanel())
  59544. deviceManager.restartLastAudioDevice();
  59545. getTopLevelComponent()->toFront (true);
  59546. }
  59547. }
  59548. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59549. {
  59550. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59551. {
  59552. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59553. if (type != 0)
  59554. {
  59555. audioDeviceSettingsComp = 0;
  59556. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59557. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59558. }
  59559. }
  59560. else if (comboBoxThatHasChanged == midiOutputSelector)
  59561. {
  59562. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59563. }
  59564. }
  59565. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59566. {
  59567. if (deviceTypeDropDown != 0)
  59568. {
  59569. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59570. }
  59571. if (audioDeviceSettingsComp == 0
  59572. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59573. {
  59574. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59575. audioDeviceSettingsComp = 0;
  59576. AudioIODeviceType* const type
  59577. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59578. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59579. if (type != 0)
  59580. {
  59581. AudioIODeviceType::DeviceSetupDetails details;
  59582. details.manager = &deviceManager;
  59583. details.minNumInputChannels = minInputChannels;
  59584. details.maxNumInputChannels = maxInputChannels;
  59585. details.minNumOutputChannels = minOutputChannels;
  59586. details.maxNumOutputChannels = maxOutputChannels;
  59587. details.useStereoPairs = showChannelsAsStereoPairs;
  59588. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59589. if (audioDeviceSettingsComp != 0)
  59590. {
  59591. addAndMakeVisible (audioDeviceSettingsComp);
  59592. audioDeviceSettingsComp->resized();
  59593. }
  59594. }
  59595. }
  59596. if (midiInputsList != 0)
  59597. {
  59598. midiInputsList->updateContent();
  59599. midiInputsList->repaint();
  59600. }
  59601. if (midiOutputSelector != 0)
  59602. {
  59603. midiOutputSelector->clear();
  59604. const StringArray midiOuts (MidiOutput::getDevices());
  59605. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59606. midiOutputSelector->addSeparator();
  59607. for (int i = 0; i < midiOuts.size(); ++i)
  59608. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59609. int current = -1;
  59610. if (deviceManager.getDefaultMidiOutput() != 0)
  59611. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59612. midiOutputSelector->setSelectedId (current, true);
  59613. }
  59614. resized();
  59615. }
  59616. END_JUCE_NAMESPACE
  59617. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59618. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59619. BEGIN_JUCE_NAMESPACE
  59620. BubbleComponent::BubbleComponent()
  59621. : side (0),
  59622. allowablePlacements (above | below | left | right),
  59623. arrowTipX (0.0f),
  59624. arrowTipY (0.0f)
  59625. {
  59626. setInterceptsMouseClicks (false, false);
  59627. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59628. setComponentEffect (&shadow);
  59629. }
  59630. BubbleComponent::~BubbleComponent()
  59631. {
  59632. }
  59633. void BubbleComponent::paint (Graphics& g)
  59634. {
  59635. int x = content.getX();
  59636. int y = content.getY();
  59637. int w = content.getWidth();
  59638. int h = content.getHeight();
  59639. int cw, ch;
  59640. getContentSize (cw, ch);
  59641. if (side == 3)
  59642. x += w - cw;
  59643. else if (side != 1)
  59644. x += (w - cw) / 2;
  59645. w = cw;
  59646. if (side == 2)
  59647. y += h - ch;
  59648. else if (side != 0)
  59649. y += (h - ch) / 2;
  59650. h = ch;
  59651. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59652. (float) x, (float) y,
  59653. (float) w, (float) h);
  59654. const int cx = x + (w - cw) / 2;
  59655. const int cy = y + (h - ch) / 2;
  59656. const int indent = 3;
  59657. g.setOrigin (cx + indent, cy + indent);
  59658. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59659. paintContent (g, cw - indent * 2, ch - indent * 2);
  59660. }
  59661. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59662. {
  59663. allowablePlacements = newPlacement;
  59664. }
  59665. void BubbleComponent::setPosition (Component* componentToPointTo)
  59666. {
  59667. jassert (componentToPointTo != 0);
  59668. Point<int> pos;
  59669. if (getParentComponent() != 0)
  59670. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59671. else
  59672. pos = componentToPointTo->localPointToGlobal (pos);
  59673. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59674. }
  59675. void BubbleComponent::setPosition (const int arrowTipX_,
  59676. const int arrowTipY_)
  59677. {
  59678. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59679. }
  59680. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59681. {
  59682. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59683. : getParentMonitorArea());
  59684. int x = 0;
  59685. int y = 0;
  59686. int w = 150;
  59687. int h = 30;
  59688. getContentSize (w, h);
  59689. w += 30;
  59690. h += 30;
  59691. const float edgeIndent = 2.0f;
  59692. const int arrowLength = jmin (10, h / 3, w / 3);
  59693. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59694. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59695. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59696. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59697. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59698. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59699. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59700. {
  59701. spaceLeft = spaceRight = 0;
  59702. }
  59703. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59704. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59705. {
  59706. spaceAbove = spaceBelow = 0;
  59707. }
  59708. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59709. {
  59710. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59711. arrowTipX = w * 0.5f;
  59712. content.setSize (w, h - arrowLength);
  59713. if (spaceAbove >= spaceBelow)
  59714. {
  59715. // above
  59716. y = rectangleToPointTo.getY() - h;
  59717. content.setPosition (0, 0);
  59718. arrowTipY = h - edgeIndent;
  59719. side = 2;
  59720. }
  59721. else
  59722. {
  59723. // below
  59724. y = rectangleToPointTo.getBottom();
  59725. content.setPosition (0, arrowLength);
  59726. arrowTipY = edgeIndent;
  59727. side = 0;
  59728. }
  59729. }
  59730. else
  59731. {
  59732. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59733. arrowTipY = h * 0.5f;
  59734. content.setSize (w - arrowLength, h);
  59735. if (spaceLeft > spaceRight)
  59736. {
  59737. // on the left
  59738. x = rectangleToPointTo.getX() - w;
  59739. content.setPosition (0, 0);
  59740. arrowTipX = w - edgeIndent;
  59741. side = 3;
  59742. }
  59743. else
  59744. {
  59745. // on the right
  59746. x = rectangleToPointTo.getRight();
  59747. content.setPosition (arrowLength, 0);
  59748. arrowTipX = edgeIndent;
  59749. side = 1;
  59750. }
  59751. }
  59752. setBounds (x, y, w, h);
  59753. }
  59754. END_JUCE_NAMESPACE
  59755. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59756. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59757. BEGIN_JUCE_NAMESPACE
  59758. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59759. : fadeOutLength (fadeOutLengthMs),
  59760. deleteAfterUse (false)
  59761. {
  59762. }
  59763. BubbleMessageComponent::~BubbleMessageComponent()
  59764. {
  59765. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59766. }
  59767. void BubbleMessageComponent::showAt (int x, int y,
  59768. const String& text,
  59769. const int numMillisecondsBeforeRemoving,
  59770. const bool removeWhenMouseClicked,
  59771. const bool deleteSelfAfterUse)
  59772. {
  59773. textLayout.clear();
  59774. textLayout.setText (text, Font (14.0f));
  59775. textLayout.layout (256, Justification::centredLeft, true);
  59776. setPosition (x, y);
  59777. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59778. }
  59779. void BubbleMessageComponent::showAt (Component* const component,
  59780. const String& text,
  59781. const int numMillisecondsBeforeRemoving,
  59782. const bool removeWhenMouseClicked,
  59783. const bool deleteSelfAfterUse)
  59784. {
  59785. textLayout.clear();
  59786. textLayout.setText (text, Font (14.0f));
  59787. textLayout.layout (256, Justification::centredLeft, true);
  59788. setPosition (component);
  59789. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59790. }
  59791. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59792. const bool removeWhenMouseClicked,
  59793. const bool deleteSelfAfterUse)
  59794. {
  59795. setVisible (true);
  59796. deleteAfterUse = deleteSelfAfterUse;
  59797. if (numMillisecondsBeforeRemoving > 0)
  59798. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59799. else
  59800. expiryTime = 0;
  59801. startTimer (77);
  59802. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59803. if (! (removeWhenMouseClicked && isShowing()))
  59804. mouseClickCounter += 0xfffff;
  59805. repaint();
  59806. }
  59807. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59808. {
  59809. w = textLayout.getWidth() + 16;
  59810. h = textLayout.getHeight() + 16;
  59811. }
  59812. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59813. {
  59814. g.setColour (findColour (TooltipWindow::textColourId));
  59815. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59816. }
  59817. void BubbleMessageComponent::timerCallback()
  59818. {
  59819. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59820. {
  59821. stopTimer();
  59822. setVisible (false);
  59823. if (deleteAfterUse)
  59824. delete this;
  59825. }
  59826. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59827. {
  59828. stopTimer();
  59829. if (deleteAfterUse)
  59830. delete this;
  59831. else
  59832. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59833. }
  59834. }
  59835. END_JUCE_NAMESPACE
  59836. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59837. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59838. BEGIN_JUCE_NAMESPACE
  59839. class ColourComponentSlider : public Slider
  59840. {
  59841. public:
  59842. ColourComponentSlider (const String& name)
  59843. : Slider (name)
  59844. {
  59845. setRange (0.0, 255.0, 1.0);
  59846. }
  59847. const String getTextFromValue (double value)
  59848. {
  59849. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59850. }
  59851. double getValueFromText (const String& text)
  59852. {
  59853. return (double) text.getHexValue32();
  59854. }
  59855. private:
  59856. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59857. };
  59858. class ColourSpaceMarker : public Component
  59859. {
  59860. public:
  59861. ColourSpaceMarker()
  59862. {
  59863. setInterceptsMouseClicks (false, false);
  59864. }
  59865. void paint (Graphics& g)
  59866. {
  59867. g.setColour (Colour::greyLevel (0.1f));
  59868. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59869. g.setColour (Colour::greyLevel (0.9f));
  59870. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59871. }
  59872. private:
  59873. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59874. };
  59875. class ColourSelector::ColourSpaceView : public Component
  59876. {
  59877. public:
  59878. ColourSpaceView (ColourSelector& owner_,
  59879. float& h_, float& s_, float& v_,
  59880. const int edgeSize)
  59881. : owner (owner_),
  59882. h (h_), s (s_), v (v_),
  59883. lastHue (0.0f),
  59884. edge (edgeSize)
  59885. {
  59886. addAndMakeVisible (&marker);
  59887. setMouseCursor (MouseCursor::CrosshairCursor);
  59888. }
  59889. void paint (Graphics& g)
  59890. {
  59891. if (colours.isNull())
  59892. {
  59893. const int width = getWidth() / 2;
  59894. const int height = getHeight() / 2;
  59895. colours = Image (Image::RGB, width, height, false);
  59896. Image::BitmapData pixels (colours, Image::BitmapData::writeOnly);
  59897. for (int y = 0; y < height; ++y)
  59898. {
  59899. const float val = 1.0f - y / (float) height;
  59900. for (int x = 0; x < width; ++x)
  59901. {
  59902. const float sat = x / (float) width;
  59903. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59904. }
  59905. }
  59906. }
  59907. g.setOpacity (1.0f);
  59908. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59909. 0, 0, colours.getWidth(), colours.getHeight());
  59910. }
  59911. void mouseDown (const MouseEvent& e)
  59912. {
  59913. mouseDrag (e);
  59914. }
  59915. void mouseDrag (const MouseEvent& e)
  59916. {
  59917. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59918. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59919. owner.setSV (sat, val);
  59920. }
  59921. void updateIfNeeded()
  59922. {
  59923. if (lastHue != h)
  59924. {
  59925. lastHue = h;
  59926. colours = Image::null;
  59927. repaint();
  59928. }
  59929. updateMarker();
  59930. }
  59931. void resized()
  59932. {
  59933. colours = Image::null;
  59934. updateMarker();
  59935. }
  59936. private:
  59937. ColourSelector& owner;
  59938. float& h;
  59939. float& s;
  59940. float& v;
  59941. float lastHue;
  59942. ColourSpaceMarker marker;
  59943. const int edge;
  59944. Image colours;
  59945. void updateMarker()
  59946. {
  59947. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59948. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59949. edge * 2, edge * 2);
  59950. }
  59951. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59952. };
  59953. class HueSelectorMarker : public Component
  59954. {
  59955. public:
  59956. HueSelectorMarker()
  59957. {
  59958. setInterceptsMouseClicks (false, false);
  59959. }
  59960. void paint (Graphics& g)
  59961. {
  59962. Path p;
  59963. p.addTriangle (1.0f, 1.0f,
  59964. getWidth() * 0.3f, getHeight() * 0.5f,
  59965. 1.0f, getHeight() - 1.0f);
  59966. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59967. getWidth() * 0.7f, getHeight() * 0.5f,
  59968. getWidth() - 1.0f, getHeight() - 1.0f);
  59969. g.setColour (Colours::white.withAlpha (0.75f));
  59970. g.fillPath (p);
  59971. g.setColour (Colours::black.withAlpha (0.75f));
  59972. g.strokePath (p, PathStrokeType (1.2f));
  59973. }
  59974. private:
  59975. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59976. };
  59977. class ColourSelector::HueSelectorComp : public Component
  59978. {
  59979. public:
  59980. HueSelectorComp (ColourSelector& owner_,
  59981. float& h_, float& s_, float& v_,
  59982. const int edgeSize)
  59983. : owner (owner_),
  59984. h (h_), s (s_), v (v_),
  59985. lastHue (0.0f),
  59986. edge (edgeSize)
  59987. {
  59988. addAndMakeVisible (&marker);
  59989. }
  59990. void paint (Graphics& g)
  59991. {
  59992. const float yScale = 1.0f / (getHeight() - edge * 2);
  59993. const Rectangle<int> clip (g.getClipBounds());
  59994. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59995. {
  59996. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59997. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59998. }
  59999. }
  60000. void resized()
  60001. {
  60002. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60003. getWidth(), edge * 2);
  60004. }
  60005. void mouseDown (const MouseEvent& e)
  60006. {
  60007. mouseDrag (e);
  60008. }
  60009. void mouseDrag (const MouseEvent& e)
  60010. {
  60011. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  60012. }
  60013. void updateIfNeeded()
  60014. {
  60015. resized();
  60016. }
  60017. private:
  60018. ColourSelector& owner;
  60019. float& h;
  60020. float& s;
  60021. float& v;
  60022. float lastHue;
  60023. HueSelectorMarker marker;
  60024. const int edge;
  60025. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  60026. };
  60027. class ColourSelector::SwatchComponent : public Component
  60028. {
  60029. public:
  60030. SwatchComponent (ColourSelector& owner_, int index_)
  60031. : owner (owner_), index (index_)
  60032. {
  60033. }
  60034. void paint (Graphics& g)
  60035. {
  60036. const Colour colour (owner.getSwatchColour (index));
  60037. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60038. Colour (0xffdddddd).overlaidWith (colour),
  60039. Colour (0xffffffff).overlaidWith (colour));
  60040. }
  60041. void mouseDown (const MouseEvent&)
  60042. {
  60043. PopupMenu m;
  60044. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60045. m.addSeparator();
  60046. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60047. m.showMenuAsync (PopupMenu::Options().withTargetComponent (this),
  60048. ModalCallbackFunction::forComponent (menuStaticCallback, this));
  60049. }
  60050. private:
  60051. ColourSelector& owner;
  60052. const int index;
  60053. static void menuStaticCallback (int result, SwatchComponent* comp)
  60054. {
  60055. if (comp != 0)
  60056. {
  60057. if (result == 1)
  60058. comp->setColourFromSwatch();
  60059. else if (result == 2)
  60060. comp->setSwatchFromColour();
  60061. }
  60062. }
  60063. void setColourFromSwatch()
  60064. {
  60065. owner.setCurrentColour (owner.getSwatchColour (index));
  60066. }
  60067. void setSwatchFromColour()
  60068. {
  60069. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  60070. {
  60071. owner.setSwatchColour (index, owner.getCurrentColour());
  60072. repaint();
  60073. }
  60074. }
  60075. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  60076. };
  60077. ColourSelector::ColourSelector (const int flags_,
  60078. const int edgeGap_,
  60079. const int gapAroundColourSpaceComponent)
  60080. : colour (Colours::white),
  60081. flags (flags_),
  60082. edgeGap (edgeGap_)
  60083. {
  60084. // not much point having a selector with no components in it!
  60085. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60086. updateHSV();
  60087. if ((flags & showSliders) != 0)
  60088. {
  60089. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60090. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60091. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60092. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60093. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60094. for (int i = 4; --i >= 0;)
  60095. sliders[i]->addListener (this);
  60096. }
  60097. if ((flags & showColourspace) != 0)
  60098. {
  60099. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  60100. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  60101. }
  60102. update();
  60103. }
  60104. ColourSelector::~ColourSelector()
  60105. {
  60106. dispatchPendingMessages();
  60107. swatchComponents.clear();
  60108. }
  60109. const Colour ColourSelector::getCurrentColour() const
  60110. {
  60111. return ((flags & showAlphaChannel) != 0) ? colour
  60112. : colour.withAlpha ((uint8) 0xff);
  60113. }
  60114. void ColourSelector::setCurrentColour (const Colour& c)
  60115. {
  60116. if (c != colour)
  60117. {
  60118. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60119. updateHSV();
  60120. update();
  60121. }
  60122. }
  60123. void ColourSelector::setHue (float newH)
  60124. {
  60125. newH = jlimit (0.0f, 1.0f, newH);
  60126. if (h != newH)
  60127. {
  60128. h = newH;
  60129. colour = Colour (h, s, v, colour.getFloatAlpha());
  60130. update();
  60131. }
  60132. }
  60133. void ColourSelector::setSV (float newS, float newV)
  60134. {
  60135. newS = jlimit (0.0f, 1.0f, newS);
  60136. newV = jlimit (0.0f, 1.0f, newV);
  60137. if (s != newS || v != newV)
  60138. {
  60139. s = newS;
  60140. v = newV;
  60141. colour = Colour (h, s, v, colour.getFloatAlpha());
  60142. update();
  60143. }
  60144. }
  60145. void ColourSelector::updateHSV()
  60146. {
  60147. colour.getHSB (h, s, v);
  60148. }
  60149. void ColourSelector::update()
  60150. {
  60151. if (sliders[0] != 0)
  60152. {
  60153. sliders[0]->setValue ((int) colour.getRed());
  60154. sliders[1]->setValue ((int) colour.getGreen());
  60155. sliders[2]->setValue ((int) colour.getBlue());
  60156. sliders[3]->setValue ((int) colour.getAlpha());
  60157. }
  60158. if (colourSpace != 0)
  60159. {
  60160. colourSpace->updateIfNeeded();
  60161. hueSelector->updateIfNeeded();
  60162. }
  60163. if ((flags & showColourAtTop) != 0)
  60164. repaint (previewArea);
  60165. sendChangeMessage();
  60166. }
  60167. void ColourSelector::paint (Graphics& g)
  60168. {
  60169. g.fillAll (findColour (backgroundColourId));
  60170. if ((flags & showColourAtTop) != 0)
  60171. {
  60172. const Colour currentColour (getCurrentColour());
  60173. g.fillCheckerBoard (previewArea, 10, 10,
  60174. Colour (0xffdddddd).overlaidWith (currentColour),
  60175. Colour (0xffffffff).overlaidWith (currentColour));
  60176. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60177. g.setFont (14.0f, true);
  60178. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60179. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60180. Justification::centred, false);
  60181. }
  60182. if ((flags & showSliders) != 0)
  60183. {
  60184. g.setColour (findColour (labelTextColourId));
  60185. g.setFont (11.0f);
  60186. for (int i = 4; --i >= 0;)
  60187. {
  60188. if (sliders[i]->isVisible())
  60189. g.drawText (sliders[i]->getName() + ":",
  60190. 0, sliders[i]->getY(),
  60191. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60192. Justification::centredRight, false);
  60193. }
  60194. }
  60195. }
  60196. void ColourSelector::resized()
  60197. {
  60198. const int swatchesPerRow = 8;
  60199. const int swatchHeight = 22;
  60200. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60201. const int numSwatches = getNumSwatches();
  60202. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60203. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60204. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60205. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60206. int y = topSpace;
  60207. if ((flags & showColourspace) != 0)
  60208. {
  60209. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60210. colourSpace->setBounds (edgeGap, y,
  60211. getWidth() - hueWidth - edgeGap - 4,
  60212. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60213. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60214. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60215. colourSpace->getHeight());
  60216. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60217. }
  60218. if ((flags & showSliders) != 0)
  60219. {
  60220. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60221. for (int i = 0; i < numSliders; ++i)
  60222. {
  60223. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60224. proportionOfWidth (0.72f), sliderHeight - 2);
  60225. y += sliderHeight;
  60226. }
  60227. }
  60228. if (numSwatches > 0)
  60229. {
  60230. const int startX = 8;
  60231. const int xGap = 4;
  60232. const int yGap = 4;
  60233. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60234. y += edgeGap;
  60235. if (swatchComponents.size() != numSwatches)
  60236. {
  60237. swatchComponents.clear();
  60238. for (int i = 0; i < numSwatches; ++i)
  60239. {
  60240. SwatchComponent* const sc = new SwatchComponent (*this, i);
  60241. swatchComponents.add (sc);
  60242. addAndMakeVisible (sc);
  60243. }
  60244. }
  60245. int x = startX;
  60246. for (int i = 0; i < swatchComponents.size(); ++i)
  60247. {
  60248. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60249. sc->setBounds (x + xGap / 2,
  60250. y + yGap / 2,
  60251. swatchWidth - xGap,
  60252. swatchHeight - yGap);
  60253. if (((i + 1) % swatchesPerRow) == 0)
  60254. {
  60255. x = startX;
  60256. y += swatchHeight;
  60257. }
  60258. else
  60259. {
  60260. x += swatchWidth;
  60261. }
  60262. }
  60263. }
  60264. }
  60265. void ColourSelector::sliderValueChanged (Slider*)
  60266. {
  60267. if (sliders[0] != 0)
  60268. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60269. (uint8) sliders[1]->getValue(),
  60270. (uint8) sliders[2]->getValue(),
  60271. (uint8) sliders[3]->getValue()));
  60272. }
  60273. int ColourSelector::getNumSwatches() const
  60274. {
  60275. return 0;
  60276. }
  60277. const Colour ColourSelector::getSwatchColour (const int) const
  60278. {
  60279. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60280. return Colours::black;
  60281. }
  60282. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60283. {
  60284. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60285. }
  60286. END_JUCE_NAMESPACE
  60287. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60288. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60289. BEGIN_JUCE_NAMESPACE
  60290. class ShadowWindow : public Component
  60291. {
  60292. public:
  60293. ShadowWindow (Component& owner, const int type_, const Image shadowImageSections [12])
  60294. : topLeft (shadowImageSections [type_ * 3]),
  60295. bottomRight (shadowImageSections [type_ * 3 + 1]),
  60296. filler (shadowImageSections [type_ * 3 + 2]),
  60297. type (type_)
  60298. {
  60299. setInterceptsMouseClicks (false, false);
  60300. if (owner.isOnDesktop())
  60301. {
  60302. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60303. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60304. | ComponentPeer::windowIsTemporary
  60305. | ComponentPeer::windowIgnoresKeyPresses);
  60306. }
  60307. else if (owner.getParentComponent() != 0)
  60308. {
  60309. owner.getParentComponent()->addChildComponent (this);
  60310. }
  60311. }
  60312. void paint (Graphics& g)
  60313. {
  60314. g.setOpacity (1.0f);
  60315. if (type < 2)
  60316. {
  60317. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60318. g.drawImage (topLeft,
  60319. 0, 0, topLeft.getWidth(), imH,
  60320. 0, 0, topLeft.getWidth(), imH);
  60321. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60322. g.drawImage (bottomRight,
  60323. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60324. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60325. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60326. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60327. }
  60328. else
  60329. {
  60330. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60331. g.drawImage (topLeft,
  60332. 0, 0, imW, topLeft.getHeight(),
  60333. 0, 0, imW, topLeft.getHeight());
  60334. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60335. g.drawImage (bottomRight,
  60336. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60337. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60338. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60339. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60340. }
  60341. }
  60342. void resized()
  60343. {
  60344. repaint(); // (needed for correct repainting)
  60345. }
  60346. private:
  60347. const Image topLeft, bottomRight, filler;
  60348. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60349. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  60350. };
  60351. DropShadower::DropShadower (const float alpha_,
  60352. const int xOffset_,
  60353. const int yOffset_,
  60354. const float blurRadius_)
  60355. : owner (0),
  60356. xOffset (xOffset_),
  60357. yOffset (yOffset_),
  60358. alpha (alpha_),
  60359. blurRadius (blurRadius_),
  60360. reentrant (false)
  60361. {
  60362. }
  60363. DropShadower::~DropShadower()
  60364. {
  60365. if (owner != 0)
  60366. owner->removeComponentListener (this);
  60367. reentrant = true;
  60368. shadowWindows.clear();
  60369. }
  60370. void DropShadower::setOwner (Component* componentToFollow)
  60371. {
  60372. if (componentToFollow != owner)
  60373. {
  60374. if (owner != 0)
  60375. owner->removeComponentListener (this);
  60376. // (the component can't be null)
  60377. jassert (componentToFollow != 0);
  60378. owner = componentToFollow;
  60379. jassert (owner != 0);
  60380. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60381. owner->addComponentListener (this);
  60382. updateShadows();
  60383. }
  60384. }
  60385. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60386. {
  60387. updateShadows();
  60388. }
  60389. void DropShadower::componentBroughtToFront (Component&)
  60390. {
  60391. bringShadowWindowsToFront();
  60392. }
  60393. void DropShadower::componentParentHierarchyChanged (Component&)
  60394. {
  60395. shadowWindows.clear();
  60396. updateShadows();
  60397. }
  60398. void DropShadower::componentVisibilityChanged (Component&)
  60399. {
  60400. updateShadows();
  60401. }
  60402. void DropShadower::updateShadows()
  60403. {
  60404. if (reentrant || owner == 0)
  60405. return;
  60406. ComponentPeer* const peer = owner->getPeer();
  60407. const bool isOwnerVisible = owner->isVisible() && (peer == 0 || ! peer->isMinimised());
  60408. const bool createShadowWindows = shadowWindows.size() == 0
  60409. && owner->getWidth() > 0
  60410. && owner->getHeight() > 0
  60411. && isOwnerVisible
  60412. && (Desktop::canUseSemiTransparentWindows()
  60413. || owner->getParentComponent() != 0);
  60414. {
  60415. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60416. const int shadowEdge = jmax (xOffset, yOffset) + (int) blurRadius;
  60417. if (createShadowWindows)
  60418. {
  60419. // keep a cached version of the image to save doing the gaussian too often
  60420. String imageId;
  60421. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60422. const int hash = imageId.hashCode();
  60423. Image bigIm (ImageCache::getFromHashCode (hash));
  60424. if (bigIm.isNull())
  60425. {
  60426. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60427. Graphics bigG (bigIm);
  60428. bigG.setColour (Colours::black.withAlpha (alpha));
  60429. bigG.fillRect (shadowEdge + xOffset,
  60430. shadowEdge + yOffset,
  60431. bigIm.getWidth() - (shadowEdge * 2),
  60432. bigIm.getHeight() - (shadowEdge * 2));
  60433. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60434. blurKernel.createGaussianBlur (blurRadius);
  60435. blurKernel.applyToImage (bigIm, bigIm,
  60436. Rectangle<int> (xOffset, yOffset,
  60437. bigIm.getWidth(), bigIm.getHeight()));
  60438. ImageCache::addImageToCache (bigIm, hash);
  60439. }
  60440. const int iw = bigIm.getWidth();
  60441. const int ih = bigIm.getHeight();
  60442. const int shadowEdge2 = shadowEdge * 2;
  60443. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60444. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60445. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60446. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60447. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60448. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60449. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60450. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60451. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60452. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60453. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60454. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60455. for (int i = 0; i < 4; ++i)
  60456. shadowWindows.add (new ShadowWindow (*owner, i, shadowImageSections));
  60457. }
  60458. if (shadowWindows.size() >= 4)
  60459. {
  60460. for (int i = shadowWindows.size(); --i >= 0;)
  60461. {
  60462. shadowWindows.getUnchecked(i)->setAlwaysOnTop (owner->isAlwaysOnTop());
  60463. shadowWindows.getUnchecked(i)->setVisible (isOwnerVisible);
  60464. }
  60465. const int x = owner->getX();
  60466. const int y = owner->getY() - shadowEdge;
  60467. const int w = owner->getWidth();
  60468. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60469. shadowWindows.getUnchecked(0)->setBounds (x - shadowEdge, y, shadowEdge, h);
  60470. shadowWindows.getUnchecked(1)->setBounds (x + w, y, shadowEdge, h);
  60471. shadowWindows.getUnchecked(2)->setBounds (x, y, w, shadowEdge);
  60472. shadowWindows.getUnchecked(3)->setBounds (x, owner->getBottom(), w, shadowEdge);
  60473. }
  60474. }
  60475. if (createShadowWindows)
  60476. bringShadowWindowsToFront();
  60477. }
  60478. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60479. const int sx, const int sy)
  60480. {
  60481. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60482. Graphics g (shadowImageSections[num]);
  60483. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60484. }
  60485. void DropShadower::bringShadowWindowsToFront()
  60486. {
  60487. if (! reentrant)
  60488. {
  60489. updateShadows();
  60490. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60491. for (int i = shadowWindows.size(); --i >= 0;)
  60492. shadowWindows.getUnchecked(i)->toBehind (owner);
  60493. }
  60494. }
  60495. END_JUCE_NAMESPACE
  60496. /*** End of inlined file: juce_DropShadower.cpp ***/
  60497. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60498. BEGIN_JUCE_NAMESPACE
  60499. class MidiKeyboardUpDownButton : public Button
  60500. {
  60501. public:
  60502. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60503. : Button (String::empty),
  60504. owner (owner_),
  60505. delta (delta_)
  60506. {
  60507. setOpaque (true);
  60508. }
  60509. void clicked()
  60510. {
  60511. int note = owner.getLowestVisibleKey();
  60512. if (delta < 0)
  60513. note = (note - 1) / 12;
  60514. else
  60515. note = note / 12 + 1;
  60516. owner.setLowestVisibleKey (note * 12);
  60517. }
  60518. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60519. {
  60520. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60521. isMouseOverButton, isButtonDown,
  60522. delta > 0);
  60523. }
  60524. private:
  60525. MidiKeyboardComponent& owner;
  60526. const int delta;
  60527. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60528. };
  60529. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60530. const Orientation orientation_)
  60531. : state (state_),
  60532. xOffset (0),
  60533. blackNoteLength (1),
  60534. keyWidth (16.0f),
  60535. orientation (orientation_),
  60536. midiChannel (1),
  60537. midiInChannelMask (0xffff),
  60538. velocity (1.0f),
  60539. noteUnderMouse (-1),
  60540. mouseDownNote (-1),
  60541. rangeStart (0),
  60542. rangeEnd (127),
  60543. firstKey (12 * 4),
  60544. canScroll (true),
  60545. mouseDragging (false),
  60546. useMousePositionForVelocity (true),
  60547. keyMappingOctave (6),
  60548. octaveNumForMiddleC (3)
  60549. {
  60550. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60551. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60552. // initialise with a default set of querty key-mappings..
  60553. const char* const keymap = "awsedftgyhujkolp;";
  60554. for (int i = String (keymap).length(); --i >= 0;)
  60555. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60556. setOpaque (true);
  60557. setWantsKeyboardFocus (true);
  60558. state.addListener (this);
  60559. }
  60560. MidiKeyboardComponent::~MidiKeyboardComponent()
  60561. {
  60562. state.removeListener (this);
  60563. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60564. }
  60565. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60566. {
  60567. keyWidth = widthInPixels;
  60568. resized();
  60569. }
  60570. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60571. {
  60572. if (orientation != newOrientation)
  60573. {
  60574. orientation = newOrientation;
  60575. resized();
  60576. }
  60577. }
  60578. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60579. const int highestNote)
  60580. {
  60581. jassert (lowestNote >= 0 && lowestNote <= 127);
  60582. jassert (highestNote >= 0 && highestNote <= 127);
  60583. jassert (lowestNote <= highestNote);
  60584. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60585. {
  60586. rangeStart = jlimit (0, 127, lowestNote);
  60587. rangeEnd = jlimit (0, 127, highestNote);
  60588. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60589. resized();
  60590. }
  60591. }
  60592. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60593. {
  60594. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60595. if (noteNumber != firstKey)
  60596. {
  60597. firstKey = noteNumber;
  60598. sendChangeMessage();
  60599. resized();
  60600. }
  60601. }
  60602. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60603. {
  60604. if (canScroll != canScroll_)
  60605. {
  60606. canScroll = canScroll_;
  60607. resized();
  60608. }
  60609. }
  60610. void MidiKeyboardComponent::colourChanged()
  60611. {
  60612. repaint();
  60613. }
  60614. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60615. {
  60616. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60617. if (midiChannel != midiChannelNumber)
  60618. {
  60619. resetAnyKeysInUse();
  60620. midiChannel = jlimit (1, 16, midiChannelNumber);
  60621. }
  60622. }
  60623. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60624. {
  60625. midiInChannelMask = midiChannelMask;
  60626. triggerAsyncUpdate();
  60627. }
  60628. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60629. {
  60630. velocity = jlimit (0.0f, 1.0f, velocity_);
  60631. useMousePositionForVelocity = useMousePositionForVelocity_;
  60632. }
  60633. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60634. {
  60635. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60636. static const float blackNoteWidth = 0.7f;
  60637. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60638. 1.0f, 2 - blackNoteWidth * 0.4f,
  60639. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60640. 4.0f, 5 - blackNoteWidth * 0.5f,
  60641. 5.0f, 6 - blackNoteWidth * 0.3f,
  60642. 6.0f };
  60643. static const float widths[] = { 1.0f, blackNoteWidth,
  60644. 1.0f, blackNoteWidth,
  60645. 1.0f, 1.0f, blackNoteWidth,
  60646. 1.0f, blackNoteWidth,
  60647. 1.0f, blackNoteWidth,
  60648. 1.0f };
  60649. const int octave = midiNoteNumber / 12;
  60650. const int note = midiNoteNumber % 12;
  60651. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60652. w = roundToInt (widths [note] * keyWidth_);
  60653. }
  60654. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60655. {
  60656. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60657. int rx, rw;
  60658. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60659. x -= xOffset + rx;
  60660. }
  60661. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60662. {
  60663. int x, y;
  60664. getKeyPos (midiNoteNumber, x, y);
  60665. return x;
  60666. }
  60667. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60668. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60669. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60670. {
  60671. if (! reallyContains (pos, false))
  60672. return -1;
  60673. Point<int> p (pos);
  60674. if (orientation != horizontalKeyboard)
  60675. {
  60676. p = Point<int> (p.getY(), p.getX());
  60677. if (orientation == verticalKeyboardFacingLeft)
  60678. p = Point<int> (p.getX(), getWidth() - p.getY());
  60679. else
  60680. p = Point<int> (getHeight() - p.getX(), p.getY());
  60681. }
  60682. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60683. }
  60684. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60685. {
  60686. if (pos.getY() < blackNoteLength)
  60687. {
  60688. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60689. {
  60690. for (int i = 0; i < 5; ++i)
  60691. {
  60692. const int note = octaveStart + blackNotes [i];
  60693. if (note >= rangeStart && note <= rangeEnd)
  60694. {
  60695. int kx, kw;
  60696. getKeyPos (note, kx, kw);
  60697. kx += xOffset;
  60698. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60699. {
  60700. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60701. return note;
  60702. }
  60703. }
  60704. }
  60705. }
  60706. }
  60707. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60708. {
  60709. for (int i = 0; i < 7; ++i)
  60710. {
  60711. const int note = octaveStart + whiteNotes [i];
  60712. if (note >= rangeStart && note <= rangeEnd)
  60713. {
  60714. int kx, kw;
  60715. getKeyPos (note, kx, kw);
  60716. kx += xOffset;
  60717. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60718. {
  60719. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60720. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60721. return note;
  60722. }
  60723. }
  60724. }
  60725. }
  60726. mousePositionVelocity = 0;
  60727. return -1;
  60728. }
  60729. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60730. {
  60731. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60732. {
  60733. int x, w;
  60734. getKeyPos (noteNum, x, w);
  60735. if (orientation == horizontalKeyboard)
  60736. repaint (x, 0, w, getHeight());
  60737. else if (orientation == verticalKeyboardFacingLeft)
  60738. repaint (0, x, getWidth(), w);
  60739. else if (orientation == verticalKeyboardFacingRight)
  60740. repaint (0, getHeight() - x - w, getWidth(), w);
  60741. }
  60742. }
  60743. void MidiKeyboardComponent::paint (Graphics& g)
  60744. {
  60745. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60746. const Colour lineColour (findColour (keySeparatorLineColourId));
  60747. const Colour textColour (findColour (textLabelColourId));
  60748. int x, w, octave;
  60749. for (octave = 0; octave < 128; octave += 12)
  60750. {
  60751. for (int white = 0; white < 7; ++white)
  60752. {
  60753. const int noteNum = octave + whiteNotes [white];
  60754. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60755. {
  60756. getKeyPos (noteNum, x, w);
  60757. if (orientation == horizontalKeyboard)
  60758. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60759. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60760. noteUnderMouse == noteNum,
  60761. lineColour, textColour);
  60762. else if (orientation == verticalKeyboardFacingLeft)
  60763. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60764. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60765. noteUnderMouse == noteNum,
  60766. lineColour, textColour);
  60767. else if (orientation == verticalKeyboardFacingRight)
  60768. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60769. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60770. noteUnderMouse == noteNum,
  60771. lineColour, textColour);
  60772. }
  60773. }
  60774. }
  60775. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60776. if (orientation == verticalKeyboardFacingLeft)
  60777. {
  60778. x1 = getWidth() - 1.0f;
  60779. x2 = getWidth() - 5.0f;
  60780. }
  60781. else if (orientation == verticalKeyboardFacingRight)
  60782. x2 = 5.0f;
  60783. else
  60784. y2 = 5.0f;
  60785. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60786. Colours::transparentBlack, x2, y2, false));
  60787. getKeyPos (rangeEnd, x, w);
  60788. x += w;
  60789. if (orientation == verticalKeyboardFacingLeft)
  60790. g.fillRect (getWidth() - 5, 0, 5, x);
  60791. else if (orientation == verticalKeyboardFacingRight)
  60792. g.fillRect (0, 0, 5, x);
  60793. else
  60794. g.fillRect (0, 0, x, 5);
  60795. g.setColour (lineColour);
  60796. if (orientation == verticalKeyboardFacingLeft)
  60797. g.fillRect (0, 0, 1, x);
  60798. else if (orientation == verticalKeyboardFacingRight)
  60799. g.fillRect (getWidth() - 1, 0, 1, x);
  60800. else
  60801. g.fillRect (0, getHeight() - 1, x, 1);
  60802. const Colour blackNoteColour (findColour (blackNoteColourId));
  60803. for (octave = 0; octave < 128; octave += 12)
  60804. {
  60805. for (int black = 0; black < 5; ++black)
  60806. {
  60807. const int noteNum = octave + blackNotes [black];
  60808. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60809. {
  60810. getKeyPos (noteNum, x, w);
  60811. if (orientation == horizontalKeyboard)
  60812. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60813. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60814. noteUnderMouse == noteNum,
  60815. blackNoteColour);
  60816. else if (orientation == verticalKeyboardFacingLeft)
  60817. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60818. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60819. noteUnderMouse == noteNum,
  60820. blackNoteColour);
  60821. else if (orientation == verticalKeyboardFacingRight)
  60822. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60823. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60824. noteUnderMouse == noteNum,
  60825. blackNoteColour);
  60826. }
  60827. }
  60828. }
  60829. }
  60830. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60831. Graphics& g, int x, int y, int w, int h,
  60832. bool isDown, bool isOver,
  60833. const Colour& lineColour,
  60834. const Colour& textColour)
  60835. {
  60836. Colour c (Colours::transparentWhite);
  60837. if (isDown)
  60838. c = findColour (keyDownOverlayColourId);
  60839. if (isOver)
  60840. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60841. g.setColour (c);
  60842. g.fillRect (x, y, w, h);
  60843. const String text (getWhiteNoteText (midiNoteNumber));
  60844. if (! text.isEmpty())
  60845. {
  60846. g.setColour (textColour);
  60847. Font f (jmin (12.0f, keyWidth * 0.9f));
  60848. f.setHorizontalScale (0.8f);
  60849. g.setFont (f);
  60850. Justification justification (Justification::centredBottom);
  60851. if (orientation == verticalKeyboardFacingLeft)
  60852. justification = Justification::centredLeft;
  60853. else if (orientation == verticalKeyboardFacingRight)
  60854. justification = Justification::centredRight;
  60855. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60856. }
  60857. g.setColour (lineColour);
  60858. if (orientation == horizontalKeyboard)
  60859. g.fillRect (x, y, 1, h);
  60860. else if (orientation == verticalKeyboardFacingLeft)
  60861. g.fillRect (x, y, w, 1);
  60862. else if (orientation == verticalKeyboardFacingRight)
  60863. g.fillRect (x, y + h - 1, w, 1);
  60864. if (midiNoteNumber == rangeEnd)
  60865. {
  60866. if (orientation == horizontalKeyboard)
  60867. g.fillRect (x + w, y, 1, h);
  60868. else if (orientation == verticalKeyboardFacingLeft)
  60869. g.fillRect (x, y + h, w, 1);
  60870. else if (orientation == verticalKeyboardFacingRight)
  60871. g.fillRect (x, y - 1, w, 1);
  60872. }
  60873. }
  60874. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60875. Graphics& g, int x, int y, int w, int h,
  60876. bool isDown, bool isOver,
  60877. const Colour& noteFillColour)
  60878. {
  60879. Colour c (noteFillColour);
  60880. if (isDown)
  60881. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60882. if (isOver)
  60883. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60884. g.setColour (c);
  60885. g.fillRect (x, y, w, h);
  60886. if (isDown)
  60887. {
  60888. g.setColour (noteFillColour);
  60889. g.drawRect (x, y, w, h);
  60890. }
  60891. else
  60892. {
  60893. const int xIndent = jmax (1, jmin (w, h) / 8);
  60894. g.setColour (c.brighter());
  60895. if (orientation == horizontalKeyboard)
  60896. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60897. else if (orientation == verticalKeyboardFacingLeft)
  60898. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60899. else if (orientation == verticalKeyboardFacingRight)
  60900. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60901. }
  60902. }
  60903. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60904. {
  60905. octaveNumForMiddleC = octaveNumForMiddleC_;
  60906. repaint();
  60907. }
  60908. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60909. {
  60910. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60911. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60912. return String::empty;
  60913. }
  60914. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60915. const bool isMouseOver_,
  60916. const bool isButtonDown,
  60917. const bool movesOctavesUp)
  60918. {
  60919. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60920. float angle;
  60921. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60922. angle = movesOctavesUp ? 0.0f : 0.5f;
  60923. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60924. angle = movesOctavesUp ? 0.25f : 0.75f;
  60925. else
  60926. angle = movesOctavesUp ? 0.75f : 0.25f;
  60927. Path path;
  60928. path.lineTo (0.0f, 1.0f);
  60929. path.lineTo (1.0f, 0.5f);
  60930. path.closeSubPath();
  60931. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60932. g.setColour (findColour (upDownButtonArrowColourId)
  60933. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60934. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60935. w - 2.0f,
  60936. h - 2.0f,
  60937. true));
  60938. }
  60939. void MidiKeyboardComponent::resized()
  60940. {
  60941. int w = getWidth();
  60942. int h = getHeight();
  60943. if (w > 0 && h > 0)
  60944. {
  60945. if (orientation != horizontalKeyboard)
  60946. swapVariables (w, h);
  60947. blackNoteLength = roundToInt (h * 0.7f);
  60948. int kx2, kw2;
  60949. getKeyPos (rangeEnd, kx2, kw2);
  60950. kx2 += kw2;
  60951. if (firstKey != rangeStart)
  60952. {
  60953. int kx1, kw1;
  60954. getKeyPos (rangeStart, kx1, kw1);
  60955. if (kx2 - kx1 <= w)
  60956. {
  60957. firstKey = rangeStart;
  60958. sendChangeMessage();
  60959. repaint();
  60960. }
  60961. }
  60962. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60963. scrollDown->setVisible (showScrollButtons);
  60964. scrollUp->setVisible (showScrollButtons);
  60965. xOffset = 0;
  60966. if (showScrollButtons)
  60967. {
  60968. const int scrollButtonW = jmin (12, w / 2);
  60969. if (orientation == horizontalKeyboard)
  60970. {
  60971. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60972. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60973. }
  60974. else if (orientation == verticalKeyboardFacingLeft)
  60975. {
  60976. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60977. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60978. }
  60979. else if (orientation == verticalKeyboardFacingRight)
  60980. {
  60981. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60982. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60983. }
  60984. int endOfLastKey, kw;
  60985. getKeyPos (rangeEnd, endOfLastKey, kw);
  60986. endOfLastKey += kw;
  60987. float mousePositionVelocity;
  60988. const int spaceAvailable = w - scrollButtonW * 2;
  60989. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60990. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60991. {
  60992. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60993. sendChangeMessage();
  60994. }
  60995. int newOffset = 0;
  60996. getKeyPos (firstKey, newOffset, kw);
  60997. xOffset = newOffset - scrollButtonW;
  60998. }
  60999. else
  61000. {
  61001. firstKey = rangeStart;
  61002. }
  61003. timerCallback();
  61004. repaint();
  61005. }
  61006. }
  61007. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61008. {
  61009. triggerAsyncUpdate();
  61010. }
  61011. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61012. {
  61013. triggerAsyncUpdate();
  61014. }
  61015. void MidiKeyboardComponent::handleAsyncUpdate()
  61016. {
  61017. for (int i = rangeStart; i <= rangeEnd; ++i)
  61018. {
  61019. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61020. {
  61021. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61022. repaintNote (i);
  61023. }
  61024. }
  61025. }
  61026. void MidiKeyboardComponent::resetAnyKeysInUse()
  61027. {
  61028. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61029. {
  61030. state.allNotesOff (midiChannel);
  61031. keysPressed.clear();
  61032. mouseDownNote = -1;
  61033. }
  61034. }
  61035. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61036. {
  61037. float mousePositionVelocity = 0.0f;
  61038. const int newNote = (mouseDragging || isMouseOver())
  61039. ? xyToNote (pos, mousePositionVelocity) : -1;
  61040. if (noteUnderMouse != newNote)
  61041. {
  61042. if (mouseDownNote >= 0)
  61043. {
  61044. state.noteOff (midiChannel, mouseDownNote);
  61045. mouseDownNote = -1;
  61046. }
  61047. if (mouseDragging && newNote >= 0)
  61048. {
  61049. if (! useMousePositionForVelocity)
  61050. mousePositionVelocity = 1.0f;
  61051. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61052. mouseDownNote = newNote;
  61053. }
  61054. repaintNote (noteUnderMouse);
  61055. noteUnderMouse = newNote;
  61056. repaintNote (noteUnderMouse);
  61057. }
  61058. else if (mouseDownNote >= 0 && ! mouseDragging)
  61059. {
  61060. state.noteOff (midiChannel, mouseDownNote);
  61061. mouseDownNote = -1;
  61062. }
  61063. }
  61064. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61065. {
  61066. updateNoteUnderMouse (e.getPosition());
  61067. stopTimer();
  61068. }
  61069. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61070. {
  61071. float mousePositionVelocity;
  61072. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61073. if (newNote >= 0)
  61074. mouseDraggedToKey (newNote, e);
  61075. updateNoteUnderMouse (e.getPosition());
  61076. }
  61077. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61078. {
  61079. return true;
  61080. }
  61081. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61082. {
  61083. }
  61084. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61085. {
  61086. float mousePositionVelocity;
  61087. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61088. mouseDragging = false;
  61089. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61090. {
  61091. repaintNote (noteUnderMouse);
  61092. noteUnderMouse = -1;
  61093. mouseDragging = true;
  61094. updateNoteUnderMouse (e.getPosition());
  61095. startTimer (500);
  61096. }
  61097. }
  61098. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61099. {
  61100. mouseDragging = false;
  61101. updateNoteUnderMouse (e.getPosition());
  61102. stopTimer();
  61103. }
  61104. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61105. {
  61106. updateNoteUnderMouse (e.getPosition());
  61107. }
  61108. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61109. {
  61110. updateNoteUnderMouse (e.getPosition());
  61111. }
  61112. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61113. {
  61114. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61115. }
  61116. void MidiKeyboardComponent::timerCallback()
  61117. {
  61118. updateNoteUnderMouse (getMouseXYRelative());
  61119. }
  61120. void MidiKeyboardComponent::clearKeyMappings()
  61121. {
  61122. resetAnyKeysInUse();
  61123. keyPressNotes.clear();
  61124. keyPresses.clear();
  61125. }
  61126. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61127. const int midiNoteOffsetFromC)
  61128. {
  61129. removeKeyPressForNote (midiNoteOffsetFromC);
  61130. keyPressNotes.add (midiNoteOffsetFromC);
  61131. keyPresses.add (key);
  61132. }
  61133. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61134. {
  61135. for (int i = keyPressNotes.size(); --i >= 0;)
  61136. {
  61137. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61138. {
  61139. keyPressNotes.remove (i);
  61140. keyPresses.remove (i);
  61141. }
  61142. }
  61143. }
  61144. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61145. {
  61146. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61147. keyMappingOctave = newOctaveNumber;
  61148. }
  61149. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61150. {
  61151. bool keyPressUsed = false;
  61152. for (int i = keyPresses.size(); --i >= 0;)
  61153. {
  61154. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61155. if (keyPresses.getReference(i).isCurrentlyDown())
  61156. {
  61157. if (! keysPressed [note])
  61158. {
  61159. keysPressed.setBit (note);
  61160. state.noteOn (midiChannel, note, velocity);
  61161. keyPressUsed = true;
  61162. }
  61163. }
  61164. else
  61165. {
  61166. if (keysPressed [note])
  61167. {
  61168. keysPressed.clearBit (note);
  61169. state.noteOff (midiChannel, note);
  61170. keyPressUsed = true;
  61171. }
  61172. }
  61173. }
  61174. return keyPressUsed;
  61175. }
  61176. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61177. {
  61178. resetAnyKeysInUse();
  61179. }
  61180. END_JUCE_NAMESPACE
  61181. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61182. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61183. #if JUCE_OPENGL
  61184. BEGIN_JUCE_NAMESPACE
  61185. extern void juce_glViewport (const int w, const int h);
  61186. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61187. const int alphaBits_,
  61188. const int depthBufferBits_,
  61189. const int stencilBufferBits_)
  61190. : redBits (bitsPerRGBComponent),
  61191. greenBits (bitsPerRGBComponent),
  61192. blueBits (bitsPerRGBComponent),
  61193. alphaBits (alphaBits_),
  61194. depthBufferBits (depthBufferBits_),
  61195. stencilBufferBits (stencilBufferBits_),
  61196. accumulationBufferRedBits (0),
  61197. accumulationBufferGreenBits (0),
  61198. accumulationBufferBlueBits (0),
  61199. accumulationBufferAlphaBits (0),
  61200. fullSceneAntiAliasingNumSamples (0)
  61201. {
  61202. }
  61203. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61204. : redBits (other.redBits),
  61205. greenBits (other.greenBits),
  61206. blueBits (other.blueBits),
  61207. alphaBits (other.alphaBits),
  61208. depthBufferBits (other.depthBufferBits),
  61209. stencilBufferBits (other.stencilBufferBits),
  61210. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61211. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61212. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61213. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61214. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61215. {
  61216. }
  61217. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61218. {
  61219. redBits = other.redBits;
  61220. greenBits = other.greenBits;
  61221. blueBits = other.blueBits;
  61222. alphaBits = other.alphaBits;
  61223. depthBufferBits = other.depthBufferBits;
  61224. stencilBufferBits = other.stencilBufferBits;
  61225. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61226. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61227. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61228. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61229. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61230. return *this;
  61231. }
  61232. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61233. {
  61234. return redBits == other.redBits
  61235. && greenBits == other.greenBits
  61236. && blueBits == other.blueBits
  61237. && alphaBits == other.alphaBits
  61238. && depthBufferBits == other.depthBufferBits
  61239. && stencilBufferBits == other.stencilBufferBits
  61240. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61241. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61242. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61243. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61244. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61245. }
  61246. static Array<OpenGLContext*> knownContexts;
  61247. OpenGLContext::OpenGLContext() throw()
  61248. {
  61249. knownContexts.add (this);
  61250. }
  61251. OpenGLContext::~OpenGLContext()
  61252. {
  61253. knownContexts.removeValue (this);
  61254. }
  61255. OpenGLContext* OpenGLContext::getCurrentContext()
  61256. {
  61257. for (int i = knownContexts.size(); --i >= 0;)
  61258. {
  61259. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61260. if (oglc->isActive())
  61261. return oglc;
  61262. }
  61263. return 0;
  61264. }
  61265. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61266. {
  61267. public:
  61268. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61269. : ComponentMovementWatcher (owner_),
  61270. owner (owner_)
  61271. {
  61272. }
  61273. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61274. {
  61275. owner->updateContextPosition();
  61276. }
  61277. void componentPeerChanged()
  61278. {
  61279. const ScopedLock sl (owner->getContextLock());
  61280. owner->deleteContext();
  61281. }
  61282. void componentVisibilityChanged()
  61283. {
  61284. if (! owner->isShowing())
  61285. {
  61286. const ScopedLock sl (owner->getContextLock());
  61287. owner->deleteContext();
  61288. }
  61289. }
  61290. private:
  61291. OpenGLComponent* const owner;
  61292. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  61293. };
  61294. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61295. : type (type_),
  61296. contextToShareListsWith (0),
  61297. needToUpdateViewport (true)
  61298. {
  61299. setOpaque (true);
  61300. componentWatcher = new OpenGLComponentWatcher (this);
  61301. }
  61302. OpenGLComponent::~OpenGLComponent()
  61303. {
  61304. deleteContext();
  61305. componentWatcher = 0;
  61306. }
  61307. void OpenGLComponent::deleteContext()
  61308. {
  61309. const ScopedLock sl (contextLock);
  61310. context = 0;
  61311. }
  61312. void OpenGLComponent::updateContextPosition()
  61313. {
  61314. needToUpdateViewport = true;
  61315. if (getWidth() > 0 && getHeight() > 0)
  61316. {
  61317. Component* const topComp = getTopLevelComponent();
  61318. if (topComp->getPeer() != 0)
  61319. {
  61320. const ScopedLock sl (contextLock);
  61321. if (context != 0)
  61322. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61323. getScreenY() - topComp->getScreenY(),
  61324. getWidth(),
  61325. getHeight(),
  61326. topComp->getHeight());
  61327. }
  61328. }
  61329. }
  61330. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61331. {
  61332. OpenGLPixelFormat pf;
  61333. const ScopedLock sl (contextLock);
  61334. if (context != 0)
  61335. pf = context->getPixelFormat();
  61336. return pf;
  61337. }
  61338. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61339. {
  61340. if (! (preferredPixelFormat == formatToUse))
  61341. {
  61342. const ScopedLock sl (contextLock);
  61343. deleteContext();
  61344. preferredPixelFormat = formatToUse;
  61345. }
  61346. }
  61347. void OpenGLComponent::shareWith (OpenGLContext* c)
  61348. {
  61349. if (contextToShareListsWith != c)
  61350. {
  61351. const ScopedLock sl (contextLock);
  61352. deleteContext();
  61353. contextToShareListsWith = c;
  61354. }
  61355. }
  61356. bool OpenGLComponent::makeCurrentContextActive()
  61357. {
  61358. if (context == 0)
  61359. {
  61360. const ScopedLock sl (contextLock);
  61361. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61362. {
  61363. context = createContext();
  61364. if (context != 0)
  61365. {
  61366. updateContextPosition();
  61367. if (context->makeActive())
  61368. newOpenGLContextCreated();
  61369. }
  61370. }
  61371. }
  61372. return context != 0 && context->makeActive();
  61373. }
  61374. void OpenGLComponent::makeCurrentContextInactive()
  61375. {
  61376. if (context != 0)
  61377. context->makeInactive();
  61378. }
  61379. bool OpenGLComponent::isActiveContext() const throw()
  61380. {
  61381. return context != 0 && context->isActive();
  61382. }
  61383. void OpenGLComponent::swapBuffers()
  61384. {
  61385. if (context != 0)
  61386. context->swapBuffers();
  61387. }
  61388. void OpenGLComponent::paint (Graphics&)
  61389. {
  61390. if (renderAndSwapBuffers())
  61391. {
  61392. ComponentPeer* const peer = getPeer();
  61393. if (peer != 0)
  61394. {
  61395. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61396. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61397. }
  61398. }
  61399. }
  61400. bool OpenGLComponent::renderAndSwapBuffers()
  61401. {
  61402. const ScopedLock sl (contextLock);
  61403. if (! makeCurrentContextActive())
  61404. return false;
  61405. if (needToUpdateViewport)
  61406. {
  61407. needToUpdateViewport = false;
  61408. juce_glViewport (getWidth(), getHeight());
  61409. }
  61410. renderOpenGL();
  61411. swapBuffers();
  61412. return true;
  61413. }
  61414. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61415. {
  61416. Component::internalRepaint (x, y, w, h);
  61417. if (context != 0)
  61418. context->repaint();
  61419. }
  61420. END_JUCE_NAMESPACE
  61421. #endif
  61422. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61423. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61424. BEGIN_JUCE_NAMESPACE
  61425. PreferencesPanel::PreferencesPanel()
  61426. : buttonSize (70)
  61427. {
  61428. }
  61429. PreferencesPanel::~PreferencesPanel()
  61430. {
  61431. }
  61432. void PreferencesPanel::addSettingsPage (const String& title,
  61433. const Drawable* icon,
  61434. const Drawable* overIcon,
  61435. const Drawable* downIcon)
  61436. {
  61437. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61438. buttons.add (button);
  61439. button->setImages (icon, overIcon, downIcon);
  61440. button->setRadioGroupId (1);
  61441. button->addListener (this);
  61442. button->setClickingTogglesState (true);
  61443. button->setWantsKeyboardFocus (false);
  61444. addAndMakeVisible (button);
  61445. resized();
  61446. if (currentPage == 0)
  61447. setCurrentPage (title);
  61448. }
  61449. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61450. {
  61451. DrawableImage icon, iconOver, iconDown;
  61452. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61453. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61454. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61455. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61456. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61457. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61458. }
  61459. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61460. {
  61461. setSize (dialogWidth, dialogHeight);
  61462. DialogWindow::showDialog (dialogTitle, this, 0, backgroundColour, false);
  61463. }
  61464. void PreferencesPanel::resized()
  61465. {
  61466. for (int i = 0; i < buttons.size(); ++i)
  61467. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61468. if (currentPage != 0)
  61469. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61470. }
  61471. void PreferencesPanel::paint (Graphics& g)
  61472. {
  61473. g.setColour (Colours::grey);
  61474. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61475. }
  61476. void PreferencesPanel::setCurrentPage (const String& pageName)
  61477. {
  61478. if (currentPageName != pageName)
  61479. {
  61480. currentPageName = pageName;
  61481. currentPage = 0;
  61482. currentPage = createComponentForPage (pageName);
  61483. if (currentPage != 0)
  61484. {
  61485. addAndMakeVisible (currentPage);
  61486. currentPage->toBack();
  61487. resized();
  61488. }
  61489. for (int i = 0; i < buttons.size(); ++i)
  61490. {
  61491. if (buttons.getUnchecked(i)->getName() == pageName)
  61492. {
  61493. buttons.getUnchecked(i)->setToggleState (true, false);
  61494. break;
  61495. }
  61496. }
  61497. }
  61498. }
  61499. void PreferencesPanel::buttonClicked (Button*)
  61500. {
  61501. for (int i = 0; i < buttons.size(); ++i)
  61502. {
  61503. if (buttons.getUnchecked(i)->getToggleState())
  61504. {
  61505. setCurrentPage (buttons.getUnchecked(i)->getName());
  61506. break;
  61507. }
  61508. }
  61509. }
  61510. END_JUCE_NAMESPACE
  61511. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61512. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61513. #if JUCE_WINDOWS || JUCE_LINUX
  61514. BEGIN_JUCE_NAMESPACE
  61515. SystemTrayIconComponent::SystemTrayIconComponent()
  61516. {
  61517. addToDesktop (0);
  61518. }
  61519. SystemTrayIconComponent::~SystemTrayIconComponent()
  61520. {
  61521. }
  61522. END_JUCE_NAMESPACE
  61523. #endif
  61524. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61525. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61526. BEGIN_JUCE_NAMESPACE
  61527. class AlertWindowTextEditor : public TextEditor
  61528. {
  61529. public:
  61530. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61531. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61532. {
  61533. setSelectAllWhenFocused (true);
  61534. }
  61535. void returnPressed()
  61536. {
  61537. // pass these up the component hierarchy to be trigger the buttons
  61538. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61539. }
  61540. void escapePressed()
  61541. {
  61542. // pass these up the component hierarchy to be trigger the buttons
  61543. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61544. }
  61545. private:
  61546. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61547. static juce_wchar getDefaultPasswordChar() throw()
  61548. {
  61549. #if JUCE_LINUX
  61550. return 0x2022;
  61551. #else
  61552. return 0x25cf;
  61553. #endif
  61554. }
  61555. };
  61556. AlertWindow::AlertWindow (const String& title,
  61557. const String& message,
  61558. AlertIconType iconType,
  61559. Component* associatedComponent_)
  61560. : TopLevelWindow (title, true),
  61561. alertIconType (iconType),
  61562. associatedComponent (associatedComponent_)
  61563. {
  61564. if (message.isEmpty())
  61565. text = " "; // to force an update if the message is empty
  61566. setMessage (message);
  61567. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61568. {
  61569. Component* const c = Desktop::getInstance().getComponent (i);
  61570. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61571. {
  61572. setAlwaysOnTop (true);
  61573. break;
  61574. }
  61575. }
  61576. if (! JUCEApplication::isStandaloneApp())
  61577. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61578. lookAndFeelChanged();
  61579. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61580. }
  61581. AlertWindow::~AlertWindow()
  61582. {
  61583. removeAllChildren();
  61584. }
  61585. void AlertWindow::userTriedToCloseWindow()
  61586. {
  61587. exitModalState (0);
  61588. }
  61589. void AlertWindow::setMessage (const String& message)
  61590. {
  61591. const String newMessage (message.substring (0, 2048));
  61592. if (text != newMessage)
  61593. {
  61594. text = newMessage;
  61595. font = getLookAndFeel().getAlertWindowMessageFont();
  61596. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61597. textLayout.setText (getName() + "\n\n", titleFont);
  61598. textLayout.appendText (text, font);
  61599. updateLayout (true);
  61600. repaint();
  61601. }
  61602. }
  61603. void AlertWindow::buttonClicked (Button* button)
  61604. {
  61605. if (button->getParentComponent() != 0)
  61606. button->getParentComponent()->exitModalState (button->getCommandID());
  61607. }
  61608. void AlertWindow::addButton (const String& name,
  61609. const int returnValue,
  61610. const KeyPress& shortcutKey1,
  61611. const KeyPress& shortcutKey2)
  61612. {
  61613. TextButton* const b = new TextButton (name, String::empty);
  61614. buttons.add (b);
  61615. b->setWantsKeyboardFocus (true);
  61616. b->setMouseClickGrabsKeyboardFocus (false);
  61617. b->setCommandToTrigger (0, returnValue, false);
  61618. b->addShortcut (shortcutKey1);
  61619. b->addShortcut (shortcutKey2);
  61620. b->addListener (this);
  61621. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61622. addAndMakeVisible (b, 0);
  61623. updateLayout (false);
  61624. }
  61625. int AlertWindow::getNumButtons() const
  61626. {
  61627. return buttons.size();
  61628. }
  61629. void AlertWindow::triggerButtonClick (const String& buttonName)
  61630. {
  61631. for (int i = buttons.size(); --i >= 0;)
  61632. {
  61633. TextButton* const b = buttons.getUnchecked(i);
  61634. if (buttonName == b->getName())
  61635. {
  61636. b->triggerClick();
  61637. break;
  61638. }
  61639. }
  61640. }
  61641. void AlertWindow::addTextEditor (const String& name,
  61642. const String& initialContents,
  61643. const String& onScreenLabel,
  61644. const bool isPasswordBox)
  61645. {
  61646. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61647. textBoxes.add (tc);
  61648. allComps.add (tc);
  61649. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61650. tc->setFont (font);
  61651. tc->setText (initialContents);
  61652. tc->setCaretPosition (initialContents.length());
  61653. addAndMakeVisible (tc);
  61654. textboxNames.add (onScreenLabel);
  61655. updateLayout (false);
  61656. }
  61657. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61658. {
  61659. for (int i = textBoxes.size(); --i >= 0;)
  61660. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61661. return textBoxes.getUnchecked(i);
  61662. return 0;
  61663. }
  61664. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61665. {
  61666. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61667. return t != 0 ? t->getText() : String::empty;
  61668. }
  61669. void AlertWindow::addComboBox (const String& name,
  61670. const StringArray& items,
  61671. const String& onScreenLabel)
  61672. {
  61673. ComboBox* const cb = new ComboBox (name);
  61674. comboBoxes.add (cb);
  61675. allComps.add (cb);
  61676. for (int i = 0; i < items.size(); ++i)
  61677. cb->addItem (items[i], i + 1);
  61678. addAndMakeVisible (cb);
  61679. cb->setSelectedItemIndex (0);
  61680. comboBoxNames.add (onScreenLabel);
  61681. updateLayout (false);
  61682. }
  61683. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61684. {
  61685. for (int i = comboBoxes.size(); --i >= 0;)
  61686. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61687. return comboBoxes.getUnchecked(i);
  61688. return 0;
  61689. }
  61690. class AlertTextComp : public TextEditor
  61691. {
  61692. public:
  61693. AlertTextComp (const String& message,
  61694. const Font& font)
  61695. {
  61696. setReadOnly (true);
  61697. setMultiLine (true, true);
  61698. setCaretVisible (false);
  61699. setScrollbarsShown (true);
  61700. lookAndFeelChanged();
  61701. setWantsKeyboardFocus (false);
  61702. setFont (font);
  61703. setText (message, false);
  61704. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61705. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61706. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61707. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61708. }
  61709. ~AlertTextComp()
  61710. {
  61711. }
  61712. int getPreferredWidth() const throw() { return bestWidth; }
  61713. void updateLayout (const int width)
  61714. {
  61715. TextLayout text;
  61716. text.appendText (getText(), getFont());
  61717. text.layout (width - 8, Justification::topLeft, true);
  61718. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61719. }
  61720. private:
  61721. int bestWidth;
  61722. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61723. };
  61724. void AlertWindow::addTextBlock (const String& textBlock)
  61725. {
  61726. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61727. textBlocks.add (c);
  61728. allComps.add (c);
  61729. addAndMakeVisible (c);
  61730. updateLayout (false);
  61731. }
  61732. void AlertWindow::addProgressBarComponent (double& progressValue)
  61733. {
  61734. ProgressBar* const pb = new ProgressBar (progressValue);
  61735. progressBars.add (pb);
  61736. allComps.add (pb);
  61737. addAndMakeVisible (pb);
  61738. updateLayout (false);
  61739. }
  61740. void AlertWindow::addCustomComponent (Component* const component)
  61741. {
  61742. customComps.add (component);
  61743. allComps.add (component);
  61744. addAndMakeVisible (component);
  61745. updateLayout (false);
  61746. }
  61747. int AlertWindow::getNumCustomComponents() const
  61748. {
  61749. return customComps.size();
  61750. }
  61751. Component* AlertWindow::getCustomComponent (const int index) const
  61752. {
  61753. return customComps [index];
  61754. }
  61755. Component* AlertWindow::removeCustomComponent (const int index)
  61756. {
  61757. Component* const c = getCustomComponent (index);
  61758. if (c != 0)
  61759. {
  61760. customComps.removeValue (c);
  61761. allComps.removeValue (c);
  61762. removeChildComponent (c);
  61763. updateLayout (false);
  61764. }
  61765. return c;
  61766. }
  61767. void AlertWindow::paint (Graphics& g)
  61768. {
  61769. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61770. g.setColour (findColour (textColourId));
  61771. g.setFont (getLookAndFeel().getAlertWindowFont());
  61772. int i;
  61773. for (i = textBoxes.size(); --i >= 0;)
  61774. {
  61775. const TextEditor* const te = textBoxes.getUnchecked(i);
  61776. g.drawFittedText (textboxNames[i],
  61777. te->getX(), te->getY() - 14,
  61778. te->getWidth(), 14,
  61779. Justification::centredLeft, 1);
  61780. }
  61781. for (i = comboBoxNames.size(); --i >= 0;)
  61782. {
  61783. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61784. g.drawFittedText (comboBoxNames[i],
  61785. cb->getX(), cb->getY() - 14,
  61786. cb->getWidth(), 14,
  61787. Justification::centredLeft, 1);
  61788. }
  61789. for (i = customComps.size(); --i >= 0;)
  61790. {
  61791. const Component* const c = customComps.getUnchecked(i);
  61792. g.drawFittedText (c->getName(),
  61793. c->getX(), c->getY() - 14,
  61794. c->getWidth(), 14,
  61795. Justification::centredLeft, 1);
  61796. }
  61797. }
  61798. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61799. {
  61800. const int titleH = 24;
  61801. const int iconWidth = 80;
  61802. const int wid = jmax (font.getStringWidth (text),
  61803. font.getStringWidth (getName()));
  61804. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61805. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61806. const int edgeGap = 10;
  61807. const int labelHeight = 18;
  61808. int iconSpace;
  61809. if (alertIconType == NoIcon)
  61810. {
  61811. textLayout.layout (w, Justification::horizontallyCentred, true);
  61812. iconSpace = 0;
  61813. }
  61814. else
  61815. {
  61816. textLayout.layout (w, Justification::left, true);
  61817. iconSpace = iconWidth;
  61818. }
  61819. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61820. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61821. const int textLayoutH = textLayout.getHeight();
  61822. const int textBottom = 16 + titleH + textLayoutH;
  61823. int h = textBottom;
  61824. int buttonW = 40;
  61825. int i;
  61826. for (i = 0; i < buttons.size(); ++i)
  61827. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61828. w = jmax (buttonW, w);
  61829. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61830. if (buttons.size() > 0)
  61831. h += 20 + buttons.getUnchecked(0)->getHeight();
  61832. for (i = customComps.size(); --i >= 0;)
  61833. {
  61834. Component* c = customComps.getUnchecked(i);
  61835. w = jmax (w, (c->getWidth() * 100) / 80);
  61836. h += 10 + c->getHeight();
  61837. if (c->getName().isNotEmpty())
  61838. h += labelHeight;
  61839. }
  61840. for (i = textBlocks.size(); --i >= 0;)
  61841. {
  61842. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61843. w = jmax (w, ac->getPreferredWidth());
  61844. }
  61845. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61846. for (i = textBlocks.size(); --i >= 0;)
  61847. {
  61848. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61849. ac->updateLayout ((int) (w * 0.8f));
  61850. h += ac->getHeight() + 10;
  61851. }
  61852. h = jmin (getParentHeight() - 50, h);
  61853. if (onlyIncreaseSize)
  61854. {
  61855. w = jmax (w, getWidth());
  61856. h = jmax (h, getHeight());
  61857. }
  61858. if (! isVisible())
  61859. {
  61860. centreAroundComponent (associatedComponent, w, h);
  61861. }
  61862. else
  61863. {
  61864. const int cx = getX() + getWidth() / 2;
  61865. const int cy = getY() + getHeight() / 2;
  61866. setBounds (cx - w / 2,
  61867. cy - h / 2,
  61868. w, h);
  61869. }
  61870. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61871. const int spacer = 16;
  61872. int totalWidth = -spacer;
  61873. for (i = buttons.size(); --i >= 0;)
  61874. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61875. int x = (w - totalWidth) / 2;
  61876. int y = (int) (getHeight() * 0.95f);
  61877. for (i = 0; i < buttons.size(); ++i)
  61878. {
  61879. TextButton* const c = buttons.getUnchecked(i);
  61880. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61881. c->setTopLeftPosition (x, ny);
  61882. if (ny < y)
  61883. y = ny;
  61884. x += c->getWidth() + spacer;
  61885. c->toFront (false);
  61886. }
  61887. y = textBottom;
  61888. for (i = 0; i < allComps.size(); ++i)
  61889. {
  61890. Component* const c = allComps.getUnchecked(i);
  61891. h = 22;
  61892. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61893. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61894. y += labelHeight;
  61895. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61896. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61897. y += labelHeight;
  61898. if (customComps.contains (c))
  61899. {
  61900. if (c->getName().isNotEmpty())
  61901. y += labelHeight;
  61902. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61903. h = c->getHeight();
  61904. }
  61905. else if (textBlocks.contains (c))
  61906. {
  61907. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61908. h = c->getHeight();
  61909. }
  61910. else
  61911. {
  61912. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61913. }
  61914. y += h + 10;
  61915. }
  61916. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61917. }
  61918. bool AlertWindow::containsAnyExtraComponents() const
  61919. {
  61920. return allComps.size() > 0;
  61921. }
  61922. void AlertWindow::mouseDown (const MouseEvent& e)
  61923. {
  61924. dragger.startDraggingComponent (this, e);
  61925. }
  61926. void AlertWindow::mouseDrag (const MouseEvent& e)
  61927. {
  61928. dragger.dragComponent (this, e, &constrainer);
  61929. }
  61930. bool AlertWindow::keyPressed (const KeyPress& key)
  61931. {
  61932. for (int i = buttons.size(); --i >= 0;)
  61933. {
  61934. TextButton* const b = buttons.getUnchecked(i);
  61935. if (b->isRegisteredForShortcut (key))
  61936. {
  61937. b->triggerClick();
  61938. return true;
  61939. }
  61940. }
  61941. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61942. {
  61943. exitModalState (0);
  61944. return true;
  61945. }
  61946. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61947. {
  61948. buttons.getUnchecked(0)->triggerClick();
  61949. return true;
  61950. }
  61951. return false;
  61952. }
  61953. void AlertWindow::lookAndFeelChanged()
  61954. {
  61955. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61956. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61957. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61958. }
  61959. int AlertWindow::getDesktopWindowStyleFlags() const
  61960. {
  61961. return getLookAndFeel().getAlertBoxWindowFlags();
  61962. }
  61963. class AlertWindowInfo
  61964. {
  61965. public:
  61966. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61967. AlertWindow::AlertIconType iconType_, int numButtons_,
  61968. ModalComponentManager::Callback* callback_, bool modal_)
  61969. : title (title_), message (message_), iconType (iconType_),
  61970. numButtons (numButtons_), returnValue (0), associatedComponent (component),
  61971. callback (callback_), modal (modal_)
  61972. {
  61973. }
  61974. String title, message, button1, button2, button3;
  61975. int invoke() const
  61976. {
  61977. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61978. return returnValue;
  61979. }
  61980. private:
  61981. AlertWindow::AlertIconType iconType;
  61982. int numButtons, returnValue;
  61983. WeakReference<Component> associatedComponent;
  61984. ModalComponentManager::Callback* callback;
  61985. bool modal;
  61986. void show()
  61987. {
  61988. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61989. : LookAndFeel::getDefaultLookAndFeel();
  61990. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61991. iconType, numButtons, associatedComponent));
  61992. jassert (alertBox != 0); // you have to return one of these!
  61993. #if JUCE_MODAL_LOOPS_PERMITTED
  61994. if (modal)
  61995. {
  61996. returnValue = alertBox->runModalLoop();
  61997. }
  61998. else
  61999. #endif
  62000. {
  62001. alertBox->enterModalState (true, callback, true);
  62002. alertBox.release();
  62003. }
  62004. }
  62005. static void* showCallback (void* userData)
  62006. {
  62007. static_cast <AlertWindowInfo*> (userData)->show();
  62008. return 0;
  62009. }
  62010. };
  62011. #if JUCE_MODAL_LOOPS_PERMITTED
  62012. void AlertWindow::showMessageBox (AlertIconType iconType,
  62013. const String& title,
  62014. const String& message,
  62015. const String& buttonText,
  62016. Component* associatedComponent)
  62017. {
  62018. AlertWindowInfo info (title, message, associatedComponent, iconType, 1, 0, true);
  62019. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62020. info.invoke();
  62021. }
  62022. #endif
  62023. void AlertWindow::showMessageBoxAsync (AlertIconType iconType,
  62024. const String& title,
  62025. const String& message,
  62026. const String& buttonText,
  62027. Component* associatedComponent)
  62028. {
  62029. AlertWindowInfo info (title, message, associatedComponent, iconType, 1, 0, false);
  62030. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62031. info.invoke();
  62032. }
  62033. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62034. const String& title,
  62035. const String& message,
  62036. const String& button1Text,
  62037. const String& button2Text,
  62038. Component* associatedComponent,
  62039. ModalComponentManager::Callback* callback)
  62040. {
  62041. AlertWindowInfo info (title, message, associatedComponent, iconType, 2, callback, callback == 0);
  62042. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62043. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62044. return info.invoke() != 0;
  62045. }
  62046. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62047. const String& title,
  62048. const String& message,
  62049. const String& button1Text,
  62050. const String& button2Text,
  62051. const String& button3Text,
  62052. Component* associatedComponent,
  62053. ModalComponentManager::Callback* callback)
  62054. {
  62055. AlertWindowInfo info (title, message, associatedComponent, iconType, 3, callback, callback == 0);
  62056. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62057. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62058. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62059. return info.invoke();
  62060. }
  62061. END_JUCE_NAMESPACE
  62062. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62063. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62064. BEGIN_JUCE_NAMESPACE
  62065. CallOutBox::CallOutBox (Component& contentComponent,
  62066. Component& componentToPointTo,
  62067. Component* const parentComponent)
  62068. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62069. {
  62070. addAndMakeVisible (&content);
  62071. if (parentComponent != 0)
  62072. {
  62073. parentComponent->addChildComponent (this);
  62074. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  62075. parentComponent->getLocalBounds());
  62076. setVisible (true);
  62077. }
  62078. else
  62079. {
  62080. if (! JUCEApplication::isStandaloneApp())
  62081. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62082. updatePosition (componentToPointTo.getScreenBounds(),
  62083. componentToPointTo.getParentMonitorArea());
  62084. addToDesktop (ComponentPeer::windowIsTemporary);
  62085. }
  62086. }
  62087. CallOutBox::~CallOutBox()
  62088. {
  62089. }
  62090. void CallOutBox::setArrowSize (const float newSize)
  62091. {
  62092. arrowSize = newSize;
  62093. borderSpace = jmax (20, (int) arrowSize);
  62094. refreshPath();
  62095. }
  62096. void CallOutBox::paint (Graphics& g)
  62097. {
  62098. if (background.isNull())
  62099. {
  62100. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62101. Graphics g2 (background);
  62102. getLookAndFeel().drawCallOutBoxBackground (*this, g2, outline);
  62103. }
  62104. g.setColour (Colours::black);
  62105. g.drawImageAt (background, 0, 0);
  62106. }
  62107. void CallOutBox::resized()
  62108. {
  62109. content.setTopLeftPosition (borderSpace, borderSpace);
  62110. refreshPath();
  62111. }
  62112. void CallOutBox::moved()
  62113. {
  62114. refreshPath();
  62115. }
  62116. void CallOutBox::childBoundsChanged (Component*)
  62117. {
  62118. updatePosition (targetArea, availableArea);
  62119. }
  62120. bool CallOutBox::hitTest (int x, int y)
  62121. {
  62122. return outline.contains ((float) x, (float) y);
  62123. }
  62124. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62125. void CallOutBox::inputAttemptWhenModal()
  62126. {
  62127. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62128. if (targetArea.contains (mousePos))
  62129. {
  62130. // if you click on the area that originally popped-up the callout, you expect it
  62131. // to get rid of the box, but deleting the box here allows the click to pass through and
  62132. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62133. postCommandMessage (callOutBoxDismissCommandId);
  62134. }
  62135. else
  62136. {
  62137. exitModalState (0);
  62138. setVisible (false);
  62139. }
  62140. }
  62141. void CallOutBox::handleCommandMessage (int commandId)
  62142. {
  62143. Component::handleCommandMessage (commandId);
  62144. if (commandId == callOutBoxDismissCommandId)
  62145. {
  62146. exitModalState (0);
  62147. setVisible (false);
  62148. }
  62149. }
  62150. bool CallOutBox::keyPressed (const KeyPress& key)
  62151. {
  62152. if (key.isKeyCode (KeyPress::escapeKey))
  62153. {
  62154. inputAttemptWhenModal();
  62155. return true;
  62156. }
  62157. return false;
  62158. }
  62159. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62160. {
  62161. targetArea = newAreaToPointTo;
  62162. availableArea = newAreaToFitIn;
  62163. Rectangle<int> bounds (0, 0,
  62164. content.getWidth() + borderSpace * 2,
  62165. content.getHeight() + borderSpace * 2);
  62166. const int hw = bounds.getWidth() / 2;
  62167. const int hh = bounds.getHeight() / 2;
  62168. const float hwReduced = (float) (hw - borderSpace * 3);
  62169. const float hhReduced = (float) (hh - borderSpace * 3);
  62170. const float arrowIndent = borderSpace - arrowSize;
  62171. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62172. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62173. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62174. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62175. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62176. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62177. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62178. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62179. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62180. float nearest = 1.0e9f;
  62181. for (int i = 0; i < 4; ++i)
  62182. {
  62183. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62184. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62185. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62186. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62187. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62188. distanceFromCentre *= 2.0f;
  62189. if (distanceFromCentre < nearest)
  62190. {
  62191. nearest = distanceFromCentre;
  62192. targetPoint = targets[i];
  62193. bounds.setPosition ((int) (centre.getX() - hw),
  62194. (int) (centre.getY() - hh));
  62195. }
  62196. }
  62197. setBounds (bounds);
  62198. }
  62199. void CallOutBox::refreshPath()
  62200. {
  62201. repaint();
  62202. background = Image::null;
  62203. outline.clear();
  62204. const float gap = 4.5f;
  62205. const float cornerSize = 9.0f;
  62206. const float cornerSize2 = 2.0f * cornerSize;
  62207. const float arrowBaseWidth = arrowSize * 0.7f;
  62208. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62209. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62210. outline.startNewSubPath (left + cornerSize, top);
  62211. if (targetY <= top)
  62212. {
  62213. outline.lineTo (targetX - arrowBaseWidth, top);
  62214. outline.lineTo (targetX, targetY);
  62215. outline.lineTo (targetX + arrowBaseWidth, top);
  62216. }
  62217. outline.lineTo (right - cornerSize, top);
  62218. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62219. if (targetX >= right)
  62220. {
  62221. outline.lineTo (right, targetY - arrowBaseWidth);
  62222. outline.lineTo (targetX, targetY);
  62223. outline.lineTo (right, targetY + arrowBaseWidth);
  62224. }
  62225. outline.lineTo (right, bottom - cornerSize);
  62226. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62227. if (targetY >= bottom)
  62228. {
  62229. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62230. outline.lineTo (targetX, targetY);
  62231. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62232. }
  62233. outline.lineTo (left + cornerSize, bottom);
  62234. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62235. if (targetX <= left)
  62236. {
  62237. outline.lineTo (left, targetY + arrowBaseWidth);
  62238. outline.lineTo (targetX, targetY);
  62239. outline.lineTo (left, targetY - arrowBaseWidth);
  62240. }
  62241. outline.lineTo (left, top + cornerSize);
  62242. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62243. outline.closeSubPath();
  62244. }
  62245. END_JUCE_NAMESPACE
  62246. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62247. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62248. BEGIN_JUCE_NAMESPACE
  62249. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62250. static Array <ComponentPeer*> heavyweightPeers;
  62251. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62252. : component (component_),
  62253. styleFlags (styleFlags_),
  62254. lastPaintTime (0),
  62255. constrainer (0),
  62256. lastDragAndDropCompUnderMouse (0),
  62257. fakeMouseMessageSent (false),
  62258. isWindowMinimised (false)
  62259. {
  62260. heavyweightPeers.add (this);
  62261. }
  62262. ComponentPeer::~ComponentPeer()
  62263. {
  62264. heavyweightPeers.removeValue (this);
  62265. Desktop::getInstance().triggerFocusCallback();
  62266. }
  62267. int ComponentPeer::getNumPeers() throw()
  62268. {
  62269. return heavyweightPeers.size();
  62270. }
  62271. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62272. {
  62273. return heavyweightPeers [index];
  62274. }
  62275. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62276. {
  62277. for (int i = heavyweightPeers.size(); --i >= 0;)
  62278. {
  62279. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62280. if (peer->getComponent() == component)
  62281. return peer;
  62282. }
  62283. return 0;
  62284. }
  62285. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62286. {
  62287. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62288. }
  62289. void ComponentPeer::updateCurrentModifiers() throw()
  62290. {
  62291. ModifierKeys::updateCurrentModifiers();
  62292. }
  62293. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62294. {
  62295. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62296. jassert (mouse != 0); // not enough sources!
  62297. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62298. }
  62299. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62300. {
  62301. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62302. jassert (mouse != 0); // not enough sources!
  62303. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62304. }
  62305. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62306. {
  62307. Graphics g (&contextToPaintTo);
  62308. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62309. g.saveState();
  62310. #endif
  62311. JUCE_TRY
  62312. {
  62313. component->paintEntireComponent (g, true);
  62314. }
  62315. JUCE_CATCH_EXCEPTION
  62316. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62317. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62318. // clearly when things are being repainted.
  62319. g.restoreState();
  62320. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62321. (uint8) Random::getSystemRandom().nextInt (255),
  62322. (uint8) Random::getSystemRandom().nextInt (255),
  62323. (uint8) 0x50));
  62324. #endif
  62325. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62326. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62327. mess up a lot of the calculations that the library needs to do.
  62328. */
  62329. jassert (roundToInt (10.1f) == 10);
  62330. }
  62331. bool ComponentPeer::handleKeyPress (const int keyCode,
  62332. const juce_wchar textCharacter)
  62333. {
  62334. updateCurrentModifiers();
  62335. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62336. ? Component::getCurrentlyFocusedComponent()
  62337. : component;
  62338. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62339. {
  62340. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62341. if (currentModalComp != 0)
  62342. target = currentModalComp;
  62343. }
  62344. const KeyPress keyInfo (keyCode,
  62345. ModifierKeys::getCurrentModifiers().getRawFlags()
  62346. & ModifierKeys::allKeyboardModifiers,
  62347. textCharacter);
  62348. bool keyWasUsed = false;
  62349. while (target != 0)
  62350. {
  62351. const WeakReference<Component> deletionChecker (target);
  62352. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  62353. if (keyListeners != 0)
  62354. {
  62355. for (int i = keyListeners->size(); --i >= 0;)
  62356. {
  62357. keyWasUsed = keyListeners->getUnchecked(i)->keyPressed (keyInfo, target);
  62358. if (keyWasUsed || deletionChecker == 0)
  62359. return keyWasUsed;
  62360. i = jmin (i, keyListeners->size());
  62361. }
  62362. }
  62363. keyWasUsed = target->keyPressed (keyInfo);
  62364. if (keyWasUsed || deletionChecker == 0)
  62365. break;
  62366. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62367. {
  62368. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62369. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62370. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62371. break;
  62372. }
  62373. target = target->getParentComponent();
  62374. }
  62375. return keyWasUsed;
  62376. }
  62377. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62378. {
  62379. updateCurrentModifiers();
  62380. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62381. ? Component::getCurrentlyFocusedComponent()
  62382. : component;
  62383. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62384. {
  62385. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62386. if (currentModalComp != 0)
  62387. target = currentModalComp;
  62388. }
  62389. bool keyWasUsed = false;
  62390. while (target != 0)
  62391. {
  62392. const WeakReference<Component> deletionChecker (target);
  62393. keyWasUsed = target->keyStateChanged (isKeyDown);
  62394. if (keyWasUsed || deletionChecker == 0)
  62395. break;
  62396. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  62397. if (keyListeners != 0)
  62398. {
  62399. for (int i = keyListeners->size(); --i >= 0;)
  62400. {
  62401. keyWasUsed = keyListeners->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62402. if (keyWasUsed || deletionChecker == 0)
  62403. return keyWasUsed;
  62404. i = jmin (i, keyListeners->size());
  62405. }
  62406. }
  62407. target = target->getParentComponent();
  62408. }
  62409. return keyWasUsed;
  62410. }
  62411. void ComponentPeer::handleModifierKeysChange()
  62412. {
  62413. updateCurrentModifiers();
  62414. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62415. if (target == 0)
  62416. target = Component::getCurrentlyFocusedComponent();
  62417. if (target == 0)
  62418. target = component;
  62419. if (target != 0)
  62420. target->internalModifierKeysChanged();
  62421. }
  62422. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62423. {
  62424. Component* const c = Component::getCurrentlyFocusedComponent();
  62425. if (component->isParentOf (c))
  62426. {
  62427. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62428. if (ti != 0 && ti->isTextInputActive())
  62429. return ti;
  62430. }
  62431. return 0;
  62432. }
  62433. void ComponentPeer::handleBroughtToFront()
  62434. {
  62435. updateCurrentModifiers();
  62436. if (component != 0)
  62437. component->internalBroughtToFront();
  62438. }
  62439. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62440. {
  62441. constrainer = newConstrainer;
  62442. }
  62443. void ComponentPeer::handleMovedOrResized()
  62444. {
  62445. updateCurrentModifiers();
  62446. const bool nowMinimised = isMinimised();
  62447. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62448. {
  62449. const WeakReference<Component> deletionChecker (component);
  62450. const Rectangle<int> newBounds (getBounds());
  62451. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62452. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62453. if (wasMoved || wasResized)
  62454. {
  62455. component->bounds = newBounds;
  62456. if (wasResized)
  62457. component->repaint();
  62458. component->sendMovedResizedMessages (wasMoved, wasResized);
  62459. if (deletionChecker == 0)
  62460. return;
  62461. }
  62462. }
  62463. if (isWindowMinimised != nowMinimised)
  62464. {
  62465. isWindowMinimised = nowMinimised;
  62466. component->minimisationStateChanged (nowMinimised);
  62467. component->sendVisibilityChangeMessage();
  62468. }
  62469. if (! isFullScreen())
  62470. lastNonFullscreenBounds = component->getBounds();
  62471. }
  62472. void ComponentPeer::handleFocusGain()
  62473. {
  62474. updateCurrentModifiers();
  62475. if (component->isParentOf (lastFocusedComponent))
  62476. {
  62477. Component::currentlyFocusedComponent = lastFocusedComponent;
  62478. Desktop::getInstance().triggerFocusCallback();
  62479. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62480. }
  62481. else
  62482. {
  62483. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62484. component->grabKeyboardFocus();
  62485. else
  62486. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62487. }
  62488. }
  62489. void ComponentPeer::handleFocusLoss()
  62490. {
  62491. updateCurrentModifiers();
  62492. if (component->hasKeyboardFocus (true))
  62493. {
  62494. lastFocusedComponent = Component::currentlyFocusedComponent;
  62495. if (lastFocusedComponent != 0)
  62496. {
  62497. Component::currentlyFocusedComponent = 0;
  62498. Desktop::getInstance().triggerFocusCallback();
  62499. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62500. }
  62501. }
  62502. }
  62503. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62504. {
  62505. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62506. ? static_cast <Component*> (lastFocusedComponent)
  62507. : component;
  62508. }
  62509. void ComponentPeer::handleScreenSizeChange()
  62510. {
  62511. updateCurrentModifiers();
  62512. component->parentSizeChanged();
  62513. handleMovedOrResized();
  62514. }
  62515. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62516. {
  62517. lastNonFullscreenBounds = newBounds;
  62518. }
  62519. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62520. {
  62521. return lastNonFullscreenBounds;
  62522. }
  62523. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62524. {
  62525. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62526. }
  62527. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62528. {
  62529. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62530. }
  62531. namespace ComponentPeerHelpers
  62532. {
  62533. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62534. const StringArray& files,
  62535. FileDragAndDropTarget* const lastOne)
  62536. {
  62537. while (c != 0)
  62538. {
  62539. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62540. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62541. return t;
  62542. c = c->getParentComponent();
  62543. }
  62544. return 0;
  62545. }
  62546. }
  62547. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62548. {
  62549. updateCurrentModifiers();
  62550. FileDragAndDropTarget* lastTarget
  62551. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62552. FileDragAndDropTarget* newTarget = 0;
  62553. Component* const compUnderMouse = component->getComponentAt (position);
  62554. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62555. {
  62556. lastDragAndDropCompUnderMouse = compUnderMouse;
  62557. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62558. if (newTarget != lastTarget)
  62559. {
  62560. if (lastTarget != 0)
  62561. lastTarget->fileDragExit (files);
  62562. dragAndDropTargetComponent = 0;
  62563. if (newTarget != 0)
  62564. {
  62565. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62566. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62567. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62568. }
  62569. }
  62570. }
  62571. else
  62572. {
  62573. newTarget = lastTarget;
  62574. }
  62575. if (newTarget != 0)
  62576. {
  62577. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62578. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62579. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62580. }
  62581. }
  62582. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62583. {
  62584. handleFileDragMove (files, Point<int> (-1, -1));
  62585. jassert (dragAndDropTargetComponent == 0);
  62586. lastDragAndDropCompUnderMouse = 0;
  62587. }
  62588. // We'll use an async message to deliver the drop, because if the target decides
  62589. // to run a modal loop, it can gum-up the operating system..
  62590. class AsyncFileDropMessage : public CallbackMessage
  62591. {
  62592. public:
  62593. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62594. const Point<int>& position_, const StringArray& files_)
  62595. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62596. {
  62597. }
  62598. void messageCallback()
  62599. {
  62600. if (target != 0)
  62601. dropTarget->filesDropped (files, position.getX(), position.getY());
  62602. }
  62603. private:
  62604. WeakReference<Component> target;
  62605. FileDragAndDropTarget* const dropTarget;
  62606. const Point<int> position;
  62607. const StringArray files;
  62608. JUCE_DECLARE_NON_COPYABLE (AsyncFileDropMessage);
  62609. };
  62610. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62611. {
  62612. handleFileDragMove (files, position);
  62613. if (dragAndDropTargetComponent != 0)
  62614. {
  62615. FileDragAndDropTarget* const target
  62616. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62617. dragAndDropTargetComponent = 0;
  62618. lastDragAndDropCompUnderMouse = 0;
  62619. if (target != 0)
  62620. {
  62621. Component* const targetComp = dynamic_cast <Component*> (target);
  62622. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62623. {
  62624. targetComp->internalModalInputAttempt();
  62625. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62626. return;
  62627. }
  62628. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62629. }
  62630. }
  62631. }
  62632. void ComponentPeer::handleUserClosingWindow()
  62633. {
  62634. updateCurrentModifiers();
  62635. component->userTriedToCloseWindow();
  62636. }
  62637. void ComponentPeer::clearMaskedRegion()
  62638. {
  62639. maskedRegion.clear();
  62640. }
  62641. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62642. {
  62643. maskedRegion.add (x, y, w, h);
  62644. }
  62645. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62646. {
  62647. StringArray s;
  62648. s.add ("Software Renderer");
  62649. return s;
  62650. }
  62651. int ComponentPeer::getCurrentRenderingEngine() throw()
  62652. {
  62653. return 0;
  62654. }
  62655. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62656. {
  62657. }
  62658. END_JUCE_NAMESPACE
  62659. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62660. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62661. BEGIN_JUCE_NAMESPACE
  62662. DialogWindow::DialogWindow (const String& name,
  62663. const Colour& backgroundColour_,
  62664. const bool escapeKeyTriggersCloseButton_,
  62665. const bool addToDesktop_)
  62666. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62667. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62668. {
  62669. }
  62670. DialogWindow::~DialogWindow()
  62671. {
  62672. }
  62673. void DialogWindow::resized()
  62674. {
  62675. DocumentWindow::resized();
  62676. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62677. if (escapeKeyTriggersCloseButton
  62678. && getCloseButton() != 0
  62679. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62680. {
  62681. getCloseButton()->addShortcut (esc);
  62682. }
  62683. }
  62684. class TempDialogWindow : public DialogWindow
  62685. {
  62686. public:
  62687. TempDialogWindow (const String& title,
  62688. Component* contentComponent,
  62689. Component* componentToCentreAround,
  62690. const Colour& colour,
  62691. const bool escapeKeyTriggersCloseButton,
  62692. const bool shouldBeResizable,
  62693. const bool useBottomRightCornerResizer)
  62694. : DialogWindow (title, colour, escapeKeyTriggersCloseButton, true)
  62695. {
  62696. if (! JUCEApplication::isStandaloneApp())
  62697. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62698. setContentNonOwned (contentComponent, true);
  62699. centreAroundComponent (componentToCentreAround, getWidth(), getHeight());
  62700. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62701. }
  62702. void closeButtonPressed()
  62703. {
  62704. setVisible (false);
  62705. }
  62706. private:
  62707. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62708. };
  62709. void DialogWindow::showDialog (const String& dialogTitle,
  62710. Component* const contentComponent,
  62711. Component* const componentToCentreAround,
  62712. const Colour& backgroundColour,
  62713. const bool escapeKeyTriggersCloseButton,
  62714. const bool shouldBeResizable,
  62715. const bool useBottomRightCornerResizer)
  62716. {
  62717. TempDialogWindow* dw = new TempDialogWindow (dialogTitle, contentComponent, componentToCentreAround,
  62718. backgroundColour, escapeKeyTriggersCloseButton,
  62719. shouldBeResizable, useBottomRightCornerResizer);
  62720. dw->enterModalState (true, 0, true);
  62721. }
  62722. #if JUCE_MODAL_LOOPS_PERMITTED
  62723. int DialogWindow::showModalDialog (const String& dialogTitle,
  62724. Component* const contentComponent,
  62725. Component* const componentToCentreAround,
  62726. const Colour& backgroundColour,
  62727. const bool escapeKeyTriggersCloseButton,
  62728. const bool shouldBeResizable,
  62729. const bool useBottomRightCornerResizer)
  62730. {
  62731. TempDialogWindow dw (dialogTitle, contentComponent, componentToCentreAround,
  62732. backgroundColour, escapeKeyTriggersCloseButton,
  62733. shouldBeResizable, useBottomRightCornerResizer);
  62734. return dw.runModalLoop();
  62735. }
  62736. #endif
  62737. END_JUCE_NAMESPACE
  62738. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62739. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62740. BEGIN_JUCE_NAMESPACE
  62741. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62742. {
  62743. public:
  62744. ButtonListenerProxy (DocumentWindow& owner_)
  62745. : owner (owner_)
  62746. {
  62747. }
  62748. void buttonClicked (Button* button)
  62749. {
  62750. if (button == owner.getMinimiseButton())
  62751. owner.minimiseButtonPressed();
  62752. else if (button == owner.getMaximiseButton())
  62753. owner.maximiseButtonPressed();
  62754. else if (button == owner.getCloseButton())
  62755. owner.closeButtonPressed();
  62756. }
  62757. private:
  62758. DocumentWindow& owner;
  62759. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62760. };
  62761. DocumentWindow::DocumentWindow (const String& title,
  62762. const Colour& backgroundColour,
  62763. const int requiredButtons_,
  62764. const bool addToDesktop_)
  62765. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62766. titleBarHeight (26),
  62767. menuBarHeight (24),
  62768. requiredButtons (requiredButtons_),
  62769. #if JUCE_MAC
  62770. positionTitleBarButtonsOnLeft (true),
  62771. #else
  62772. positionTitleBarButtonsOnLeft (false),
  62773. #endif
  62774. drawTitleTextCentred (true),
  62775. menuBarModel (0)
  62776. {
  62777. setResizeLimits (128, 128, 32768, 32768);
  62778. lookAndFeelChanged();
  62779. }
  62780. DocumentWindow::~DocumentWindow()
  62781. {
  62782. // Don't delete or remove the resizer components yourself! They're managed by the
  62783. // DocumentWindow, and you should leave them alone! You may have deleted them
  62784. // accidentally by careless use of deleteAllChildren()..?
  62785. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62786. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62787. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62788. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62789. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62790. titleBarButtons[i] = 0;
  62791. menuBar = 0;
  62792. }
  62793. void DocumentWindow::repaintTitleBar()
  62794. {
  62795. repaint (getTitleBarArea());
  62796. }
  62797. void DocumentWindow::setName (const String& newName)
  62798. {
  62799. if (newName != getName())
  62800. {
  62801. Component::setName (newName);
  62802. repaintTitleBar();
  62803. }
  62804. }
  62805. void DocumentWindow::setIcon (const Image& imageToUse)
  62806. {
  62807. titleBarIcon = imageToUse;
  62808. repaintTitleBar();
  62809. }
  62810. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62811. {
  62812. titleBarHeight = newHeight;
  62813. resized();
  62814. repaintTitleBar();
  62815. }
  62816. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62817. const bool positionTitleBarButtonsOnLeft_)
  62818. {
  62819. requiredButtons = requiredButtons_;
  62820. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62821. lookAndFeelChanged();
  62822. }
  62823. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62824. {
  62825. drawTitleTextCentred = textShouldBeCentred;
  62826. repaintTitleBar();
  62827. }
  62828. void DocumentWindow::setMenuBar (MenuBarModel* newMenuBarModel, const int newMenuBarHeight)
  62829. {
  62830. if (menuBarModel != newMenuBarModel)
  62831. {
  62832. menuBar = 0;
  62833. menuBarModel = newMenuBarModel;
  62834. menuBarHeight = newMenuBarHeight > 0 ? newMenuBarHeight
  62835. : getLookAndFeel().getDefaultMenuBarHeight();
  62836. if (menuBarModel != 0)
  62837. setMenuBarComponent (new MenuBarComponent (menuBarModel));
  62838. resized();
  62839. }
  62840. }
  62841. Component* DocumentWindow::getMenuBarComponent() const throw()
  62842. {
  62843. return menuBar;
  62844. }
  62845. void DocumentWindow::setMenuBarComponent (Component* newMenuBarComponent)
  62846. {
  62847. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62848. Component::addAndMakeVisible (menuBar = newMenuBarComponent);
  62849. if (menuBar != 0)
  62850. menuBar->setEnabled (isActiveWindow());
  62851. resized();
  62852. }
  62853. void DocumentWindow::closeButtonPressed()
  62854. {
  62855. /* If you've got a close button, you have to override this method to get
  62856. rid of your window!
  62857. If the window is just a pop-up, you should override this method and make
  62858. it delete the window in whatever way is appropriate for your app. E.g. you
  62859. might just want to call "delete this".
  62860. If your app is centred around this window such that the whole app should quit when
  62861. the window is closed, then you will probably want to use this method as an opportunity
  62862. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62863. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62864. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62865. or closing it via the taskbar icon on Windows).
  62866. */
  62867. jassertfalse;
  62868. }
  62869. void DocumentWindow::minimiseButtonPressed()
  62870. {
  62871. setMinimised (true);
  62872. }
  62873. void DocumentWindow::maximiseButtonPressed()
  62874. {
  62875. setFullScreen (! isFullScreen());
  62876. }
  62877. void DocumentWindow::paint (Graphics& g)
  62878. {
  62879. ResizableWindow::paint (g);
  62880. if (resizableBorder == 0)
  62881. {
  62882. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62883. const BorderSize<int> border (getBorderThickness());
  62884. g.fillRect (0, 0, getWidth(), border.getTop());
  62885. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62886. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62887. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62888. }
  62889. const Rectangle<int> titleBarArea (getTitleBarArea());
  62890. g.reduceClipRegion (titleBarArea);
  62891. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62892. int titleSpaceX1 = 6;
  62893. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62894. for (int i = 0; i < 3; ++i)
  62895. {
  62896. if (titleBarButtons[i] != 0)
  62897. {
  62898. if (positionTitleBarButtonsOnLeft)
  62899. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62900. else
  62901. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62902. }
  62903. }
  62904. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62905. titleBarArea.getWidth(),
  62906. titleBarArea.getHeight(),
  62907. titleSpaceX1,
  62908. jmax (1, titleSpaceX2 - titleSpaceX1),
  62909. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62910. ! drawTitleTextCentred);
  62911. }
  62912. void DocumentWindow::resized()
  62913. {
  62914. ResizableWindow::resized();
  62915. if (titleBarButtons[1] != 0)
  62916. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62917. const Rectangle<int> titleBarArea (getTitleBarArea());
  62918. getLookAndFeel()
  62919. .positionDocumentWindowButtons (*this,
  62920. titleBarArea.getX(), titleBarArea.getY(),
  62921. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62922. titleBarButtons[0],
  62923. titleBarButtons[1],
  62924. titleBarButtons[2],
  62925. positionTitleBarButtonsOnLeft);
  62926. if (menuBar != 0)
  62927. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62928. titleBarArea.getWidth(), menuBarHeight);
  62929. }
  62930. const BorderSize<int> DocumentWindow::getBorderThickness()
  62931. {
  62932. return BorderSize<int> ((isFullScreen() || isUsingNativeTitleBar())
  62933. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62934. }
  62935. const BorderSize<int> DocumentWindow::getContentComponentBorder()
  62936. {
  62937. BorderSize<int> border (getBorderThickness());
  62938. border.setTop (border.getTop()
  62939. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62940. + (menuBar != 0 ? menuBarHeight : 0));
  62941. return border;
  62942. }
  62943. int DocumentWindow::getTitleBarHeight() const
  62944. {
  62945. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62946. }
  62947. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62948. {
  62949. const BorderSize<int> border (getBorderThickness());
  62950. return Rectangle<int> (border.getLeft(), border.getTop(),
  62951. getWidth() - border.getLeftAndRight(),
  62952. getTitleBarHeight());
  62953. }
  62954. Button* DocumentWindow::getCloseButton() const throw() { return titleBarButtons[2]; }
  62955. Button* DocumentWindow::getMinimiseButton() const throw() { return titleBarButtons[0]; }
  62956. Button* DocumentWindow::getMaximiseButton() const throw() { return titleBarButtons[1]; }
  62957. int DocumentWindow::getDesktopWindowStyleFlags() const
  62958. {
  62959. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62960. if ((requiredButtons & minimiseButton) != 0)
  62961. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62962. if ((requiredButtons & maximiseButton) != 0)
  62963. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62964. if ((requiredButtons & closeButton) != 0)
  62965. styleFlags |= ComponentPeer::windowHasCloseButton;
  62966. return styleFlags;
  62967. }
  62968. void DocumentWindow::lookAndFeelChanged()
  62969. {
  62970. int i;
  62971. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62972. titleBarButtons[i] = 0;
  62973. if (! isUsingNativeTitleBar())
  62974. {
  62975. LookAndFeel& lf = getLookAndFeel();
  62976. if ((requiredButtons & minimiseButton) != 0)
  62977. titleBarButtons[0] = lf.createDocumentWindowButton (minimiseButton);
  62978. if ((requiredButtons & maximiseButton) != 0)
  62979. titleBarButtons[1] = lf.createDocumentWindowButton (maximiseButton);
  62980. if ((requiredButtons & closeButton) != 0)
  62981. titleBarButtons[2] = lf.createDocumentWindowButton (closeButton);
  62982. for (i = 0; i < 3; ++i)
  62983. {
  62984. if (titleBarButtons[i] != 0)
  62985. {
  62986. if (buttonListener == 0)
  62987. buttonListener = new ButtonListenerProxy (*this);
  62988. titleBarButtons[i]->addListener (buttonListener);
  62989. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62990. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62991. Component::addAndMakeVisible (titleBarButtons[i]);
  62992. }
  62993. }
  62994. if (getCloseButton() != 0)
  62995. {
  62996. #if JUCE_MAC
  62997. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62998. #else
  62999. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63000. #endif
  63001. }
  63002. }
  63003. activeWindowStatusChanged();
  63004. ResizableWindow::lookAndFeelChanged();
  63005. }
  63006. void DocumentWindow::parentHierarchyChanged()
  63007. {
  63008. lookAndFeelChanged();
  63009. }
  63010. void DocumentWindow::activeWindowStatusChanged()
  63011. {
  63012. ResizableWindow::activeWindowStatusChanged();
  63013. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63014. if (titleBarButtons[i] != 0)
  63015. titleBarButtons[i]->setEnabled (isActiveWindow());
  63016. if (menuBar != 0)
  63017. menuBar->setEnabled (isActiveWindow());
  63018. }
  63019. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63020. {
  63021. if (getTitleBarArea().contains (e.x, e.y)
  63022. && getMaximiseButton() != 0)
  63023. {
  63024. getMaximiseButton()->triggerClick();
  63025. }
  63026. }
  63027. void DocumentWindow::userTriedToCloseWindow()
  63028. {
  63029. closeButtonPressed();
  63030. }
  63031. END_JUCE_NAMESPACE
  63032. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63033. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63034. BEGIN_JUCE_NAMESPACE
  63035. ResizableWindow::ResizableWindow (const String& name,
  63036. const bool addToDesktop_)
  63037. : TopLevelWindow (name, addToDesktop_),
  63038. ownsContentComponent (false),
  63039. resizeToFitContent (false),
  63040. fullscreen (false),
  63041. lastNonFullScreenPos (50, 50, 256, 256),
  63042. constrainer (0)
  63043. #if JUCE_DEBUG
  63044. , hasBeenResized (false)
  63045. #endif
  63046. {
  63047. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63048. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63049. if (addToDesktop_)
  63050. Component::addToDesktop (getDesktopWindowStyleFlags());
  63051. }
  63052. ResizableWindow::ResizableWindow (const String& name,
  63053. const Colour& backgroundColour_,
  63054. const bool addToDesktop_)
  63055. : TopLevelWindow (name, addToDesktop_),
  63056. ownsContentComponent (false),
  63057. resizeToFitContent (false),
  63058. fullscreen (false),
  63059. lastNonFullScreenPos (50, 50, 256, 256),
  63060. constrainer (0)
  63061. #if JUCE_DEBUG
  63062. , hasBeenResized (false)
  63063. #endif
  63064. {
  63065. setBackgroundColour (backgroundColour_);
  63066. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63067. if (addToDesktop_)
  63068. Component::addToDesktop (getDesktopWindowStyleFlags());
  63069. }
  63070. ResizableWindow::~ResizableWindow()
  63071. {
  63072. // Don't delete or remove the resizer components yourself! They're managed by the
  63073. // ResizableWindow, and you should leave them alone! You may have deleted them
  63074. // accidentally by careless use of deleteAllChildren()..?
  63075. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  63076. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  63077. resizableCorner = 0;
  63078. resizableBorder = 0;
  63079. clearContentComponent();
  63080. // have you been adding your own components directly to this window..? tut tut tut.
  63081. // Read the instructions for using a ResizableWindow!
  63082. jassert (getNumChildComponents() == 0);
  63083. }
  63084. int ResizableWindow::getDesktopWindowStyleFlags() const
  63085. {
  63086. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63087. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63088. styleFlags |= ComponentPeer::windowIsResizable;
  63089. return styleFlags;
  63090. }
  63091. void ResizableWindow::clearContentComponent()
  63092. {
  63093. if (ownsContentComponent)
  63094. {
  63095. contentComponent.deleteAndZero();
  63096. }
  63097. else
  63098. {
  63099. removeChildComponent (contentComponent);
  63100. contentComponent = 0;
  63101. }
  63102. }
  63103. void ResizableWindow::setContent (Component* newContentComponent,
  63104. const bool takeOwnership,
  63105. const bool resizeToFitWhenContentChangesSize)
  63106. {
  63107. if (newContentComponent != contentComponent)
  63108. {
  63109. clearContentComponent();
  63110. contentComponent = newContentComponent;
  63111. Component::addAndMakeVisible (contentComponent);
  63112. }
  63113. ownsContentComponent = takeOwnership;
  63114. resizeToFitContent = resizeToFitWhenContentChangesSize;
  63115. if (resizeToFitWhenContentChangesSize)
  63116. childBoundsChanged (contentComponent);
  63117. resized(); // must always be called to position the new content comp
  63118. }
  63119. void ResizableWindow::setContentOwned (Component* newContentComponent, const bool resizeToFitWhenContentChangesSize)
  63120. {
  63121. setContent (newContentComponent, true, resizeToFitWhenContentChangesSize);
  63122. }
  63123. void ResizableWindow::setContentNonOwned (Component* newContentComponent, const bool resizeToFitWhenContentChangesSize)
  63124. {
  63125. setContent (newContentComponent, false, resizeToFitWhenContentChangesSize);
  63126. }
  63127. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63128. const bool deleteOldOne,
  63129. const bool resizeToFitWhenContentChangesSize)
  63130. {
  63131. if (newContentComponent != contentComponent)
  63132. {
  63133. if (deleteOldOne)
  63134. {
  63135. contentComponent.deleteAndZero();
  63136. }
  63137. else
  63138. {
  63139. removeChildComponent (contentComponent);
  63140. contentComponent = 0;
  63141. }
  63142. }
  63143. setContent (newContentComponent, true, resizeToFitWhenContentChangesSize);
  63144. }
  63145. void ResizableWindow::setContentComponentSize (int width, int height)
  63146. {
  63147. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63148. const BorderSize<int> border (getContentComponentBorder());
  63149. setSize (width + border.getLeftAndRight(),
  63150. height + border.getTopAndBottom());
  63151. }
  63152. const BorderSize<int> ResizableWindow::getBorderThickness()
  63153. {
  63154. return BorderSize<int> (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63155. }
  63156. const BorderSize<int> ResizableWindow::getContentComponentBorder()
  63157. {
  63158. return getBorderThickness();
  63159. }
  63160. void ResizableWindow::moved()
  63161. {
  63162. updateLastPos();
  63163. }
  63164. void ResizableWindow::visibilityChanged()
  63165. {
  63166. TopLevelWindow::visibilityChanged();
  63167. updateLastPos();
  63168. }
  63169. void ResizableWindow::resized()
  63170. {
  63171. if (resizableBorder != 0)
  63172. {
  63173. #if JUCE_WINDOWS || JUCE_LINUX
  63174. // hide the resizable border if the OS already provides one..
  63175. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63176. #else
  63177. resizableBorder->setVisible (! isFullScreen());
  63178. #endif
  63179. resizableBorder->setBorderThickness (getBorderThickness());
  63180. resizableBorder->setSize (getWidth(), getHeight());
  63181. resizableBorder->toBack();
  63182. }
  63183. if (resizableCorner != 0)
  63184. {
  63185. #if JUCE_MAC
  63186. // hide the resizable border if the OS already provides one..
  63187. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63188. #else
  63189. resizableCorner->setVisible (! isFullScreen());
  63190. #endif
  63191. const int resizerSize = 18;
  63192. resizableCorner->setBounds (getWidth() - resizerSize,
  63193. getHeight() - resizerSize,
  63194. resizerSize, resizerSize);
  63195. }
  63196. if (contentComponent != 0)
  63197. contentComponent->setBoundsInset (getContentComponentBorder());
  63198. updateLastPos();
  63199. #if JUCE_DEBUG
  63200. hasBeenResized = true;
  63201. #endif
  63202. }
  63203. void ResizableWindow::childBoundsChanged (Component* child)
  63204. {
  63205. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63206. {
  63207. // not going to look very good if this component has a zero size..
  63208. jassert (child->getWidth() > 0);
  63209. jassert (child->getHeight() > 0);
  63210. const BorderSize<int> borders (getContentComponentBorder());
  63211. setSize (child->getWidth() + borders.getLeftAndRight(),
  63212. child->getHeight() + borders.getTopAndBottom());
  63213. }
  63214. }
  63215. void ResizableWindow::activeWindowStatusChanged()
  63216. {
  63217. const BorderSize<int> border (getContentComponentBorder());
  63218. Rectangle<int> area (getLocalBounds());
  63219. repaint (area.removeFromTop (border.getTop()));
  63220. repaint (area.removeFromLeft (border.getLeft()));
  63221. repaint (area.removeFromRight (border.getRight()));
  63222. repaint (area.removeFromBottom (border.getBottom()));
  63223. }
  63224. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63225. const bool useBottomRightCornerResizer)
  63226. {
  63227. if (shouldBeResizable)
  63228. {
  63229. if (useBottomRightCornerResizer)
  63230. {
  63231. resizableBorder = 0;
  63232. if (resizableCorner == 0)
  63233. {
  63234. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63235. resizableCorner->setAlwaysOnTop (true);
  63236. }
  63237. }
  63238. else
  63239. {
  63240. resizableCorner = 0;
  63241. if (resizableBorder == 0)
  63242. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63243. }
  63244. }
  63245. else
  63246. {
  63247. resizableCorner = 0;
  63248. resizableBorder = 0;
  63249. }
  63250. if (isUsingNativeTitleBar())
  63251. recreateDesktopWindow();
  63252. childBoundsChanged (contentComponent);
  63253. resized();
  63254. }
  63255. bool ResizableWindow::isResizable() const throw()
  63256. {
  63257. return resizableCorner != 0
  63258. || resizableBorder != 0;
  63259. }
  63260. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63261. const int newMinimumHeight,
  63262. const int newMaximumWidth,
  63263. const int newMaximumHeight) throw()
  63264. {
  63265. // if you've set up a custom constrainer then these settings won't have any effect..
  63266. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63267. if (constrainer == 0)
  63268. setConstrainer (&defaultConstrainer);
  63269. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63270. newMaximumWidth, newMaximumHeight);
  63271. setBoundsConstrained (getBounds());
  63272. }
  63273. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63274. {
  63275. if (constrainer != newConstrainer)
  63276. {
  63277. constrainer = newConstrainer;
  63278. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63279. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63280. resizableCorner = 0;
  63281. resizableBorder = 0;
  63282. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63283. ComponentPeer* const peer = getPeer();
  63284. if (peer != 0)
  63285. peer->setConstrainer (newConstrainer);
  63286. }
  63287. }
  63288. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63289. {
  63290. if (constrainer != 0)
  63291. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63292. else
  63293. setBounds (bounds);
  63294. }
  63295. void ResizableWindow::paint (Graphics& g)
  63296. {
  63297. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63298. getBorderThickness(), *this);
  63299. if (! isFullScreen())
  63300. {
  63301. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63302. getBorderThickness(), *this);
  63303. }
  63304. #if JUCE_DEBUG
  63305. /* If this fails, then you've probably written a subclass with a resized()
  63306. callback but forgotten to make it call its parent class's resized() method.
  63307. It's important when you override methods like resized(), moved(),
  63308. etc., that you make sure the base class methods also get called.
  63309. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63310. because your content should all be inside the content component - and it's the
  63311. content component's resized() method that you should be using to do your
  63312. layout.
  63313. */
  63314. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63315. #endif
  63316. }
  63317. void ResizableWindow::lookAndFeelChanged()
  63318. {
  63319. resized();
  63320. if (isOnDesktop())
  63321. {
  63322. Component::addToDesktop (getDesktopWindowStyleFlags());
  63323. ComponentPeer* const peer = getPeer();
  63324. if (peer != 0)
  63325. peer->setConstrainer (constrainer);
  63326. }
  63327. }
  63328. const Colour ResizableWindow::getBackgroundColour() const throw()
  63329. {
  63330. return findColour (backgroundColourId, false);
  63331. }
  63332. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63333. {
  63334. Colour backgroundColour (newColour);
  63335. if (! Desktop::canUseSemiTransparentWindows())
  63336. backgroundColour = newColour.withAlpha (1.0f);
  63337. setColour (backgroundColourId, backgroundColour);
  63338. setOpaque (backgroundColour.isOpaque());
  63339. repaint();
  63340. }
  63341. bool ResizableWindow::isFullScreen() const
  63342. {
  63343. if (isOnDesktop())
  63344. {
  63345. ComponentPeer* const peer = getPeer();
  63346. return peer != 0 && peer->isFullScreen();
  63347. }
  63348. return fullscreen;
  63349. }
  63350. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63351. {
  63352. if (shouldBeFullScreen != isFullScreen())
  63353. {
  63354. updateLastPos();
  63355. fullscreen = shouldBeFullScreen;
  63356. if (isOnDesktop())
  63357. {
  63358. ComponentPeer* const peer = getPeer();
  63359. if (peer != 0)
  63360. {
  63361. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63362. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63363. peer->setFullScreen (shouldBeFullScreen);
  63364. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63365. setBounds (lastPos);
  63366. }
  63367. else
  63368. {
  63369. jassertfalse;
  63370. }
  63371. }
  63372. else
  63373. {
  63374. if (shouldBeFullScreen)
  63375. setBounds (0, 0, getParentWidth(), getParentHeight());
  63376. else
  63377. setBounds (lastNonFullScreenPos);
  63378. }
  63379. resized();
  63380. }
  63381. }
  63382. bool ResizableWindow::isMinimised() const
  63383. {
  63384. ComponentPeer* const peer = getPeer();
  63385. return (peer != 0) && peer->isMinimised();
  63386. }
  63387. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63388. {
  63389. if (shouldMinimise != isMinimised())
  63390. {
  63391. ComponentPeer* const peer = getPeer();
  63392. if (peer != 0)
  63393. {
  63394. updateLastPos();
  63395. peer->setMinimised (shouldMinimise);
  63396. }
  63397. else
  63398. {
  63399. jassertfalse;
  63400. }
  63401. }
  63402. }
  63403. void ResizableWindow::updateLastPos()
  63404. {
  63405. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63406. {
  63407. lastNonFullScreenPos = getBounds();
  63408. }
  63409. }
  63410. void ResizableWindow::parentSizeChanged()
  63411. {
  63412. if (isFullScreen() && getParentComponent() != 0)
  63413. {
  63414. setBounds (0, 0, getParentWidth(), getParentHeight());
  63415. }
  63416. }
  63417. const String ResizableWindow::getWindowStateAsString()
  63418. {
  63419. updateLastPos();
  63420. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63421. }
  63422. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63423. {
  63424. StringArray tokens;
  63425. tokens.addTokens (s, false);
  63426. tokens.removeEmptyStrings();
  63427. tokens.trim();
  63428. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63429. const int firstCoord = fs ? 1 : 0;
  63430. if (tokens.size() != firstCoord + 4)
  63431. return false;
  63432. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63433. tokens[firstCoord + 1].getIntValue(),
  63434. tokens[firstCoord + 2].getIntValue(),
  63435. tokens[firstCoord + 3].getIntValue());
  63436. if (newPos.isEmpty())
  63437. return false;
  63438. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63439. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63440. if (peer != 0)
  63441. peer->getFrameSize().addTo (newPos);
  63442. if (! screen.contains (newPos))
  63443. {
  63444. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63445. jmin (newPos.getHeight(), screen.getHeight()));
  63446. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63447. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63448. }
  63449. if (peer != 0)
  63450. {
  63451. peer->getFrameSize().subtractFrom (newPos);
  63452. peer->setNonFullScreenBounds (newPos);
  63453. }
  63454. lastNonFullScreenPos = newPos;
  63455. setFullScreen (fs);
  63456. if (! fs)
  63457. setBoundsConstrained (newPos);
  63458. return true;
  63459. }
  63460. void ResizableWindow::mouseDown (const MouseEvent& e)
  63461. {
  63462. if (! isFullScreen())
  63463. dragger.startDraggingComponent (this, e);
  63464. }
  63465. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63466. {
  63467. if (! isFullScreen())
  63468. dragger.dragComponent (this, e, constrainer);
  63469. }
  63470. #if JUCE_DEBUG
  63471. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63472. {
  63473. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63474. manages its child components automatically, and if you add your own it'll cause
  63475. trouble. Instead, use setContentComponent() to give it a component which
  63476. will be automatically resized and kept in the right place - then you can add
  63477. subcomponents to the content comp. See the notes for the ResizableWindow class
  63478. for more info.
  63479. If you really know what you're doing and want to avoid this assertion, just call
  63480. Component::addChildComponent directly.
  63481. */
  63482. jassertfalse;
  63483. Component::addChildComponent (child, zOrder);
  63484. }
  63485. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63486. {
  63487. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63488. manages its child components automatically, and if you add your own it'll cause
  63489. trouble. Instead, use setContentComponent() to give it a component which
  63490. will be automatically resized and kept in the right place - then you can add
  63491. subcomponents to the content comp. See the notes for the ResizableWindow class
  63492. for more info.
  63493. If you really know what you're doing and want to avoid this assertion, just call
  63494. Component::addAndMakeVisible directly.
  63495. */
  63496. jassertfalse;
  63497. Component::addAndMakeVisible (child, zOrder);
  63498. }
  63499. #endif
  63500. END_JUCE_NAMESPACE
  63501. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63502. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63503. BEGIN_JUCE_NAMESPACE
  63504. SplashScreen::SplashScreen()
  63505. {
  63506. setOpaque (true);
  63507. }
  63508. SplashScreen::~SplashScreen()
  63509. {
  63510. }
  63511. void SplashScreen::show (const String& title,
  63512. const Image& backgroundImage_,
  63513. const int minimumTimeToDisplayFor,
  63514. const bool useDropShadow,
  63515. const bool removeOnMouseClick)
  63516. {
  63517. backgroundImage = backgroundImage_;
  63518. jassert (backgroundImage_.isValid());
  63519. if (backgroundImage_.isValid())
  63520. {
  63521. setOpaque (! backgroundImage_.hasAlphaChannel());
  63522. show (title,
  63523. backgroundImage_.getWidth(),
  63524. backgroundImage_.getHeight(),
  63525. minimumTimeToDisplayFor,
  63526. useDropShadow,
  63527. removeOnMouseClick);
  63528. }
  63529. }
  63530. void SplashScreen::show (const String& title,
  63531. const int width,
  63532. const int height,
  63533. const int minimumTimeToDisplayFor,
  63534. const bool useDropShadow,
  63535. const bool removeOnMouseClick)
  63536. {
  63537. setName (title);
  63538. setAlwaysOnTop (true);
  63539. setVisible (true);
  63540. centreWithSize (width, height);
  63541. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63542. toFront (false);
  63543. #if JUCE_MODAL_LOOPS_PERMITTED
  63544. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63545. #endif
  63546. repaint();
  63547. originalClickCounter = removeOnMouseClick
  63548. ? Desktop::getMouseButtonClickCounter()
  63549. : std::numeric_limits<int>::max();
  63550. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63551. startTimer (50);
  63552. }
  63553. void SplashScreen::paint (Graphics& g)
  63554. {
  63555. g.setOpacity (1.0f);
  63556. g.drawImage (backgroundImage,
  63557. 0, 0, getWidth(), getHeight(),
  63558. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63559. }
  63560. void SplashScreen::timerCallback()
  63561. {
  63562. if (Time::getCurrentTime() > earliestTimeToDelete
  63563. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63564. {
  63565. delete this;
  63566. }
  63567. }
  63568. END_JUCE_NAMESPACE
  63569. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63570. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63571. BEGIN_JUCE_NAMESPACE
  63572. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63573. const bool hasProgressBar,
  63574. const bool hasCancelButton,
  63575. const int timeOutMsWhenCancelling_,
  63576. const String& cancelButtonText)
  63577. : Thread ("Juce Progress Window"),
  63578. progress (0.0),
  63579. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63580. {
  63581. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63582. .createAlertWindow (title, String::empty, cancelButtonText,
  63583. String::empty, String::empty,
  63584. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63585. if (hasProgressBar)
  63586. alertWindow->addProgressBarComponent (progress);
  63587. }
  63588. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63589. {
  63590. stopThread (timeOutMsWhenCancelling);
  63591. }
  63592. #if JUCE_MODAL_LOOPS_PERMITTED
  63593. bool ThreadWithProgressWindow::runThread (const int priority)
  63594. {
  63595. startThread (priority);
  63596. startTimer (100);
  63597. {
  63598. const ScopedLock sl (messageLock);
  63599. alertWindow->setMessage (message);
  63600. }
  63601. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63602. stopThread (timeOutMsWhenCancelling);
  63603. alertWindow->setVisible (false);
  63604. return finishedNaturally;
  63605. }
  63606. #endif
  63607. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63608. {
  63609. progress = newProgress;
  63610. }
  63611. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63612. {
  63613. const ScopedLock sl (messageLock);
  63614. message = newStatusMessage;
  63615. }
  63616. void ThreadWithProgressWindow::timerCallback()
  63617. {
  63618. if (! isThreadRunning())
  63619. {
  63620. // thread has finished normally..
  63621. alertWindow->exitModalState (1);
  63622. alertWindow->setVisible (false);
  63623. }
  63624. else
  63625. {
  63626. const ScopedLock sl (messageLock);
  63627. alertWindow->setMessage (message);
  63628. }
  63629. }
  63630. END_JUCE_NAMESPACE
  63631. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63632. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63633. BEGIN_JUCE_NAMESPACE
  63634. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63635. const int millisecondsBeforeTipAppears_)
  63636. : Component ("tooltip"),
  63637. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63638. mouseClicks (0),
  63639. lastHideTime (0),
  63640. lastComponentUnderMouse (0),
  63641. changedCompsSinceShown (true)
  63642. {
  63643. if (Desktop::getInstance().getMainMouseSource().canHover())
  63644. startTimer (123);
  63645. setAlwaysOnTop (true);
  63646. setOpaque (true);
  63647. if (parentComponent != 0)
  63648. parentComponent->addChildComponent (this);
  63649. }
  63650. TooltipWindow::~TooltipWindow()
  63651. {
  63652. hide();
  63653. }
  63654. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63655. {
  63656. millisecondsBeforeTipAppears = newTimeMs;
  63657. }
  63658. void TooltipWindow::paint (Graphics& g)
  63659. {
  63660. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63661. }
  63662. void TooltipWindow::mouseEnter (const MouseEvent&)
  63663. {
  63664. hide();
  63665. }
  63666. void TooltipWindow::showFor (const String& tip)
  63667. {
  63668. jassert (tip.isNotEmpty());
  63669. if (tipShowing != tip)
  63670. repaint();
  63671. tipShowing = tip;
  63672. Point<int> mousePos (Desktop::getMousePosition());
  63673. if (getParentComponent() != 0)
  63674. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63675. int x, y, w, h;
  63676. getLookAndFeel().getTooltipSize (tip, w, h);
  63677. if (mousePos.getX() > getParentWidth() / 2)
  63678. x = mousePos.getX() - (w + 12);
  63679. else
  63680. x = mousePos.getX() + 24;
  63681. if (mousePos.getY() > getParentHeight() / 2)
  63682. y = mousePos.getY() - (h + 6);
  63683. else
  63684. y = mousePos.getY() + 6;
  63685. setBounds (x, y, w, h);
  63686. setVisible (true);
  63687. if (getParentComponent() == 0)
  63688. {
  63689. addToDesktop (ComponentPeer::windowHasDropShadow
  63690. | ComponentPeer::windowIsTemporary
  63691. | ComponentPeer::windowIgnoresKeyPresses);
  63692. }
  63693. toFront (false);
  63694. }
  63695. const String TooltipWindow::getTipFor (Component* const c)
  63696. {
  63697. if (c != 0
  63698. && Process::isForegroundProcess()
  63699. && ! Component::isMouseButtonDownAnywhere())
  63700. {
  63701. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63702. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63703. return ttc->getTooltip();
  63704. }
  63705. return String::empty;
  63706. }
  63707. void TooltipWindow::hide()
  63708. {
  63709. tipShowing = String::empty;
  63710. removeFromDesktop();
  63711. setVisible (false);
  63712. }
  63713. void TooltipWindow::timerCallback()
  63714. {
  63715. const unsigned int now = Time::getApproximateMillisecondCounter();
  63716. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63717. const String newTip (getTipFor (newComp));
  63718. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63719. lastComponentUnderMouse = newComp;
  63720. lastTipUnderMouse = newTip;
  63721. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63722. const bool mouseWasClicked = clickCount > mouseClicks;
  63723. mouseClicks = clickCount;
  63724. const Point<int> mousePos (Desktop::getMousePosition());
  63725. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63726. lastMousePos = mousePos;
  63727. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63728. lastCompChangeTime = now;
  63729. if (isVisible() || now < lastHideTime + 500)
  63730. {
  63731. // if a tip is currently visible (or has just disappeared), update to a new one
  63732. // immediately if needed..
  63733. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63734. {
  63735. if (isVisible())
  63736. {
  63737. lastHideTime = now;
  63738. hide();
  63739. }
  63740. }
  63741. else if (tipChanged)
  63742. {
  63743. showFor (newTip);
  63744. }
  63745. }
  63746. else
  63747. {
  63748. // if there isn't currently a tip, but one is needed, only let it
  63749. // appear after a timeout..
  63750. if (newTip.isNotEmpty()
  63751. && newTip != tipShowing
  63752. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63753. {
  63754. showFor (newTip);
  63755. }
  63756. }
  63757. }
  63758. END_JUCE_NAMESPACE
  63759. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63760. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63761. BEGIN_JUCE_NAMESPACE
  63762. /** Keeps track of the active top level window.
  63763. */
  63764. class TopLevelWindowManager : public Timer,
  63765. public DeletedAtShutdown
  63766. {
  63767. public:
  63768. TopLevelWindowManager()
  63769. : currentActive (0)
  63770. {
  63771. }
  63772. ~TopLevelWindowManager()
  63773. {
  63774. clearSingletonInstance();
  63775. }
  63776. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63777. void timerCallback()
  63778. {
  63779. startTimer (jmin (1731, getTimerInterval() * 2));
  63780. TopLevelWindow* active = 0;
  63781. if (Process::isForegroundProcess())
  63782. {
  63783. active = currentActive;
  63784. Component* const c = Component::getCurrentlyFocusedComponent();
  63785. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63786. if (tlw == 0 && c != 0)
  63787. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63788. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63789. if (tlw != 0)
  63790. active = tlw;
  63791. }
  63792. if (active != currentActive)
  63793. {
  63794. currentActive = active;
  63795. for (int i = windows.size(); --i >= 0;)
  63796. {
  63797. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63798. tlw->setWindowActive (isWindowActive (tlw));
  63799. i = jmin (i, windows.size() - 1);
  63800. }
  63801. Desktop::getInstance().triggerFocusCallback();
  63802. }
  63803. }
  63804. bool addWindow (TopLevelWindow* const w)
  63805. {
  63806. windows.add (w);
  63807. startTimer (10);
  63808. return isWindowActive (w);
  63809. }
  63810. void removeWindow (TopLevelWindow* const w)
  63811. {
  63812. startTimer (10);
  63813. if (currentActive == w)
  63814. currentActive = 0;
  63815. windows.removeValue (w);
  63816. if (windows.size() == 0)
  63817. deleteInstance();
  63818. }
  63819. Array <TopLevelWindow*> windows;
  63820. private:
  63821. TopLevelWindow* currentActive;
  63822. bool isWindowActive (TopLevelWindow* const tlw) const
  63823. {
  63824. return (tlw == currentActive
  63825. || tlw->isParentOf (currentActive)
  63826. || tlw->hasKeyboardFocus (true))
  63827. && tlw->isShowing();
  63828. }
  63829. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63830. };
  63831. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63832. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63833. {
  63834. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63835. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63836. }
  63837. TopLevelWindow::TopLevelWindow (const String& name,
  63838. const bool addToDesktop_)
  63839. : Component (name),
  63840. useDropShadow (true),
  63841. useNativeTitleBar (false),
  63842. windowIsActive_ (false)
  63843. {
  63844. setOpaque (true);
  63845. if (addToDesktop_)
  63846. Component::addToDesktop (getDesktopWindowStyleFlags());
  63847. else
  63848. setDropShadowEnabled (true);
  63849. setWantsKeyboardFocus (true);
  63850. setBroughtToFrontOnMouseClick (true);
  63851. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63852. }
  63853. TopLevelWindow::~TopLevelWindow()
  63854. {
  63855. shadower = 0;
  63856. TopLevelWindowManager::getInstance()->removeWindow (this);
  63857. }
  63858. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63859. {
  63860. if (hasKeyboardFocus (true))
  63861. TopLevelWindowManager::getInstance()->timerCallback();
  63862. else
  63863. TopLevelWindowManager::getInstance()->startTimer (10);
  63864. }
  63865. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63866. {
  63867. if (windowIsActive_ != isNowActive)
  63868. {
  63869. windowIsActive_ = isNowActive;
  63870. activeWindowStatusChanged();
  63871. }
  63872. }
  63873. void TopLevelWindow::activeWindowStatusChanged()
  63874. {
  63875. }
  63876. void TopLevelWindow::visibilityChanged()
  63877. {
  63878. if (isShowing()
  63879. && (getPeer()->getStyleFlags() & (ComponentPeer::windowIsTemporary
  63880. | ComponentPeer::windowIgnoresKeyPresses)) == 0)
  63881. {
  63882. toFront (true);
  63883. }
  63884. }
  63885. void TopLevelWindow::parentHierarchyChanged()
  63886. {
  63887. setDropShadowEnabled (useDropShadow);
  63888. }
  63889. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63890. {
  63891. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63892. if (useDropShadow)
  63893. styleFlags |= ComponentPeer::windowHasDropShadow;
  63894. if (useNativeTitleBar)
  63895. styleFlags |= ComponentPeer::windowHasTitleBar;
  63896. return styleFlags;
  63897. }
  63898. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63899. {
  63900. useDropShadow = useShadow;
  63901. if (isOnDesktop())
  63902. {
  63903. shadower = 0;
  63904. Component::addToDesktop (getDesktopWindowStyleFlags());
  63905. }
  63906. else
  63907. {
  63908. if (useShadow && isOpaque())
  63909. {
  63910. if (shadower == 0)
  63911. {
  63912. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63913. if (shadower != 0)
  63914. shadower->setOwner (this);
  63915. }
  63916. }
  63917. else
  63918. {
  63919. shadower = 0;
  63920. }
  63921. }
  63922. }
  63923. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63924. {
  63925. if (useNativeTitleBar != useNativeTitleBar_)
  63926. {
  63927. useNativeTitleBar = useNativeTitleBar_;
  63928. recreateDesktopWindow();
  63929. sendLookAndFeelChange();
  63930. }
  63931. }
  63932. void TopLevelWindow::recreateDesktopWindow()
  63933. {
  63934. if (isOnDesktop())
  63935. {
  63936. Component::addToDesktop (getDesktopWindowStyleFlags());
  63937. toFront (true);
  63938. }
  63939. }
  63940. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63941. {
  63942. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63943. because this class needs to make sure its layout corresponds with settings like whether
  63944. it's got a native title bar or not.
  63945. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63946. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63947. method, then add or remove whatever flags are necessary from this value before returning it.
  63948. */
  63949. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63950. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63951. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63952. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63953. sendLookAndFeelChange();
  63954. }
  63955. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63956. {
  63957. if (c == 0)
  63958. c = TopLevelWindow::getActiveTopLevelWindow();
  63959. if (c == 0)
  63960. {
  63961. centreWithSize (width, height);
  63962. }
  63963. else
  63964. {
  63965. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63966. Rectangle<int> parentArea (c->getParentMonitorArea());
  63967. if (getParentComponent() != 0)
  63968. {
  63969. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63970. parentArea = getParentComponent()->getLocalBounds();
  63971. }
  63972. parentArea.reduce (12, 12);
  63973. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63974. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63975. width, height);
  63976. }
  63977. }
  63978. int TopLevelWindow::getNumTopLevelWindows() throw()
  63979. {
  63980. return TopLevelWindowManager::getInstance()->windows.size();
  63981. }
  63982. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63983. {
  63984. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63985. }
  63986. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63987. {
  63988. TopLevelWindow* best = 0;
  63989. int bestNumTWLParents = -1;
  63990. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63991. {
  63992. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63993. if (tlw->isActiveWindow())
  63994. {
  63995. int numTWLParents = 0;
  63996. const Component* c = tlw->getParentComponent();
  63997. while (c != 0)
  63998. {
  63999. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64000. ++numTWLParents;
  64001. c = c->getParentComponent();
  64002. }
  64003. if (bestNumTWLParents < numTWLParents)
  64004. {
  64005. best = tlw;
  64006. bestNumTWLParents = numTWLParents;
  64007. }
  64008. }
  64009. }
  64010. return best;
  64011. }
  64012. END_JUCE_NAMESPACE
  64013. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64014. /*** Start of inlined file: juce_MarkerList.cpp ***/
  64015. BEGIN_JUCE_NAMESPACE
  64016. MarkerList::MarkerList()
  64017. {
  64018. }
  64019. MarkerList::MarkerList (const MarkerList& other)
  64020. {
  64021. operator= (other);
  64022. }
  64023. MarkerList& MarkerList::operator= (const MarkerList& other)
  64024. {
  64025. if (other != *this)
  64026. {
  64027. markers.clear();
  64028. markers.addCopiesOf (other.markers);
  64029. markersHaveChanged();
  64030. }
  64031. return *this;
  64032. }
  64033. MarkerList::~MarkerList()
  64034. {
  64035. listeners.call (&MarkerList::Listener::markerListBeingDeleted, this);
  64036. }
  64037. bool MarkerList::operator== (const MarkerList& other) const throw()
  64038. {
  64039. if (other.markers.size() != markers.size())
  64040. return false;
  64041. for (int i = markers.size(); --i >= 0;)
  64042. {
  64043. const Marker* const m1 = markers.getUnchecked(i);
  64044. jassert (m1 != 0);
  64045. const Marker* const m2 = other.getMarker (m1->name);
  64046. if (m2 == 0 || *m1 != *m2)
  64047. return false;
  64048. }
  64049. return true;
  64050. }
  64051. bool MarkerList::operator!= (const MarkerList& other) const throw()
  64052. {
  64053. return ! operator== (other);
  64054. }
  64055. int MarkerList::getNumMarkers() const throw()
  64056. {
  64057. return markers.size();
  64058. }
  64059. const MarkerList::Marker* MarkerList::getMarker (const int index) const throw()
  64060. {
  64061. return markers [index];
  64062. }
  64063. const MarkerList::Marker* MarkerList::getMarker (const String& name) const throw()
  64064. {
  64065. for (int i = 0; i < markers.size(); ++i)
  64066. {
  64067. const Marker* const m = markers.getUnchecked(i);
  64068. if (m->name == name)
  64069. return m;
  64070. }
  64071. return 0;
  64072. }
  64073. void MarkerList::setMarker (const String& name, const RelativeCoordinate& position)
  64074. {
  64075. Marker* const m = const_cast <Marker*> (getMarker (name));
  64076. if (m != 0)
  64077. {
  64078. if (m->position != position)
  64079. {
  64080. m->position = position;
  64081. markersHaveChanged();
  64082. }
  64083. return;
  64084. }
  64085. markers.add (new Marker (name, position));
  64086. markersHaveChanged();
  64087. }
  64088. void MarkerList::removeMarker (const int index)
  64089. {
  64090. if (isPositiveAndBelow (index, markers.size()))
  64091. {
  64092. markers.remove (index);
  64093. markersHaveChanged();
  64094. }
  64095. }
  64096. void MarkerList::removeMarker (const String& name)
  64097. {
  64098. for (int i = 0; i < markers.size(); ++i)
  64099. {
  64100. const Marker* const m = markers.getUnchecked(i);
  64101. if (m->name == name)
  64102. {
  64103. markers.remove (i);
  64104. markersHaveChanged();
  64105. }
  64106. }
  64107. }
  64108. void MarkerList::markersHaveChanged()
  64109. {
  64110. listeners.call (&MarkerList::Listener::markersChanged, this);
  64111. }
  64112. void MarkerList::Listener::markerListBeingDeleted (MarkerList*)
  64113. {
  64114. }
  64115. void MarkerList::addListener (Listener* listener)
  64116. {
  64117. listeners.add (listener);
  64118. }
  64119. void MarkerList::removeListener (Listener* listener)
  64120. {
  64121. listeners.remove (listener);
  64122. }
  64123. MarkerList::Marker::Marker (const Marker& other)
  64124. : name (other.name), position (other.position)
  64125. {
  64126. }
  64127. MarkerList::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  64128. : name (name_), position (position_)
  64129. {
  64130. }
  64131. bool MarkerList::Marker::operator== (const Marker& other) const throw()
  64132. {
  64133. return name == other.name && position == other.position;
  64134. }
  64135. bool MarkerList::Marker::operator!= (const Marker& other) const throw()
  64136. {
  64137. return ! operator== (other);
  64138. }
  64139. const Identifier MarkerList::ValueTreeWrapper::markerTag ("Marker");
  64140. const Identifier MarkerList::ValueTreeWrapper::nameProperty ("name");
  64141. const Identifier MarkerList::ValueTreeWrapper::posProperty ("position");
  64142. MarkerList::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  64143. : state (state_)
  64144. {
  64145. }
  64146. int MarkerList::ValueTreeWrapper::getNumMarkers() const
  64147. {
  64148. return state.getNumChildren();
  64149. }
  64150. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (int index) const
  64151. {
  64152. return state.getChild (index);
  64153. }
  64154. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (const String& name) const
  64155. {
  64156. return state.getChildWithProperty (nameProperty, name);
  64157. }
  64158. bool MarkerList::ValueTreeWrapper::containsMarker (const ValueTree& marker) const
  64159. {
  64160. return marker.isAChildOf (state);
  64161. }
  64162. const MarkerList::Marker MarkerList::ValueTreeWrapper::getMarker (const ValueTree& marker) const
  64163. {
  64164. jassert (containsMarker (marker));
  64165. return MarkerList::Marker (marker [nameProperty], RelativeCoordinate (marker [posProperty].toString()));
  64166. }
  64167. void MarkerList::ValueTreeWrapper::setMarker (const MarkerList::Marker& m, UndoManager* undoManager)
  64168. {
  64169. ValueTree marker (state.getChildWithProperty (nameProperty, m.name));
  64170. if (marker.isValid())
  64171. {
  64172. marker.setProperty (posProperty, m.position.toString(), undoManager);
  64173. }
  64174. else
  64175. {
  64176. marker = ValueTree (markerTag);
  64177. marker.setProperty (nameProperty, m.name, 0);
  64178. marker.setProperty (posProperty, m.position.toString(), 0);
  64179. state.addChild (marker, -1, undoManager);
  64180. }
  64181. }
  64182. void MarkerList::ValueTreeWrapper::removeMarker (const ValueTree& marker, UndoManager* undoManager)
  64183. {
  64184. state.removeChild (marker, undoManager);
  64185. }
  64186. double MarkerList::getMarkerPosition (const Marker& marker, Component* parentComponent) const
  64187. {
  64188. if (parentComponent != 0)
  64189. {
  64190. RelativeCoordinatePositionerBase::ComponentScope scope (*parentComponent);
  64191. return marker.position.resolve (&scope);
  64192. }
  64193. else
  64194. {
  64195. return marker.position.resolve (0);
  64196. }
  64197. }
  64198. void MarkerList::ValueTreeWrapper::applyTo (MarkerList& markerList)
  64199. {
  64200. const int numMarkers = getNumMarkers();
  64201. StringArray updatedMarkers;
  64202. int i;
  64203. for (i = 0; i < numMarkers; ++i)
  64204. {
  64205. const ValueTree marker (state.getChild (i));
  64206. const String name (marker [nameProperty].toString());
  64207. markerList.setMarker (name, RelativeCoordinate (marker [posProperty].toString()));
  64208. updatedMarkers.add (name);
  64209. }
  64210. for (i = markerList.getNumMarkers(); --i >= 0;)
  64211. if (! updatedMarkers.contains (markerList.getMarker (i)->name))
  64212. markerList.removeMarker (i);
  64213. }
  64214. void MarkerList::ValueTreeWrapper::readFrom (const MarkerList& markerList, UndoManager* undoManager)
  64215. {
  64216. state.removeAllChildren (undoManager);
  64217. for (int i = 0; i < markerList.getNumMarkers(); ++i)
  64218. setMarker (*markerList.getMarker(i), undoManager);
  64219. }
  64220. END_JUCE_NAMESPACE
  64221. /*** End of inlined file: juce_MarkerList.cpp ***/
  64222. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64223. BEGIN_JUCE_NAMESPACE
  64224. const String RelativeCoordinate::Strings::parent ("parent");
  64225. const String RelativeCoordinate::Strings::left ("left");
  64226. const String RelativeCoordinate::Strings::right ("right");
  64227. const String RelativeCoordinate::Strings::top ("top");
  64228. const String RelativeCoordinate::Strings::bottom ("bottom");
  64229. const String RelativeCoordinate::Strings::x ("x");
  64230. const String RelativeCoordinate::Strings::y ("y");
  64231. const String RelativeCoordinate::Strings::width ("width");
  64232. const String RelativeCoordinate::Strings::height ("height");
  64233. RelativeCoordinate::StandardStrings::Type RelativeCoordinate::StandardStrings::getTypeOf (const String& s) throw()
  64234. {
  64235. if (s == Strings::left) return left;
  64236. if (s == Strings::right) return right;
  64237. if (s == Strings::top) return top;
  64238. if (s == Strings::bottom) return bottom;
  64239. if (s == Strings::x) return x;
  64240. if (s == Strings::y) return y;
  64241. if (s == Strings::width) return width;
  64242. if (s == Strings::height) return height;
  64243. if (s == Strings::parent) return parent;
  64244. return unknown;
  64245. }
  64246. RelativeCoordinate::RelativeCoordinate()
  64247. {
  64248. }
  64249. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64250. : term (term_)
  64251. {
  64252. }
  64253. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64254. : term (other.term)
  64255. {
  64256. }
  64257. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64258. {
  64259. term = other.term;
  64260. return *this;
  64261. }
  64262. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64263. : term (absoluteDistanceFromOrigin)
  64264. {
  64265. }
  64266. RelativeCoordinate::RelativeCoordinate (const String& s)
  64267. {
  64268. try
  64269. {
  64270. term = Expression (s);
  64271. }
  64272. catch (...)
  64273. {}
  64274. }
  64275. RelativeCoordinate::~RelativeCoordinate()
  64276. {
  64277. }
  64278. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64279. {
  64280. return term.toString() == other.term.toString();
  64281. }
  64282. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64283. {
  64284. return ! operator== (other);
  64285. }
  64286. double RelativeCoordinate::resolve (const Expression::Scope* scope) const
  64287. {
  64288. try
  64289. {
  64290. if (scope != 0)
  64291. return term.evaluate (*scope);
  64292. else
  64293. return term.evaluate();
  64294. }
  64295. catch (...)
  64296. {}
  64297. return 0.0;
  64298. }
  64299. bool RelativeCoordinate::isRecursive (const Expression::Scope* scope) const
  64300. {
  64301. try
  64302. {
  64303. if (scope != 0)
  64304. term.evaluate (*scope);
  64305. else
  64306. term.evaluate();
  64307. }
  64308. catch (...)
  64309. {
  64310. return true;
  64311. }
  64312. return false;
  64313. }
  64314. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::Scope* scope)
  64315. {
  64316. try
  64317. {
  64318. if (scope != 0)
  64319. {
  64320. term = term.adjustedToGiveNewResult (newPos, *scope);
  64321. }
  64322. else
  64323. {
  64324. Expression::Scope defaultScope;
  64325. term = term.adjustedToGiveNewResult (newPos, defaultScope);
  64326. }
  64327. }
  64328. catch (...)
  64329. {}
  64330. }
  64331. bool RelativeCoordinate::isDynamic() const
  64332. {
  64333. return term.usesAnySymbols();
  64334. }
  64335. const String RelativeCoordinate::toString() const
  64336. {
  64337. return term.toString();
  64338. }
  64339. END_JUCE_NAMESPACE
  64340. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64341. /*** Start of inlined file: juce_RelativePoint.cpp ***/
  64342. BEGIN_JUCE_NAMESPACE
  64343. namespace RelativePointHelpers
  64344. {
  64345. inline void skipComma (String::CharPointerType& s)
  64346. {
  64347. s = s.findEndOfWhitespace();
  64348. if (*s == ',')
  64349. ++s;
  64350. }
  64351. }
  64352. RelativePoint::RelativePoint()
  64353. {
  64354. }
  64355. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64356. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64357. {
  64358. }
  64359. RelativePoint::RelativePoint (const float x_, const float y_)
  64360. : x (x_), y (y_)
  64361. {
  64362. }
  64363. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64364. : x (x_), y (y_)
  64365. {
  64366. }
  64367. RelativePoint::RelativePoint (const String& s)
  64368. {
  64369. String::CharPointerType text (s.getCharPointer());
  64370. x = RelativeCoordinate (Expression::parse (text));
  64371. RelativePointHelpers::skipComma (text);
  64372. y = RelativeCoordinate (Expression::parse (text));
  64373. }
  64374. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64375. {
  64376. return x == other.x && y == other.y;
  64377. }
  64378. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64379. {
  64380. return ! operator== (other);
  64381. }
  64382. const Point<float> RelativePoint::resolve (const Expression::Scope* scope) const
  64383. {
  64384. return Point<float> ((float) x.resolve (scope),
  64385. (float) y.resolve (scope));
  64386. }
  64387. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::Scope* scope)
  64388. {
  64389. x.moveToAbsolute (newPos.getX(), scope);
  64390. y.moveToAbsolute (newPos.getY(), scope);
  64391. }
  64392. const String RelativePoint::toString() const
  64393. {
  64394. return x.toString() + ", " + y.toString();
  64395. }
  64396. bool RelativePoint::isDynamic() const
  64397. {
  64398. return x.isDynamic() || y.isDynamic();
  64399. }
  64400. END_JUCE_NAMESPACE
  64401. /*** End of inlined file: juce_RelativePoint.cpp ***/
  64402. /*** Start of inlined file: juce_RelativeRectangle.cpp ***/
  64403. BEGIN_JUCE_NAMESPACE
  64404. namespace RelativeRectangleHelpers
  64405. {
  64406. inline void skipComma (String::CharPointerType& s)
  64407. {
  64408. s = s.findEndOfWhitespace();
  64409. if (*s == ',')
  64410. ++s;
  64411. }
  64412. bool dependsOnSymbolsOtherThanThis (const Expression& e)
  64413. {
  64414. if (e.getType() == Expression::operatorType && e.getSymbolOrFunction() == ".")
  64415. return true;
  64416. if (e.getType() == Expression::symbolType)
  64417. {
  64418. switch (RelativeCoordinate::StandardStrings::getTypeOf (e.getSymbolOrFunction()))
  64419. {
  64420. case RelativeCoordinate::StandardStrings::x:
  64421. case RelativeCoordinate::StandardStrings::y:
  64422. case RelativeCoordinate::StandardStrings::left:
  64423. case RelativeCoordinate::StandardStrings::right:
  64424. case RelativeCoordinate::StandardStrings::top:
  64425. case RelativeCoordinate::StandardStrings::bottom: return false;
  64426. default: break;
  64427. }
  64428. return true;
  64429. }
  64430. else
  64431. {
  64432. for (int i = e.getNumInputs(); --i >= 0;)
  64433. if (dependsOnSymbolsOtherThanThis (e.getInput(i)))
  64434. return true;
  64435. }
  64436. return false;
  64437. }
  64438. }
  64439. RelativeRectangle::RelativeRectangle()
  64440. {
  64441. }
  64442. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64443. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64444. : left (left_), right (right_), top (top_), bottom (bottom_)
  64445. {
  64446. }
  64447. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect)
  64448. : left (rect.getX()),
  64449. right (Expression::symbol (RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64450. top (rect.getY()),
  64451. bottom (Expression::symbol (RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64452. {
  64453. }
  64454. RelativeRectangle::RelativeRectangle (const String& s)
  64455. {
  64456. String::CharPointerType text (s.getCharPointer());
  64457. left = RelativeCoordinate (Expression::parse (text));
  64458. RelativeRectangleHelpers::skipComma (text);
  64459. top = RelativeCoordinate (Expression::parse (text));
  64460. RelativeRectangleHelpers::skipComma (text);
  64461. right = RelativeCoordinate (Expression::parse (text));
  64462. RelativeRectangleHelpers::skipComma (text);
  64463. bottom = RelativeCoordinate (Expression::parse (text));
  64464. }
  64465. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64466. {
  64467. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64468. }
  64469. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64470. {
  64471. return ! operator== (other);
  64472. }
  64473. // An expression context that can evaluate expressions using "this"
  64474. class RelativeRectangleLocalScope : public Expression::Scope
  64475. {
  64476. public:
  64477. RelativeRectangleLocalScope (const RelativeRectangle& rect_) : rect (rect_) {}
  64478. const Expression getSymbolValue (const String& symbol) const
  64479. {
  64480. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  64481. {
  64482. case RelativeCoordinate::StandardStrings::x:
  64483. case RelativeCoordinate::StandardStrings::left: return rect.left.getExpression();
  64484. case RelativeCoordinate::StandardStrings::y:
  64485. case RelativeCoordinate::StandardStrings::top: return rect.top.getExpression();
  64486. case RelativeCoordinate::StandardStrings::right: return rect.right.getExpression();
  64487. case RelativeCoordinate::StandardStrings::bottom: return rect.bottom.getExpression();
  64488. default: break;
  64489. }
  64490. return Expression::Scope::getSymbolValue (symbol);
  64491. }
  64492. private:
  64493. const RelativeRectangle& rect;
  64494. JUCE_DECLARE_NON_COPYABLE (RelativeRectangleLocalScope);
  64495. };
  64496. const Rectangle<float> RelativeRectangle::resolve (const Expression::Scope* scope) const
  64497. {
  64498. if (scope == 0)
  64499. {
  64500. RelativeRectangleLocalScope scope (*this);
  64501. return resolve (&scope);
  64502. }
  64503. else
  64504. {
  64505. const double l = left.resolve (scope);
  64506. const double r = right.resolve (scope);
  64507. const double t = top.resolve (scope);
  64508. const double b = bottom.resolve (scope);
  64509. return Rectangle<float> ((float) l, (float) t, (float) jmax (0.0, r - l), (float) jmax (0.0, b - t));
  64510. }
  64511. }
  64512. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope)
  64513. {
  64514. left.moveToAbsolute (newPos.getX(), scope);
  64515. right.moveToAbsolute (newPos.getRight(), scope);
  64516. top.moveToAbsolute (newPos.getY(), scope);
  64517. bottom.moveToAbsolute (newPos.getBottom(), scope);
  64518. }
  64519. bool RelativeRectangle::isDynamic() const
  64520. {
  64521. using namespace RelativeRectangleHelpers;
  64522. return dependsOnSymbolsOtherThanThis (left.getExpression())
  64523. || dependsOnSymbolsOtherThanThis (right.getExpression())
  64524. || dependsOnSymbolsOtherThanThis (top.getExpression())
  64525. || dependsOnSymbolsOtherThanThis (bottom.getExpression());
  64526. }
  64527. const String RelativeRectangle::toString() const
  64528. {
  64529. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64530. }
  64531. void RelativeRectangle::renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope)
  64532. {
  64533. left = left.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64534. right = right.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64535. top = top.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64536. bottom = bottom.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64537. }
  64538. class RelativeRectangleComponentPositioner : public RelativeCoordinatePositionerBase
  64539. {
  64540. public:
  64541. RelativeRectangleComponentPositioner (Component& component_, const RelativeRectangle& rectangle_)
  64542. : RelativeCoordinatePositionerBase (component_),
  64543. rectangle (rectangle_)
  64544. {
  64545. }
  64546. bool registerCoordinates()
  64547. {
  64548. bool ok = addCoordinate (rectangle.left);
  64549. ok = addCoordinate (rectangle.right) && ok;
  64550. ok = addCoordinate (rectangle.top) && ok;
  64551. ok = addCoordinate (rectangle.bottom) && ok;
  64552. return ok;
  64553. }
  64554. bool isUsingRectangle (const RelativeRectangle& other) const throw()
  64555. {
  64556. return rectangle == other;
  64557. }
  64558. void applyToComponentBounds()
  64559. {
  64560. for (int i = 4; --i >= 0;)
  64561. {
  64562. ComponentScope scope (getComponent());
  64563. const Rectangle<int> newBounds (rectangle.resolve (&scope).getSmallestIntegerContainer());
  64564. if (newBounds == getComponent().getBounds())
  64565. return;
  64566. getComponent().setBounds (newBounds);
  64567. }
  64568. jassertfalse; // must be a recursive reference!
  64569. }
  64570. void applyNewBounds (const Rectangle<int>& newBounds)
  64571. {
  64572. if (newBounds != getComponent().getBounds())
  64573. {
  64574. ComponentScope scope (getComponent());
  64575. rectangle.moveToAbsolute (newBounds.toFloat(), &scope);
  64576. applyToComponentBounds();
  64577. }
  64578. }
  64579. private:
  64580. RelativeRectangle rectangle;
  64581. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeRectangleComponentPositioner);
  64582. };
  64583. void RelativeRectangle::applyToComponent (Component& component) const
  64584. {
  64585. if (isDynamic())
  64586. {
  64587. RelativeRectangleComponentPositioner* current = dynamic_cast <RelativeRectangleComponentPositioner*> (component.getPositioner());
  64588. if (current == 0 || ! current->isUsingRectangle (*this))
  64589. {
  64590. RelativeRectangleComponentPositioner* p = new RelativeRectangleComponentPositioner (component, *this);
  64591. component.setPositioner (p);
  64592. p->apply();
  64593. }
  64594. }
  64595. else
  64596. {
  64597. component.setPositioner (0);
  64598. component.setBounds (resolve (0).getSmallestIntegerContainer());
  64599. }
  64600. }
  64601. END_JUCE_NAMESPACE
  64602. /*** End of inlined file: juce_RelativeRectangle.cpp ***/
  64603. /*** Start of inlined file: juce_RelativePointPath.cpp ***/
  64604. BEGIN_JUCE_NAMESPACE
  64605. RelativePointPath::RelativePointPath()
  64606. : usesNonZeroWinding (true),
  64607. containsDynamicPoints (false)
  64608. {
  64609. }
  64610. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64611. : usesNonZeroWinding (true),
  64612. containsDynamicPoints (false)
  64613. {
  64614. for (int i = 0; i < other.elements.size(); ++i)
  64615. elements.add (other.elements.getUnchecked(i)->clone());
  64616. }
  64617. RelativePointPath::RelativePointPath (const Path& path)
  64618. : usesNonZeroWinding (path.isUsingNonZeroWinding()),
  64619. containsDynamicPoints (false)
  64620. {
  64621. for (Path::Iterator i (path); i.next();)
  64622. {
  64623. switch (i.elementType)
  64624. {
  64625. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64626. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64627. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64628. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64629. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64630. default: jassertfalse; break;
  64631. }
  64632. }
  64633. }
  64634. RelativePointPath::~RelativePointPath()
  64635. {
  64636. }
  64637. bool RelativePointPath::operator== (const RelativePointPath& other) const throw()
  64638. {
  64639. if (elements.size() != other.elements.size()
  64640. || usesNonZeroWinding != other.usesNonZeroWinding
  64641. || containsDynamicPoints != other.containsDynamicPoints)
  64642. return false;
  64643. for (int i = 0; i < elements.size(); ++i)
  64644. {
  64645. ElementBase* const e1 = elements.getUnchecked(i);
  64646. ElementBase* const e2 = other.elements.getUnchecked(i);
  64647. if (e1->type != e2->type)
  64648. return false;
  64649. int numPoints1, numPoints2;
  64650. const RelativePoint* const points1 = e1->getControlPoints (numPoints1);
  64651. const RelativePoint* const points2 = e2->getControlPoints (numPoints2);
  64652. jassert (numPoints1 == numPoints2);
  64653. for (int j = numPoints1; --j >= 0;)
  64654. if (points1[j] != points2[j])
  64655. return false;
  64656. }
  64657. return true;
  64658. }
  64659. bool RelativePointPath::operator!= (const RelativePointPath& other) const throw()
  64660. {
  64661. return ! operator== (other);
  64662. }
  64663. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64664. {
  64665. elements.swapWithArray (other.elements);
  64666. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64667. swapVariables (containsDynamicPoints, other.containsDynamicPoints);
  64668. }
  64669. void RelativePointPath::createPath (Path& path, Expression::Scope* scope) const
  64670. {
  64671. for (int i = 0; i < elements.size(); ++i)
  64672. elements.getUnchecked(i)->addToPath (path, scope);
  64673. }
  64674. bool RelativePointPath::containsAnyDynamicPoints() const
  64675. {
  64676. return containsDynamicPoints;
  64677. }
  64678. void RelativePointPath::addElement (ElementBase* newElement)
  64679. {
  64680. if (newElement != 0)
  64681. {
  64682. elements.add (newElement);
  64683. containsDynamicPoints = containsDynamicPoints || newElement->isDynamic();
  64684. }
  64685. }
  64686. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64687. {
  64688. }
  64689. bool RelativePointPath::ElementBase::isDynamic()
  64690. {
  64691. int numPoints;
  64692. const RelativePoint* const points = getControlPoints (numPoints);
  64693. for (int i = numPoints; --i >= 0;)
  64694. if (points[i].isDynamic())
  64695. return true;
  64696. return false;
  64697. }
  64698. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64699. : ElementBase (startSubPathElement), startPos (pos)
  64700. {
  64701. }
  64702. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64703. {
  64704. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64705. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64706. return v;
  64707. }
  64708. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::Scope* scope) const
  64709. {
  64710. path.startNewSubPath (startPos.resolve (scope));
  64711. }
  64712. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64713. {
  64714. numPoints = 1;
  64715. return &startPos;
  64716. }
  64717. RelativePointPath::ElementBase* RelativePointPath::StartSubPath::clone() const
  64718. {
  64719. return new StartSubPath (startPos);
  64720. }
  64721. RelativePointPath::CloseSubPath::CloseSubPath()
  64722. : ElementBase (closeSubPathElement)
  64723. {
  64724. }
  64725. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64726. {
  64727. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64728. }
  64729. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::Scope*) const
  64730. {
  64731. path.closeSubPath();
  64732. }
  64733. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64734. {
  64735. numPoints = 0;
  64736. return 0;
  64737. }
  64738. RelativePointPath::ElementBase* RelativePointPath::CloseSubPath::clone() const
  64739. {
  64740. return new CloseSubPath();
  64741. }
  64742. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64743. : ElementBase (lineToElement), endPoint (endPoint_)
  64744. {
  64745. }
  64746. const ValueTree RelativePointPath::LineTo::createTree() const
  64747. {
  64748. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64749. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64750. return v;
  64751. }
  64752. void RelativePointPath::LineTo::addToPath (Path& path, Expression::Scope* scope) const
  64753. {
  64754. path.lineTo (endPoint.resolve (scope));
  64755. }
  64756. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64757. {
  64758. numPoints = 1;
  64759. return &endPoint;
  64760. }
  64761. RelativePointPath::ElementBase* RelativePointPath::LineTo::clone() const
  64762. {
  64763. return new LineTo (endPoint);
  64764. }
  64765. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64766. : ElementBase (quadraticToElement)
  64767. {
  64768. controlPoints[0] = controlPoint;
  64769. controlPoints[1] = endPoint;
  64770. }
  64771. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64772. {
  64773. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64774. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64775. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64776. return v;
  64777. }
  64778. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::Scope* scope) const
  64779. {
  64780. path.quadraticTo (controlPoints[0].resolve (scope),
  64781. controlPoints[1].resolve (scope));
  64782. }
  64783. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64784. {
  64785. numPoints = 2;
  64786. return controlPoints;
  64787. }
  64788. RelativePointPath::ElementBase* RelativePointPath::QuadraticTo::clone() const
  64789. {
  64790. return new QuadraticTo (controlPoints[0], controlPoints[1]);
  64791. }
  64792. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64793. : ElementBase (cubicToElement)
  64794. {
  64795. controlPoints[0] = controlPoint1;
  64796. controlPoints[1] = controlPoint2;
  64797. controlPoints[2] = endPoint;
  64798. }
  64799. const ValueTree RelativePointPath::CubicTo::createTree() const
  64800. {
  64801. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64802. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64803. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64804. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64805. return v;
  64806. }
  64807. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::Scope* scope) const
  64808. {
  64809. path.cubicTo (controlPoints[0].resolve (scope),
  64810. controlPoints[1].resolve (scope),
  64811. controlPoints[2].resolve (scope));
  64812. }
  64813. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64814. {
  64815. numPoints = 3;
  64816. return controlPoints;
  64817. }
  64818. RelativePointPath::ElementBase* RelativePointPath::CubicTo::clone() const
  64819. {
  64820. return new CubicTo (controlPoints[0], controlPoints[1], controlPoints[2]);
  64821. }
  64822. END_JUCE_NAMESPACE
  64823. /*** End of inlined file: juce_RelativePointPath.cpp ***/
  64824. /*** Start of inlined file: juce_RelativeParallelogram.cpp ***/
  64825. BEGIN_JUCE_NAMESPACE
  64826. RelativeParallelogram::RelativeParallelogram()
  64827. {
  64828. }
  64829. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64830. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64831. {
  64832. }
  64833. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64834. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64835. {
  64836. }
  64837. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64838. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64839. {
  64840. }
  64841. RelativeParallelogram::~RelativeParallelogram()
  64842. {
  64843. }
  64844. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::Scope* const scope) const
  64845. {
  64846. points[0] = topLeft.resolve (scope);
  64847. points[1] = topRight.resolve (scope);
  64848. points[2] = bottomLeft.resolve (scope);
  64849. }
  64850. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::Scope* const scope) const
  64851. {
  64852. resolveThreePoints (points, scope);
  64853. points[3] = points[1] + (points[2] - points[0]);
  64854. }
  64855. const Rectangle<float> RelativeParallelogram::getBounds (Expression::Scope* const scope) const
  64856. {
  64857. Point<float> points[4];
  64858. resolveFourCorners (points, scope);
  64859. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64860. }
  64861. void RelativeParallelogram::getPath (Path& path, Expression::Scope* const scope) const
  64862. {
  64863. Point<float> points[4];
  64864. resolveFourCorners (points, scope);
  64865. path.startNewSubPath (points[0]);
  64866. path.lineTo (points[1]);
  64867. path.lineTo (points[3]);
  64868. path.lineTo (points[2]);
  64869. path.closeSubPath();
  64870. }
  64871. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::Scope* const scope)
  64872. {
  64873. Point<float> corners[3];
  64874. resolveThreePoints (corners, scope);
  64875. const Line<float> top (corners[0], corners[1]);
  64876. const Line<float> left (corners[0], corners[2]);
  64877. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64878. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64879. topRight.moveToAbsolute (newTopRight, scope);
  64880. bottomLeft.moveToAbsolute (newBottomLeft, scope);
  64881. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64882. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64883. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64884. }
  64885. bool RelativeParallelogram::isDynamic() const
  64886. {
  64887. return topLeft.isDynamic() || topRight.isDynamic() || bottomLeft.isDynamic();
  64888. }
  64889. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64890. {
  64891. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64892. }
  64893. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64894. {
  64895. return ! operator== (other);
  64896. }
  64897. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64898. {
  64899. const Point<float> tr (corners[1] - corners[0]);
  64900. const Point<float> bl (corners[2] - corners[0]);
  64901. target -= corners[0];
  64902. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64903. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64904. }
  64905. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64906. {
  64907. return corners[0]
  64908. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64909. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64910. }
  64911. const Rectangle<float> RelativeParallelogram::getBoundingBox (const Point<float>* const p) throw()
  64912. {
  64913. const Point<float> points[] = { p[0], p[1], p[2], p[1] + (p[2] - p[0]) };
  64914. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64915. }
  64916. END_JUCE_NAMESPACE
  64917. /*** End of inlined file: juce_RelativeParallelogram.cpp ***/
  64918. /*** Start of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64919. BEGIN_JUCE_NAMESPACE
  64920. RelativeCoordinatePositionerBase::ComponentScope::ComponentScope (Component& component_)
  64921. : component (component_)
  64922. {
  64923. }
  64924. const Expression RelativeCoordinatePositionerBase::ComponentScope::getSymbolValue (const String& symbol) const
  64925. {
  64926. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  64927. {
  64928. case RelativeCoordinate::StandardStrings::x:
  64929. case RelativeCoordinate::StandardStrings::left: return Expression ((double) component.getX());
  64930. case RelativeCoordinate::StandardStrings::y:
  64931. case RelativeCoordinate::StandardStrings::top: return Expression ((double) component.getY());
  64932. case RelativeCoordinate::StandardStrings::width: return Expression ((double) component.getWidth());
  64933. case RelativeCoordinate::StandardStrings::height: return Expression ((double) component.getHeight());
  64934. case RelativeCoordinate::StandardStrings::right: return Expression ((double) component.getRight());
  64935. case RelativeCoordinate::StandardStrings::bottom: return Expression ((double) component.getBottom());
  64936. default: break;
  64937. }
  64938. MarkerList* list;
  64939. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64940. if (marker != 0)
  64941. return marker->position.getExpression();
  64942. return Expression::Scope::getSymbolValue (symbol);
  64943. }
  64944. void RelativeCoordinatePositionerBase::ComponentScope::visitRelativeScope (const String& scopeName, Visitor& visitor) const
  64945. {
  64946. Component* targetComp = 0;
  64947. if (scopeName == RelativeCoordinate::Strings::parent)
  64948. targetComp = component.getParentComponent();
  64949. else
  64950. targetComp = findSiblingComponent (scopeName);
  64951. if (targetComp != 0)
  64952. visitor.visit (ComponentScope (*targetComp));
  64953. else
  64954. Expression::Scope::visitRelativeScope (scopeName, visitor);
  64955. }
  64956. const String RelativeCoordinatePositionerBase::ComponentScope::getScopeUID() const
  64957. {
  64958. return String::toHexString ((int) (pointer_sized_int) (void*) &component);
  64959. }
  64960. Component* RelativeCoordinatePositionerBase::ComponentScope::findSiblingComponent (const String& componentID) const
  64961. {
  64962. Component* const parent = component.getParentComponent();
  64963. if (parent != 0)
  64964. {
  64965. for (int i = parent->getNumChildComponents(); --i >= 0;)
  64966. {
  64967. Component* const c = parent->getChildComponent(i);
  64968. if (c->getComponentID() == componentID)
  64969. return c;
  64970. }
  64971. }
  64972. return 0;
  64973. }
  64974. const MarkerList::Marker* RelativeCoordinatePositionerBase::ComponentScope::findMarker (const String& name, MarkerList*& list) const
  64975. {
  64976. const MarkerList::Marker* marker = 0;
  64977. Component* const parent = component.getParentComponent();
  64978. if (parent != 0)
  64979. {
  64980. list = parent->getMarkers (true);
  64981. if (list != 0)
  64982. marker = list->getMarker (name);
  64983. if (marker == 0)
  64984. {
  64985. list = parent->getMarkers (false);
  64986. if (list != 0)
  64987. marker = list->getMarker (name);
  64988. }
  64989. }
  64990. return marker;
  64991. }
  64992. class RelativeCoordinatePositionerBase::DependencyFinderScope : public ComponentScope
  64993. {
  64994. public:
  64995. DependencyFinderScope (Component& component_, RelativeCoordinatePositionerBase& positioner_, bool& ok_)
  64996. : ComponentScope (component_), positioner (positioner_), ok (ok_)
  64997. {
  64998. }
  64999. const Expression getSymbolValue (const String& symbol) const
  65000. {
  65001. if (symbol == RelativeCoordinate::Strings::left || symbol == RelativeCoordinate::Strings::x
  65002. || symbol == RelativeCoordinate::Strings::width || symbol == RelativeCoordinate::Strings::right
  65003. || symbol == RelativeCoordinate::Strings::top || symbol == RelativeCoordinate::Strings::y
  65004. || symbol == RelativeCoordinate::Strings::height || symbol == RelativeCoordinate::Strings::bottom)
  65005. {
  65006. positioner.registerComponentListener (component);
  65007. }
  65008. else
  65009. {
  65010. MarkerList* list;
  65011. const MarkerList::Marker* const marker = findMarker (symbol, list);
  65012. if (marker != 0)
  65013. {
  65014. positioner.registerMarkerListListener (list);
  65015. }
  65016. else
  65017. {
  65018. // The marker we want doesn't exist, so watch all lists in case they change and the marker appears later..
  65019. positioner.registerMarkerListListener (component.getMarkers (true));
  65020. positioner.registerMarkerListListener (component.getMarkers (false));
  65021. ok = false;
  65022. }
  65023. }
  65024. return ComponentScope::getSymbolValue (symbol);
  65025. }
  65026. void visitRelativeScope (const String& scopeName, Visitor& visitor) const
  65027. {
  65028. Component* targetComp = 0;
  65029. if (scopeName == RelativeCoordinate::Strings::parent)
  65030. targetComp = component.getParentComponent();
  65031. else
  65032. targetComp = findSiblingComponent (scopeName);
  65033. if (targetComp != 0)
  65034. {
  65035. visitor.visit (DependencyFinderScope (*targetComp, positioner, ok));
  65036. }
  65037. else
  65038. {
  65039. // The named component doesn't exist, so we'll watch the parent for changes in case it appears later..
  65040. Component* const parent = component.getParentComponent();
  65041. if (parent != 0)
  65042. positioner.registerComponentListener (*parent);
  65043. positioner.registerComponentListener (component);
  65044. ok = false;
  65045. }
  65046. }
  65047. private:
  65048. RelativeCoordinatePositionerBase& positioner;
  65049. bool& ok;
  65050. JUCE_DECLARE_NON_COPYABLE (DependencyFinderScope);
  65051. };
  65052. RelativeCoordinatePositionerBase::RelativeCoordinatePositionerBase (Component& component_)
  65053. : Component::Positioner (component_), registeredOk (false)
  65054. {
  65055. }
  65056. RelativeCoordinatePositionerBase::~RelativeCoordinatePositionerBase()
  65057. {
  65058. unregisterListeners();
  65059. }
  65060. void RelativeCoordinatePositionerBase::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  65061. {
  65062. apply();
  65063. }
  65064. void RelativeCoordinatePositionerBase::componentParentHierarchyChanged (Component&)
  65065. {
  65066. apply();
  65067. }
  65068. void RelativeCoordinatePositionerBase::componentChildrenChanged (Component& changed)
  65069. {
  65070. if (getComponent().getParentComponent() == &changed && ! registeredOk)
  65071. apply();
  65072. }
  65073. void RelativeCoordinatePositionerBase::componentBeingDeleted (Component& component)
  65074. {
  65075. jassert (sourceComponents.contains (&component));
  65076. sourceComponents.removeValue (&component);
  65077. registeredOk = false;
  65078. }
  65079. void RelativeCoordinatePositionerBase::markersChanged (MarkerList*)
  65080. {
  65081. apply();
  65082. }
  65083. void RelativeCoordinatePositionerBase::markerListBeingDeleted (MarkerList* markerList)
  65084. {
  65085. jassert (sourceMarkerLists.contains (markerList));
  65086. sourceMarkerLists.removeValue (markerList);
  65087. }
  65088. void RelativeCoordinatePositionerBase::apply()
  65089. {
  65090. if (! registeredOk)
  65091. {
  65092. unregisterListeners();
  65093. registeredOk = registerCoordinates();
  65094. }
  65095. applyToComponentBounds();
  65096. }
  65097. bool RelativeCoordinatePositionerBase::addCoordinate (const RelativeCoordinate& coord)
  65098. {
  65099. bool ok = true;
  65100. DependencyFinderScope finderScope (getComponent(), *this, ok);
  65101. coord.getExpression().evaluate (finderScope);
  65102. return ok;
  65103. }
  65104. bool RelativeCoordinatePositionerBase::addPoint (const RelativePoint& point)
  65105. {
  65106. const bool ok = addCoordinate (point.x);
  65107. return addCoordinate (point.y) && ok;
  65108. }
  65109. void RelativeCoordinatePositionerBase::registerComponentListener (Component& comp)
  65110. {
  65111. if (! sourceComponents.contains (&comp))
  65112. {
  65113. comp.addComponentListener (this);
  65114. sourceComponents.add (&comp);
  65115. }
  65116. }
  65117. void RelativeCoordinatePositionerBase::registerMarkerListListener (MarkerList* const list)
  65118. {
  65119. if (list != 0 && ! sourceMarkerLists.contains (list))
  65120. {
  65121. list->addListener (this);
  65122. sourceMarkerLists.add (list);
  65123. }
  65124. }
  65125. void RelativeCoordinatePositionerBase::unregisterListeners()
  65126. {
  65127. int i;
  65128. for (i = sourceComponents.size(); --i >= 0;)
  65129. sourceComponents.getUnchecked(i)->removeComponentListener (this);
  65130. for (i = sourceMarkerLists.size(); --i >= 0;)
  65131. sourceMarkerLists.getUnchecked(i)->removeListener (this);
  65132. sourceComponents.clear();
  65133. sourceMarkerLists.clear();
  65134. }
  65135. END_JUCE_NAMESPACE
  65136. /*** End of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  65137. #endif
  65138. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  65139. /*** Start of inlined file: juce_Colour.cpp ***/
  65140. BEGIN_JUCE_NAMESPACE
  65141. namespace ColourHelpers
  65142. {
  65143. uint8 floatAlphaToInt (const float alpha) throw()
  65144. {
  65145. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  65146. }
  65147. void convertHSBtoRGB (float h, float s, float v,
  65148. uint8& r, uint8& g, uint8& b) throw()
  65149. {
  65150. v = jlimit (0.0f, 1.0f, v);
  65151. v *= 255.0f;
  65152. const uint8 intV = (uint8) roundToInt (v);
  65153. if (s <= 0)
  65154. {
  65155. r = intV;
  65156. g = intV;
  65157. b = intV;
  65158. }
  65159. else
  65160. {
  65161. s = jmin (1.0f, s);
  65162. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  65163. const float f = h - std::floor (h);
  65164. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  65165. if (h < 1.0f)
  65166. {
  65167. r = intV;
  65168. g = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  65169. b = x;
  65170. }
  65171. else if (h < 2.0f)
  65172. {
  65173. r = (uint8) roundToInt (v * (1.0f - s * f));
  65174. g = intV;
  65175. b = x;
  65176. }
  65177. else if (h < 3.0f)
  65178. {
  65179. r = x;
  65180. g = intV;
  65181. b = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  65182. }
  65183. else if (h < 4.0f)
  65184. {
  65185. r = x;
  65186. g = (uint8) roundToInt (v * (1.0f - s * f));
  65187. b = intV;
  65188. }
  65189. else if (h < 5.0f)
  65190. {
  65191. r = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  65192. g = x;
  65193. b = intV;
  65194. }
  65195. else
  65196. {
  65197. r = intV;
  65198. g = x;
  65199. b = (uint8) roundToInt (v * (1.0f - s * f));
  65200. }
  65201. }
  65202. }
  65203. }
  65204. Colour::Colour() throw()
  65205. : argb (0)
  65206. {
  65207. }
  65208. Colour::Colour (const Colour& other) throw()
  65209. : argb (other.argb)
  65210. {
  65211. }
  65212. Colour& Colour::operator= (const Colour& other) throw()
  65213. {
  65214. argb = other.argb;
  65215. return *this;
  65216. }
  65217. bool Colour::operator== (const Colour& other) const throw()
  65218. {
  65219. return argb.getARGB() == other.argb.getARGB();
  65220. }
  65221. bool Colour::operator!= (const Colour& other) const throw()
  65222. {
  65223. return argb.getARGB() != other.argb.getARGB();
  65224. }
  65225. Colour::Colour (const uint32 argb_) throw()
  65226. : argb (argb_)
  65227. {
  65228. }
  65229. Colour::Colour (const uint8 red,
  65230. const uint8 green,
  65231. const uint8 blue) throw()
  65232. {
  65233. argb.setARGB (0xff, red, green, blue);
  65234. }
  65235. const Colour Colour::fromRGB (const uint8 red,
  65236. const uint8 green,
  65237. const uint8 blue) throw()
  65238. {
  65239. return Colour (red, green, blue);
  65240. }
  65241. Colour::Colour (const uint8 red,
  65242. const uint8 green,
  65243. const uint8 blue,
  65244. const uint8 alpha) throw()
  65245. {
  65246. argb.setARGB (alpha, red, green, blue);
  65247. }
  65248. const Colour Colour::fromRGBA (const uint8 red,
  65249. const uint8 green,
  65250. const uint8 blue,
  65251. const uint8 alpha) throw()
  65252. {
  65253. return Colour (red, green, blue, alpha);
  65254. }
  65255. Colour::Colour (const uint8 red,
  65256. const uint8 green,
  65257. const uint8 blue,
  65258. const float alpha) throw()
  65259. {
  65260. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  65261. }
  65262. const Colour Colour::fromRGBAFloat (const uint8 red,
  65263. const uint8 green,
  65264. const uint8 blue,
  65265. const float alpha) throw()
  65266. {
  65267. return Colour (red, green, blue, alpha);
  65268. }
  65269. Colour::Colour (const float hue,
  65270. const float saturation,
  65271. const float brightness,
  65272. const float alpha) throw()
  65273. {
  65274. uint8 r, g, b;
  65275. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65276. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  65277. }
  65278. const Colour Colour::fromHSV (const float hue,
  65279. const float saturation,
  65280. const float brightness,
  65281. const float alpha) throw()
  65282. {
  65283. return Colour (hue, saturation, brightness, alpha);
  65284. }
  65285. Colour::Colour (const float hue,
  65286. const float saturation,
  65287. const float brightness,
  65288. const uint8 alpha) throw()
  65289. {
  65290. uint8 r, g, b;
  65291. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65292. argb.setARGB (alpha, r, g, b);
  65293. }
  65294. Colour::~Colour() throw()
  65295. {
  65296. }
  65297. const PixelARGB Colour::getPixelARGB() const throw()
  65298. {
  65299. PixelARGB p (argb);
  65300. p.premultiply();
  65301. return p;
  65302. }
  65303. uint32 Colour::getARGB() const throw()
  65304. {
  65305. return argb.getARGB();
  65306. }
  65307. bool Colour::isTransparent() const throw()
  65308. {
  65309. return getAlpha() == 0;
  65310. }
  65311. bool Colour::isOpaque() const throw()
  65312. {
  65313. return getAlpha() == 0xff;
  65314. }
  65315. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  65316. {
  65317. PixelARGB newCol (argb);
  65318. newCol.setAlpha (newAlpha);
  65319. return Colour (newCol.getARGB());
  65320. }
  65321. const Colour Colour::withAlpha (const float newAlpha) const throw()
  65322. {
  65323. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  65324. PixelARGB newCol (argb);
  65325. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  65326. return Colour (newCol.getARGB());
  65327. }
  65328. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  65329. {
  65330. jassert (alphaMultiplier >= 0);
  65331. PixelARGB newCol (argb);
  65332. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  65333. return Colour (newCol.getARGB());
  65334. }
  65335. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65336. {
  65337. const int destAlpha = getAlpha();
  65338. if (destAlpha > 0)
  65339. {
  65340. const int invA = 0xff - (int) src.getAlpha();
  65341. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65342. if (resA > 0)
  65343. {
  65344. const int da = (invA * destAlpha) / resA;
  65345. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65346. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65347. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65348. (uint8) resA);
  65349. }
  65350. return *this;
  65351. }
  65352. else
  65353. {
  65354. return src;
  65355. }
  65356. }
  65357. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65358. {
  65359. if (proportionOfOther <= 0)
  65360. return *this;
  65361. if (proportionOfOther >= 1.0f)
  65362. return other;
  65363. PixelARGB c1 (getPixelARGB());
  65364. const PixelARGB c2 (other.getPixelARGB());
  65365. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65366. c1.unpremultiply();
  65367. return Colour (c1.getARGB());
  65368. }
  65369. float Colour::getFloatRed() const throw()
  65370. {
  65371. return getRed() / 255.0f;
  65372. }
  65373. float Colour::getFloatGreen() const throw()
  65374. {
  65375. return getGreen() / 255.0f;
  65376. }
  65377. float Colour::getFloatBlue() const throw()
  65378. {
  65379. return getBlue() / 255.0f;
  65380. }
  65381. float Colour::getFloatAlpha() const throw()
  65382. {
  65383. return getAlpha() / 255.0f;
  65384. }
  65385. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65386. {
  65387. const int r = getRed();
  65388. const int g = getGreen();
  65389. const int b = getBlue();
  65390. const int hi = jmax (r, g, b);
  65391. const int lo = jmin (r, g, b);
  65392. if (hi != 0)
  65393. {
  65394. s = (hi - lo) / (float) hi;
  65395. if (s > 0)
  65396. {
  65397. const float invDiff = 1.0f / (hi - lo);
  65398. const float red = (hi - r) * invDiff;
  65399. const float green = (hi - g) * invDiff;
  65400. const float blue = (hi - b) * invDiff;
  65401. if (r == hi)
  65402. h = blue - green;
  65403. else if (g == hi)
  65404. h = 2.0f + red - blue;
  65405. else
  65406. h = 4.0f + green - red;
  65407. h *= 1.0f / 6.0f;
  65408. if (h < 0)
  65409. ++h;
  65410. }
  65411. else
  65412. {
  65413. h = 0;
  65414. }
  65415. }
  65416. else
  65417. {
  65418. s = 0;
  65419. h = 0;
  65420. }
  65421. v = hi / 255.0f;
  65422. }
  65423. float Colour::getHue() const throw()
  65424. {
  65425. float h, s, b;
  65426. getHSB (h, s, b);
  65427. return h;
  65428. }
  65429. const Colour Colour::withHue (const float hue) const throw()
  65430. {
  65431. float h, s, b;
  65432. getHSB (h, s, b);
  65433. return Colour (hue, s, b, getAlpha());
  65434. }
  65435. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65436. {
  65437. float h, s, b;
  65438. getHSB (h, s, b);
  65439. return Colour (h + amountToRotate, s, b, getAlpha());
  65440. }
  65441. float Colour::getSaturation() const throw()
  65442. {
  65443. float h, s, b;
  65444. getHSB (h, s, b);
  65445. return s;
  65446. }
  65447. const Colour Colour::withSaturation (const float saturation) const throw()
  65448. {
  65449. float h, s, b;
  65450. getHSB (h, s, b);
  65451. return Colour (h, saturation, b, getAlpha());
  65452. }
  65453. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65454. {
  65455. float h, s, b;
  65456. getHSB (h, s, b);
  65457. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65458. }
  65459. float Colour::getBrightness() const throw()
  65460. {
  65461. float h, s, b;
  65462. getHSB (h, s, b);
  65463. return b;
  65464. }
  65465. const Colour Colour::withBrightness (const float brightness) const throw()
  65466. {
  65467. float h, s, b;
  65468. getHSB (h, s, b);
  65469. return Colour (h, s, brightness, getAlpha());
  65470. }
  65471. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65472. {
  65473. float h, s, b;
  65474. getHSB (h, s, b);
  65475. b *= amount;
  65476. if (b > 1.0f)
  65477. b = 1.0f;
  65478. return Colour (h, s, b, getAlpha());
  65479. }
  65480. const Colour Colour::brighter (float amount) const throw()
  65481. {
  65482. amount = 1.0f / (1.0f + amount);
  65483. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65484. (uint8) (255 - (amount * (255 - getGreen()))),
  65485. (uint8) (255 - (amount * (255 - getBlue()))),
  65486. getAlpha());
  65487. }
  65488. const Colour Colour::darker (float amount) const throw()
  65489. {
  65490. amount = 1.0f / (1.0f + amount);
  65491. return Colour ((uint8) (amount * getRed()),
  65492. (uint8) (amount * getGreen()),
  65493. (uint8) (amount * getBlue()),
  65494. getAlpha());
  65495. }
  65496. const Colour Colour::greyLevel (const float brightness) throw()
  65497. {
  65498. const uint8 level
  65499. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65500. return Colour (level, level, level);
  65501. }
  65502. const Colour Colour::contrasting (const float amount) const throw()
  65503. {
  65504. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65505. ? Colours::black
  65506. : Colours::white).withAlpha (amount));
  65507. }
  65508. const Colour Colour::contrasting (const Colour& colour1,
  65509. const Colour& colour2) throw()
  65510. {
  65511. const float b1 = colour1.getBrightness();
  65512. const float b2 = colour2.getBrightness();
  65513. float best = 0.0f;
  65514. float bestDist = 0.0f;
  65515. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65516. {
  65517. const float d1 = std::abs (i - b1);
  65518. const float d2 = std::abs (i - b2);
  65519. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65520. if (dist > bestDist)
  65521. {
  65522. best = i;
  65523. bestDist = dist;
  65524. }
  65525. }
  65526. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65527. .withBrightness (best);
  65528. }
  65529. const String Colour::toString() const
  65530. {
  65531. return String::toHexString ((int) argb.getARGB());
  65532. }
  65533. const Colour Colour::fromString (const String& encodedColourString)
  65534. {
  65535. return Colour ((uint32) encodedColourString.getHexValue32());
  65536. }
  65537. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65538. {
  65539. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65540. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65541. .toUpperCase();
  65542. }
  65543. END_JUCE_NAMESPACE
  65544. /*** End of inlined file: juce_Colour.cpp ***/
  65545. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65546. BEGIN_JUCE_NAMESPACE
  65547. ColourGradient::ColourGradient() throw()
  65548. {
  65549. #if JUCE_DEBUG
  65550. point1.setX (987654.0f);
  65551. #endif
  65552. }
  65553. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65554. const Colour& colour2, const float x2_, const float y2_,
  65555. const bool isRadial_)
  65556. : point1 (x1_, y1_),
  65557. point2 (x2_, y2_),
  65558. isRadial (isRadial_)
  65559. {
  65560. colours.add (ColourPoint (0.0, colour1));
  65561. colours.add (ColourPoint (1.0, colour2));
  65562. }
  65563. ColourGradient::~ColourGradient()
  65564. {
  65565. }
  65566. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65567. {
  65568. return point1 == other.point1 && point2 == other.point2
  65569. && isRadial == other.isRadial
  65570. && colours == other.colours;
  65571. }
  65572. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65573. {
  65574. return ! operator== (other);
  65575. }
  65576. void ColourGradient::clearColours()
  65577. {
  65578. colours.clear();
  65579. }
  65580. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65581. {
  65582. // must be within the two end-points
  65583. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65584. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65585. int i;
  65586. for (i = 0; i < colours.size(); ++i)
  65587. if (colours.getReference(i).position > pos)
  65588. break;
  65589. colours.insert (i, ColourPoint (pos, colour));
  65590. return i;
  65591. }
  65592. void ColourGradient::removeColour (int index)
  65593. {
  65594. jassert (index > 0 && index < colours.size() - 1);
  65595. colours.remove (index);
  65596. }
  65597. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65598. {
  65599. for (int i = 0; i < colours.size(); ++i)
  65600. {
  65601. Colour& c = colours.getReference(i).colour;
  65602. c = c.withMultipliedAlpha (multiplier);
  65603. }
  65604. }
  65605. int ColourGradient::getNumColours() const throw()
  65606. {
  65607. return colours.size();
  65608. }
  65609. double ColourGradient::getColourPosition (const int index) const throw()
  65610. {
  65611. if (isPositiveAndBelow (index, colours.size()))
  65612. return colours.getReference (index).position;
  65613. return 0;
  65614. }
  65615. const Colour ColourGradient::getColour (const int index) const throw()
  65616. {
  65617. if (isPositiveAndBelow (index, colours.size()))
  65618. return colours.getReference (index).colour;
  65619. return Colour();
  65620. }
  65621. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65622. {
  65623. if (isPositiveAndBelow (index, colours.size()))
  65624. colours.getReference (index).colour = newColour;
  65625. }
  65626. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65627. {
  65628. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65629. if (position <= 0 || colours.size() <= 1)
  65630. return colours.getReference(0).colour;
  65631. int i = colours.size() - 1;
  65632. while (position < colours.getReference(i).position)
  65633. --i;
  65634. const ColourPoint& p1 = colours.getReference (i);
  65635. if (i >= colours.size() - 1)
  65636. return p1.colour;
  65637. const ColourPoint& p2 = colours.getReference (i + 1);
  65638. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65639. }
  65640. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65641. {
  65642. #if JUCE_DEBUG
  65643. // trying to use the object without setting its co-ordinates? Have a careful read of
  65644. // the comments for the constructors.
  65645. jassert (point1.getX() != 987654.0f);
  65646. #endif
  65647. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65648. 3 * (int) point1.transformedBy (transform)
  65649. .getDistanceFrom (point2.transformedBy (transform)));
  65650. lookupTable.malloc (numEntries);
  65651. if (colours.size() >= 2)
  65652. {
  65653. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65654. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65655. int index = 0;
  65656. for (int j = 1; j < colours.size(); ++j)
  65657. {
  65658. const ColourPoint& p = colours.getReference (j);
  65659. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65660. const PixelARGB pix2 (p.colour.getPixelARGB());
  65661. for (int i = 0; i < numToDo; ++i)
  65662. {
  65663. jassert (index >= 0 && index < numEntries);
  65664. lookupTable[index] = pix1;
  65665. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65666. ++index;
  65667. }
  65668. pix1 = pix2;
  65669. }
  65670. while (index < numEntries)
  65671. lookupTable [index++] = pix1;
  65672. }
  65673. else
  65674. {
  65675. jassertfalse; // no colours specified!
  65676. }
  65677. return numEntries;
  65678. }
  65679. bool ColourGradient::isOpaque() const throw()
  65680. {
  65681. for (int i = 0; i < colours.size(); ++i)
  65682. if (! colours.getReference(i).colour.isOpaque())
  65683. return false;
  65684. return true;
  65685. }
  65686. bool ColourGradient::isInvisible() const throw()
  65687. {
  65688. for (int i = 0; i < colours.size(); ++i)
  65689. if (! colours.getReference(i).colour.isTransparent())
  65690. return false;
  65691. return true;
  65692. }
  65693. bool ColourGradient::ColourPoint::operator== (const ColourPoint& other) const throw()
  65694. {
  65695. return position == other.position && colour == other.colour;
  65696. }
  65697. bool ColourGradient::ColourPoint::operator!= (const ColourPoint& other) const throw()
  65698. {
  65699. return position != other.position || colour != other.colour;
  65700. }
  65701. END_JUCE_NAMESPACE
  65702. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65703. /*** Start of inlined file: juce_Colours.cpp ***/
  65704. BEGIN_JUCE_NAMESPACE
  65705. const Colour Colours::transparentBlack (0);
  65706. const Colour Colours::transparentWhite (0x00ffffff);
  65707. const Colour Colours::aliceblue (0xfff0f8ff);
  65708. const Colour Colours::antiquewhite (0xfffaebd7);
  65709. const Colour Colours::aqua (0xff00ffff);
  65710. const Colour Colours::aquamarine (0xff7fffd4);
  65711. const Colour Colours::azure (0xfff0ffff);
  65712. const Colour Colours::beige (0xfff5f5dc);
  65713. const Colour Colours::bisque (0xffffe4c4);
  65714. const Colour Colours::black (0xff000000);
  65715. const Colour Colours::blanchedalmond (0xffffebcd);
  65716. const Colour Colours::blue (0xff0000ff);
  65717. const Colour Colours::blueviolet (0xff8a2be2);
  65718. const Colour Colours::brown (0xffa52a2a);
  65719. const Colour Colours::burlywood (0xffdeb887);
  65720. const Colour Colours::cadetblue (0xff5f9ea0);
  65721. const Colour Colours::chartreuse (0xff7fff00);
  65722. const Colour Colours::chocolate (0xffd2691e);
  65723. const Colour Colours::coral (0xffff7f50);
  65724. const Colour Colours::cornflowerblue (0xff6495ed);
  65725. const Colour Colours::cornsilk (0xfffff8dc);
  65726. const Colour Colours::crimson (0xffdc143c);
  65727. const Colour Colours::cyan (0xff00ffff);
  65728. const Colour Colours::darkblue (0xff00008b);
  65729. const Colour Colours::darkcyan (0xff008b8b);
  65730. const Colour Colours::darkgoldenrod (0xffb8860b);
  65731. const Colour Colours::darkgrey (0xff555555);
  65732. const Colour Colours::darkgreen (0xff006400);
  65733. const Colour Colours::darkkhaki (0xffbdb76b);
  65734. const Colour Colours::darkmagenta (0xff8b008b);
  65735. const Colour Colours::darkolivegreen (0xff556b2f);
  65736. const Colour Colours::darkorange (0xffff8c00);
  65737. const Colour Colours::darkorchid (0xff9932cc);
  65738. const Colour Colours::darkred (0xff8b0000);
  65739. const Colour Colours::darksalmon (0xffe9967a);
  65740. const Colour Colours::darkseagreen (0xff8fbc8f);
  65741. const Colour Colours::darkslateblue (0xff483d8b);
  65742. const Colour Colours::darkslategrey (0xff2f4f4f);
  65743. const Colour Colours::darkturquoise (0xff00ced1);
  65744. const Colour Colours::darkviolet (0xff9400d3);
  65745. const Colour Colours::deeppink (0xffff1493);
  65746. const Colour Colours::deepskyblue (0xff00bfff);
  65747. const Colour Colours::dimgrey (0xff696969);
  65748. const Colour Colours::dodgerblue (0xff1e90ff);
  65749. const Colour Colours::firebrick (0xffb22222);
  65750. const Colour Colours::floralwhite (0xfffffaf0);
  65751. const Colour Colours::forestgreen (0xff228b22);
  65752. const Colour Colours::fuchsia (0xffff00ff);
  65753. const Colour Colours::gainsboro (0xffdcdcdc);
  65754. const Colour Colours::gold (0xffffd700);
  65755. const Colour Colours::goldenrod (0xffdaa520);
  65756. const Colour Colours::grey (0xff808080);
  65757. const Colour Colours::green (0xff008000);
  65758. const Colour Colours::greenyellow (0xffadff2f);
  65759. const Colour Colours::honeydew (0xfff0fff0);
  65760. const Colour Colours::hotpink (0xffff69b4);
  65761. const Colour Colours::indianred (0xffcd5c5c);
  65762. const Colour Colours::indigo (0xff4b0082);
  65763. const Colour Colours::ivory (0xfffffff0);
  65764. const Colour Colours::khaki (0xfff0e68c);
  65765. const Colour Colours::lavender (0xffe6e6fa);
  65766. const Colour Colours::lavenderblush (0xfffff0f5);
  65767. const Colour Colours::lemonchiffon (0xfffffacd);
  65768. const Colour Colours::lightblue (0xffadd8e6);
  65769. const Colour Colours::lightcoral (0xfff08080);
  65770. const Colour Colours::lightcyan (0xffe0ffff);
  65771. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65772. const Colour Colours::lightgreen (0xff90ee90);
  65773. const Colour Colours::lightgrey (0xffd3d3d3);
  65774. const Colour Colours::lightpink (0xffffb6c1);
  65775. const Colour Colours::lightsalmon (0xffffa07a);
  65776. const Colour Colours::lightseagreen (0xff20b2aa);
  65777. const Colour Colours::lightskyblue (0xff87cefa);
  65778. const Colour Colours::lightslategrey (0xff778899);
  65779. const Colour Colours::lightsteelblue (0xffb0c4de);
  65780. const Colour Colours::lightyellow (0xffffffe0);
  65781. const Colour Colours::lime (0xff00ff00);
  65782. const Colour Colours::limegreen (0xff32cd32);
  65783. const Colour Colours::linen (0xfffaf0e6);
  65784. const Colour Colours::magenta (0xffff00ff);
  65785. const Colour Colours::maroon (0xff800000);
  65786. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65787. const Colour Colours::mediumblue (0xff0000cd);
  65788. const Colour Colours::mediumorchid (0xffba55d3);
  65789. const Colour Colours::mediumpurple (0xff9370db);
  65790. const Colour Colours::mediumseagreen (0xff3cb371);
  65791. const Colour Colours::mediumslateblue (0xff7b68ee);
  65792. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65793. const Colour Colours::mediumturquoise (0xff48d1cc);
  65794. const Colour Colours::mediumvioletred (0xffc71585);
  65795. const Colour Colours::midnightblue (0xff191970);
  65796. const Colour Colours::mintcream (0xfff5fffa);
  65797. const Colour Colours::mistyrose (0xffffe4e1);
  65798. const Colour Colours::navajowhite (0xffffdead);
  65799. const Colour Colours::navy (0xff000080);
  65800. const Colour Colours::oldlace (0xfffdf5e6);
  65801. const Colour Colours::olive (0xff808000);
  65802. const Colour Colours::olivedrab (0xff6b8e23);
  65803. const Colour Colours::orange (0xffffa500);
  65804. const Colour Colours::orangered (0xffff4500);
  65805. const Colour Colours::orchid (0xffda70d6);
  65806. const Colour Colours::palegoldenrod (0xffeee8aa);
  65807. const Colour Colours::palegreen (0xff98fb98);
  65808. const Colour Colours::paleturquoise (0xffafeeee);
  65809. const Colour Colours::palevioletred (0xffdb7093);
  65810. const Colour Colours::papayawhip (0xffffefd5);
  65811. const Colour Colours::peachpuff (0xffffdab9);
  65812. const Colour Colours::peru (0xffcd853f);
  65813. const Colour Colours::pink (0xffffc0cb);
  65814. const Colour Colours::plum (0xffdda0dd);
  65815. const Colour Colours::powderblue (0xffb0e0e6);
  65816. const Colour Colours::purple (0xff800080);
  65817. const Colour Colours::red (0xffff0000);
  65818. const Colour Colours::rosybrown (0xffbc8f8f);
  65819. const Colour Colours::royalblue (0xff4169e1);
  65820. const Colour Colours::saddlebrown (0xff8b4513);
  65821. const Colour Colours::salmon (0xfffa8072);
  65822. const Colour Colours::sandybrown (0xfff4a460);
  65823. const Colour Colours::seagreen (0xff2e8b57);
  65824. const Colour Colours::seashell (0xfffff5ee);
  65825. const Colour Colours::sienna (0xffa0522d);
  65826. const Colour Colours::silver (0xffc0c0c0);
  65827. const Colour Colours::skyblue (0xff87ceeb);
  65828. const Colour Colours::slateblue (0xff6a5acd);
  65829. const Colour Colours::slategrey (0xff708090);
  65830. const Colour Colours::snow (0xfffffafa);
  65831. const Colour Colours::springgreen (0xff00ff7f);
  65832. const Colour Colours::steelblue (0xff4682b4);
  65833. const Colour Colours::tan (0xffd2b48c);
  65834. const Colour Colours::teal (0xff008080);
  65835. const Colour Colours::thistle (0xffd8bfd8);
  65836. const Colour Colours::tomato (0xffff6347);
  65837. const Colour Colours::turquoise (0xff40e0d0);
  65838. const Colour Colours::violet (0xffee82ee);
  65839. const Colour Colours::wheat (0xfff5deb3);
  65840. const Colour Colours::white (0xffffffff);
  65841. const Colour Colours::whitesmoke (0xfff5f5f5);
  65842. const Colour Colours::yellow (0xffffff00);
  65843. const Colour Colours::yellowgreen (0xff9acd32);
  65844. const Colour Colours::findColourForName (const String& colourName,
  65845. const Colour& defaultColour)
  65846. {
  65847. static const int presets[] =
  65848. {
  65849. // (first value is the string's hashcode, second is ARGB)
  65850. 0x05978fff, 0xff000000, /* black */
  65851. 0x06bdcc29, 0xffffffff, /* white */
  65852. 0x002e305a, 0xff0000ff, /* blue */
  65853. 0x00308adf, 0xff808080, /* grey */
  65854. 0x05e0cf03, 0xff008000, /* green */
  65855. 0x0001b891, 0xffff0000, /* red */
  65856. 0xd43c6474, 0xffffff00, /* yellow */
  65857. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65858. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65859. 0x002dcebc, 0xff00ffff, /* aqua */
  65860. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65861. 0x0590228f, 0xfff0ffff, /* azure */
  65862. 0x05947fe4, 0xfff5f5dc, /* beige */
  65863. 0xad388e35, 0xffffe4c4, /* bisque */
  65864. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65865. 0x39129959, 0xff8a2be2, /* blueviolet */
  65866. 0x059a8136, 0xffa52a2a, /* brown */
  65867. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65868. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65869. 0x6b748956, 0xff7fff00, /* chartreuse */
  65870. 0x2903623c, 0xffd2691e, /* chocolate */
  65871. 0x05a74431, 0xffff7f50, /* coral */
  65872. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65873. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65874. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65875. 0x002ed323, 0xff00ffff, /* cyan */
  65876. 0x67cc74d0, 0xff00008b, /* darkblue */
  65877. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65878. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65879. 0x67cecf55, 0xff555555, /* darkgrey */
  65880. 0x920b194d, 0xff006400, /* darkgreen */
  65881. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65882. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65883. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65884. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65885. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65886. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65887. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65888. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65889. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65890. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65891. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65892. 0xc8769375, 0xff9400d3, /* darkviolet */
  65893. 0x25832862, 0xffff1493, /* deeppink */
  65894. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65895. 0x634c8b67, 0xff696969, /* dimgrey */
  65896. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65897. 0xef19e3cb, 0xffb22222, /* firebrick */
  65898. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65899. 0xd086fd06, 0xff228b22, /* forestgreen */
  65900. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65901. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65902. 0x00308060, 0xffffd700, /* gold */
  65903. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65904. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65905. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65906. 0x41892743, 0xffff69b4, /* hotpink */
  65907. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65908. 0xb969fed2, 0xff4b0082, /* indigo */
  65909. 0x05fef6a9, 0xfffffff0, /* ivory */
  65910. 0x06149302, 0xfff0e68c, /* khaki */
  65911. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65912. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65913. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65914. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65915. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65916. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65917. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65918. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65919. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65920. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65921. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65922. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65923. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65924. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65925. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65926. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65927. 0x0032afd5, 0xff00ff00, /* lime */
  65928. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65929. 0x06234efa, 0xfffaf0e6, /* linen */
  65930. 0x316858a9, 0xffff00ff, /* magenta */
  65931. 0xbf8ca470, 0xff800000, /* maroon */
  65932. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65933. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65934. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65935. 0x07556b71, 0xff9370db, /* mediumpurple */
  65936. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65937. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65938. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65939. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65940. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65941. 0x168eb32a, 0xff191970, /* midnightblue */
  65942. 0x4306b960, 0xfff5fffa, /* mintcream */
  65943. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65944. 0xe97218a6, 0xffffdead, /* navajowhite */
  65945. 0x00337bb6, 0xff000080, /* navy */
  65946. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65947. 0x064ee1db, 0xff808000, /* olive */
  65948. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65949. 0xc3de262e, 0xffffa500, /* orange */
  65950. 0x58bebba3, 0xffff4500, /* orangered */
  65951. 0xc3def8a3, 0xffda70d6, /* orchid */
  65952. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65953. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65954. 0x74022737, 0xffafeeee, /* paleturquoise */
  65955. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65956. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65957. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65958. 0x003472f8, 0xffcd853f, /* peru */
  65959. 0x00348176, 0xffffc0cb, /* pink */
  65960. 0x00348d94, 0xffdda0dd, /* plum */
  65961. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65962. 0xc5c507bc, 0xff800080, /* purple */
  65963. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65964. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65965. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65966. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65967. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65968. 0x34636c14, 0xff2e8b57, /* seagreen */
  65969. 0x3507fb41, 0xfffff5ee, /* seashell */
  65970. 0xca348772, 0xffa0522d, /* sienna */
  65971. 0xca37d30d, 0xffc0c0c0, /* silver */
  65972. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65973. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65974. 0x44ab37f8, 0xff708090, /* slategrey */
  65975. 0x0035f183, 0xfffffafa, /* snow */
  65976. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65977. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65978. 0x0001bfa1, 0xffd2b48c, /* tan */
  65979. 0x0036425c, 0xff008080, /* teal */
  65980. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65981. 0xcc41600a, 0xffff6347, /* tomato */
  65982. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65983. 0xcf57947f, 0xffee82ee, /* violet */
  65984. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65985. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65986. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65987. };
  65988. const int hash = colourName.trim().toLowerCase().hashCode();
  65989. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65990. if (presets [i] == hash)
  65991. return Colour (presets [i + 1]);
  65992. return defaultColour;
  65993. }
  65994. END_JUCE_NAMESPACE
  65995. /*** End of inlined file: juce_Colours.cpp ***/
  65996. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65997. BEGIN_JUCE_NAMESPACE
  65998. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65999. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  66000. const Path& path, const AffineTransform& transform)
  66001. : bounds (bounds_),
  66002. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66003. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66004. needToCheckEmptinesss (true)
  66005. {
  66006. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  66007. int* t = table;
  66008. for (int i = bounds.getHeight(); --i >= 0;)
  66009. {
  66010. *t = 0;
  66011. t += lineStrideElements;
  66012. }
  66013. const int topLimit = bounds.getY() << 8;
  66014. const int heightLimit = bounds.getHeight() << 8;
  66015. const int leftLimit = bounds.getX() << 8;
  66016. const int rightLimit = bounds.getRight() << 8;
  66017. PathFlatteningIterator iter (path, transform);
  66018. while (iter.next())
  66019. {
  66020. int y1 = roundToInt (iter.y1 * 256.0f);
  66021. int y2 = roundToInt (iter.y2 * 256.0f);
  66022. if (y1 != y2)
  66023. {
  66024. y1 -= topLimit;
  66025. y2 -= topLimit;
  66026. const int startY = y1;
  66027. int direction = -1;
  66028. if (y1 > y2)
  66029. {
  66030. swapVariables (y1, y2);
  66031. direction = 1;
  66032. }
  66033. if (y1 < 0)
  66034. y1 = 0;
  66035. if (y2 > heightLimit)
  66036. y2 = heightLimit;
  66037. if (y1 < y2)
  66038. {
  66039. const double startX = 256.0f * iter.x1;
  66040. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  66041. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  66042. do
  66043. {
  66044. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  66045. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  66046. if (x < leftLimit)
  66047. x = leftLimit;
  66048. else if (x >= rightLimit)
  66049. x = rightLimit - 1;
  66050. addEdgePoint (x, y1 >> 8, direction * step);
  66051. y1 += step;
  66052. }
  66053. while (y1 < y2);
  66054. }
  66055. }
  66056. }
  66057. sanitiseLevels (path.isUsingNonZeroWinding());
  66058. }
  66059. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  66060. : bounds (rectangleToAdd),
  66061. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66062. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66063. needToCheckEmptinesss (true)
  66064. {
  66065. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66066. table[0] = 0;
  66067. const int x1 = rectangleToAdd.getX() << 8;
  66068. const int x2 = rectangleToAdd.getRight() << 8;
  66069. int* t = table;
  66070. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  66071. {
  66072. t[0] = 2;
  66073. t[1] = x1;
  66074. t[2] = 255;
  66075. t[3] = x2;
  66076. t[4] = 0;
  66077. t += lineStrideElements;
  66078. }
  66079. }
  66080. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  66081. : bounds (rectanglesToAdd.getBounds()),
  66082. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66083. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66084. needToCheckEmptinesss (true)
  66085. {
  66086. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66087. int* t = table;
  66088. for (int i = bounds.getHeight(); --i >= 0;)
  66089. {
  66090. *t = 0;
  66091. t += lineStrideElements;
  66092. }
  66093. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  66094. {
  66095. const Rectangle<int>* const r = iter.getRectangle();
  66096. const int x1 = r->getX() << 8;
  66097. const int x2 = r->getRight() << 8;
  66098. int y = r->getY() - bounds.getY();
  66099. for (int j = r->getHeight(); --j >= 0;)
  66100. {
  66101. addEdgePoint (x1, y, 255);
  66102. addEdgePoint (x2, y, -255);
  66103. ++y;
  66104. }
  66105. }
  66106. sanitiseLevels (true);
  66107. }
  66108. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  66109. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  66110. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  66111. 2 + (int) rectangleToAdd.getWidth(),
  66112. 2 + (int) rectangleToAdd.getHeight())),
  66113. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66114. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66115. needToCheckEmptinesss (true)
  66116. {
  66117. jassert (! rectangleToAdd.isEmpty());
  66118. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66119. table[0] = 0;
  66120. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  66121. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  66122. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  66123. jassert (y1 < 256);
  66124. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  66125. if (x2 <= x1 || y2 <= y1)
  66126. {
  66127. bounds.setHeight (0);
  66128. return;
  66129. }
  66130. int lineY = 0;
  66131. int* t = table;
  66132. if ((y1 >> 8) == (y2 >> 8))
  66133. {
  66134. t[0] = 2;
  66135. t[1] = x1;
  66136. t[2] = y2 - y1;
  66137. t[3] = x2;
  66138. t[4] = 0;
  66139. ++lineY;
  66140. t += lineStrideElements;
  66141. }
  66142. else
  66143. {
  66144. t[0] = 2;
  66145. t[1] = x1;
  66146. t[2] = 255 - (y1 & 255);
  66147. t[3] = x2;
  66148. t[4] = 0;
  66149. ++lineY;
  66150. t += lineStrideElements;
  66151. while (lineY < (y2 >> 8))
  66152. {
  66153. t[0] = 2;
  66154. t[1] = x1;
  66155. t[2] = 255;
  66156. t[3] = x2;
  66157. t[4] = 0;
  66158. ++lineY;
  66159. t += lineStrideElements;
  66160. }
  66161. jassert (lineY < bounds.getHeight());
  66162. t[0] = 2;
  66163. t[1] = x1;
  66164. t[2] = y2 & 255;
  66165. t[3] = x2;
  66166. t[4] = 0;
  66167. ++lineY;
  66168. t += lineStrideElements;
  66169. }
  66170. while (lineY < bounds.getHeight())
  66171. {
  66172. t[0] = 0;
  66173. t += lineStrideElements;
  66174. ++lineY;
  66175. }
  66176. }
  66177. EdgeTable::EdgeTable (const EdgeTable& other)
  66178. {
  66179. operator= (other);
  66180. }
  66181. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  66182. {
  66183. bounds = other.bounds;
  66184. maxEdgesPerLine = other.maxEdgesPerLine;
  66185. lineStrideElements = other.lineStrideElements;
  66186. needToCheckEmptinesss = other.needToCheckEmptinesss;
  66187. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66188. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  66189. return *this;
  66190. }
  66191. EdgeTable::~EdgeTable()
  66192. {
  66193. }
  66194. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  66195. {
  66196. while (--numLines >= 0)
  66197. {
  66198. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  66199. src += srcLineStride;
  66200. dest += destLineStride;
  66201. }
  66202. }
  66203. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  66204. {
  66205. // Convert the table from relative windings to absolute levels..
  66206. int* lineStart = table;
  66207. for (int i = bounds.getHeight(); --i >= 0;)
  66208. {
  66209. int* line = lineStart;
  66210. lineStart += lineStrideElements;
  66211. int num = *line;
  66212. if (num == 0)
  66213. continue;
  66214. int level = 0;
  66215. if (useNonZeroWinding)
  66216. {
  66217. while (--num > 0)
  66218. {
  66219. line += 2;
  66220. level += *line;
  66221. int corrected = abs (level);
  66222. if (corrected >> 8)
  66223. corrected = 255;
  66224. *line = corrected;
  66225. }
  66226. }
  66227. else
  66228. {
  66229. while (--num > 0)
  66230. {
  66231. line += 2;
  66232. level += *line;
  66233. int corrected = abs (level);
  66234. if (corrected >> 8)
  66235. {
  66236. corrected &= 511;
  66237. if (corrected >> 8)
  66238. corrected = 511 - corrected;
  66239. }
  66240. *line = corrected;
  66241. }
  66242. }
  66243. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  66244. }
  66245. }
  66246. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  66247. {
  66248. if (newNumEdgesPerLine != maxEdgesPerLine)
  66249. {
  66250. maxEdgesPerLine = newNumEdgesPerLine;
  66251. jassert (bounds.getHeight() > 0);
  66252. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  66253. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  66254. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  66255. table.swapWith (newTable);
  66256. lineStrideElements = newLineStrideElements;
  66257. }
  66258. }
  66259. void EdgeTable::optimiseTable()
  66260. {
  66261. int maxLineElements = 0;
  66262. for (int i = bounds.getHeight(); --i >= 0;)
  66263. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  66264. remapTableForNumEdges (maxLineElements);
  66265. }
  66266. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  66267. {
  66268. jassert (y >= 0 && y < bounds.getHeight());
  66269. int* line = table + lineStrideElements * y;
  66270. const int numPoints = line[0];
  66271. int n = numPoints << 1;
  66272. if (n > 0)
  66273. {
  66274. while (n > 0)
  66275. {
  66276. const int cx = line [n - 1];
  66277. if (cx <= x)
  66278. {
  66279. if (cx == x)
  66280. {
  66281. line [n] += winding;
  66282. return;
  66283. }
  66284. break;
  66285. }
  66286. n -= 2;
  66287. }
  66288. if (numPoints >= maxEdgesPerLine)
  66289. {
  66290. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66291. jassert (numPoints < maxEdgesPerLine);
  66292. line = table + lineStrideElements * y;
  66293. }
  66294. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  66295. }
  66296. line [n + 1] = x;
  66297. line [n + 2] = winding;
  66298. line[0]++;
  66299. }
  66300. void EdgeTable::translate (float dx, const int dy) throw()
  66301. {
  66302. bounds.translate ((int) std::floor (dx), dy);
  66303. int* lineStart = table;
  66304. const int intDx = (int) (dx * 256.0f);
  66305. for (int i = bounds.getHeight(); --i >= 0;)
  66306. {
  66307. int* line = lineStart;
  66308. lineStart += lineStrideElements;
  66309. int num = *line++;
  66310. while (--num >= 0)
  66311. {
  66312. *line += intDx;
  66313. line += 2;
  66314. }
  66315. }
  66316. }
  66317. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  66318. {
  66319. jassert (y >= 0 && y < bounds.getHeight());
  66320. int* dest = table + lineStrideElements * y;
  66321. if (dest[0] == 0)
  66322. return;
  66323. int otherNumPoints = *otherLine;
  66324. if (otherNumPoints == 0)
  66325. {
  66326. *dest = 0;
  66327. return;
  66328. }
  66329. const int right = bounds.getRight() << 8;
  66330. // optimise for the common case where our line lies entirely within a
  66331. // single pair of points, as happens when clipping to a simple rect.
  66332. if (otherNumPoints == 2 && otherLine[2] >= 255)
  66333. {
  66334. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  66335. return;
  66336. }
  66337. ++otherLine;
  66338. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  66339. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  66340. memcpy (temp, dest, lineSizeBytes);
  66341. const int* src1 = temp;
  66342. int srcNum1 = *src1++;
  66343. int x1 = *src1++;
  66344. const int* src2 = otherLine;
  66345. int srcNum2 = otherNumPoints;
  66346. int x2 = *src2++;
  66347. int destIndex = 0, destTotal = 0;
  66348. int level1 = 0, level2 = 0;
  66349. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66350. while (srcNum1 > 0 && srcNum2 > 0)
  66351. {
  66352. int nextX;
  66353. if (x1 < x2)
  66354. {
  66355. nextX = x1;
  66356. level1 = *src1++;
  66357. x1 = *src1++;
  66358. --srcNum1;
  66359. }
  66360. else if (x1 == x2)
  66361. {
  66362. nextX = x1;
  66363. level1 = *src1++;
  66364. level2 = *src2++;
  66365. x1 = *src1++;
  66366. x2 = *src2++;
  66367. --srcNum1;
  66368. --srcNum2;
  66369. }
  66370. else
  66371. {
  66372. nextX = x2;
  66373. level2 = *src2++;
  66374. x2 = *src2++;
  66375. --srcNum2;
  66376. }
  66377. if (nextX > lastX)
  66378. {
  66379. if (nextX >= right)
  66380. break;
  66381. lastX = nextX;
  66382. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66383. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  66384. if (nextLevel != lastLevel)
  66385. {
  66386. if (destTotal >= maxEdgesPerLine)
  66387. {
  66388. dest[0] = destTotal;
  66389. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66390. dest = table + lineStrideElements * y;
  66391. }
  66392. ++destTotal;
  66393. lastLevel = nextLevel;
  66394. dest[++destIndex] = nextX;
  66395. dest[++destIndex] = nextLevel;
  66396. }
  66397. }
  66398. }
  66399. if (lastLevel > 0)
  66400. {
  66401. if (destTotal >= maxEdgesPerLine)
  66402. {
  66403. dest[0] = destTotal;
  66404. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66405. dest = table + lineStrideElements * y;
  66406. }
  66407. ++destTotal;
  66408. dest[++destIndex] = right;
  66409. dest[++destIndex] = 0;
  66410. }
  66411. dest[0] = destTotal;
  66412. #if JUCE_DEBUG
  66413. int last = std::numeric_limits<int>::min();
  66414. for (int i = 0; i < dest[0]; ++i)
  66415. {
  66416. jassert (dest[i * 2 + 1] > last);
  66417. last = dest[i * 2 + 1];
  66418. }
  66419. jassert (dest [dest[0] * 2] == 0);
  66420. #endif
  66421. }
  66422. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66423. {
  66424. int* lastItem = dest + (dest[0] * 2 - 1);
  66425. if (x2 < lastItem[0])
  66426. {
  66427. if (x2 <= dest[1])
  66428. {
  66429. dest[0] = 0;
  66430. return;
  66431. }
  66432. while (x2 < lastItem[-2])
  66433. {
  66434. --(dest[0]);
  66435. lastItem -= 2;
  66436. }
  66437. lastItem[0] = x2;
  66438. lastItem[1] = 0;
  66439. }
  66440. if (x1 > dest[1])
  66441. {
  66442. while (lastItem[0] > x1)
  66443. lastItem -= 2;
  66444. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66445. if (itemsRemoved > 0)
  66446. {
  66447. dest[0] -= itemsRemoved;
  66448. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66449. }
  66450. dest[1] = x1;
  66451. }
  66452. }
  66453. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  66454. {
  66455. const Rectangle<int> clipped (r.getIntersection (bounds));
  66456. if (clipped.isEmpty())
  66457. {
  66458. needToCheckEmptinesss = false;
  66459. bounds.setHeight (0);
  66460. }
  66461. else
  66462. {
  66463. const int top = clipped.getY() - bounds.getY();
  66464. const int bottom = clipped.getBottom() - bounds.getY();
  66465. if (bottom < bounds.getHeight())
  66466. bounds.setHeight (bottom);
  66467. if (clipped.getRight() < bounds.getRight())
  66468. bounds.setRight (clipped.getRight());
  66469. for (int i = top; --i >= 0;)
  66470. table [lineStrideElements * i] = 0;
  66471. if (clipped.getX() > bounds.getX())
  66472. {
  66473. const int x1 = clipped.getX() << 8;
  66474. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66475. int* line = table + lineStrideElements * top;
  66476. for (int i = bottom - top; --i >= 0;)
  66477. {
  66478. if (line[0] != 0)
  66479. clipEdgeTableLineToRange (line, x1, x2);
  66480. line += lineStrideElements;
  66481. }
  66482. }
  66483. needToCheckEmptinesss = true;
  66484. }
  66485. }
  66486. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  66487. {
  66488. const Rectangle<int> clipped (r.getIntersection (bounds));
  66489. if (! clipped.isEmpty())
  66490. {
  66491. const int top = clipped.getY() - bounds.getY();
  66492. const int bottom = clipped.getBottom() - bounds.getY();
  66493. //XXX optimise here by shortening the table if it fills top or bottom
  66494. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66495. clipped.getX() << 8, 0,
  66496. clipped.getRight() << 8, 255,
  66497. std::numeric_limits<int>::max(), 0 };
  66498. for (int i = top; i < bottom; ++i)
  66499. intersectWithEdgeTableLine (i, rectLine);
  66500. needToCheckEmptinesss = true;
  66501. }
  66502. }
  66503. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66504. {
  66505. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66506. if (clipped.isEmpty())
  66507. {
  66508. needToCheckEmptinesss = false;
  66509. bounds.setHeight (0);
  66510. }
  66511. else
  66512. {
  66513. const int top = clipped.getY() - bounds.getY();
  66514. const int bottom = clipped.getBottom() - bounds.getY();
  66515. if (bottom < bounds.getHeight())
  66516. bounds.setHeight (bottom);
  66517. if (clipped.getRight() < bounds.getRight())
  66518. bounds.setRight (clipped.getRight());
  66519. int i = 0;
  66520. for (i = top; --i >= 0;)
  66521. table [lineStrideElements * i] = 0;
  66522. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66523. for (i = top; i < bottom; ++i)
  66524. {
  66525. intersectWithEdgeTableLine (i, otherLine);
  66526. otherLine += other.lineStrideElements;
  66527. }
  66528. needToCheckEmptinesss = true;
  66529. }
  66530. }
  66531. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  66532. {
  66533. y -= bounds.getY();
  66534. if (y < 0 || y >= bounds.getHeight())
  66535. return;
  66536. needToCheckEmptinesss = true;
  66537. if (numPixels <= 0)
  66538. {
  66539. table [lineStrideElements * y] = 0;
  66540. return;
  66541. }
  66542. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66543. int destIndex = 0, lastLevel = 0;
  66544. while (--numPixels >= 0)
  66545. {
  66546. const int alpha = *mask;
  66547. mask += maskStride;
  66548. if (alpha != lastLevel)
  66549. {
  66550. tempLine[++destIndex] = (x << 8);
  66551. tempLine[++destIndex] = alpha;
  66552. lastLevel = alpha;
  66553. }
  66554. ++x;
  66555. }
  66556. if (lastLevel > 0)
  66557. {
  66558. tempLine[++destIndex] = (x << 8);
  66559. tempLine[++destIndex] = 0;
  66560. }
  66561. tempLine[0] = destIndex >> 1;
  66562. intersectWithEdgeTableLine (y, tempLine);
  66563. }
  66564. bool EdgeTable::isEmpty() throw()
  66565. {
  66566. if (needToCheckEmptinesss)
  66567. {
  66568. needToCheckEmptinesss = false;
  66569. int* t = table;
  66570. for (int i = bounds.getHeight(); --i >= 0;)
  66571. {
  66572. if (t[0] > 1)
  66573. return false;
  66574. t += lineStrideElements;
  66575. }
  66576. bounds.setHeight (0);
  66577. }
  66578. return bounds.getHeight() == 0;
  66579. }
  66580. END_JUCE_NAMESPACE
  66581. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66582. /*** Start of inlined file: juce_FillType.cpp ***/
  66583. BEGIN_JUCE_NAMESPACE
  66584. FillType::FillType() throw()
  66585. : colour (0xff000000), image (0)
  66586. {
  66587. }
  66588. FillType::FillType (const Colour& colour_) throw()
  66589. : colour (colour_), image (0)
  66590. {
  66591. }
  66592. FillType::FillType (const ColourGradient& gradient_)
  66593. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66594. {
  66595. }
  66596. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66597. : colour (0xff000000), image (image_), transform (transform_)
  66598. {
  66599. }
  66600. FillType::FillType (const FillType& other)
  66601. : colour (other.colour),
  66602. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66603. image (other.image), transform (other.transform)
  66604. {
  66605. }
  66606. FillType& FillType::operator= (const FillType& other)
  66607. {
  66608. if (this != &other)
  66609. {
  66610. colour = other.colour;
  66611. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66612. image = other.image;
  66613. transform = other.transform;
  66614. }
  66615. return *this;
  66616. }
  66617. FillType::~FillType() throw()
  66618. {
  66619. }
  66620. bool FillType::operator== (const FillType& other) const
  66621. {
  66622. return colour == other.colour && image == other.image
  66623. && transform == other.transform
  66624. && (gradient == other.gradient
  66625. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66626. }
  66627. bool FillType::operator!= (const FillType& other) const
  66628. {
  66629. return ! operator== (other);
  66630. }
  66631. void FillType::setColour (const Colour& newColour) throw()
  66632. {
  66633. gradient = 0;
  66634. image = Image::null;
  66635. colour = newColour;
  66636. }
  66637. void FillType::setGradient (const ColourGradient& newGradient)
  66638. {
  66639. if (gradient != 0)
  66640. {
  66641. *gradient = newGradient;
  66642. }
  66643. else
  66644. {
  66645. image = Image::null;
  66646. gradient = new ColourGradient (newGradient);
  66647. colour = Colours::black;
  66648. }
  66649. }
  66650. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66651. {
  66652. gradient = 0;
  66653. image = image_;
  66654. transform = transform_;
  66655. colour = Colours::black;
  66656. }
  66657. void FillType::setOpacity (const float newOpacity) throw()
  66658. {
  66659. colour = colour.withAlpha (newOpacity);
  66660. }
  66661. bool FillType::isInvisible() const throw()
  66662. {
  66663. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66664. }
  66665. END_JUCE_NAMESPACE
  66666. /*** End of inlined file: juce_FillType.cpp ***/
  66667. /*** Start of inlined file: juce_Graphics.cpp ***/
  66668. BEGIN_JUCE_NAMESPACE
  66669. namespace
  66670. {
  66671. template <typename Type>
  66672. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66673. {
  66674. const int maxVal = 0x3fffffff;
  66675. return (int) x >= -maxVal && (int) x <= maxVal
  66676. && (int) y >= -maxVal && (int) y <= maxVal
  66677. && (int) w >= -maxVal && (int) w <= maxVal
  66678. && (int) h >= -maxVal && (int) h <= maxVal;
  66679. }
  66680. }
  66681. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66682. {
  66683. }
  66684. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66685. {
  66686. }
  66687. Graphics::Graphics (const Image& imageToDrawOnto)
  66688. : context (imageToDrawOnto.createLowLevelContext()),
  66689. contextToDelete (context),
  66690. saveStatePending (false)
  66691. {
  66692. }
  66693. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66694. : context (internalContext),
  66695. saveStatePending (false)
  66696. {
  66697. }
  66698. Graphics::~Graphics()
  66699. {
  66700. }
  66701. void Graphics::resetToDefaultState()
  66702. {
  66703. saveStateIfPending();
  66704. context->setFill (FillType());
  66705. context->setFont (Font());
  66706. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66707. }
  66708. bool Graphics::isVectorDevice() const
  66709. {
  66710. return context->isVectorDevice();
  66711. }
  66712. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66713. {
  66714. saveStateIfPending();
  66715. return context->clipToRectangle (area);
  66716. }
  66717. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66718. {
  66719. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66720. }
  66721. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66722. {
  66723. saveStateIfPending();
  66724. return context->clipToRectangleList (clipRegion);
  66725. }
  66726. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66727. {
  66728. saveStateIfPending();
  66729. context->clipToPath (path, transform);
  66730. return ! context->isClipEmpty();
  66731. }
  66732. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66733. {
  66734. saveStateIfPending();
  66735. context->clipToImageAlpha (image, transform);
  66736. return ! context->isClipEmpty();
  66737. }
  66738. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66739. {
  66740. saveStateIfPending();
  66741. context->excludeClipRectangle (rectangleToExclude);
  66742. }
  66743. bool Graphics::isClipEmpty() const
  66744. {
  66745. return context->isClipEmpty();
  66746. }
  66747. const Rectangle<int> Graphics::getClipBounds() const
  66748. {
  66749. return context->getClipBounds();
  66750. }
  66751. void Graphics::saveState()
  66752. {
  66753. saveStateIfPending();
  66754. saveStatePending = true;
  66755. }
  66756. void Graphics::restoreState()
  66757. {
  66758. if (saveStatePending)
  66759. saveStatePending = false;
  66760. else
  66761. context->restoreState();
  66762. }
  66763. void Graphics::saveStateIfPending()
  66764. {
  66765. if (saveStatePending)
  66766. {
  66767. saveStatePending = false;
  66768. context->saveState();
  66769. }
  66770. }
  66771. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66772. {
  66773. saveStateIfPending();
  66774. context->setOrigin (newOriginX, newOriginY);
  66775. }
  66776. void Graphics::addTransform (const AffineTransform& transform)
  66777. {
  66778. saveStateIfPending();
  66779. context->addTransform (transform);
  66780. }
  66781. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66782. {
  66783. return context->clipRegionIntersects (area);
  66784. }
  66785. void Graphics::beginTransparencyLayer (float layerOpacity)
  66786. {
  66787. saveStateIfPending();
  66788. context->beginTransparencyLayer (layerOpacity);
  66789. }
  66790. void Graphics::endTransparencyLayer()
  66791. {
  66792. context->endTransparencyLayer();
  66793. }
  66794. void Graphics::setColour (const Colour& newColour)
  66795. {
  66796. saveStateIfPending();
  66797. context->setFill (newColour);
  66798. }
  66799. void Graphics::setOpacity (const float newOpacity)
  66800. {
  66801. saveStateIfPending();
  66802. context->setOpacity (newOpacity);
  66803. }
  66804. void Graphics::setGradientFill (const ColourGradient& gradient)
  66805. {
  66806. setFillType (gradient);
  66807. }
  66808. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66809. {
  66810. saveStateIfPending();
  66811. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66812. context->setOpacity (opacity);
  66813. }
  66814. void Graphics::setFillType (const FillType& newFill)
  66815. {
  66816. saveStateIfPending();
  66817. context->setFill (newFill);
  66818. }
  66819. void Graphics::setFont (const Font& newFont)
  66820. {
  66821. saveStateIfPending();
  66822. context->setFont (newFont);
  66823. }
  66824. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66825. {
  66826. saveStateIfPending();
  66827. Font f (context->getFont());
  66828. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66829. context->setFont (f);
  66830. }
  66831. const Font Graphics::getCurrentFont() const
  66832. {
  66833. return context->getFont();
  66834. }
  66835. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66836. {
  66837. if (text.isNotEmpty()
  66838. && startX < context->getClipBounds().getRight())
  66839. {
  66840. GlyphArrangement arr;
  66841. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66842. arr.draw (*this);
  66843. }
  66844. }
  66845. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66846. {
  66847. if (text.isNotEmpty())
  66848. {
  66849. GlyphArrangement arr;
  66850. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66851. arr.draw (*this, transform);
  66852. }
  66853. }
  66854. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66855. {
  66856. if (text.isNotEmpty()
  66857. && startX < context->getClipBounds().getRight())
  66858. {
  66859. GlyphArrangement arr;
  66860. arr.addJustifiedText (context->getFont(), text,
  66861. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66862. Justification::left);
  66863. arr.draw (*this);
  66864. }
  66865. }
  66866. void Graphics::drawText (const String& text,
  66867. const int x, const int y, const int width, const int height,
  66868. const Justification& justificationType,
  66869. const bool useEllipsesIfTooBig) const
  66870. {
  66871. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66872. {
  66873. GlyphArrangement arr;
  66874. arr.addCurtailedLineOfText (context->getFont(), text,
  66875. 0.0f, 0.0f, (float) width,
  66876. useEllipsesIfTooBig);
  66877. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66878. (float) x, (float) y, (float) width, (float) height,
  66879. justificationType);
  66880. arr.draw (*this);
  66881. }
  66882. }
  66883. void Graphics::drawFittedText (const String& text,
  66884. const int x, const int y, const int width, const int height,
  66885. const Justification& justification,
  66886. const int maximumNumberOfLines,
  66887. const float minimumHorizontalScale) const
  66888. {
  66889. if (text.isNotEmpty()
  66890. && width > 0 && height > 0
  66891. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66892. {
  66893. GlyphArrangement arr;
  66894. arr.addFittedText (context->getFont(), text,
  66895. (float) x, (float) y, (float) width, (float) height,
  66896. justification,
  66897. maximumNumberOfLines,
  66898. minimumHorizontalScale);
  66899. arr.draw (*this);
  66900. }
  66901. }
  66902. void Graphics::fillRect (int x, int y, int width, int height) const
  66903. {
  66904. // passing in a silly number can cause maths problems in rendering!
  66905. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66906. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66907. }
  66908. void Graphics::fillRect (const Rectangle<int>& r) const
  66909. {
  66910. context->fillRect (r, false);
  66911. }
  66912. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66913. {
  66914. // passing in a silly number can cause maths problems in rendering!
  66915. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66916. Path p;
  66917. p.addRectangle (x, y, width, height);
  66918. fillPath (p);
  66919. }
  66920. void Graphics::setPixel (int x, int y) const
  66921. {
  66922. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66923. }
  66924. void Graphics::fillAll() const
  66925. {
  66926. fillRect (context->getClipBounds());
  66927. }
  66928. void Graphics::fillAll (const Colour& colourToUse) const
  66929. {
  66930. if (! colourToUse.isTransparent())
  66931. {
  66932. const Rectangle<int> clip (context->getClipBounds());
  66933. context->saveState();
  66934. context->setFill (colourToUse);
  66935. context->fillRect (clip, false);
  66936. context->restoreState();
  66937. }
  66938. }
  66939. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66940. {
  66941. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66942. context->fillPath (path, transform);
  66943. }
  66944. void Graphics::strokePath (const Path& path,
  66945. const PathStrokeType& strokeType,
  66946. const AffineTransform& transform) const
  66947. {
  66948. Path stroke;
  66949. strokeType.createStrokedPath (stroke, path, transform, context->getScaleFactor());
  66950. fillPath (stroke);
  66951. }
  66952. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66953. const int lineThickness) const
  66954. {
  66955. // passing in a silly number can cause maths problems in rendering!
  66956. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66957. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66958. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66959. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66960. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66961. }
  66962. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66963. {
  66964. // passing in a silly number can cause maths problems in rendering!
  66965. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66966. Path p;
  66967. p.addRectangle (x, y, width, lineThickness);
  66968. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66969. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66970. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66971. fillPath (p);
  66972. }
  66973. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66974. {
  66975. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66976. }
  66977. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66978. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66979. const bool useGradient, const bool sharpEdgeOnOutside) const
  66980. {
  66981. // passing in a silly number can cause maths problems in rendering!
  66982. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66983. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66984. {
  66985. context->saveState();
  66986. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66987. const float ramp = oldOpacity / bevelThickness;
  66988. for (int i = bevelThickness; --i >= 0;)
  66989. {
  66990. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66991. : oldOpacity;
  66992. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66993. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66994. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66995. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66996. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66997. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66998. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66999. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  67000. }
  67001. context->restoreState();
  67002. }
  67003. }
  67004. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  67005. {
  67006. // passing in a silly number can cause maths problems in rendering!
  67007. jassert (areCoordsSensibleNumbers (x, y, width, height));
  67008. Path p;
  67009. p.addEllipse (x, y, width, height);
  67010. fillPath (p);
  67011. }
  67012. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  67013. const float lineThickness) const
  67014. {
  67015. // passing in a silly number can cause maths problems in rendering!
  67016. jassert (areCoordsSensibleNumbers (x, y, width, height));
  67017. Path p;
  67018. p.addEllipse (x, y, width, height);
  67019. strokePath (p, PathStrokeType (lineThickness));
  67020. }
  67021. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  67022. {
  67023. // passing in a silly number can cause maths problems in rendering!
  67024. jassert (areCoordsSensibleNumbers (x, y, width, height));
  67025. Path p;
  67026. p.addRoundedRectangle (x, y, width, height, cornerSize);
  67027. fillPath (p);
  67028. }
  67029. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  67030. {
  67031. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  67032. }
  67033. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  67034. const float cornerSize, const float lineThickness) const
  67035. {
  67036. // passing in a silly number can cause maths problems in rendering!
  67037. jassert (areCoordsSensibleNumbers (x, y, width, height));
  67038. Path p;
  67039. p.addRoundedRectangle (x, y, width, height, cornerSize);
  67040. strokePath (p, PathStrokeType (lineThickness));
  67041. }
  67042. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  67043. {
  67044. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  67045. }
  67046. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  67047. {
  67048. Path p;
  67049. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  67050. fillPath (p);
  67051. }
  67052. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  67053. const int checkWidth, const int checkHeight,
  67054. const Colour& colour1, const Colour& colour2) const
  67055. {
  67056. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  67057. if (checkWidth > 0 && checkHeight > 0)
  67058. {
  67059. context->saveState();
  67060. if (colour1 == colour2)
  67061. {
  67062. context->setFill (colour1);
  67063. context->fillRect (area, false);
  67064. }
  67065. else
  67066. {
  67067. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  67068. if (! clipped.isEmpty())
  67069. {
  67070. context->clipToRectangle (clipped);
  67071. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  67072. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  67073. const int startX = area.getX() + checkNumX * checkWidth;
  67074. const int startY = area.getY() + checkNumY * checkHeight;
  67075. const int right = clipped.getRight();
  67076. const int bottom = clipped.getBottom();
  67077. for (int i = 0; i < 2; ++i)
  67078. {
  67079. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  67080. int cy = i;
  67081. for (int y = startY; y < bottom; y += checkHeight)
  67082. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  67083. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  67084. }
  67085. }
  67086. }
  67087. context->restoreState();
  67088. }
  67089. }
  67090. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  67091. {
  67092. context->drawVerticalLine (x, top, bottom);
  67093. }
  67094. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  67095. {
  67096. context->drawHorizontalLine (y, left, right);
  67097. }
  67098. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2) const
  67099. {
  67100. context->drawLine (Line<float> (x1, y1, x2, y2));
  67101. }
  67102. void Graphics::drawLine (const Line<float>& line) const
  67103. {
  67104. context->drawLine (line);
  67105. }
  67106. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2, const float lineThickness) const
  67107. {
  67108. drawLine (Line<float> (x1, y1, x2, y2), lineThickness);
  67109. }
  67110. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  67111. {
  67112. Path p;
  67113. p.addLineSegment (line, lineThickness);
  67114. fillPath (p);
  67115. }
  67116. void Graphics::drawDashedLine (const Line<float>& line, const float* const dashLengths,
  67117. const int numDashLengths, const float lineThickness, int n) const
  67118. {
  67119. jassert (n >= 0 && n < numDashLengths); // your start index must be valid!
  67120. const Point<double> delta ((line.getEnd() - line.getStart()).toDouble());
  67121. const double totalLen = delta.getDistanceFromOrigin();
  67122. if (totalLen >= 0.1)
  67123. {
  67124. const double onePixAlpha = 1.0 / totalLen;
  67125. for (double alpha = 0.0; alpha < 1.0;)
  67126. {
  67127. jassert (dashLengths[n] > 0); // can't have zero-length dashes!
  67128. const double lastAlpha = alpha;
  67129. alpha = jmin (1.0, alpha + dashLengths [n] * onePixAlpha);
  67130. n = (n + 1) % numDashLengths;
  67131. if ((n & 1) != 0)
  67132. {
  67133. const Line<float> segment (line.getStart() + (delta * lastAlpha).toFloat(),
  67134. line.getStart() + (delta * alpha).toFloat());
  67135. if (lineThickness != 1.0f)
  67136. drawLine (segment, lineThickness);
  67137. else
  67138. context->drawLine (segment);
  67139. }
  67140. }
  67141. }
  67142. }
  67143. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  67144. {
  67145. saveStateIfPending();
  67146. context->setInterpolationQuality (newQuality);
  67147. }
  67148. void Graphics::drawImageAt (const Image& imageToDraw,
  67149. const int topLeftX, const int topLeftY,
  67150. const bool fillAlphaChannelWithCurrentBrush) const
  67151. {
  67152. const int imageW = imageToDraw.getWidth();
  67153. const int imageH = imageToDraw.getHeight();
  67154. drawImage (imageToDraw,
  67155. topLeftX, topLeftY, imageW, imageH,
  67156. 0, 0, imageW, imageH,
  67157. fillAlphaChannelWithCurrentBrush);
  67158. }
  67159. void Graphics::drawImageWithin (const Image& imageToDraw,
  67160. const int destX, const int destY,
  67161. const int destW, const int destH,
  67162. const RectanglePlacement& placementWithinTarget,
  67163. const bool fillAlphaChannelWithCurrentBrush) const
  67164. {
  67165. // passing in a silly number can cause maths problems in rendering!
  67166. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  67167. if (imageToDraw.isValid())
  67168. {
  67169. const int imageW = imageToDraw.getWidth();
  67170. const int imageH = imageToDraw.getHeight();
  67171. if (imageW > 0 && imageH > 0)
  67172. {
  67173. double newX = 0.0, newY = 0.0;
  67174. double newW = imageW;
  67175. double newH = imageH;
  67176. placementWithinTarget.applyTo (newX, newY, newW, newH,
  67177. destX, destY, destW, destH);
  67178. if (newW > 0 && newH > 0)
  67179. {
  67180. drawImage (imageToDraw,
  67181. roundToInt (newX), roundToInt (newY),
  67182. roundToInt (newW), roundToInt (newH),
  67183. 0, 0, imageW, imageH,
  67184. fillAlphaChannelWithCurrentBrush);
  67185. }
  67186. }
  67187. }
  67188. }
  67189. void Graphics::drawImage (const Image& imageToDraw,
  67190. int dx, int dy, int dw, int dh,
  67191. int sx, int sy, int sw, int sh,
  67192. const bool fillAlphaChannelWithCurrentBrush) const
  67193. {
  67194. // passing in a silly number can cause maths problems in rendering!
  67195. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  67196. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  67197. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  67198. {
  67199. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  67200. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  67201. .translated ((float) dx, (float) dy),
  67202. fillAlphaChannelWithCurrentBrush);
  67203. }
  67204. }
  67205. void Graphics::drawImageTransformed (const Image& imageToDraw,
  67206. const AffineTransform& transform,
  67207. const bool fillAlphaChannelWithCurrentBrush) const
  67208. {
  67209. if (imageToDraw.isValid() && ! context->isClipEmpty())
  67210. {
  67211. if (fillAlphaChannelWithCurrentBrush)
  67212. {
  67213. context->saveState();
  67214. context->clipToImageAlpha (imageToDraw, transform);
  67215. fillAll();
  67216. context->restoreState();
  67217. }
  67218. else
  67219. {
  67220. context->drawImage (imageToDraw, transform, false);
  67221. }
  67222. }
  67223. }
  67224. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  67225. : context (g)
  67226. {
  67227. context.saveState();
  67228. }
  67229. Graphics::ScopedSaveState::~ScopedSaveState()
  67230. {
  67231. context.restoreState();
  67232. }
  67233. END_JUCE_NAMESPACE
  67234. /*** End of inlined file: juce_Graphics.cpp ***/
  67235. /*** Start of inlined file: juce_Justification.cpp ***/
  67236. BEGIN_JUCE_NAMESPACE
  67237. Justification::Justification (const Justification& other) throw()
  67238. : flags (other.flags)
  67239. {
  67240. }
  67241. Justification& Justification::operator= (const Justification& other) throw()
  67242. {
  67243. flags = other.flags;
  67244. return *this;
  67245. }
  67246. int Justification::getOnlyVerticalFlags() const throw()
  67247. {
  67248. return flags & (top | bottom | verticallyCentred);
  67249. }
  67250. int Justification::getOnlyHorizontalFlags() const throw()
  67251. {
  67252. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  67253. }
  67254. END_JUCE_NAMESPACE
  67255. /*** End of inlined file: juce_Justification.cpp ***/
  67256. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67257. BEGIN_JUCE_NAMESPACE
  67258. // this will throw an assertion if you try to draw something that's not
  67259. // possible in postscript
  67260. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  67261. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  67262. #define notPossibleInPostscriptAssert jassertfalse
  67263. #else
  67264. #define notPossibleInPostscriptAssert
  67265. #endif
  67266. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  67267. const String& documentTitle,
  67268. const int totalWidth_,
  67269. const int totalHeight_)
  67270. : out (resultingPostScript),
  67271. totalWidth (totalWidth_),
  67272. totalHeight (totalHeight_),
  67273. needToClip (true)
  67274. {
  67275. stateStack.add (new SavedState());
  67276. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  67277. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  67278. out << "%!PS-Adobe-3.0 EPSF-3.0"
  67279. "\n%%BoundingBox: 0 0 600 824"
  67280. "\n%%Pages: 0"
  67281. "\n%%Creator: Raw Material Software JUCE"
  67282. "\n%%Title: " << documentTitle <<
  67283. "\n%%CreationDate: none"
  67284. "\n%%LanguageLevel: 2"
  67285. "\n%%EndComments"
  67286. "\n%%BeginProlog"
  67287. "\n%%BeginResource: JRes"
  67288. "\n/bd {bind def} bind def"
  67289. "\n/c {setrgbcolor} bd"
  67290. "\n/m {moveto} bd"
  67291. "\n/l {lineto} bd"
  67292. "\n/rl {rlineto} bd"
  67293. "\n/ct {curveto} bd"
  67294. "\n/cp {closepath} bd"
  67295. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  67296. "\n/doclip {initclip newpath} bd"
  67297. "\n/endclip {clip newpath} bd"
  67298. "\n%%EndResource"
  67299. "\n%%EndProlog"
  67300. "\n%%BeginSetup"
  67301. "\n%%EndSetup"
  67302. "\n%%Page: 1 1"
  67303. "\n%%BeginPageSetup"
  67304. "\n%%EndPageSetup\n\n"
  67305. << "40 800 translate\n"
  67306. << scale << ' ' << scale << " scale\n\n";
  67307. }
  67308. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  67309. {
  67310. }
  67311. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  67312. {
  67313. return true;
  67314. }
  67315. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  67316. {
  67317. if (x != 0 || y != 0)
  67318. {
  67319. stateStack.getLast()->xOffset += x;
  67320. stateStack.getLast()->yOffset += y;
  67321. needToClip = true;
  67322. }
  67323. }
  67324. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  67325. {
  67326. //xxx
  67327. jassertfalse;
  67328. }
  67329. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  67330. {
  67331. jassertfalse; //xxx
  67332. return 1.0f;
  67333. }
  67334. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  67335. {
  67336. needToClip = true;
  67337. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67338. }
  67339. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67340. {
  67341. needToClip = true;
  67342. return stateStack.getLast()->clip.clipTo (clipRegion);
  67343. }
  67344. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67345. {
  67346. needToClip = true;
  67347. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67348. }
  67349. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67350. {
  67351. writeClip();
  67352. Path p (path);
  67353. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67354. writePath (p);
  67355. out << "clip\n";
  67356. }
  67357. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67358. {
  67359. needToClip = true;
  67360. jassertfalse; // xxx
  67361. }
  67362. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67363. {
  67364. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67365. }
  67366. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67367. {
  67368. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67369. -stateStack.getLast()->yOffset);
  67370. }
  67371. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67372. {
  67373. return stateStack.getLast()->clip.isEmpty();
  67374. }
  67375. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67376. : xOffset (0),
  67377. yOffset (0)
  67378. {
  67379. }
  67380. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67381. {
  67382. }
  67383. void LowLevelGraphicsPostScriptRenderer::saveState()
  67384. {
  67385. stateStack.add (new SavedState (*stateStack.getLast()));
  67386. }
  67387. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67388. {
  67389. jassert (stateStack.size() > 0);
  67390. if (stateStack.size() > 0)
  67391. stateStack.removeLast();
  67392. }
  67393. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  67394. {
  67395. }
  67396. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  67397. {
  67398. }
  67399. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67400. {
  67401. if (needToClip)
  67402. {
  67403. needToClip = false;
  67404. out << "doclip ";
  67405. int itemsOnLine = 0;
  67406. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67407. {
  67408. if (++itemsOnLine == 6)
  67409. {
  67410. itemsOnLine = 0;
  67411. out << '\n';
  67412. }
  67413. const Rectangle<int>& r = *i.getRectangle();
  67414. out << r.getX() << ' ' << -r.getY() << ' '
  67415. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67416. }
  67417. out << "endclip\n";
  67418. }
  67419. }
  67420. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67421. {
  67422. Colour c (Colours::white.overlaidWith (colour));
  67423. if (lastColour != c)
  67424. {
  67425. lastColour = c;
  67426. out << String (c.getFloatRed(), 3) << ' '
  67427. << String (c.getFloatGreen(), 3) << ' '
  67428. << String (c.getFloatBlue(), 3) << " c\n";
  67429. }
  67430. }
  67431. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67432. {
  67433. out << String (x, 2) << ' '
  67434. << String (-y, 2) << ' ';
  67435. }
  67436. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67437. {
  67438. out << "newpath ";
  67439. float lastX = 0.0f;
  67440. float lastY = 0.0f;
  67441. int itemsOnLine = 0;
  67442. Path::Iterator i (path);
  67443. while (i.next())
  67444. {
  67445. if (++itemsOnLine == 4)
  67446. {
  67447. itemsOnLine = 0;
  67448. out << '\n';
  67449. }
  67450. switch (i.elementType)
  67451. {
  67452. case Path::Iterator::startNewSubPath:
  67453. writeXY (i.x1, i.y1);
  67454. lastX = i.x1;
  67455. lastY = i.y1;
  67456. out << "m ";
  67457. break;
  67458. case Path::Iterator::lineTo:
  67459. writeXY (i.x1, i.y1);
  67460. lastX = i.x1;
  67461. lastY = i.y1;
  67462. out << "l ";
  67463. break;
  67464. case Path::Iterator::quadraticTo:
  67465. {
  67466. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67467. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67468. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67469. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67470. writeXY (cp1x, cp1y);
  67471. writeXY (cp2x, cp2y);
  67472. writeXY (i.x2, i.y2);
  67473. out << "ct ";
  67474. lastX = i.x2;
  67475. lastY = i.y2;
  67476. }
  67477. break;
  67478. case Path::Iterator::cubicTo:
  67479. writeXY (i.x1, i.y1);
  67480. writeXY (i.x2, i.y2);
  67481. writeXY (i.x3, i.y3);
  67482. out << "ct ";
  67483. lastX = i.x3;
  67484. lastY = i.y3;
  67485. break;
  67486. case Path::Iterator::closePath:
  67487. out << "cp ";
  67488. break;
  67489. default:
  67490. jassertfalse;
  67491. break;
  67492. }
  67493. }
  67494. out << '\n';
  67495. }
  67496. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67497. {
  67498. out << "[ "
  67499. << trans.mat00 << ' '
  67500. << trans.mat10 << ' '
  67501. << trans.mat01 << ' '
  67502. << trans.mat11 << ' '
  67503. << trans.mat02 << ' '
  67504. << trans.mat12 << " ] concat ";
  67505. }
  67506. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67507. {
  67508. stateStack.getLast()->fillType = fillType;
  67509. }
  67510. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67511. {
  67512. }
  67513. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67514. {
  67515. }
  67516. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67517. {
  67518. if (stateStack.getLast()->fillType.isColour())
  67519. {
  67520. writeClip();
  67521. writeColour (stateStack.getLast()->fillType.colour);
  67522. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67523. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67524. }
  67525. else
  67526. {
  67527. Path p;
  67528. p.addRectangle (r);
  67529. fillPath (p, AffineTransform::identity);
  67530. }
  67531. }
  67532. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67533. {
  67534. if (stateStack.getLast()->fillType.isColour())
  67535. {
  67536. writeClip();
  67537. Path p (path);
  67538. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67539. (float) stateStack.getLast()->yOffset));
  67540. writePath (p);
  67541. writeColour (stateStack.getLast()->fillType.colour);
  67542. out << "fill\n";
  67543. }
  67544. else if (stateStack.getLast()->fillType.isGradient())
  67545. {
  67546. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67547. // postscript can't do semi-transparent ones.
  67548. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67549. writeClip();
  67550. out << "gsave ";
  67551. {
  67552. Path p (path);
  67553. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67554. writePath (p);
  67555. out << "clip\n";
  67556. }
  67557. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67558. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67559. // time-being, this just fills it with the average colour..
  67560. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67561. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67562. out << "grestore\n";
  67563. }
  67564. }
  67565. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67566. const int sx, const int sy,
  67567. const int maxW, const int maxH) const
  67568. {
  67569. out << "{<\n";
  67570. const int w = jmin (maxW, im.getWidth());
  67571. const int h = jmin (maxH, im.getHeight());
  67572. int charsOnLine = 0;
  67573. const Image::BitmapData srcData (im, 0, 0, w, h);
  67574. Colour pixel;
  67575. for (int y = h; --y >= 0;)
  67576. {
  67577. for (int x = 0; x < w; ++x)
  67578. {
  67579. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67580. if (x >= sx && y >= sy)
  67581. {
  67582. if (im.isARGB())
  67583. {
  67584. PixelARGB p (*(const PixelARGB*) pixelData);
  67585. p.unpremultiply();
  67586. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67587. }
  67588. else if (im.isRGB())
  67589. {
  67590. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67591. }
  67592. else
  67593. {
  67594. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67595. }
  67596. }
  67597. else
  67598. {
  67599. pixel = Colours::transparentWhite;
  67600. }
  67601. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67602. out << String::toHexString (pixelValues, 3, 0);
  67603. charsOnLine += 3;
  67604. if (charsOnLine > 100)
  67605. {
  67606. out << '\n';
  67607. charsOnLine = 0;
  67608. }
  67609. }
  67610. }
  67611. out << "\n>}\n";
  67612. }
  67613. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67614. {
  67615. const int w = sourceImage.getWidth();
  67616. const int h = sourceImage.getHeight();
  67617. writeClip();
  67618. out << "gsave ";
  67619. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67620. .scaled (1.0f, -1.0f));
  67621. RectangleList imageClip;
  67622. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67623. out << "newpath ";
  67624. int itemsOnLine = 0;
  67625. for (RectangleList::Iterator i (imageClip); i.next();)
  67626. {
  67627. if (++itemsOnLine == 6)
  67628. {
  67629. out << '\n';
  67630. itemsOnLine = 0;
  67631. }
  67632. const Rectangle<int>& r = *i.getRectangle();
  67633. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67634. }
  67635. out << " clip newpath\n";
  67636. out << w << ' ' << h << " scale\n";
  67637. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67638. writeImage (sourceImage, 0, 0, w, h);
  67639. out << "false 3 colorimage grestore\n";
  67640. needToClip = true;
  67641. }
  67642. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67643. {
  67644. Path p;
  67645. p.addLineSegment (line, 1.0f);
  67646. fillPath (p, AffineTransform::identity);
  67647. }
  67648. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67649. {
  67650. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67651. }
  67652. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67653. {
  67654. drawLine (Line<float> (left, (float) y, right, (float) y));
  67655. }
  67656. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67657. {
  67658. stateStack.getLast()->font = newFont;
  67659. }
  67660. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67661. {
  67662. return stateStack.getLast()->font;
  67663. }
  67664. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67665. {
  67666. Path p;
  67667. Font& font = stateStack.getLast()->font;
  67668. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67669. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67670. }
  67671. END_JUCE_NAMESPACE
  67672. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67673. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67674. BEGIN_JUCE_NAMESPACE
  67675. #if JUCE_MSVC
  67676. #pragma warning (push)
  67677. #pragma warning (disable: 4127) // "expression is constant" warning
  67678. #if JUCE_DEBUG
  67679. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67680. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67681. #endif
  67682. #endif
  67683. namespace SoftwareRendererClasses
  67684. {
  67685. template <class PixelType, bool replaceExisting = false>
  67686. class SolidColourEdgeTableRenderer
  67687. {
  67688. public:
  67689. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67690. : data (data_),
  67691. sourceColour (colour)
  67692. {
  67693. if (sizeof (PixelType) == 3)
  67694. {
  67695. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67696. && sourceColour.getGreen() == sourceColour.getBlue();
  67697. filler[0].set (sourceColour);
  67698. filler[1].set (sourceColour);
  67699. filler[2].set (sourceColour);
  67700. filler[3].set (sourceColour);
  67701. }
  67702. }
  67703. forcedinline void setEdgeTableYPos (const int y) throw()
  67704. {
  67705. linePixels = (PixelType*) data.getLinePointer (y);
  67706. }
  67707. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67708. {
  67709. if (replaceExisting)
  67710. linePixels[x].set (sourceColour);
  67711. else
  67712. linePixels[x].blend (sourceColour, alphaLevel);
  67713. }
  67714. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67715. {
  67716. if (replaceExisting)
  67717. linePixels[x].set (sourceColour);
  67718. else
  67719. linePixels[x].blend (sourceColour);
  67720. }
  67721. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67722. {
  67723. PixelARGB p (sourceColour);
  67724. p.multiplyAlpha (alphaLevel);
  67725. PixelType* dest = linePixels + x;
  67726. if (replaceExisting || p.getAlpha() >= 0xff)
  67727. replaceLine (dest, p, width);
  67728. else
  67729. blendLine (dest, p, width);
  67730. }
  67731. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67732. {
  67733. PixelType* dest = linePixels + x;
  67734. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67735. replaceLine (dest, sourceColour, width);
  67736. else
  67737. blendLine (dest, sourceColour, width);
  67738. }
  67739. private:
  67740. const Image::BitmapData& data;
  67741. PixelType* linePixels;
  67742. PixelARGB sourceColour;
  67743. PixelRGB filler [4];
  67744. bool areRGBComponentsEqual;
  67745. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67746. {
  67747. do
  67748. {
  67749. dest->blend (colour);
  67750. ++dest;
  67751. } while (--width > 0);
  67752. }
  67753. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67754. {
  67755. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67756. {
  67757. memset (dest, colour.getRed(), width * 3);
  67758. }
  67759. else
  67760. {
  67761. if (width >> 5)
  67762. {
  67763. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67764. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67765. {
  67766. dest->set (colour);
  67767. ++dest;
  67768. --width;
  67769. }
  67770. while (width > 4)
  67771. {
  67772. int* d = reinterpret_cast<int*> (dest);
  67773. *d++ = intFiller[0];
  67774. *d++ = intFiller[1];
  67775. *d++ = intFiller[2];
  67776. dest = reinterpret_cast<PixelRGB*> (d);
  67777. width -= 4;
  67778. }
  67779. }
  67780. while (--width >= 0)
  67781. {
  67782. dest->set (colour);
  67783. ++dest;
  67784. }
  67785. }
  67786. }
  67787. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67788. {
  67789. memset (dest, colour.getAlpha(), width);
  67790. }
  67791. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67792. {
  67793. do
  67794. {
  67795. dest->set (colour);
  67796. ++dest;
  67797. } while (--width > 0);
  67798. }
  67799. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67800. };
  67801. class LinearGradientPixelGenerator
  67802. {
  67803. public:
  67804. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67805. : lookupTable (lookupTable_), numEntries (numEntries_)
  67806. {
  67807. jassert (numEntries_ >= 0);
  67808. Point<float> p1 (gradient.point1);
  67809. Point<float> p2 (gradient.point2);
  67810. if (! transform.isIdentity())
  67811. {
  67812. const Line<float> l (p2, p1);
  67813. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67814. p1.applyTransform (transform);
  67815. p2.applyTransform (transform);
  67816. p3.applyTransform (transform);
  67817. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67818. }
  67819. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67820. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67821. if (vertical)
  67822. {
  67823. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67824. start = roundToInt (p1.getY() * scale);
  67825. }
  67826. else if (horizontal)
  67827. {
  67828. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67829. start = roundToInt (p1.getX() * scale);
  67830. }
  67831. else
  67832. {
  67833. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67834. yTerm = p1.getY() - p1.getX() / grad;
  67835. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67836. grad *= scale;
  67837. }
  67838. }
  67839. forcedinline void setY (const int y) throw()
  67840. {
  67841. if (vertical)
  67842. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67843. else if (! horizontal)
  67844. start = roundToInt ((y - yTerm) * grad);
  67845. }
  67846. inline const PixelARGB getPixel (const int x) const throw()
  67847. {
  67848. return vertical ? linePix
  67849. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67850. }
  67851. private:
  67852. const PixelARGB* const lookupTable;
  67853. const int numEntries;
  67854. PixelARGB linePix;
  67855. int start, scale;
  67856. double grad, yTerm;
  67857. bool vertical, horizontal;
  67858. enum { numScaleBits = 12 };
  67859. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67860. };
  67861. class RadialGradientPixelGenerator
  67862. {
  67863. public:
  67864. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67865. const PixelARGB* const lookupTable_, const int numEntries_)
  67866. : lookupTable (lookupTable_),
  67867. numEntries (numEntries_),
  67868. gx1 (gradient.point1.getX()),
  67869. gy1 (gradient.point1.getY())
  67870. {
  67871. jassert (numEntries_ >= 0);
  67872. const Point<float> diff (gradient.point1 - gradient.point2);
  67873. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67874. invScale = numEntries / std::sqrt (maxDist);
  67875. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67876. }
  67877. forcedinline void setY (const int y) throw()
  67878. {
  67879. dy = y - gy1;
  67880. dy *= dy;
  67881. }
  67882. inline const PixelARGB getPixel (const int px) const throw()
  67883. {
  67884. double x = px - gx1;
  67885. x *= x;
  67886. x += dy;
  67887. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67888. }
  67889. protected:
  67890. const PixelARGB* const lookupTable;
  67891. const int numEntries;
  67892. const double gx1, gy1;
  67893. double maxDist, invScale, dy;
  67894. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67895. };
  67896. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67897. {
  67898. public:
  67899. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67900. const PixelARGB* const lookupTable_, const int numEntries_)
  67901. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67902. inverseTransform (transform.inverted())
  67903. {
  67904. tM10 = inverseTransform.mat10;
  67905. tM00 = inverseTransform.mat00;
  67906. }
  67907. forcedinline void setY (const int y) throw()
  67908. {
  67909. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67910. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67911. }
  67912. inline const PixelARGB getPixel (const int px) const throw()
  67913. {
  67914. double x = px;
  67915. const double y = tM10 * x + lineYM11;
  67916. x = tM00 * x + lineYM01;
  67917. x *= x;
  67918. x += y * y;
  67919. if (x >= maxDist)
  67920. return lookupTable [numEntries];
  67921. else
  67922. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67923. }
  67924. private:
  67925. double tM10, tM00, lineYM01, lineYM11;
  67926. const AffineTransform inverseTransform;
  67927. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67928. };
  67929. template <class PixelType, class GradientType>
  67930. class GradientEdgeTableRenderer : public GradientType
  67931. {
  67932. public:
  67933. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67934. const PixelARGB* const lookupTable_, const int numEntries_)
  67935. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67936. destData (destData_)
  67937. {
  67938. }
  67939. forcedinline void setEdgeTableYPos (const int y) throw()
  67940. {
  67941. linePixels = (PixelType*) destData.getLinePointer (y);
  67942. GradientType::setY (y);
  67943. }
  67944. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67945. {
  67946. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67947. }
  67948. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67949. {
  67950. linePixels[x].blend (GradientType::getPixel (x));
  67951. }
  67952. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67953. {
  67954. PixelType* dest = linePixels + x;
  67955. if (alphaLevel < 0xff)
  67956. {
  67957. do
  67958. {
  67959. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67960. } while (--width > 0);
  67961. }
  67962. else
  67963. {
  67964. do
  67965. {
  67966. (dest++)->blend (GradientType::getPixel (x++));
  67967. } while (--width > 0);
  67968. }
  67969. }
  67970. void handleEdgeTableLineFull (int x, int width) const throw()
  67971. {
  67972. PixelType* dest = linePixels + x;
  67973. do
  67974. {
  67975. (dest++)->blend (GradientType::getPixel (x++));
  67976. } while (--width > 0);
  67977. }
  67978. private:
  67979. const Image::BitmapData& destData;
  67980. PixelType* linePixels;
  67981. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67982. };
  67983. namespace RenderingHelpers
  67984. {
  67985. forcedinline int safeModulo (int n, const int divisor) throw()
  67986. {
  67987. jassert (divisor > 0);
  67988. n %= divisor;
  67989. return (n < 0) ? (n + divisor) : n;
  67990. }
  67991. }
  67992. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67993. class ImageFillEdgeTableRenderer
  67994. {
  67995. public:
  67996. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67997. const Image::BitmapData& srcData_,
  67998. const int extraAlpha_,
  67999. const int x, const int y)
  68000. : destData (destData_),
  68001. srcData (srcData_),
  68002. extraAlpha (extraAlpha_ + 1),
  68003. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  68004. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  68005. {
  68006. }
  68007. forcedinline void setEdgeTableYPos (int y) throw()
  68008. {
  68009. linePixels = (DestPixelType*) destData.getLinePointer (y);
  68010. y -= yOffset;
  68011. if (repeatPattern)
  68012. {
  68013. jassert (y >= 0);
  68014. y %= srcData.height;
  68015. }
  68016. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  68017. }
  68018. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  68019. {
  68020. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  68021. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  68022. }
  68023. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  68024. {
  68025. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  68026. }
  68027. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  68028. {
  68029. DestPixelType* dest = linePixels + x;
  68030. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  68031. x -= xOffset;
  68032. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  68033. if (alphaLevel < 0xfe)
  68034. {
  68035. do
  68036. {
  68037. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  68038. } while (--width > 0);
  68039. }
  68040. else
  68041. {
  68042. if (repeatPattern)
  68043. {
  68044. do
  68045. {
  68046. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  68047. } while (--width > 0);
  68048. }
  68049. else
  68050. {
  68051. copyRow (dest, sourceLineStart + x, width);
  68052. }
  68053. }
  68054. }
  68055. void handleEdgeTableLineFull (int x, int width) const throw()
  68056. {
  68057. DestPixelType* dest = linePixels + x;
  68058. x -= xOffset;
  68059. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  68060. if (extraAlpha < 0xfe)
  68061. {
  68062. do
  68063. {
  68064. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  68065. } while (--width > 0);
  68066. }
  68067. else
  68068. {
  68069. if (repeatPattern)
  68070. {
  68071. do
  68072. {
  68073. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  68074. } while (--width > 0);
  68075. }
  68076. else
  68077. {
  68078. copyRow (dest, sourceLineStart + x, width);
  68079. }
  68080. }
  68081. }
  68082. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  68083. {
  68084. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  68085. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  68086. uint8* mask = (uint8*) (s + x - xOffset);
  68087. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  68088. mask += PixelARGB::indexA;
  68089. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  68090. }
  68091. private:
  68092. const Image::BitmapData& destData;
  68093. const Image::BitmapData& srcData;
  68094. const int extraAlpha, xOffset, yOffset;
  68095. DestPixelType* linePixels;
  68096. SrcPixelType* sourceLineStart;
  68097. template <class PixelType1, class PixelType2>
  68098. static forcedinline void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  68099. {
  68100. do
  68101. {
  68102. dest++ ->blend (*src++);
  68103. } while (--width > 0);
  68104. }
  68105. static forcedinline void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  68106. {
  68107. memcpy (dest, src, width * sizeof (PixelRGB));
  68108. }
  68109. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  68110. };
  68111. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  68112. class TransformedImageFillEdgeTableRenderer
  68113. {
  68114. public:
  68115. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  68116. const Image::BitmapData& srcData_,
  68117. const AffineTransform& transform,
  68118. const int extraAlpha_,
  68119. const bool betterQuality_)
  68120. : interpolator (transform,
  68121. betterQuality_ ? 0.5f : 0.0f,
  68122. betterQuality_ ? -128 : 0),
  68123. destData (destData_),
  68124. srcData (srcData_),
  68125. extraAlpha (extraAlpha_ + 1),
  68126. betterQuality (betterQuality_),
  68127. maxX (srcData_.width - 1),
  68128. maxY (srcData_.height - 1),
  68129. scratchSize (2048)
  68130. {
  68131. scratchBuffer.malloc (scratchSize);
  68132. }
  68133. forcedinline void setEdgeTableYPos (const int newY) throw()
  68134. {
  68135. y = newY;
  68136. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  68137. }
  68138. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  68139. {
  68140. SrcPixelType p;
  68141. generate (&p, x, 1);
  68142. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  68143. }
  68144. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  68145. {
  68146. SrcPixelType p;
  68147. generate (&p, x, 1);
  68148. linePixels[x].blend (p, extraAlpha);
  68149. }
  68150. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  68151. {
  68152. if (width > scratchSize)
  68153. {
  68154. scratchSize = width;
  68155. scratchBuffer.malloc (scratchSize);
  68156. }
  68157. SrcPixelType* span = scratchBuffer;
  68158. generate (span, x, width);
  68159. DestPixelType* dest = linePixels + x;
  68160. alphaLevel *= extraAlpha;
  68161. alphaLevel >>= 8;
  68162. if (alphaLevel < 0xfe)
  68163. {
  68164. do
  68165. {
  68166. dest++ ->blend (*span++, alphaLevel);
  68167. } while (--width > 0);
  68168. }
  68169. else
  68170. {
  68171. do
  68172. {
  68173. dest++ ->blend (*span++);
  68174. } while (--width > 0);
  68175. }
  68176. }
  68177. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  68178. {
  68179. handleEdgeTableLine (x, width, 255);
  68180. }
  68181. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  68182. {
  68183. if (width > scratchSize)
  68184. {
  68185. scratchSize = width;
  68186. scratchBuffer.malloc (scratchSize);
  68187. }
  68188. y = y_;
  68189. generate (scratchBuffer.getData(), x, width);
  68190. et.clipLineToMask (x, y_,
  68191. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  68192. sizeof (SrcPixelType), width);
  68193. }
  68194. private:
  68195. template <class PixelType>
  68196. void generate (PixelType* dest, const int x, int numPixels) throw()
  68197. {
  68198. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  68199. do
  68200. {
  68201. int hiResX, hiResY;
  68202. this->interpolator.next (hiResX, hiResY);
  68203. int loResX = hiResX >> 8;
  68204. int loResY = hiResY >> 8;
  68205. if (repeatPattern)
  68206. {
  68207. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  68208. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  68209. }
  68210. if (betterQuality)
  68211. {
  68212. if (isPositiveAndBelow (loResX, maxX))
  68213. {
  68214. if (isPositiveAndBelow (loResY, maxY))
  68215. {
  68216. // In the centre of the image..
  68217. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  68218. hiResX & 255, hiResY & 255);
  68219. ++dest;
  68220. continue;
  68221. }
  68222. else
  68223. {
  68224. // At a top or bottom edge..
  68225. if (! repeatPattern)
  68226. {
  68227. if (loResY < 0)
  68228. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255);
  68229. else
  68230. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255);
  68231. ++dest;
  68232. continue;
  68233. }
  68234. }
  68235. }
  68236. else
  68237. {
  68238. if (isPositiveAndBelow (loResY, maxY))
  68239. {
  68240. // At a left or right hand edge..
  68241. if (! repeatPattern)
  68242. {
  68243. if (loResX < 0)
  68244. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255);
  68245. else
  68246. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255);
  68247. ++dest;
  68248. continue;
  68249. }
  68250. }
  68251. }
  68252. }
  68253. if (! repeatPattern)
  68254. {
  68255. if (loResX < 0) loResX = 0;
  68256. if (loResY < 0) loResY = 0;
  68257. if (loResX > maxX) loResX = maxX;
  68258. if (loResY > maxY) loResY = maxY;
  68259. }
  68260. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  68261. ++dest;
  68262. } while (--numPixels > 0);
  68263. }
  68264. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  68265. {
  68266. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  68267. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  68268. c[0] += weight * src[0];
  68269. c[1] += weight * src[1];
  68270. c[2] += weight * src[2];
  68271. c[3] += weight * src[3];
  68272. weight = subPixelX * (256 - subPixelY);
  68273. c[0] += weight * src[4];
  68274. c[1] += weight * src[5];
  68275. c[2] += weight * src[6];
  68276. c[3] += weight * src[7];
  68277. src += this->srcData.lineStride;
  68278. weight = (256 - subPixelX) * subPixelY;
  68279. c[0] += weight * src[0];
  68280. c[1] += weight * src[1];
  68281. c[2] += weight * src[2];
  68282. c[3] += weight * src[3];
  68283. weight = subPixelX * subPixelY;
  68284. c[0] += weight * src[4];
  68285. c[1] += weight * src[5];
  68286. c[2] += weight * src[6];
  68287. c[3] += weight * src[7];
  68288. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  68289. (uint8) (c[PixelARGB::indexR] >> 16),
  68290. (uint8) (c[PixelARGB::indexG] >> 16),
  68291. (uint8) (c[PixelARGB::indexB] >> 16));
  68292. }
  68293. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX) throw()
  68294. {
  68295. uint32 c[4] = { 128, 128, 128, 128 };
  68296. uint32 weight = 256 - subPixelX;
  68297. c[0] += weight * src[0];
  68298. c[1] += weight * src[1];
  68299. c[2] += weight * src[2];
  68300. c[3] += weight * src[3];
  68301. weight = subPixelX;
  68302. c[0] += weight * src[4];
  68303. c[1] += weight * src[5];
  68304. c[2] += weight * src[6];
  68305. c[3] += weight * src[7];
  68306. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 8),
  68307. (uint8) (c[PixelARGB::indexR] >> 8),
  68308. (uint8) (c[PixelARGB::indexG] >> 8),
  68309. (uint8) (c[PixelARGB::indexB] >> 8));
  68310. }
  68311. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY) throw()
  68312. {
  68313. uint32 c[4] = { 128, 128, 128, 128 };
  68314. uint32 weight = 256 - subPixelY;
  68315. c[0] += weight * src[0];
  68316. c[1] += weight * src[1];
  68317. c[2] += weight * src[2];
  68318. c[3] += weight * src[3];
  68319. src += this->srcData.lineStride;
  68320. weight = subPixelY;
  68321. c[0] += weight * src[0];
  68322. c[1] += weight * src[1];
  68323. c[2] += weight * src[2];
  68324. c[3] += weight * src[3];
  68325. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 8),
  68326. (uint8) (c[PixelARGB::indexR] >> 8),
  68327. (uint8) (c[PixelARGB::indexG] >> 8),
  68328. (uint8) (c[PixelARGB::indexB] >> 8));
  68329. }
  68330. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  68331. {
  68332. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  68333. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  68334. c[0] += weight * src[0];
  68335. c[1] += weight * src[1];
  68336. c[2] += weight * src[2];
  68337. weight = subPixelX * (256 - subPixelY);
  68338. c[0] += weight * src[3];
  68339. c[1] += weight * src[4];
  68340. c[2] += weight * src[5];
  68341. src += this->srcData.lineStride;
  68342. weight = (256 - subPixelX) * subPixelY;
  68343. c[0] += weight * src[0];
  68344. c[1] += weight * src[1];
  68345. c[2] += weight * src[2];
  68346. weight = subPixelX * subPixelY;
  68347. c[0] += weight * src[3];
  68348. c[1] += weight * src[4];
  68349. c[2] += weight * src[5];
  68350. dest->setARGB ((uint8) 255,
  68351. (uint8) (c[PixelRGB::indexR] >> 16),
  68352. (uint8) (c[PixelRGB::indexG] >> 16),
  68353. (uint8) (c[PixelRGB::indexB] >> 16));
  68354. }
  68355. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX) throw()
  68356. {
  68357. uint32 c[3] = { 128, 128, 128 };
  68358. const uint32 weight = 256 - subPixelX;
  68359. c[0] += weight * src[0];
  68360. c[1] += weight * src[1];
  68361. c[2] += weight * src[2];
  68362. c[0] += subPixelX * src[3];
  68363. c[1] += subPixelX * src[4];
  68364. c[2] += subPixelX * src[5];
  68365. dest->setARGB ((uint8) 255,
  68366. (uint8) (c[PixelRGB::indexR] >> 8),
  68367. (uint8) (c[PixelRGB::indexG] >> 8),
  68368. (uint8) (c[PixelRGB::indexB] >> 8));
  68369. }
  68370. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY) throw()
  68371. {
  68372. uint32 c[3] = { 128, 128, 128 };
  68373. const uint32 weight = 256 - subPixelY;
  68374. c[0] += weight * src[0];
  68375. c[1] += weight * src[1];
  68376. c[2] += weight * src[2];
  68377. src += this->srcData.lineStride;
  68378. c[0] += subPixelY * src[0];
  68379. c[1] += subPixelY * src[1];
  68380. c[2] += subPixelY * src[2];
  68381. dest->setARGB ((uint8) 255,
  68382. (uint8) (c[PixelRGB::indexR] >> 8),
  68383. (uint8) (c[PixelRGB::indexG] >> 8),
  68384. (uint8) (c[PixelRGB::indexB] >> 8));
  68385. }
  68386. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  68387. {
  68388. uint32 c = 256 * 128;
  68389. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  68390. c += src[1] * (subPixelX * (256 - subPixelY));
  68391. src += this->srcData.lineStride;
  68392. c += src[0] * ((256 - subPixelX) * subPixelY);
  68393. c += src[1] * (subPixelX * subPixelY);
  68394. *((uint8*) dest) = (uint8) (c >> 16);
  68395. }
  68396. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX) throw()
  68397. {
  68398. uint32 c = 128;
  68399. c += src[0] * (256 - subPixelX);
  68400. c += src[1] * subPixelX;
  68401. *((uint8*) dest) = (uint8) (c >> 8);
  68402. }
  68403. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY) throw()
  68404. {
  68405. uint32 c = 128;
  68406. c += src[0] * (256 - subPixelY);
  68407. src += this->srcData.lineStride;
  68408. c += src[0] * subPixelY;
  68409. *((uint8*) dest) = (uint8) (c >> 8);
  68410. }
  68411. class TransformedImageSpanInterpolator
  68412. {
  68413. public:
  68414. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  68415. : inverseTransform (transform.inverted()),
  68416. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  68417. {}
  68418. void setStartOfLine (float x, float y, const int numPixels) throw()
  68419. {
  68420. jassert (numPixels > 0);
  68421. x += pixelOffset;
  68422. y += pixelOffset;
  68423. float x1 = x, y1 = y;
  68424. x += numPixels;
  68425. inverseTransform.transformPoints (x1, y1, x, y);
  68426. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  68427. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  68428. }
  68429. void next (int& x, int& y) throw()
  68430. {
  68431. x = xBresenham.n;
  68432. xBresenham.stepToNext();
  68433. y = yBresenham.n;
  68434. yBresenham.stepToNext();
  68435. }
  68436. private:
  68437. class BresenhamInterpolator
  68438. {
  68439. public:
  68440. BresenhamInterpolator() throw() {}
  68441. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  68442. {
  68443. numSteps = numSteps_;
  68444. step = (n2 - n1) / numSteps;
  68445. remainder = modulo = (n2 - n1) % numSteps;
  68446. n = n1 + pixelOffsetInt;
  68447. if (modulo <= 0)
  68448. {
  68449. modulo += numSteps;
  68450. remainder += numSteps;
  68451. --step;
  68452. }
  68453. modulo -= numSteps;
  68454. }
  68455. forcedinline void stepToNext() throw()
  68456. {
  68457. modulo += remainder;
  68458. n += step;
  68459. if (modulo > 0)
  68460. {
  68461. modulo -= numSteps;
  68462. ++n;
  68463. }
  68464. }
  68465. int n;
  68466. private:
  68467. int numSteps, step, modulo, remainder;
  68468. };
  68469. const AffineTransform inverseTransform;
  68470. BresenhamInterpolator xBresenham, yBresenham;
  68471. const float pixelOffset;
  68472. const int pixelOffsetInt;
  68473. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  68474. };
  68475. TransformedImageSpanInterpolator interpolator;
  68476. const Image::BitmapData& destData;
  68477. const Image::BitmapData& srcData;
  68478. const int extraAlpha;
  68479. const bool betterQuality;
  68480. const int maxX, maxY;
  68481. int y;
  68482. DestPixelType* linePixels;
  68483. HeapBlock <SrcPixelType> scratchBuffer;
  68484. int scratchSize;
  68485. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  68486. };
  68487. class ClipRegionBase : public ReferenceCountedObject
  68488. {
  68489. public:
  68490. ClipRegionBase() {}
  68491. virtual ~ClipRegionBase() {}
  68492. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68493. virtual const Ptr clone() const = 0;
  68494. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68495. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68496. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68497. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68498. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68499. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68500. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68501. virtual const Ptr translated (const Point<int>& delta) = 0;
  68502. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68503. virtual const Rectangle<int> getClipBounds() const = 0;
  68504. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68505. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68506. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68507. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68508. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68509. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68510. protected:
  68511. template <class Iterator>
  68512. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68513. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68514. {
  68515. switch (destData.pixelFormat)
  68516. {
  68517. case Image::ARGB:
  68518. switch (srcData.pixelFormat)
  68519. {
  68520. case Image::ARGB:
  68521. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68522. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68523. break;
  68524. case Image::RGB:
  68525. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68526. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68527. break;
  68528. default:
  68529. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68530. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68531. break;
  68532. }
  68533. break;
  68534. case Image::RGB:
  68535. switch (srcData.pixelFormat)
  68536. {
  68537. case Image::ARGB:
  68538. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68539. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68540. break;
  68541. case Image::RGB:
  68542. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68543. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68544. break;
  68545. default:
  68546. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68547. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68548. break;
  68549. }
  68550. break;
  68551. default:
  68552. switch (srcData.pixelFormat)
  68553. {
  68554. case Image::ARGB:
  68555. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68556. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68557. break;
  68558. case Image::RGB:
  68559. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68560. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68561. break;
  68562. default:
  68563. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68564. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68565. break;
  68566. }
  68567. break;
  68568. }
  68569. }
  68570. template <class Iterator>
  68571. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68572. {
  68573. switch (destData.pixelFormat)
  68574. {
  68575. case Image::ARGB:
  68576. switch (srcData.pixelFormat)
  68577. {
  68578. case Image::ARGB:
  68579. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68580. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68581. break;
  68582. case Image::RGB:
  68583. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68584. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68585. break;
  68586. default:
  68587. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68588. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68589. break;
  68590. }
  68591. break;
  68592. case Image::RGB:
  68593. switch (srcData.pixelFormat)
  68594. {
  68595. case Image::ARGB:
  68596. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68597. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68598. break;
  68599. case Image::RGB:
  68600. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68601. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68602. break;
  68603. default:
  68604. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68605. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68606. break;
  68607. }
  68608. break;
  68609. default:
  68610. switch (srcData.pixelFormat)
  68611. {
  68612. case Image::ARGB:
  68613. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68614. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68615. break;
  68616. case Image::RGB:
  68617. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68618. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68619. break;
  68620. default:
  68621. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68622. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68623. break;
  68624. }
  68625. break;
  68626. }
  68627. }
  68628. template <class Iterator, class DestPixelType>
  68629. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68630. {
  68631. jassert (destData.pixelStride == sizeof (DestPixelType));
  68632. if (replaceContents)
  68633. {
  68634. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68635. iter.iterate (r);
  68636. }
  68637. else
  68638. {
  68639. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68640. iter.iterate (r);
  68641. }
  68642. }
  68643. template <class Iterator, class DestPixelType>
  68644. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68645. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68646. {
  68647. jassert (destData.pixelStride == sizeof (DestPixelType));
  68648. if (g.isRadial)
  68649. {
  68650. if (isIdentity)
  68651. {
  68652. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68653. iter.iterate (renderer);
  68654. }
  68655. else
  68656. {
  68657. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68658. iter.iterate (renderer);
  68659. }
  68660. }
  68661. else
  68662. {
  68663. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68664. iter.iterate (renderer);
  68665. }
  68666. }
  68667. };
  68668. class ClipRegion_EdgeTable : public ClipRegionBase
  68669. {
  68670. public:
  68671. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68672. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68673. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68674. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68675. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68676. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68677. ~ClipRegion_EdgeTable() {}
  68678. const Ptr clone() const
  68679. {
  68680. return new ClipRegion_EdgeTable (*this);
  68681. }
  68682. const Ptr applyClipTo (const Ptr& target) const
  68683. {
  68684. return target->clipToEdgeTable (edgeTable);
  68685. }
  68686. const Ptr clipToRectangle (const Rectangle<int>& r)
  68687. {
  68688. edgeTable.clipToRectangle (r);
  68689. return edgeTable.isEmpty() ? 0 : this;
  68690. }
  68691. const Ptr clipToRectangleList (const RectangleList& r)
  68692. {
  68693. RectangleList inverse (edgeTable.getMaximumBounds());
  68694. if (inverse.subtract (r))
  68695. for (RectangleList::Iterator iter (inverse); iter.next();)
  68696. edgeTable.excludeRectangle (*iter.getRectangle());
  68697. return edgeTable.isEmpty() ? 0 : this;
  68698. }
  68699. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68700. {
  68701. edgeTable.excludeRectangle (r);
  68702. return edgeTable.isEmpty() ? 0 : this;
  68703. }
  68704. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68705. {
  68706. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68707. edgeTable.clipToEdgeTable (et);
  68708. return edgeTable.isEmpty() ? 0 : this;
  68709. }
  68710. const Ptr clipToEdgeTable (const EdgeTable& et)
  68711. {
  68712. edgeTable.clipToEdgeTable (et);
  68713. return edgeTable.isEmpty() ? 0 : this;
  68714. }
  68715. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68716. {
  68717. const Image::BitmapData srcData (image, Image::BitmapData::readOnly);
  68718. if (transform.isOnlyTranslation())
  68719. {
  68720. // If our translation doesn't involve any distortion, just use a simple blit..
  68721. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68722. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68723. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68724. {
  68725. const int imageX = ((tx + 128) >> 8);
  68726. const int imageY = ((ty + 128) >> 8);
  68727. if (image.getFormat() == Image::ARGB)
  68728. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68729. else
  68730. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68731. return edgeTable.isEmpty() ? 0 : this;
  68732. }
  68733. }
  68734. if (transform.isSingularity())
  68735. return 0;
  68736. {
  68737. Path p;
  68738. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68739. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68740. edgeTable.clipToEdgeTable (et2);
  68741. }
  68742. if (! edgeTable.isEmpty())
  68743. {
  68744. if (image.getFormat() == Image::ARGB)
  68745. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68746. else
  68747. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68748. }
  68749. return edgeTable.isEmpty() ? 0 : this;
  68750. }
  68751. const Ptr translated (const Point<int>& delta)
  68752. {
  68753. edgeTable.translate ((float) delta.getX(), delta.getY());
  68754. return edgeTable.isEmpty() ? 0 : this;
  68755. }
  68756. bool clipRegionIntersects (const Rectangle<int>& r) const
  68757. {
  68758. return edgeTable.getMaximumBounds().intersects (r);
  68759. }
  68760. const Rectangle<int> getClipBounds() const
  68761. {
  68762. return edgeTable.getMaximumBounds();
  68763. }
  68764. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68765. {
  68766. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68767. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68768. if (! clipped.isEmpty())
  68769. {
  68770. ClipRegion_EdgeTable et (clipped);
  68771. et.edgeTable.clipToEdgeTable (edgeTable);
  68772. et.fillAllWithColour (destData, colour, replaceContents);
  68773. }
  68774. }
  68775. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68776. {
  68777. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68778. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68779. if (! clipped.isEmpty())
  68780. {
  68781. ClipRegion_EdgeTable et (clipped);
  68782. et.edgeTable.clipToEdgeTable (edgeTable);
  68783. et.fillAllWithColour (destData, colour, false);
  68784. }
  68785. }
  68786. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68787. {
  68788. switch (destData.pixelFormat)
  68789. {
  68790. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68791. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68792. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68793. }
  68794. }
  68795. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68796. {
  68797. HeapBlock <PixelARGB> lookupTable;
  68798. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68799. jassert (numLookupEntries > 0);
  68800. switch (destData.pixelFormat)
  68801. {
  68802. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68803. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68804. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68805. }
  68806. }
  68807. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68808. {
  68809. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68810. }
  68811. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68812. {
  68813. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68814. }
  68815. EdgeTable edgeTable;
  68816. private:
  68817. template <class SrcPixelType>
  68818. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68819. {
  68820. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68821. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68822. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68823. edgeTable.getMaximumBounds().getWidth());
  68824. }
  68825. template <class SrcPixelType>
  68826. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68827. {
  68828. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68829. edgeTable.clipToRectangle (r);
  68830. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68831. for (int y = 0; y < r.getHeight(); ++y)
  68832. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68833. }
  68834. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68835. };
  68836. class ClipRegion_RectangleList : public ClipRegionBase
  68837. {
  68838. public:
  68839. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68840. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68841. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68842. ~ClipRegion_RectangleList() {}
  68843. const Ptr clone() const
  68844. {
  68845. return new ClipRegion_RectangleList (*this);
  68846. }
  68847. const Ptr applyClipTo (const Ptr& target) const
  68848. {
  68849. return target->clipToRectangleList (clip);
  68850. }
  68851. const Ptr clipToRectangle (const Rectangle<int>& r)
  68852. {
  68853. clip.clipTo (r);
  68854. return clip.isEmpty() ? 0 : this;
  68855. }
  68856. const Ptr clipToRectangleList (const RectangleList& r)
  68857. {
  68858. clip.clipTo (r);
  68859. return clip.isEmpty() ? 0 : this;
  68860. }
  68861. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68862. {
  68863. clip.subtract (r);
  68864. return clip.isEmpty() ? 0 : this;
  68865. }
  68866. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68867. {
  68868. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68869. }
  68870. const Ptr clipToEdgeTable (const EdgeTable& et)
  68871. {
  68872. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68873. }
  68874. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68875. {
  68876. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68877. }
  68878. const Ptr translated (const Point<int>& delta)
  68879. {
  68880. clip.offsetAll (delta.getX(), delta.getY());
  68881. return clip.isEmpty() ? 0 : this;
  68882. }
  68883. bool clipRegionIntersects (const Rectangle<int>& r) const
  68884. {
  68885. return clip.intersects (r);
  68886. }
  68887. const Rectangle<int> getClipBounds() const
  68888. {
  68889. return clip.getBounds();
  68890. }
  68891. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68892. {
  68893. SubRectangleIterator iter (clip, area);
  68894. switch (destData.pixelFormat)
  68895. {
  68896. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68897. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68898. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68899. }
  68900. }
  68901. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68902. {
  68903. SubRectangleIteratorFloat iter (clip, area);
  68904. switch (destData.pixelFormat)
  68905. {
  68906. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68907. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68908. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68909. }
  68910. }
  68911. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68912. {
  68913. switch (destData.pixelFormat)
  68914. {
  68915. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68916. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68917. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68918. }
  68919. }
  68920. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68921. {
  68922. HeapBlock <PixelARGB> lookupTable;
  68923. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68924. jassert (numLookupEntries > 0);
  68925. switch (destData.pixelFormat)
  68926. {
  68927. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68928. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68929. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68930. }
  68931. }
  68932. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68933. {
  68934. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68935. }
  68936. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68937. {
  68938. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68939. }
  68940. RectangleList clip;
  68941. template <class Renderer>
  68942. void iterate (Renderer& r) const throw()
  68943. {
  68944. RectangleList::Iterator iter (clip);
  68945. while (iter.next())
  68946. {
  68947. const Rectangle<int> rect (*iter.getRectangle());
  68948. const int x = rect.getX();
  68949. const int w = rect.getWidth();
  68950. jassert (w > 0);
  68951. const int bottom = rect.getBottom();
  68952. for (int y = rect.getY(); y < bottom; ++y)
  68953. {
  68954. r.setEdgeTableYPos (y);
  68955. r.handleEdgeTableLineFull (x, w);
  68956. }
  68957. }
  68958. }
  68959. private:
  68960. class SubRectangleIterator
  68961. {
  68962. public:
  68963. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68964. : clip (clip_), area (area_)
  68965. {
  68966. }
  68967. template <class Renderer>
  68968. void iterate (Renderer& r) const throw()
  68969. {
  68970. RectangleList::Iterator iter (clip);
  68971. while (iter.next())
  68972. {
  68973. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68974. if (! rect.isEmpty())
  68975. {
  68976. const int x = rect.getX();
  68977. const int w = rect.getWidth();
  68978. const int bottom = rect.getBottom();
  68979. for (int y = rect.getY(); y < bottom; ++y)
  68980. {
  68981. r.setEdgeTableYPos (y);
  68982. r.handleEdgeTableLineFull (x, w);
  68983. }
  68984. }
  68985. }
  68986. }
  68987. private:
  68988. const RectangleList& clip;
  68989. const Rectangle<int> area;
  68990. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68991. };
  68992. class SubRectangleIteratorFloat
  68993. {
  68994. public:
  68995. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68996. : clip (clip_), area (area_)
  68997. {
  68998. }
  68999. template <class Renderer>
  69000. void iterate (Renderer& r) const throw()
  69001. {
  69002. int left = roundToInt (area.getX() * 256.0f);
  69003. int top = roundToInt (area.getY() * 256.0f);
  69004. int right = roundToInt (area.getRight() * 256.0f);
  69005. int bottom = roundToInt (area.getBottom() * 256.0f);
  69006. int totalTop, totalLeft, totalBottom, totalRight;
  69007. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  69008. if ((top >> 8) == (bottom >> 8))
  69009. {
  69010. topAlpha = bottom - top;
  69011. bottomAlpha = 0;
  69012. totalTop = top >> 8;
  69013. totalBottom = bottom = top = totalTop + 1;
  69014. }
  69015. else
  69016. {
  69017. if ((top & 255) == 0)
  69018. {
  69019. topAlpha = 0;
  69020. top = totalTop = (top >> 8);
  69021. }
  69022. else
  69023. {
  69024. topAlpha = 255 - (top & 255);
  69025. totalTop = (top >> 8);
  69026. top = totalTop + 1;
  69027. }
  69028. bottomAlpha = bottom & 255;
  69029. bottom >>= 8;
  69030. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  69031. }
  69032. if ((left >> 8) == (right >> 8))
  69033. {
  69034. leftAlpha = right - left;
  69035. rightAlpha = 0;
  69036. totalLeft = (left >> 8);
  69037. totalRight = right = left = totalLeft + 1;
  69038. }
  69039. else
  69040. {
  69041. if ((left & 255) == 0)
  69042. {
  69043. leftAlpha = 0;
  69044. left = totalLeft = (left >> 8);
  69045. }
  69046. else
  69047. {
  69048. leftAlpha = 255 - (left & 255);
  69049. totalLeft = (left >> 8);
  69050. left = totalLeft + 1;
  69051. }
  69052. rightAlpha = right & 255;
  69053. right >>= 8;
  69054. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  69055. }
  69056. RectangleList::Iterator iter (clip);
  69057. while (iter.next())
  69058. {
  69059. const int clipLeft = iter.getRectangle()->getX();
  69060. const int clipRight = iter.getRectangle()->getRight();
  69061. const int clipTop = iter.getRectangle()->getY();
  69062. const int clipBottom = iter.getRectangle()->getBottom();
  69063. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  69064. {
  69065. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  69066. {
  69067. if (topAlpha != 0 && totalTop >= clipTop)
  69068. {
  69069. r.setEdgeTableYPos (totalTop);
  69070. r.handleEdgeTablePixel (left, topAlpha);
  69071. }
  69072. const int endY = jmin (bottom, clipBottom);
  69073. for (int y = jmax (clipTop, top); y < endY; ++y)
  69074. {
  69075. r.setEdgeTableYPos (y);
  69076. r.handleEdgeTablePixelFull (left);
  69077. }
  69078. if (bottomAlpha != 0 && bottom < clipBottom)
  69079. {
  69080. r.setEdgeTableYPos (bottom);
  69081. r.handleEdgeTablePixel (left, bottomAlpha);
  69082. }
  69083. }
  69084. else
  69085. {
  69086. const int clippedLeft = jmax (left, clipLeft);
  69087. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  69088. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  69089. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  69090. if (topAlpha != 0 && totalTop >= clipTop)
  69091. {
  69092. r.setEdgeTableYPos (totalTop);
  69093. if (doLeftAlpha)
  69094. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  69095. if (clippedWidth > 0)
  69096. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  69097. if (doRightAlpha)
  69098. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  69099. }
  69100. const int endY = jmin (bottom, clipBottom);
  69101. for (int y = jmax (clipTop, top); y < endY; ++y)
  69102. {
  69103. r.setEdgeTableYPos (y);
  69104. if (doLeftAlpha)
  69105. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  69106. if (clippedWidth > 0)
  69107. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  69108. if (doRightAlpha)
  69109. r.handleEdgeTablePixel (right, rightAlpha);
  69110. }
  69111. if (bottomAlpha != 0 && bottom < clipBottom)
  69112. {
  69113. r.setEdgeTableYPos (bottom);
  69114. if (doLeftAlpha)
  69115. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  69116. if (clippedWidth > 0)
  69117. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  69118. if (doRightAlpha)
  69119. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  69120. }
  69121. }
  69122. }
  69123. }
  69124. }
  69125. private:
  69126. const RectangleList& clip;
  69127. const Rectangle<float>& area;
  69128. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  69129. };
  69130. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  69131. };
  69132. }
  69133. class LowLevelGraphicsSoftwareRenderer::SavedState
  69134. {
  69135. public:
  69136. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  69137. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  69138. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  69139. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  69140. {
  69141. }
  69142. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  69143. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  69144. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  69145. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  69146. {
  69147. }
  69148. SavedState (const SavedState& other)
  69149. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  69150. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  69151. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  69152. interpolationQuality (other.interpolationQuality)
  69153. {
  69154. }
  69155. void setOrigin (const int x, const int y) throw()
  69156. {
  69157. if (isOnlyTranslated)
  69158. {
  69159. xOffset += x;
  69160. yOffset += y;
  69161. }
  69162. else
  69163. {
  69164. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  69165. }
  69166. }
  69167. void addTransform (const AffineTransform& t)
  69168. {
  69169. if ((! isOnlyTranslated)
  69170. || (! t.isOnlyTranslation())
  69171. || (int) (t.getTranslationX() * 256.0f) != 0
  69172. || (int) (t.getTranslationY() * 256.0f) != 0)
  69173. {
  69174. complexTransform = getTransformWith (t);
  69175. isOnlyTranslated = false;
  69176. }
  69177. else
  69178. {
  69179. xOffset += (int) t.getTranslationX();
  69180. yOffset += (int) t.getTranslationY();
  69181. }
  69182. }
  69183. float getScaleFactor() const
  69184. {
  69185. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  69186. }
  69187. bool clipToRectangle (const Rectangle<int>& r)
  69188. {
  69189. if (clip != 0)
  69190. {
  69191. if (isOnlyTranslated)
  69192. {
  69193. cloneClipIfMultiplyReferenced();
  69194. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  69195. }
  69196. else
  69197. {
  69198. Path p;
  69199. p.addRectangle (r);
  69200. clipToPath (p, AffineTransform::identity);
  69201. }
  69202. }
  69203. return clip != 0;
  69204. }
  69205. bool clipToRectangleList (const RectangleList& r)
  69206. {
  69207. if (clip != 0)
  69208. {
  69209. if (isOnlyTranslated)
  69210. {
  69211. cloneClipIfMultiplyReferenced();
  69212. RectangleList offsetList (r);
  69213. offsetList.offsetAll (xOffset, yOffset);
  69214. clip = clip->clipToRectangleList (offsetList);
  69215. }
  69216. else
  69217. {
  69218. clipToPath (r.toPath(), AffineTransform::identity);
  69219. }
  69220. }
  69221. return clip != 0;
  69222. }
  69223. bool excludeClipRectangle (const Rectangle<int>& r)
  69224. {
  69225. if (clip != 0)
  69226. {
  69227. cloneClipIfMultiplyReferenced();
  69228. if (isOnlyTranslated)
  69229. {
  69230. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  69231. }
  69232. else
  69233. {
  69234. Path p;
  69235. p.addRectangle (r.toFloat());
  69236. p.applyTransform (complexTransform);
  69237. p.addRectangle (clip->getClipBounds().toFloat());
  69238. p.setUsingNonZeroWinding (false);
  69239. clip = clip->clipToPath (p, AffineTransform::identity);
  69240. }
  69241. }
  69242. return clip != 0;
  69243. }
  69244. void clipToPath (const Path& p, const AffineTransform& transform)
  69245. {
  69246. if (clip != 0)
  69247. {
  69248. cloneClipIfMultiplyReferenced();
  69249. clip = clip->clipToPath (p, getTransformWith (transform));
  69250. }
  69251. }
  69252. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  69253. {
  69254. if (clip != 0)
  69255. {
  69256. if (sourceImage.hasAlphaChannel())
  69257. {
  69258. cloneClipIfMultiplyReferenced();
  69259. clip = clip->clipToImageAlpha (sourceImage, getTransformWith (t),
  69260. interpolationQuality != Graphics::lowResamplingQuality);
  69261. }
  69262. else
  69263. {
  69264. Path p;
  69265. p.addRectangle (sourceImage.getBounds());
  69266. clipToPath (p, t);
  69267. }
  69268. }
  69269. }
  69270. bool clipRegionIntersects (const Rectangle<int>& r) const
  69271. {
  69272. if (clip != 0)
  69273. {
  69274. if (isOnlyTranslated)
  69275. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  69276. else
  69277. return getClipBounds().intersects (r);
  69278. }
  69279. return false;
  69280. }
  69281. const Rectangle<int> getUntransformedClipBounds() const
  69282. {
  69283. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  69284. }
  69285. const Rectangle<int> getClipBounds() const
  69286. {
  69287. if (clip != 0)
  69288. {
  69289. if (isOnlyTranslated)
  69290. return clip->getClipBounds().translated (-xOffset, -yOffset);
  69291. else
  69292. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  69293. }
  69294. return Rectangle<int>();
  69295. }
  69296. SavedState* beginTransparencyLayer (float opacity)
  69297. {
  69298. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  69299. SavedState* s = new SavedState (*this);
  69300. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  69301. s->compositionAlpha = opacity;
  69302. if (s->isOnlyTranslated)
  69303. {
  69304. s->xOffset -= layerBounds.getX();
  69305. s->yOffset -= layerBounds.getY();
  69306. }
  69307. else
  69308. {
  69309. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -layerBounds.getX(),
  69310. (float) -layerBounds.getY()));
  69311. }
  69312. s->cloneClipIfMultiplyReferenced();
  69313. s->clip = s->clip->translated (-layerBounds.getPosition());
  69314. return s;
  69315. }
  69316. void endTransparencyLayer (SavedState& layerState)
  69317. {
  69318. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  69319. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  69320. g->setOpacity (layerState.compositionAlpha);
  69321. g->drawImage (layerState.image, AffineTransform::translation ((float) layerBounds.getX(),
  69322. (float) layerBounds.getY()), false);
  69323. }
  69324. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  69325. {
  69326. if (clip != 0)
  69327. {
  69328. if (isOnlyTranslated)
  69329. {
  69330. if (fillType.isColour())
  69331. {
  69332. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  69333. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  69334. }
  69335. else
  69336. {
  69337. const Rectangle<int> totalClip (clip->getClipBounds());
  69338. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  69339. if (! clipped.isEmpty())
  69340. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  69341. }
  69342. }
  69343. else
  69344. {
  69345. Path p;
  69346. p.addRectangle (r);
  69347. fillPath (p, AffineTransform::identity);
  69348. }
  69349. }
  69350. }
  69351. void fillRect (const Rectangle<float>& r)
  69352. {
  69353. if (clip != 0)
  69354. {
  69355. if (isOnlyTranslated)
  69356. {
  69357. if (fillType.isColour())
  69358. {
  69359. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  69360. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  69361. }
  69362. else
  69363. {
  69364. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  69365. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  69366. if (! clipped.isEmpty())
  69367. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  69368. }
  69369. }
  69370. else
  69371. {
  69372. Path p;
  69373. p.addRectangle (r);
  69374. fillPath (p, AffineTransform::identity);
  69375. }
  69376. }
  69377. }
  69378. void fillPath (const Path& path, const AffineTransform& transform)
  69379. {
  69380. if (clip != 0)
  69381. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  69382. }
  69383. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  69384. {
  69385. jassert (isOnlyTranslated);
  69386. if (clip != 0)
  69387. {
  69388. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  69389. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  69390. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  69391. fillShape (shapeToFill, false);
  69392. }
  69393. }
  69394. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  69395. {
  69396. jassert (clip != 0);
  69397. shapeToFill = clip->applyClipTo (shapeToFill);
  69398. if (shapeToFill != 0)
  69399. {
  69400. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  69401. if (fillType.isGradient())
  69402. {
  69403. jassert (! replaceContents); // that option is just for solid colours
  69404. ColourGradient g2 (*(fillType.gradient));
  69405. g2.multiplyOpacity (fillType.getOpacity());
  69406. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  69407. const bool isIdentity = transform.isOnlyTranslation();
  69408. if (isIdentity)
  69409. {
  69410. // If our translation doesn't involve any distortion, we can speed it up..
  69411. g2.point1.applyTransform (transform);
  69412. g2.point2.applyTransform (transform);
  69413. transform = AffineTransform::identity;
  69414. }
  69415. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  69416. }
  69417. else if (fillType.isTiledImage())
  69418. {
  69419. renderImage (fillType.image, fillType.transform, shapeToFill);
  69420. }
  69421. else
  69422. {
  69423. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  69424. }
  69425. }
  69426. }
  69427. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  69428. {
  69429. const AffineTransform transform (getTransformWith (t));
  69430. const Image::BitmapData destData (image, Image::BitmapData::readWrite);
  69431. const Image::BitmapData srcData (sourceImage, Image::BitmapData::readOnly);
  69432. const int alpha = fillType.colour.getAlpha();
  69433. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69434. if (transform.isOnlyTranslation())
  69435. {
  69436. // If our translation doesn't involve any distortion, just use a simple blit..
  69437. int tx = (int) (transform.getTranslationX() * 256.0f);
  69438. int ty = (int) (transform.getTranslationY() * 256.0f);
  69439. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69440. {
  69441. tx = ((tx + 128) >> 8);
  69442. ty = ((ty + 128) >> 8);
  69443. if (tiledFillClipRegion != 0)
  69444. {
  69445. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69446. }
  69447. else
  69448. {
  69449. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  69450. c = clip->applyClipTo (c);
  69451. if (c != 0)
  69452. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69453. }
  69454. return;
  69455. }
  69456. }
  69457. if (transform.isSingularity())
  69458. return;
  69459. if (tiledFillClipRegion != 0)
  69460. {
  69461. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69462. }
  69463. else
  69464. {
  69465. Path p;
  69466. p.addRectangle (sourceImage.getBounds());
  69467. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69468. c = c->clipToPath (p, transform);
  69469. if (c != 0)
  69470. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69471. }
  69472. }
  69473. Image image;
  69474. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69475. private:
  69476. AffineTransform complexTransform;
  69477. int xOffset, yOffset;
  69478. float compositionAlpha;
  69479. public:
  69480. bool isOnlyTranslated;
  69481. Font font;
  69482. FillType fillType;
  69483. Graphics::ResamplingQuality interpolationQuality;
  69484. private:
  69485. void cloneClipIfMultiplyReferenced()
  69486. {
  69487. if (clip->getReferenceCount() > 1)
  69488. clip = clip->clone();
  69489. }
  69490. const AffineTransform getTransform() const
  69491. {
  69492. if (isOnlyTranslated)
  69493. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  69494. return complexTransform;
  69495. }
  69496. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  69497. {
  69498. if (isOnlyTranslated)
  69499. return userTransform.translated ((float) xOffset, (float) yOffset);
  69500. return userTransform.followedBy (complexTransform);
  69501. }
  69502. SavedState& operator= (const SavedState&);
  69503. };
  69504. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69505. : image (image_),
  69506. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  69507. {
  69508. }
  69509. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69510. const RectangleList& initialClip)
  69511. : image (image_),
  69512. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  69513. {
  69514. }
  69515. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69516. {
  69517. }
  69518. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69519. {
  69520. return false;
  69521. }
  69522. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69523. {
  69524. currentState->setOrigin (x, y);
  69525. }
  69526. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  69527. {
  69528. currentState->addTransform (transform);
  69529. }
  69530. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  69531. {
  69532. return currentState->getScaleFactor();
  69533. }
  69534. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69535. {
  69536. return currentState->clipToRectangle (r);
  69537. }
  69538. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69539. {
  69540. return currentState->clipToRectangleList (clipRegion);
  69541. }
  69542. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69543. {
  69544. currentState->excludeClipRectangle (r);
  69545. }
  69546. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69547. {
  69548. currentState->clipToPath (path, transform);
  69549. }
  69550. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69551. {
  69552. currentState->clipToImageAlpha (sourceImage, transform);
  69553. }
  69554. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69555. {
  69556. return currentState->clipRegionIntersects (r);
  69557. }
  69558. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69559. {
  69560. return currentState->getClipBounds();
  69561. }
  69562. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69563. {
  69564. return currentState->clip == 0;
  69565. }
  69566. void LowLevelGraphicsSoftwareRenderer::saveState()
  69567. {
  69568. stateStack.add (new SavedState (*currentState));
  69569. }
  69570. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69571. {
  69572. SavedState* const top = stateStack.getLast();
  69573. if (top != 0)
  69574. {
  69575. currentState = top;
  69576. stateStack.removeLast (1, false);
  69577. }
  69578. else
  69579. {
  69580. jassertfalse; // trying to pop with an empty stack!
  69581. }
  69582. }
  69583. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  69584. {
  69585. saveState();
  69586. currentState = currentState->beginTransparencyLayer (opacity);
  69587. }
  69588. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  69589. {
  69590. const ScopedPointer<SavedState> layer (currentState);
  69591. restoreState();
  69592. currentState->endTransparencyLayer (*layer);
  69593. }
  69594. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69595. {
  69596. currentState->fillType = fillType;
  69597. }
  69598. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69599. {
  69600. currentState->fillType.setOpacity (newOpacity);
  69601. }
  69602. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69603. {
  69604. currentState->interpolationQuality = quality;
  69605. }
  69606. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69607. {
  69608. currentState->fillRect (r, replaceExistingContents);
  69609. }
  69610. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69611. {
  69612. currentState->fillPath (path, transform);
  69613. }
  69614. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69615. {
  69616. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  69617. }
  69618. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69619. {
  69620. Path p;
  69621. p.addLineSegment (line, 1.0f);
  69622. fillPath (p, AffineTransform::identity);
  69623. }
  69624. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69625. {
  69626. if (bottom > top)
  69627. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69628. }
  69629. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69630. {
  69631. if (right > left)
  69632. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69633. }
  69634. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69635. {
  69636. public:
  69637. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69638. void draw (SavedState& state, float x, const float y) const
  69639. {
  69640. if (snapToIntegerCoordinate)
  69641. x = std::floor (x + 0.5f);
  69642. if (edgeTable != 0)
  69643. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69644. }
  69645. void generate (const Font& newFont, const int glyphNumber)
  69646. {
  69647. font = newFont;
  69648. snapToIntegerCoordinate = newFont.getTypeface()->isHinted();
  69649. glyph = glyphNumber;
  69650. const float fontHeight = font.getHeight();
  69651. edgeTable = font.getTypeface()->getEdgeTableForGlyph (glyphNumber,
  69652. AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69653. #if JUCE_MAC || JUCE_IOS
  69654. .translated (0.0f, -0.5f)
  69655. #endif
  69656. );
  69657. }
  69658. Font font;
  69659. int glyph, lastAccessCount;
  69660. bool snapToIntegerCoordinate;
  69661. private:
  69662. ScopedPointer <EdgeTable> edgeTable;
  69663. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69664. };
  69665. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69666. {
  69667. public:
  69668. GlyphCache()
  69669. : accessCounter (0), hits (0), misses (0)
  69670. {
  69671. addNewGlyphSlots (120);
  69672. }
  69673. ~GlyphCache()
  69674. {
  69675. clearSingletonInstance();
  69676. }
  69677. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69678. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69679. {
  69680. ++accessCounter;
  69681. int oldestCounter = std::numeric_limits<int>::max();
  69682. CachedGlyph* oldest = 0;
  69683. for (int i = glyphs.size(); --i >= 0;)
  69684. {
  69685. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69686. if (glyph->glyph == glyphNumber && glyph->font == font)
  69687. {
  69688. ++hits;
  69689. glyph->lastAccessCount = accessCounter;
  69690. glyph->draw (state, x, y);
  69691. return;
  69692. }
  69693. if (glyph->lastAccessCount <= oldestCounter)
  69694. {
  69695. oldestCounter = glyph->lastAccessCount;
  69696. oldest = glyph;
  69697. }
  69698. }
  69699. if (hits + ++misses > (glyphs.size() << 4))
  69700. {
  69701. if (misses * 2 > hits)
  69702. addNewGlyphSlots (32);
  69703. hits = misses = 0;
  69704. oldest = glyphs.getLast();
  69705. }
  69706. jassert (oldest != 0);
  69707. oldest->lastAccessCount = accessCounter;
  69708. oldest->generate (font, glyphNumber);
  69709. oldest->draw (state, x, y);
  69710. }
  69711. private:
  69712. friend class OwnedArray <CachedGlyph>;
  69713. OwnedArray <CachedGlyph> glyphs;
  69714. int accessCounter, hits, misses;
  69715. void addNewGlyphSlots (int num)
  69716. {
  69717. while (--num >= 0)
  69718. glyphs.add (new CachedGlyph());
  69719. }
  69720. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69721. };
  69722. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69723. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69724. {
  69725. currentState->font = newFont;
  69726. }
  69727. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69728. {
  69729. return currentState->font;
  69730. }
  69731. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69732. {
  69733. Font& f = currentState->font;
  69734. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69735. {
  69736. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69737. transform.getTranslationX(),
  69738. transform.getTranslationY());
  69739. }
  69740. else
  69741. {
  69742. const float fontHeight = f.getHeight();
  69743. const ScopedPointer<EdgeTable> et (f.getTypeface()->getEdgeTableForGlyph (glyphNumber,
  69744. AffineTransform::scale (fontHeight * f.getHorizontalScale(), fontHeight)
  69745. .followedBy (transform)));
  69746. if (et != 0)
  69747. currentState->fillEdgeTable (*et, 0.0f, 0);
  69748. }
  69749. }
  69750. #if JUCE_MSVC
  69751. #pragma warning (pop)
  69752. #if JUCE_DEBUG
  69753. #pragma optimize ("", on) // resets optimisations to the project defaults
  69754. #endif
  69755. #endif
  69756. END_JUCE_NAMESPACE
  69757. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69758. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69759. BEGIN_JUCE_NAMESPACE
  69760. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69761. : flags (other.flags)
  69762. {
  69763. }
  69764. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69765. {
  69766. flags = other.flags;
  69767. return *this;
  69768. }
  69769. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69770. const double dx, const double dy, const double dw, const double dh) const throw()
  69771. {
  69772. if (w == 0 || h == 0)
  69773. return;
  69774. if ((flags & stretchToFit) != 0)
  69775. {
  69776. x = dx;
  69777. y = dy;
  69778. w = dw;
  69779. h = dh;
  69780. }
  69781. else
  69782. {
  69783. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69784. : jmin (dw / w, dh / h);
  69785. if ((flags & onlyReduceInSize) != 0)
  69786. scale = jmin (scale, 1.0);
  69787. if ((flags & onlyIncreaseInSize) != 0)
  69788. scale = jmax (scale, 1.0);
  69789. w *= scale;
  69790. h *= scale;
  69791. if ((flags & xLeft) != 0)
  69792. x = dx;
  69793. else if ((flags & xRight) != 0)
  69794. x = dx + dw - w;
  69795. else
  69796. x = dx + (dw - w) * 0.5;
  69797. if ((flags & yTop) != 0)
  69798. y = dy;
  69799. else if ((flags & yBottom) != 0)
  69800. y = dy + dh - h;
  69801. else
  69802. y = dy + (dh - h) * 0.5;
  69803. }
  69804. }
  69805. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69806. {
  69807. if (source.isEmpty())
  69808. return AffineTransform::identity;
  69809. float newX = destination.getX();
  69810. float newY = destination.getY();
  69811. float scaleX = destination.getWidth() / source.getWidth();
  69812. float scaleY = destination.getHeight() / source.getHeight();
  69813. if ((flags & stretchToFit) == 0)
  69814. {
  69815. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69816. : jmin (scaleX, scaleY);
  69817. if ((flags & onlyReduceInSize) != 0)
  69818. scaleX = jmin (scaleX, 1.0f);
  69819. if ((flags & onlyIncreaseInSize) != 0)
  69820. scaleX = jmax (scaleX, 1.0f);
  69821. scaleY = scaleX;
  69822. if ((flags & xRight) != 0)
  69823. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69824. else if ((flags & xLeft) == 0)
  69825. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69826. if ((flags & yBottom) != 0)
  69827. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69828. else if ((flags & yTop) == 0)
  69829. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69830. }
  69831. return AffineTransform::translation (-source.getX(), -source.getY())
  69832. .scaled (scaleX, scaleY)
  69833. .translated (newX, newY);
  69834. }
  69835. END_JUCE_NAMESPACE
  69836. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69837. /*** Start of inlined file: juce_Drawable.cpp ***/
  69838. BEGIN_JUCE_NAMESPACE
  69839. Drawable::Drawable()
  69840. {
  69841. setInterceptsMouseClicks (false, false);
  69842. setPaintingIsUnclipped (true);
  69843. }
  69844. Drawable::~Drawable()
  69845. {
  69846. }
  69847. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69848. {
  69849. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69850. }
  69851. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69852. {
  69853. Graphics::ScopedSaveState ss (g);
  69854. const float oldOpacity = getAlpha();
  69855. setAlpha (opacity);
  69856. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69857. (float) -originRelativeToComponent.getY())
  69858. .followedBy (getTransform())
  69859. .followedBy (transform));
  69860. if (! g.isClipEmpty())
  69861. paintEntireComponent (g, false);
  69862. setAlpha (oldOpacity);
  69863. }
  69864. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69865. {
  69866. draw (g, opacity, AffineTransform::translation (x, y));
  69867. }
  69868. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69869. {
  69870. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69871. }
  69872. DrawableComposite* Drawable::getParent() const
  69873. {
  69874. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69875. }
  69876. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69877. {
  69878. g.setOrigin (originRelativeToComponent.getX(),
  69879. originRelativeToComponent.getY());
  69880. }
  69881. void Drawable::parentHierarchyChanged()
  69882. {
  69883. setBoundsToEnclose (getDrawableBounds());
  69884. }
  69885. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69886. {
  69887. Drawable* const parent = getParent();
  69888. Point<int> parentOrigin;
  69889. if (parent != 0)
  69890. parentOrigin = parent->originRelativeToComponent;
  69891. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69892. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69893. setBounds (newBounds);
  69894. }
  69895. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69896. {
  69897. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69898. }
  69899. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69900. {
  69901. if (! area.isEmpty())
  69902. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69903. }
  69904. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69905. {
  69906. Drawable* result = 0;
  69907. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69908. if (image.isValid())
  69909. {
  69910. DrawableImage* const di = new DrawableImage();
  69911. di->setImage (image);
  69912. result = di;
  69913. }
  69914. else
  69915. {
  69916. const String asString (String::createStringFromData (data, (int) numBytes));
  69917. XmlDocument doc (asString);
  69918. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69919. if (outer != 0 && outer->hasTagName ("svg"))
  69920. {
  69921. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69922. if (svg != 0)
  69923. result = Drawable::createFromSVG (*svg);
  69924. }
  69925. }
  69926. return result;
  69927. }
  69928. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69929. {
  69930. MemoryOutputStream mo;
  69931. mo.writeFromInputStream (dataSource, -1);
  69932. return createFromImageData (mo.getData(), mo.getDataSize());
  69933. }
  69934. Drawable* Drawable::createFromImageFile (const File& file)
  69935. {
  69936. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69937. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69938. }
  69939. template <class DrawableClass>
  69940. class DrawableTypeHandler : public ComponentBuilder::TypeHandler
  69941. {
  69942. public:
  69943. DrawableTypeHandler()
  69944. : ComponentBuilder::TypeHandler (DrawableClass::valueTreeType)
  69945. {
  69946. }
  69947. Component* addNewComponentFromState (const ValueTree& state, Component* parent)
  69948. {
  69949. DrawableClass* const d = new DrawableClass();
  69950. if (parent != 0)
  69951. parent->addAndMakeVisible (d);
  69952. updateComponentFromState (d, state);
  69953. return d;
  69954. }
  69955. void updateComponentFromState (Component* component, const ValueTree& state)
  69956. {
  69957. DrawableClass* const d = dynamic_cast <DrawableClass*> (component);
  69958. jassert (d != 0);
  69959. d->refreshFromValueTree (state, *this->getBuilder());
  69960. }
  69961. };
  69962. void Drawable::registerDrawableTypeHandlers (ComponentBuilder& builder)
  69963. {
  69964. builder.registerTypeHandler (new DrawableTypeHandler <DrawablePath>());
  69965. builder.registerTypeHandler (new DrawableTypeHandler <DrawableComposite>());
  69966. builder.registerTypeHandler (new DrawableTypeHandler <DrawableRectangle>());
  69967. builder.registerTypeHandler (new DrawableTypeHandler <DrawableImage>());
  69968. builder.registerTypeHandler (new DrawableTypeHandler <DrawableText>());
  69969. }
  69970. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider)
  69971. {
  69972. ComponentBuilder builder (tree);
  69973. builder.setImageProvider (imageProvider);
  69974. registerDrawableTypeHandlers (builder);
  69975. ScopedPointer<Component> comp (builder.createComponent());
  69976. Drawable* const d = dynamic_cast<Drawable*> (static_cast <Component*> (comp));
  69977. if (d != 0)
  69978. comp.release();
  69979. return d;
  69980. }
  69981. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69982. : state (state_)
  69983. {
  69984. }
  69985. const String Drawable::ValueTreeWrapperBase::getID() const
  69986. {
  69987. return state [ComponentBuilder::idProperty];
  69988. }
  69989. void Drawable::ValueTreeWrapperBase::setID (const String& newID)
  69990. {
  69991. if (newID.isEmpty())
  69992. state.removeProperty (ComponentBuilder::idProperty, 0);
  69993. else
  69994. state.setProperty (ComponentBuilder::idProperty, newID, 0);
  69995. }
  69996. END_JUCE_NAMESPACE
  69997. /*** End of inlined file: juce_Drawable.cpp ***/
  69998. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69999. BEGIN_JUCE_NAMESPACE
  70000. DrawableShape::DrawableShape()
  70001. : strokeType (0.0f),
  70002. mainFill (Colours::black),
  70003. strokeFill (Colours::black)
  70004. {
  70005. }
  70006. DrawableShape::DrawableShape (const DrawableShape& other)
  70007. : strokeType (other.strokeType),
  70008. mainFill (other.mainFill),
  70009. strokeFill (other.strokeFill)
  70010. {
  70011. }
  70012. DrawableShape::~DrawableShape()
  70013. {
  70014. }
  70015. class DrawableShape::RelativePositioner : public RelativeCoordinatePositionerBase
  70016. {
  70017. public:
  70018. RelativePositioner (DrawableShape& component_, const DrawableShape::RelativeFillType& fill_, bool isMainFill_)
  70019. : RelativeCoordinatePositionerBase (component_),
  70020. owner (component_),
  70021. fill (fill_),
  70022. isMainFill (isMainFill_)
  70023. {
  70024. }
  70025. bool registerCoordinates()
  70026. {
  70027. bool ok = addPoint (fill.gradientPoint1);
  70028. ok = addPoint (fill.gradientPoint2) && ok;
  70029. return addPoint (fill.gradientPoint3) && ok;
  70030. }
  70031. void applyToComponentBounds()
  70032. {
  70033. ComponentScope scope (owner);
  70034. if (isMainFill ? owner.mainFill.recalculateCoords (&scope)
  70035. : owner.strokeFill.recalculateCoords (&scope))
  70036. owner.repaint();
  70037. }
  70038. void applyNewBounds (const Rectangle<int>&)
  70039. {
  70040. jassertfalse; // drawables can't be resized directly!
  70041. }
  70042. private:
  70043. DrawableShape& owner;
  70044. const DrawableShape::RelativeFillType fill;
  70045. const bool isMainFill;
  70046. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70047. };
  70048. void DrawableShape::setFill (const FillType& newFill)
  70049. {
  70050. setFill (RelativeFillType (newFill));
  70051. }
  70052. void DrawableShape::setStrokeFill (const FillType& newFill)
  70053. {
  70054. setStrokeFill (RelativeFillType (newFill));
  70055. }
  70056. void DrawableShape::setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  70057. ScopedPointer<RelativeCoordinatePositionerBase>& positioner)
  70058. {
  70059. if (fill != newFill)
  70060. {
  70061. fill = newFill;
  70062. positioner = 0;
  70063. if (fill.isDynamic())
  70064. {
  70065. positioner = new RelativePositioner (*this, fill, true);
  70066. positioner->apply();
  70067. }
  70068. else
  70069. {
  70070. fill.recalculateCoords (0);
  70071. }
  70072. repaint();
  70073. }
  70074. }
  70075. void DrawableShape::setFill (const RelativeFillType& newFill)
  70076. {
  70077. setFillInternal (mainFill, newFill, mainFillPositioner);
  70078. }
  70079. void DrawableShape::setStrokeFill (const RelativeFillType& newFill)
  70080. {
  70081. setFillInternal (strokeFill, newFill, strokeFillPositioner);
  70082. }
  70083. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  70084. {
  70085. if (strokeType != newStrokeType)
  70086. {
  70087. strokeType = newStrokeType;
  70088. strokeChanged();
  70089. }
  70090. }
  70091. void DrawableShape::setStrokeThickness (const float newThickness)
  70092. {
  70093. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  70094. }
  70095. bool DrawableShape::isStrokeVisible() const throw()
  70096. {
  70097. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.fill.isInvisible();
  70098. }
  70099. void DrawableShape::refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider* imageProvider)
  70100. {
  70101. setFill (newState.getFill (FillAndStrokeState::fill, imageProvider));
  70102. setStrokeFill (newState.getFill (FillAndStrokeState::stroke, imageProvider));
  70103. }
  70104. void DrawableShape::writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  70105. {
  70106. state.setFill (FillAndStrokeState::fill, mainFill, imageProvider, undoManager);
  70107. state.setFill (FillAndStrokeState::stroke, strokeFill, imageProvider, undoManager);
  70108. state.setStrokeType (strokeType, undoManager);
  70109. }
  70110. void DrawableShape::paint (Graphics& g)
  70111. {
  70112. transformContextToCorrectOrigin (g);
  70113. g.setFillType (mainFill.fill);
  70114. g.fillPath (path);
  70115. if (isStrokeVisible())
  70116. {
  70117. g.setFillType (strokeFill.fill);
  70118. g.fillPath (strokePath);
  70119. }
  70120. }
  70121. void DrawableShape::pathChanged()
  70122. {
  70123. strokeChanged();
  70124. }
  70125. void DrawableShape::strokeChanged()
  70126. {
  70127. strokePath.clear();
  70128. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  70129. setBoundsToEnclose (getDrawableBounds());
  70130. repaint();
  70131. }
  70132. const Rectangle<float> DrawableShape::getDrawableBounds() const
  70133. {
  70134. if (isStrokeVisible())
  70135. return strokePath.getBounds();
  70136. else
  70137. return path.getBounds();
  70138. }
  70139. bool DrawableShape::hitTest (int x, int y)
  70140. {
  70141. bool allowsClicksOnThisComponent, allowsClicksOnChildComponents;
  70142. getInterceptsMouseClicks (allowsClicksOnThisComponent, allowsClicksOnChildComponents);
  70143. if (! allowsClicksOnThisComponent)
  70144. return false;
  70145. const float globalX = (float) (x - originRelativeToComponent.getX());
  70146. const float globalY = (float) (y - originRelativeToComponent.getY());
  70147. return path.contains (globalX, globalY)
  70148. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  70149. }
  70150. DrawableShape::RelativeFillType::RelativeFillType()
  70151. {
  70152. }
  70153. DrawableShape::RelativeFillType::RelativeFillType (const FillType& fill_)
  70154. : fill (fill_)
  70155. {
  70156. if (fill.isGradient())
  70157. {
  70158. const ColourGradient& g = *fill.gradient;
  70159. gradientPoint1 = g.point1.transformedBy (fill.transform);
  70160. gradientPoint2 = g.point2.transformedBy (fill.transform);
  70161. gradientPoint3 = Point<float> (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  70162. g.point1.getY() + g.point1.getX() - g.point2.getX())
  70163. .transformedBy (fill.transform);
  70164. fill.transform = AffineTransform::identity;
  70165. }
  70166. }
  70167. DrawableShape::RelativeFillType::RelativeFillType (const RelativeFillType& other)
  70168. : fill (other.fill),
  70169. gradientPoint1 (other.gradientPoint1),
  70170. gradientPoint2 (other.gradientPoint2),
  70171. gradientPoint3 (other.gradientPoint3)
  70172. {
  70173. }
  70174. DrawableShape::RelativeFillType& DrawableShape::RelativeFillType::operator= (const RelativeFillType& other)
  70175. {
  70176. fill = other.fill;
  70177. gradientPoint1 = other.gradientPoint1;
  70178. gradientPoint2 = other.gradientPoint2;
  70179. gradientPoint3 = other.gradientPoint3;
  70180. return *this;
  70181. }
  70182. bool DrawableShape::RelativeFillType::operator== (const RelativeFillType& other) const
  70183. {
  70184. return fill == other.fill
  70185. && ((! fill.isGradient())
  70186. || (gradientPoint1 == other.gradientPoint1
  70187. && gradientPoint2 == other.gradientPoint2
  70188. && gradientPoint3 == other.gradientPoint3));
  70189. }
  70190. bool DrawableShape::RelativeFillType::operator!= (const RelativeFillType& other) const
  70191. {
  70192. return ! operator== (other);
  70193. }
  70194. bool DrawableShape::RelativeFillType::recalculateCoords (Expression::Scope* scope)
  70195. {
  70196. if (fill.isGradient())
  70197. {
  70198. const Point<float> g1 (gradientPoint1.resolve (scope));
  70199. const Point<float> g2 (gradientPoint2.resolve (scope));
  70200. AffineTransform t;
  70201. ColourGradient& g = *fill.gradient;
  70202. if (g.isRadial)
  70203. {
  70204. const Point<float> g3 (gradientPoint3.resolve (scope));
  70205. const Point<float> g3Source (g1.getX() + g2.getY() - g1.getY(),
  70206. g1.getY() + g1.getX() - g2.getX());
  70207. t = AffineTransform::fromTargetPoints (g1.getX(), g1.getY(), g1.getX(), g1.getY(),
  70208. g2.getX(), g2.getY(), g2.getX(), g2.getY(),
  70209. g3Source.getX(), g3Source.getY(), g3.getX(), g3.getY());
  70210. }
  70211. if (g.point1 != g1 || g.point2 != g2 || fill.transform != t)
  70212. {
  70213. g.point1 = g1;
  70214. g.point2 = g2;
  70215. fill.transform = t;
  70216. return true;
  70217. }
  70218. }
  70219. return false;
  70220. }
  70221. bool DrawableShape::RelativeFillType::isDynamic() const
  70222. {
  70223. return gradientPoint1.isDynamic() || gradientPoint2.isDynamic() || gradientPoint3.isDynamic();
  70224. }
  70225. void DrawableShape::RelativeFillType::writeTo (ValueTree& v, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  70226. {
  70227. if (fill.isColour())
  70228. {
  70229. v.setProperty (FillAndStrokeState::type, "solid", undoManager);
  70230. v.setProperty (FillAndStrokeState::colour, String::toHexString ((int) fill.colour.getARGB()), undoManager);
  70231. }
  70232. else if (fill.isGradient())
  70233. {
  70234. v.setProperty (FillAndStrokeState::type, "gradient", undoManager);
  70235. v.setProperty (FillAndStrokeState::gradientPoint1, gradientPoint1.toString(), undoManager);
  70236. v.setProperty (FillAndStrokeState::gradientPoint2, gradientPoint2.toString(), undoManager);
  70237. v.setProperty (FillAndStrokeState::gradientPoint3, gradientPoint3.toString(), undoManager);
  70238. const ColourGradient& cg = *fill.gradient;
  70239. v.setProperty (FillAndStrokeState::radial, cg.isRadial, undoManager);
  70240. String s;
  70241. for (int i = 0; i < cg.getNumColours(); ++i)
  70242. s << ' ' << cg.getColourPosition (i)
  70243. << ' ' << String::toHexString ((int) cg.getColour(i).getARGB());
  70244. v.setProperty (FillAndStrokeState::colours, s.trimStart(), undoManager);
  70245. }
  70246. else if (fill.isTiledImage())
  70247. {
  70248. v.setProperty (FillAndStrokeState::type, "image", undoManager);
  70249. if (imageProvider != 0)
  70250. v.setProperty (FillAndStrokeState::imageId, imageProvider->getIdentifierForImage (fill.image), undoManager);
  70251. if (fill.getOpacity() < 1.0f)
  70252. v.setProperty (FillAndStrokeState::imageOpacity, fill.getOpacity(), undoManager);
  70253. else
  70254. v.removeProperty (FillAndStrokeState::imageOpacity, undoManager);
  70255. }
  70256. else
  70257. {
  70258. jassertfalse;
  70259. }
  70260. }
  70261. bool DrawableShape::RelativeFillType::readFrom (const ValueTree& v, ComponentBuilder::ImageProvider* imageProvider)
  70262. {
  70263. const String newType (v [FillAndStrokeState::type].toString());
  70264. if (newType == "solid")
  70265. {
  70266. const String colourString (v [FillAndStrokeState::colour].toString());
  70267. fill.setColour (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  70268. : (uint32) colourString.getHexValue32()));
  70269. return true;
  70270. }
  70271. else if (newType == "gradient")
  70272. {
  70273. ColourGradient g;
  70274. g.isRadial = v [FillAndStrokeState::radial];
  70275. StringArray colourSteps;
  70276. colourSteps.addTokens (v [FillAndStrokeState::colours].toString(), false);
  70277. for (int i = 0; i < colourSteps.size() / 2; ++i)
  70278. g.addColour (colourSteps[i * 2].getDoubleValue(),
  70279. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  70280. fill.setGradient (g);
  70281. gradientPoint1 = RelativePoint (v [FillAndStrokeState::gradientPoint1]);
  70282. gradientPoint2 = RelativePoint (v [FillAndStrokeState::gradientPoint2]);
  70283. gradientPoint3 = RelativePoint (v [FillAndStrokeState::gradientPoint3]);
  70284. return true;
  70285. }
  70286. else if (newType == "image")
  70287. {
  70288. Image im;
  70289. if (imageProvider != 0)
  70290. im = imageProvider->getImageForIdentifier (v [FillAndStrokeState::imageId]);
  70291. fill.setTiledImage (im, AffineTransform::identity);
  70292. fill.setOpacity ((float) v.getProperty (FillAndStrokeState::imageOpacity, 1.0f));
  70293. return true;
  70294. }
  70295. jassertfalse;
  70296. return false;
  70297. }
  70298. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  70299. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  70300. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  70301. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  70302. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  70303. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  70304. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  70305. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  70306. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  70307. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  70308. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  70309. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  70310. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  70311. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  70312. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  70313. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  70314. : Drawable::ValueTreeWrapperBase (state_)
  70315. {
  70316. }
  70317. const DrawableShape::RelativeFillType DrawableShape::FillAndStrokeState::getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider* imageProvider) const
  70318. {
  70319. DrawableShape::RelativeFillType f;
  70320. f.readFrom (state.getChildWithName (fillOrStrokeType), imageProvider);
  70321. return f;
  70322. }
  70323. ValueTree DrawableShape::FillAndStrokeState::getFillState (const Identifier& fillOrStrokeType)
  70324. {
  70325. ValueTree v (state.getChildWithName (fillOrStrokeType));
  70326. if (v.isValid())
  70327. return v;
  70328. setFill (fillOrStrokeType, FillType (Colours::black), 0, 0);
  70329. return getFillState (fillOrStrokeType);
  70330. }
  70331. void DrawableShape::FillAndStrokeState::setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  70332. ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager)
  70333. {
  70334. ValueTree v (state.getOrCreateChildWithName (fillOrStrokeType, undoManager));
  70335. newFill.writeTo (v, imageProvider, undoManager);
  70336. }
  70337. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  70338. {
  70339. const String jointStyleString (state [jointStyle].toString());
  70340. const String capStyleString (state [capStyle].toString());
  70341. return PathStrokeType (state [strokeWidth],
  70342. jointStyleString == "curved" ? PathStrokeType::curved
  70343. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  70344. : PathStrokeType::mitered),
  70345. capStyleString == "square" ? PathStrokeType::square
  70346. : (capStyleString == "round" ? PathStrokeType::rounded
  70347. : PathStrokeType::butt));
  70348. }
  70349. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  70350. {
  70351. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  70352. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  70353. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  70354. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  70355. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  70356. }
  70357. END_JUCE_NAMESPACE
  70358. /*** End of inlined file: juce_DrawableShape.cpp ***/
  70359. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  70360. BEGIN_JUCE_NAMESPACE
  70361. DrawableComposite::DrawableComposite()
  70362. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  70363. updateBoundsReentrant (false)
  70364. {
  70365. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  70366. RelativeCoordinate (100.0),
  70367. RelativeCoordinate (0.0),
  70368. RelativeCoordinate (100.0)));
  70369. }
  70370. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  70371. : bounds (other.bounds),
  70372. markersX (other.markersX),
  70373. markersY (other.markersY),
  70374. updateBoundsReentrant (false)
  70375. {
  70376. for (int i = 0; i < other.getNumChildComponents(); ++i)
  70377. {
  70378. const Drawable* const d = dynamic_cast <const Drawable*> (other.getChildComponent(i));
  70379. if (d != 0)
  70380. addAndMakeVisible (d->createCopy());
  70381. }
  70382. }
  70383. DrawableComposite::~DrawableComposite()
  70384. {
  70385. deleteAllChildren();
  70386. }
  70387. Drawable* DrawableComposite::createCopy() const
  70388. {
  70389. return new DrawableComposite (*this);
  70390. }
  70391. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  70392. {
  70393. Rectangle<float> r;
  70394. for (int i = getNumChildComponents(); --i >= 0;)
  70395. {
  70396. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70397. if (d != 0)
  70398. r = r.getUnion (d->isTransformed() ? d->getDrawableBounds().transformed (d->getTransform())
  70399. : d->getDrawableBounds());
  70400. }
  70401. return r;
  70402. }
  70403. MarkerList* DrawableComposite::getMarkers (bool xAxis)
  70404. {
  70405. return xAxis ? &markersX : &markersY;
  70406. }
  70407. const RelativeRectangle DrawableComposite::getContentArea() const
  70408. {
  70409. jassert (markersX.getNumMarkers() >= 2 && markersX.getMarker (0)->name == contentLeftMarkerName && markersX.getMarker (1)->name == contentRightMarkerName);
  70410. jassert (markersY.getNumMarkers() >= 2 && markersY.getMarker (0)->name == contentTopMarkerName && markersY.getMarker (1)->name == contentBottomMarkerName);
  70411. return RelativeRectangle (markersX.getMarker(0)->position, markersX.getMarker(1)->position,
  70412. markersY.getMarker(0)->position, markersY.getMarker(1)->position);
  70413. }
  70414. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  70415. {
  70416. markersX.setMarker (contentLeftMarkerName, newArea.left);
  70417. markersX.setMarker (contentRightMarkerName, newArea.right);
  70418. markersY.setMarker (contentTopMarkerName, newArea.top);
  70419. markersY.setMarker (contentBottomMarkerName, newArea.bottom);
  70420. }
  70421. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBounds)
  70422. {
  70423. if (bounds != newBounds)
  70424. {
  70425. bounds = newBounds;
  70426. if (bounds.isDynamic())
  70427. {
  70428. Drawable::Positioner<DrawableComposite>* const p = new Drawable::Positioner<DrawableComposite> (*this);
  70429. setPositioner (p);
  70430. p->apply();
  70431. }
  70432. else
  70433. {
  70434. setPositioner (0);
  70435. recalculateCoordinates (0);
  70436. }
  70437. }
  70438. }
  70439. void DrawableComposite::resetBoundingBoxToContentArea()
  70440. {
  70441. const RelativeRectangle content (getContentArea());
  70442. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70443. RelativePoint (content.right, content.top),
  70444. RelativePoint (content.left, content.bottom)));
  70445. }
  70446. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  70447. {
  70448. const Rectangle<float> activeArea (getDrawableBounds());
  70449. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  70450. RelativeCoordinate (activeArea.getRight()),
  70451. RelativeCoordinate (activeArea.getY()),
  70452. RelativeCoordinate (activeArea.getBottom())));
  70453. resetBoundingBoxToContentArea();
  70454. }
  70455. bool DrawableComposite::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70456. {
  70457. bool ok = positioner.addPoint (bounds.topLeft);
  70458. ok = positioner.addPoint (bounds.topRight) && ok;
  70459. return positioner.addPoint (bounds.bottomLeft) && ok;
  70460. }
  70461. void DrawableComposite::recalculateCoordinates (Expression::Scope* scope)
  70462. {
  70463. Point<float> resolved[3];
  70464. bounds.resolveThreePoints (resolved, scope);
  70465. const Rectangle<float> content (getContentArea().resolve (scope));
  70466. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  70467. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  70468. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  70469. if (t.isSingularity())
  70470. t = AffineTransform::identity;
  70471. setTransform (t);
  70472. }
  70473. void DrawableComposite::parentHierarchyChanged()
  70474. {
  70475. DrawableComposite* parent = getParent();
  70476. if (parent != 0)
  70477. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  70478. }
  70479. void DrawableComposite::childBoundsChanged (Component*)
  70480. {
  70481. updateBoundsToFitChildren();
  70482. }
  70483. void DrawableComposite::childrenChanged()
  70484. {
  70485. updateBoundsToFitChildren();
  70486. }
  70487. void DrawableComposite::updateBoundsToFitChildren()
  70488. {
  70489. if (! updateBoundsReentrant)
  70490. {
  70491. const ScopedValueSetter<bool> setter (updateBoundsReentrant, true, false);
  70492. Rectangle<int> childArea;
  70493. for (int i = getNumChildComponents(); --i >= 0;)
  70494. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  70495. const Point<int> delta (childArea.getPosition());
  70496. childArea += getPosition();
  70497. if (childArea != getBounds())
  70498. {
  70499. if (! delta.isOrigin())
  70500. {
  70501. originRelativeToComponent -= delta;
  70502. for (int i = getNumChildComponents(); --i >= 0;)
  70503. {
  70504. Component* const c = getChildComponent(i);
  70505. if (c != 0)
  70506. c->setBounds (c->getBounds() - delta);
  70507. }
  70508. }
  70509. setBounds (childArea);
  70510. }
  70511. }
  70512. }
  70513. const char* const DrawableComposite::contentLeftMarkerName = "left";
  70514. const char* const DrawableComposite::contentRightMarkerName = "right";
  70515. const char* const DrawableComposite::contentTopMarkerName = "top";
  70516. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  70517. const Identifier DrawableComposite::valueTreeType ("Group");
  70518. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70519. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70520. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70521. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70522. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70523. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70524. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70525. : ValueTreeWrapperBase (state_)
  70526. {
  70527. jassert (state.hasType (valueTreeType));
  70528. }
  70529. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70530. {
  70531. return state.getChildWithName (childGroupTag);
  70532. }
  70533. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70534. {
  70535. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70536. }
  70537. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70538. {
  70539. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70540. state.getProperty (topRight, "100, 0"),
  70541. state.getProperty (bottomLeft, "0, 100"));
  70542. }
  70543. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70544. {
  70545. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70546. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70547. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70548. }
  70549. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70550. {
  70551. const RelativeRectangle content (getContentArea());
  70552. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70553. RelativePoint (content.right, content.top),
  70554. RelativePoint (content.left, content.bottom)), undoManager);
  70555. }
  70556. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70557. {
  70558. MarkerList::ValueTreeWrapper markersX (getMarkerList (true));
  70559. MarkerList::ValueTreeWrapper markersY (getMarkerList (false));
  70560. return RelativeRectangle (markersX.getMarker (markersX.getMarkerState (0)).position,
  70561. markersX.getMarker (markersX.getMarkerState (1)).position,
  70562. markersY.getMarker (markersY.getMarkerState (0)).position,
  70563. markersY.getMarker (markersY.getMarkerState (1)).position);
  70564. }
  70565. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70566. {
  70567. MarkerList::ValueTreeWrapper markersX (getMarkerListCreating (true, 0));
  70568. MarkerList::ValueTreeWrapper markersY (getMarkerListCreating (false, 0));
  70569. markersX.setMarker (MarkerList::Marker (contentLeftMarkerName, newArea.left), undoManager);
  70570. markersX.setMarker (MarkerList::Marker (contentRightMarkerName, newArea.right), undoManager);
  70571. markersY.setMarker (MarkerList::Marker (contentTopMarkerName, newArea.top), undoManager);
  70572. markersY.setMarker (MarkerList::Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70573. }
  70574. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70575. {
  70576. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70577. }
  70578. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70579. {
  70580. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70581. }
  70582. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70583. {
  70584. const ValueTreeWrapper wrapper (tree);
  70585. setComponentID (wrapper.getID());
  70586. wrapper.getMarkerList (true).applyTo (markersX);
  70587. wrapper.getMarkerList (false).applyTo (markersY);
  70588. setBoundingBox (wrapper.getBoundingBox());
  70589. builder.updateChildComponents (*this, wrapper.getChildList());
  70590. }
  70591. const ValueTree DrawableComposite::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70592. {
  70593. ValueTree tree (valueTreeType);
  70594. ValueTreeWrapper v (tree);
  70595. v.setID (getComponentID());
  70596. v.setBoundingBox (bounds, 0);
  70597. ValueTree childList (v.getChildListCreating (0));
  70598. for (int i = 0; i < getNumChildComponents(); ++i)
  70599. {
  70600. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70601. jassert (d != 0); // You can't save a mix of Drawables and normal components!
  70602. childList.addChild (d->createValueTree (imageProvider), -1, 0);
  70603. }
  70604. v.getMarkerListCreating (true, 0).readFrom (markersX, 0);
  70605. v.getMarkerListCreating (false, 0).readFrom (markersY, 0);
  70606. return tree;
  70607. }
  70608. END_JUCE_NAMESPACE
  70609. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70610. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70611. BEGIN_JUCE_NAMESPACE
  70612. DrawableImage::DrawableImage()
  70613. : image (0),
  70614. opacity (1.0f),
  70615. overlayColour (0x00000000)
  70616. {
  70617. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70618. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70619. }
  70620. DrawableImage::DrawableImage (const DrawableImage& other)
  70621. : image (other.image),
  70622. opacity (other.opacity),
  70623. overlayColour (other.overlayColour),
  70624. bounds (other.bounds)
  70625. {
  70626. }
  70627. DrawableImage::~DrawableImage()
  70628. {
  70629. }
  70630. void DrawableImage::setImage (const Image& imageToUse)
  70631. {
  70632. image = imageToUse;
  70633. setBounds (imageToUse.getBounds());
  70634. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70635. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70636. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70637. recalculateCoordinates (0);
  70638. repaint();
  70639. }
  70640. void DrawableImage::setOpacity (const float newOpacity)
  70641. {
  70642. opacity = newOpacity;
  70643. }
  70644. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70645. {
  70646. overlayColour = newOverlayColour;
  70647. }
  70648. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70649. {
  70650. if (bounds != newBounds)
  70651. {
  70652. bounds = newBounds;
  70653. if (bounds.isDynamic())
  70654. {
  70655. Drawable::Positioner<DrawableImage>* const p = new Drawable::Positioner<DrawableImage> (*this);
  70656. setPositioner (p);
  70657. p->apply();
  70658. }
  70659. else
  70660. {
  70661. setPositioner (0);
  70662. recalculateCoordinates (0);
  70663. }
  70664. }
  70665. }
  70666. bool DrawableImage::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70667. {
  70668. bool ok = positioner.addPoint (bounds.topLeft);
  70669. ok = positioner.addPoint (bounds.topRight) && ok;
  70670. return positioner.addPoint (bounds.bottomLeft) && ok;
  70671. }
  70672. void DrawableImage::recalculateCoordinates (Expression::Scope* scope)
  70673. {
  70674. if (image.isValid())
  70675. {
  70676. Point<float> resolved[3];
  70677. bounds.resolveThreePoints (resolved, scope);
  70678. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70679. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70680. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70681. tr.getX(), tr.getY(),
  70682. bl.getX(), bl.getY()));
  70683. if (t.isSingularity())
  70684. t = AffineTransform::identity;
  70685. setTransform (t);
  70686. }
  70687. }
  70688. void DrawableImage::paint (Graphics& g)
  70689. {
  70690. if (image.isValid())
  70691. {
  70692. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70693. {
  70694. g.setOpacity (opacity);
  70695. g.drawImageAt (image, 0, 0, false);
  70696. }
  70697. if (! overlayColour.isTransparent())
  70698. {
  70699. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70700. g.drawImageAt (image, 0, 0, true);
  70701. }
  70702. }
  70703. }
  70704. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70705. {
  70706. return image.getBounds().toFloat();
  70707. }
  70708. bool DrawableImage::hitTest (int x, int y) const
  70709. {
  70710. return (! image.isNull())
  70711. && image.getPixelAt (x, y).getAlpha() >= 127;
  70712. }
  70713. Drawable* DrawableImage::createCopy() const
  70714. {
  70715. return new DrawableImage (*this);
  70716. }
  70717. const Identifier DrawableImage::valueTreeType ("Image");
  70718. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70719. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70720. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70721. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70722. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70723. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70724. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70725. : ValueTreeWrapperBase (state_)
  70726. {
  70727. jassert (state.hasType (valueTreeType));
  70728. }
  70729. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70730. {
  70731. return state [image];
  70732. }
  70733. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70734. {
  70735. return state.getPropertyAsValue (image, undoManager);
  70736. }
  70737. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70738. {
  70739. state.setProperty (image, newIdentifier, undoManager);
  70740. }
  70741. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70742. {
  70743. return (float) state.getProperty (opacity, 1.0);
  70744. }
  70745. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70746. {
  70747. if (! state.hasProperty (opacity))
  70748. state.setProperty (opacity, 1.0, undoManager);
  70749. return state.getPropertyAsValue (opacity, undoManager);
  70750. }
  70751. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70752. {
  70753. state.setProperty (opacity, newOpacity, undoManager);
  70754. }
  70755. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70756. {
  70757. return Colour (state [overlay].toString().getHexValue32());
  70758. }
  70759. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70760. {
  70761. if (newColour.isTransparent())
  70762. state.removeProperty (overlay, undoManager);
  70763. else
  70764. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70765. }
  70766. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70767. {
  70768. return state.getPropertyAsValue (overlay, undoManager);
  70769. }
  70770. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70771. {
  70772. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70773. state.getProperty (topRight, "100, 0"),
  70774. state.getProperty (bottomLeft, "0, 100"));
  70775. }
  70776. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70777. {
  70778. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70779. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70780. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70781. }
  70782. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70783. {
  70784. const ValueTreeWrapper controller (tree);
  70785. setComponentID (controller.getID());
  70786. const float newOpacity = controller.getOpacity();
  70787. const Colour newOverlayColour (controller.getOverlayColour());
  70788. Image newImage;
  70789. const var imageIdentifier (controller.getImageIdentifier());
  70790. jassert (builder.getImageProvider() != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70791. if (builder.getImageProvider() != 0)
  70792. newImage = builder.getImageProvider()->getImageForIdentifier (imageIdentifier);
  70793. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70794. if (bounds != newBounds || newOpacity != opacity
  70795. || overlayColour != newOverlayColour || image != newImage)
  70796. {
  70797. repaint();
  70798. opacity = newOpacity;
  70799. overlayColour = newOverlayColour;
  70800. if (image != newImage)
  70801. setImage (newImage);
  70802. setBoundingBox (newBounds);
  70803. }
  70804. }
  70805. const ValueTree DrawableImage::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70806. {
  70807. ValueTree tree (valueTreeType);
  70808. ValueTreeWrapper v (tree);
  70809. v.setID (getComponentID());
  70810. v.setOpacity (opacity, 0);
  70811. v.setOverlayColour (overlayColour, 0);
  70812. v.setBoundingBox (bounds, 0);
  70813. if (image.isValid())
  70814. {
  70815. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70816. if (imageProvider != 0)
  70817. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70818. }
  70819. return tree;
  70820. }
  70821. END_JUCE_NAMESPACE
  70822. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70823. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70824. BEGIN_JUCE_NAMESPACE
  70825. DrawablePath::DrawablePath()
  70826. {
  70827. }
  70828. DrawablePath::DrawablePath (const DrawablePath& other)
  70829. : DrawableShape (other)
  70830. {
  70831. if (other.relativePath != 0)
  70832. setPath (*other.relativePath);
  70833. else
  70834. setPath (other.path);
  70835. }
  70836. DrawablePath::~DrawablePath()
  70837. {
  70838. }
  70839. Drawable* DrawablePath::createCopy() const
  70840. {
  70841. return new DrawablePath (*this);
  70842. }
  70843. void DrawablePath::setPath (const Path& newPath)
  70844. {
  70845. path = newPath;
  70846. pathChanged();
  70847. }
  70848. const Path& DrawablePath::getPath() const
  70849. {
  70850. return path;
  70851. }
  70852. const Path& DrawablePath::getStrokePath() const
  70853. {
  70854. return strokePath;
  70855. }
  70856. void DrawablePath::applyRelativePath (const RelativePointPath& newRelativePath, Expression::Scope* scope)
  70857. {
  70858. Path newPath;
  70859. newRelativePath.createPath (newPath, scope);
  70860. if (path != newPath)
  70861. {
  70862. path.swapWithPath (newPath);
  70863. pathChanged();
  70864. }
  70865. }
  70866. class DrawablePath::RelativePositioner : public RelativeCoordinatePositionerBase
  70867. {
  70868. public:
  70869. RelativePositioner (DrawablePath& component_)
  70870. : RelativeCoordinatePositionerBase (component_),
  70871. owner (component_)
  70872. {
  70873. }
  70874. bool registerCoordinates()
  70875. {
  70876. bool ok = true;
  70877. jassert (owner.relativePath != 0);
  70878. const RelativePointPath& path = *owner.relativePath;
  70879. for (int i = 0; i < path.elements.size(); ++i)
  70880. {
  70881. RelativePointPath::ElementBase* const e = path.elements.getUnchecked(i);
  70882. int numPoints;
  70883. RelativePoint* const points = e->getControlPoints (numPoints);
  70884. for (int j = numPoints; --j >= 0;)
  70885. ok = addPoint (points[j]) && ok;
  70886. }
  70887. return ok;
  70888. }
  70889. void applyToComponentBounds()
  70890. {
  70891. jassert (owner.relativePath != 0);
  70892. ComponentScope scope (getComponent());
  70893. owner.applyRelativePath (*owner.relativePath, &scope);
  70894. }
  70895. void applyNewBounds (const Rectangle<int>&)
  70896. {
  70897. jassertfalse; // drawables can't be resized directly!
  70898. }
  70899. private:
  70900. DrawablePath& owner;
  70901. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70902. };
  70903. void DrawablePath::setPath (const RelativePointPath& newRelativePath)
  70904. {
  70905. if (newRelativePath.containsAnyDynamicPoints())
  70906. {
  70907. if (relativePath == 0 || newRelativePath != *relativePath)
  70908. {
  70909. relativePath = new RelativePointPath (newRelativePath);
  70910. RelativePositioner* const p = new RelativePositioner (*this);
  70911. setPositioner (p);
  70912. p->apply();
  70913. }
  70914. }
  70915. else
  70916. {
  70917. relativePath = 0;
  70918. applyRelativePath (newRelativePath, 0);
  70919. }
  70920. }
  70921. const Identifier DrawablePath::valueTreeType ("Path");
  70922. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70923. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70924. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70925. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70926. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70927. : FillAndStrokeState (state_)
  70928. {
  70929. jassert (state.hasType (valueTreeType));
  70930. }
  70931. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70932. {
  70933. return state.getOrCreateChildWithName (path, 0);
  70934. }
  70935. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70936. {
  70937. return state [nonZeroWinding];
  70938. }
  70939. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70940. {
  70941. state.setProperty (nonZeroWinding, b, undoManager);
  70942. }
  70943. void DrawablePath::ValueTreeWrapper::readFrom (const RelativePointPath& relativePath, UndoManager* undoManager)
  70944. {
  70945. setUsesNonZeroWinding (relativePath.usesNonZeroWinding, undoManager);
  70946. ValueTree pathTree (getPathState());
  70947. pathTree.removeAllChildren (undoManager);
  70948. for (int i = 0; i < relativePath.elements.size(); ++i)
  70949. pathTree.addChild (relativePath.elements.getUnchecked(i)->createTree(), -1, undoManager);
  70950. }
  70951. void DrawablePath::ValueTreeWrapper::writeTo (RelativePointPath& relativePath) const
  70952. {
  70953. relativePath.usesNonZeroWinding = usesNonZeroWinding();
  70954. RelativePoint points[3];
  70955. const ValueTree pathTree (state.getChildWithName (path));
  70956. const int num = pathTree.getNumChildren();
  70957. for (int i = 0; i < num; ++i)
  70958. {
  70959. const Element e (pathTree.getChild(i));
  70960. const int numCps = e.getNumControlPoints();
  70961. for (int j = 0; j < numCps; ++j)
  70962. points[j] = e.getControlPoint (j);
  70963. const Identifier type (e.getType());
  70964. RelativePointPath::ElementBase* newElement = 0;
  70965. if (type == Element::startSubPathElement) newElement = new RelativePointPath::StartSubPath (points[0]);
  70966. else if (type == Element::closeSubPathElement) newElement = new RelativePointPath::CloseSubPath();
  70967. else if (type == Element::lineToElement) newElement = new RelativePointPath::LineTo (points[0]);
  70968. else if (type == Element::quadraticToElement) newElement = new RelativePointPath::QuadraticTo (points[0], points[1]);
  70969. else if (type == Element::cubicToElement) newElement = new RelativePointPath::CubicTo (points[0], points[1], points[2]);
  70970. else jassertfalse;
  70971. relativePath.addElement (newElement);
  70972. }
  70973. }
  70974. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70975. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70976. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70977. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70978. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70979. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70980. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70981. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70982. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70983. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70984. : state (state_)
  70985. {
  70986. }
  70987. DrawablePath::ValueTreeWrapper::Element::~Element()
  70988. {
  70989. }
  70990. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70991. {
  70992. return ValueTreeWrapper (state.getParent().getParent());
  70993. }
  70994. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70995. {
  70996. return Element (state.getSibling (-1));
  70997. }
  70998. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70999. {
  71000. const Identifier i (state.getType());
  71001. if (i == startSubPathElement || i == lineToElement) return 1;
  71002. if (i == quadraticToElement) return 2;
  71003. if (i == cubicToElement) return 3;
  71004. return 0;
  71005. }
  71006. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  71007. {
  71008. jassert (index >= 0 && index < getNumControlPoints());
  71009. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  71010. }
  71011. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  71012. {
  71013. jassert (index >= 0 && index < getNumControlPoints());
  71014. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  71015. }
  71016. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  71017. {
  71018. jassert (index >= 0 && index < getNumControlPoints());
  71019. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  71020. }
  71021. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  71022. {
  71023. const Identifier i (state.getType());
  71024. if (i == startSubPathElement)
  71025. return getControlPoint (0);
  71026. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  71027. return getPreviousElement().getEndPoint();
  71028. }
  71029. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  71030. {
  71031. const Identifier i (state.getType());
  71032. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  71033. if (i == quadraticToElement) return getControlPoint (1);
  71034. if (i == cubicToElement) return getControlPoint (2);
  71035. jassert (i == closeSubPathElement);
  71036. return RelativePoint();
  71037. }
  71038. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::Scope* scope) const
  71039. {
  71040. const Identifier i (state.getType());
  71041. if (i == lineToElement || i == closeSubPathElement)
  71042. return getEndPoint().resolve (scope).getDistanceFrom (getStartPoint().resolve (scope));
  71043. if (i == cubicToElement)
  71044. {
  71045. Path p;
  71046. p.startNewSubPath (getStartPoint().resolve (scope));
  71047. p.cubicTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope), getControlPoint (2).resolve (scope));
  71048. return p.getLength();
  71049. }
  71050. if (i == quadraticToElement)
  71051. {
  71052. Path p;
  71053. p.startNewSubPath (getStartPoint().resolve (scope));
  71054. p.quadraticTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope));
  71055. return p.getLength();
  71056. }
  71057. jassert (i == startSubPathElement);
  71058. return 0;
  71059. }
  71060. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  71061. {
  71062. return state [mode].toString();
  71063. }
  71064. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  71065. {
  71066. if (state.hasType (cubicToElement))
  71067. state.setProperty (mode, newMode, undoManager);
  71068. }
  71069. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  71070. {
  71071. const Identifier i (state.getType());
  71072. if (i == quadraticToElement || i == cubicToElement)
  71073. {
  71074. ValueTree newState (lineToElement);
  71075. Element e (newState);
  71076. e.setControlPoint (0, getEndPoint(), undoManager);
  71077. state = newState;
  71078. }
  71079. }
  71080. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::Scope* scope, UndoManager* undoManager)
  71081. {
  71082. const Identifier i (state.getType());
  71083. if (i == lineToElement || i == quadraticToElement)
  71084. {
  71085. ValueTree newState (cubicToElement);
  71086. Element e (newState);
  71087. const RelativePoint start (getStartPoint());
  71088. const RelativePoint end (getEndPoint());
  71089. const Point<float> startResolved (start.resolve (scope));
  71090. const Point<float> endResolved (end.resolve (scope));
  71091. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  71092. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  71093. e.setControlPoint (2, end, undoManager);
  71094. state = newState;
  71095. }
  71096. }
  71097. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  71098. {
  71099. const Identifier i (state.getType());
  71100. if (i != startSubPathElement)
  71101. {
  71102. ValueTree newState (startSubPathElement);
  71103. Element e (newState);
  71104. e.setControlPoint (0, getEndPoint(), undoManager);
  71105. state = newState;
  71106. }
  71107. }
  71108. namespace DrawablePathHelpers
  71109. {
  71110. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  71111. {
  71112. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  71113. mid2 (points[1] + (points[2] - points[1]) * proportion),
  71114. mid3 (points[2] + (points[3] - points[2]) * proportion);
  71115. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  71116. newCp2 (mid2 + (mid3 - mid2) * proportion);
  71117. return newCp1 + (newCp2 - newCp1) * proportion;
  71118. }
  71119. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  71120. {
  71121. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  71122. mid2 (points[1] + (points[2] - points[1]) * proportion);
  71123. return mid1 + (mid2 - mid1) * proportion;
  71124. }
  71125. }
  71126. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope* scope) const
  71127. {
  71128. using namespace DrawablePathHelpers;
  71129. const Identifier type (state.getType());
  71130. float bestProp = 0;
  71131. if (type == cubicToElement)
  71132. {
  71133. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  71134. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  71135. float bestDistance = std::numeric_limits<float>::max();
  71136. for (int i = 110; --i >= 0;)
  71137. {
  71138. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  71139. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  71140. const float distance = centre.getDistanceFrom (targetPoint);
  71141. if (distance < bestDistance)
  71142. {
  71143. bestProp = prop;
  71144. bestDistance = distance;
  71145. }
  71146. }
  71147. }
  71148. else if (type == quadraticToElement)
  71149. {
  71150. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  71151. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  71152. float bestDistance = std::numeric_limits<float>::max();
  71153. for (int i = 110; --i >= 0;)
  71154. {
  71155. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  71156. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  71157. const float distance = centre.getDistanceFrom (targetPoint);
  71158. if (distance < bestDistance)
  71159. {
  71160. bestProp = prop;
  71161. bestDistance = distance;
  71162. }
  71163. }
  71164. }
  71165. else if (type == lineToElement)
  71166. {
  71167. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  71168. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  71169. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  71170. }
  71171. return bestProp;
  71172. }
  71173. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::Scope* scope, UndoManager* undoManager)
  71174. {
  71175. ValueTree newTree;
  71176. const Identifier type (state.getType());
  71177. if (type == cubicToElement)
  71178. {
  71179. float bestProp = findProportionAlongLine (targetPoint, scope);
  71180. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  71181. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  71182. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  71183. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  71184. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  71185. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  71186. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  71187. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  71188. setControlPoint (0, mid1, undoManager);
  71189. setControlPoint (1, newCp1, undoManager);
  71190. setControlPoint (2, newCentre, undoManager);
  71191. setModeOfEndPoint (roundedMode, undoManager);
  71192. Element newElement (newTree = ValueTree (cubicToElement));
  71193. newElement.setControlPoint (0, newCp2, 0);
  71194. newElement.setControlPoint (1, mid3, 0);
  71195. newElement.setControlPoint (2, rp4, 0);
  71196. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  71197. }
  71198. else if (type == quadraticToElement)
  71199. {
  71200. float bestProp = findProportionAlongLine (targetPoint, scope);
  71201. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  71202. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  71203. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  71204. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  71205. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  71206. setControlPoint (0, mid1, undoManager);
  71207. setControlPoint (1, newCentre, undoManager);
  71208. setModeOfEndPoint (roundedMode, undoManager);
  71209. Element newElement (newTree = ValueTree (quadraticToElement));
  71210. newElement.setControlPoint (0, mid2, 0);
  71211. newElement.setControlPoint (1, rp3, 0);
  71212. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  71213. }
  71214. else if (type == lineToElement)
  71215. {
  71216. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  71217. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  71218. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  71219. setControlPoint (0, newPoint, undoManager);
  71220. Element newElement (newTree = ValueTree (lineToElement));
  71221. newElement.setControlPoint (0, rp2, 0);
  71222. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  71223. }
  71224. else if (type == closeSubPathElement)
  71225. {
  71226. }
  71227. return newTree;
  71228. }
  71229. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  71230. {
  71231. state.getParent().removeChild (state, undoManager);
  71232. }
  71233. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  71234. {
  71235. ValueTreeWrapper v (tree);
  71236. setComponentID (v.getID());
  71237. refreshFillTypes (v, builder.getImageProvider());
  71238. setStrokeType (v.getStrokeType());
  71239. RelativePointPath newRelativePath;
  71240. v.writeTo (newRelativePath);
  71241. setPath (newRelativePath);
  71242. }
  71243. const ValueTree DrawablePath::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  71244. {
  71245. ValueTree tree (valueTreeType);
  71246. ValueTreeWrapper v (tree);
  71247. v.setID (getComponentID());
  71248. writeTo (v, imageProvider, 0);
  71249. if (relativePath != 0)
  71250. v.readFrom (*relativePath, 0);
  71251. else
  71252. v.readFrom (RelativePointPath (path), 0);
  71253. return tree;
  71254. }
  71255. END_JUCE_NAMESPACE
  71256. /*** End of inlined file: juce_DrawablePath.cpp ***/
  71257. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  71258. BEGIN_JUCE_NAMESPACE
  71259. DrawableRectangle::DrawableRectangle()
  71260. {
  71261. }
  71262. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  71263. : DrawableShape (other),
  71264. bounds (other.bounds),
  71265. cornerSize (other.cornerSize)
  71266. {
  71267. }
  71268. DrawableRectangle::~DrawableRectangle()
  71269. {
  71270. }
  71271. Drawable* DrawableRectangle::createCopy() const
  71272. {
  71273. return new DrawableRectangle (*this);
  71274. }
  71275. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  71276. {
  71277. if (bounds != newBounds)
  71278. {
  71279. bounds = newBounds;
  71280. rebuildPath();
  71281. }
  71282. }
  71283. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  71284. {
  71285. if (cornerSize != newSize)
  71286. {
  71287. cornerSize = newSize;
  71288. rebuildPath();
  71289. }
  71290. }
  71291. void DrawableRectangle::rebuildPath()
  71292. {
  71293. if (bounds.isDynamic() || cornerSize.isDynamic())
  71294. {
  71295. Drawable::Positioner<DrawableRectangle>* const p = new Drawable::Positioner<DrawableRectangle> (*this);
  71296. setPositioner (p);
  71297. p->apply();
  71298. }
  71299. else
  71300. {
  71301. setPositioner (0);
  71302. recalculateCoordinates (0);
  71303. }
  71304. }
  71305. bool DrawableRectangle::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  71306. {
  71307. bool ok = positioner.addPoint (bounds.topLeft);
  71308. ok = positioner.addPoint (bounds.topRight) && ok;
  71309. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  71310. return positioner.addPoint (cornerSize) && ok;
  71311. }
  71312. void DrawableRectangle::recalculateCoordinates (Expression::Scope* scope)
  71313. {
  71314. Point<float> points[3];
  71315. bounds.resolveThreePoints (points, scope);
  71316. const float cornerSizeX = (float) cornerSize.x.resolve (scope);
  71317. const float cornerSizeY = (float) cornerSize.y.resolve (scope);
  71318. const float w = Line<float> (points[0], points[1]).getLength();
  71319. const float h = Line<float> (points[0], points[2]).getLength();
  71320. Path newPath;
  71321. if (cornerSizeX > 0 && cornerSizeY > 0)
  71322. newPath.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  71323. else
  71324. newPath.addRectangle (0, 0, w, h);
  71325. newPath.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  71326. w, 0, points[1].getX(), points[1].getY(),
  71327. 0, h, points[2].getX(), points[2].getY()));
  71328. if (path != newPath)
  71329. {
  71330. path.swapWithPath (newPath);
  71331. pathChanged();
  71332. }
  71333. }
  71334. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  71335. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  71336. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  71337. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71338. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  71339. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71340. : FillAndStrokeState (state_)
  71341. {
  71342. jassert (state.hasType (valueTreeType));
  71343. }
  71344. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  71345. {
  71346. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  71347. state.getProperty (topRight, "100, 0"),
  71348. state.getProperty (bottomLeft, "0, 100"));
  71349. }
  71350. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71351. {
  71352. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71353. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71354. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71355. }
  71356. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  71357. {
  71358. state.setProperty (cornerSize, newSize.toString(), undoManager);
  71359. }
  71360. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  71361. {
  71362. return RelativePoint (state [cornerSize]);
  71363. }
  71364. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  71365. {
  71366. return state.getPropertyAsValue (cornerSize, undoManager);
  71367. }
  71368. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  71369. {
  71370. ValueTreeWrapper v (tree);
  71371. setComponentID (v.getID());
  71372. refreshFillTypes (v, builder.getImageProvider());
  71373. setStrokeType (v.getStrokeType());
  71374. setRectangle (v.getRectangle());
  71375. setCornerSize (v.getCornerSize());
  71376. }
  71377. const ValueTree DrawableRectangle::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  71378. {
  71379. ValueTree tree (valueTreeType);
  71380. ValueTreeWrapper v (tree);
  71381. v.setID (getComponentID());
  71382. writeTo (v, imageProvider, 0);
  71383. v.setRectangle (bounds, 0);
  71384. v.setCornerSize (cornerSize, 0);
  71385. return tree;
  71386. }
  71387. END_JUCE_NAMESPACE
  71388. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  71389. /*** Start of inlined file: juce_DrawableText.cpp ***/
  71390. BEGIN_JUCE_NAMESPACE
  71391. DrawableText::DrawableText()
  71392. : colour (Colours::black),
  71393. justification (Justification::centredLeft)
  71394. {
  71395. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  71396. RelativePoint (50.0f, 0.0f),
  71397. RelativePoint (0.0f, 20.0f)));
  71398. setFont (Font (15.0f), true);
  71399. }
  71400. DrawableText::DrawableText (const DrawableText& other)
  71401. : bounds (other.bounds),
  71402. fontSizeControlPoint (other.fontSizeControlPoint),
  71403. font (other.font),
  71404. text (other.text),
  71405. colour (other.colour),
  71406. justification (other.justification)
  71407. {
  71408. }
  71409. DrawableText::~DrawableText()
  71410. {
  71411. }
  71412. void DrawableText::setText (const String& newText)
  71413. {
  71414. if (text != newText)
  71415. {
  71416. text = newText;
  71417. refreshBounds();
  71418. }
  71419. }
  71420. void DrawableText::setColour (const Colour& newColour)
  71421. {
  71422. if (colour != newColour)
  71423. {
  71424. colour = newColour;
  71425. repaint();
  71426. }
  71427. }
  71428. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  71429. {
  71430. if (font != newFont)
  71431. {
  71432. font = newFont;
  71433. if (applySizeAndScale)
  71434. {
  71435. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (resolvedPoints,
  71436. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  71437. }
  71438. refreshBounds();
  71439. }
  71440. }
  71441. void DrawableText::setJustification (const Justification& newJustification)
  71442. {
  71443. justification = newJustification;
  71444. repaint();
  71445. }
  71446. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  71447. {
  71448. if (bounds != newBounds)
  71449. {
  71450. bounds = newBounds;
  71451. refreshBounds();
  71452. }
  71453. }
  71454. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  71455. {
  71456. if (fontSizeControlPoint != newPoint)
  71457. {
  71458. fontSizeControlPoint = newPoint;
  71459. refreshBounds();
  71460. }
  71461. }
  71462. void DrawableText::refreshBounds()
  71463. {
  71464. if (bounds.isDynamic() || fontSizeControlPoint.isDynamic())
  71465. {
  71466. Drawable::Positioner<DrawableText>* const p = new Drawable::Positioner<DrawableText> (*this);
  71467. setPositioner (p);
  71468. p->apply();
  71469. }
  71470. else
  71471. {
  71472. setPositioner (0);
  71473. recalculateCoordinates (0);
  71474. }
  71475. }
  71476. bool DrawableText::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  71477. {
  71478. bool ok = positioner.addPoint (bounds.topLeft);
  71479. ok = positioner.addPoint (bounds.topRight) && ok;
  71480. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  71481. return positioner.addPoint (fontSizeControlPoint) && ok;
  71482. }
  71483. void DrawableText::recalculateCoordinates (Expression::Scope* scope)
  71484. {
  71485. bounds.resolveThreePoints (resolvedPoints, scope);
  71486. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71487. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71488. const Point<float> fontCoords (RelativeParallelogram::getInternalCoordForPoint (resolvedPoints, fontSizeControlPoint.resolve (scope)));
  71489. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  71490. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  71491. scaledFont = font;
  71492. scaledFont.setHeight (fontHeight);
  71493. scaledFont.setHorizontalScale (fontWidth / fontHeight);
  71494. setBoundsToEnclose (getDrawableBounds());
  71495. repaint();
  71496. }
  71497. const AffineTransform DrawableText::getArrangementAndTransform (GlyphArrangement& glyphs) const
  71498. {
  71499. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71500. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71501. glyphs.addFittedText (scaledFont, text, 0, 0, w, h, justification, 0x100000);
  71502. return AffineTransform::fromTargetPoints (0, 0, resolvedPoints[0].getX(), resolvedPoints[0].getY(),
  71503. w, 0, resolvedPoints[1].getX(), resolvedPoints[1].getY(),
  71504. 0, h, resolvedPoints[2].getX(), resolvedPoints[2].getY());
  71505. }
  71506. void DrawableText::paint (Graphics& g)
  71507. {
  71508. transformContextToCorrectOrigin (g);
  71509. g.setColour (colour);
  71510. GlyphArrangement ga;
  71511. const AffineTransform transform (getArrangementAndTransform (ga));
  71512. ga.draw (g, transform);
  71513. }
  71514. const Rectangle<float> DrawableText::getDrawableBounds() const
  71515. {
  71516. return RelativeParallelogram::getBoundingBox (resolvedPoints);
  71517. }
  71518. Drawable* DrawableText::createCopy() const
  71519. {
  71520. return new DrawableText (*this);
  71521. }
  71522. const Identifier DrawableText::valueTreeType ("Text");
  71523. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71524. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71525. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71526. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71527. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71528. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71529. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71530. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71531. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71532. : ValueTreeWrapperBase (state_)
  71533. {
  71534. jassert (state.hasType (valueTreeType));
  71535. }
  71536. const String DrawableText::ValueTreeWrapper::getText() const
  71537. {
  71538. return state [text].toString();
  71539. }
  71540. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71541. {
  71542. state.setProperty (text, newText, undoManager);
  71543. }
  71544. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71545. {
  71546. return state.getPropertyAsValue (text, undoManager);
  71547. }
  71548. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71549. {
  71550. return Colour::fromString (state [colour].toString());
  71551. }
  71552. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71553. {
  71554. state.setProperty (colour, newColour.toString(), undoManager);
  71555. }
  71556. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71557. {
  71558. return Justification ((int) state [justification]);
  71559. }
  71560. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71561. {
  71562. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71563. }
  71564. const Font DrawableText::ValueTreeWrapper::getFont() const
  71565. {
  71566. return Font::fromString (state [font]);
  71567. }
  71568. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71569. {
  71570. state.setProperty (font, newFont.toString(), undoManager);
  71571. }
  71572. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71573. {
  71574. return state.getPropertyAsValue (font, undoManager);
  71575. }
  71576. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71577. {
  71578. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71579. }
  71580. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71581. {
  71582. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71583. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71584. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71585. }
  71586. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71587. {
  71588. return state [fontSizeAnchor].toString();
  71589. }
  71590. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71591. {
  71592. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71593. }
  71594. void DrawableText::refreshFromValueTree (const ValueTree& tree, ComponentBuilder&)
  71595. {
  71596. ValueTreeWrapper v (tree);
  71597. setComponentID (v.getID());
  71598. const RelativeParallelogram newBounds (v.getBoundingBox());
  71599. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71600. const Colour newColour (v.getColour());
  71601. const Justification newJustification (v.getJustification());
  71602. const String newText (v.getText());
  71603. const Font newFont (v.getFont());
  71604. if (text != newText || font != newFont || justification != newJustification
  71605. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71606. {
  71607. setBoundingBox (newBounds);
  71608. setFontSizeControlPoint (newFontPoint);
  71609. setColour (newColour);
  71610. setFont (newFont, false);
  71611. setJustification (newJustification);
  71612. setText (newText);
  71613. }
  71614. }
  71615. const ValueTree DrawableText::createValueTree (ComponentBuilder::ImageProvider*) const
  71616. {
  71617. ValueTree tree (valueTreeType);
  71618. ValueTreeWrapper v (tree);
  71619. v.setID (getComponentID());
  71620. v.setText (text, 0);
  71621. v.setFont (font, 0);
  71622. v.setJustification (justification, 0);
  71623. v.setColour (colour, 0);
  71624. v.setBoundingBox (bounds, 0);
  71625. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71626. return tree;
  71627. }
  71628. END_JUCE_NAMESPACE
  71629. /*** End of inlined file: juce_DrawableText.cpp ***/
  71630. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71631. BEGIN_JUCE_NAMESPACE
  71632. class SVGState
  71633. {
  71634. public:
  71635. SVGState (const XmlElement* const topLevel)
  71636. : topLevelXml (topLevel),
  71637. elementX (0), elementY (0),
  71638. width (512), height (512),
  71639. viewBoxW (0), viewBoxH (0)
  71640. {
  71641. }
  71642. Drawable* parseSVGElement (const XmlElement& xml)
  71643. {
  71644. if (! xml.hasTagName ("svg"))
  71645. return 0;
  71646. DrawableComposite* const drawable = new DrawableComposite();
  71647. drawable->setName (xml.getStringAttribute ("id"));
  71648. SVGState newState (*this);
  71649. if (xml.hasAttribute ("transform"))
  71650. newState.addTransform (xml);
  71651. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71652. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71653. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71654. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71655. if (xml.hasAttribute ("viewBox"))
  71656. {
  71657. const String viewBoxAtt (xml.getStringAttribute ("viewBox"));
  71658. String::CharPointerType viewParams (viewBoxAtt.getCharPointer());
  71659. float vx, vy, vw, vh;
  71660. if (parseCoords (viewParams, vx, vy, true)
  71661. && parseCoords (viewParams, vw, vh, true)
  71662. && vw > 0
  71663. && vh > 0)
  71664. {
  71665. newState.viewBoxW = vw;
  71666. newState.viewBoxH = vh;
  71667. int placementFlags = 0;
  71668. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71669. if (aspect.containsIgnoreCase ("none"))
  71670. {
  71671. placementFlags = RectanglePlacement::stretchToFit;
  71672. }
  71673. else
  71674. {
  71675. if (aspect.containsIgnoreCase ("slice"))
  71676. placementFlags |= RectanglePlacement::fillDestination;
  71677. if (aspect.containsIgnoreCase ("xMin"))
  71678. placementFlags |= RectanglePlacement::xLeft;
  71679. else if (aspect.containsIgnoreCase ("xMax"))
  71680. placementFlags |= RectanglePlacement::xRight;
  71681. else
  71682. placementFlags |= RectanglePlacement::xMid;
  71683. if (aspect.containsIgnoreCase ("yMin"))
  71684. placementFlags |= RectanglePlacement::yTop;
  71685. else if (aspect.containsIgnoreCase ("yMax"))
  71686. placementFlags |= RectanglePlacement::yBottom;
  71687. else
  71688. placementFlags |= RectanglePlacement::yMid;
  71689. }
  71690. const RectanglePlacement placement (placementFlags);
  71691. newState.transform
  71692. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71693. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71694. .followedBy (newState.transform);
  71695. }
  71696. }
  71697. else
  71698. {
  71699. if (viewBoxW == 0)
  71700. newState.viewBoxW = newState.width;
  71701. if (viewBoxH == 0)
  71702. newState.viewBoxH = newState.height;
  71703. }
  71704. newState.parseSubElements (xml, drawable);
  71705. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71706. return drawable;
  71707. }
  71708. private:
  71709. const XmlElement* const topLevelXml;
  71710. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71711. AffineTransform transform;
  71712. String cssStyleText;
  71713. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71714. {
  71715. forEachXmlChildElement (xml, e)
  71716. {
  71717. Drawable* d = 0;
  71718. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71719. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71720. else if (e->hasTagName ("path")) d = parsePath (*e);
  71721. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71722. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71723. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71724. else if (e->hasTagName ("line")) d = parseLine (*e);
  71725. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71726. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71727. else if (e->hasTagName ("text")) d = parseText (*e);
  71728. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71729. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71730. parentDrawable->addAndMakeVisible (d);
  71731. }
  71732. }
  71733. DrawableComposite* parseSwitch (const XmlElement& xml)
  71734. {
  71735. const XmlElement* const group = xml.getChildByName ("g");
  71736. if (group != 0)
  71737. return parseGroupElement (*group);
  71738. return 0;
  71739. }
  71740. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71741. {
  71742. DrawableComposite* const drawable = new DrawableComposite();
  71743. drawable->setName (xml.getStringAttribute ("id"));
  71744. if (xml.hasAttribute ("transform"))
  71745. {
  71746. SVGState newState (*this);
  71747. newState.addTransform (xml);
  71748. newState.parseSubElements (xml, drawable);
  71749. }
  71750. else
  71751. {
  71752. parseSubElements (xml, drawable);
  71753. }
  71754. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71755. return drawable;
  71756. }
  71757. Drawable* parsePath (const XmlElement& xml) const
  71758. {
  71759. const String dAttribute (xml.getStringAttribute ("d").trimStart());
  71760. String::CharPointerType d (dAttribute.getCharPointer());
  71761. Path path;
  71762. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71763. path.setUsingNonZeroWinding (false);
  71764. float lastX = 0, lastY = 0;
  71765. float lastX2 = 0, lastY2 = 0;
  71766. juce_wchar lastCommandChar = 0;
  71767. bool isRelative = true;
  71768. bool carryOn = true;
  71769. const CharPointer_ASCII validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71770. while (! d.isEmpty())
  71771. {
  71772. float x, y, x2, y2, x3, y3;
  71773. if (validCommandChars.indexOf (*d) >= 0)
  71774. {
  71775. lastCommandChar = d.getAndAdvance();
  71776. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71777. }
  71778. switch (lastCommandChar)
  71779. {
  71780. case 'M':
  71781. case 'm':
  71782. case 'L':
  71783. case 'l':
  71784. if (parseCoords (d, x, y, false))
  71785. {
  71786. if (isRelative)
  71787. {
  71788. x += lastX;
  71789. y += lastY;
  71790. }
  71791. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71792. {
  71793. path.startNewSubPath (x, y);
  71794. lastCommandChar = 'l';
  71795. }
  71796. else
  71797. path.lineTo (x, y);
  71798. lastX2 = lastX;
  71799. lastY2 = lastY;
  71800. lastX = x;
  71801. lastY = y;
  71802. }
  71803. else
  71804. {
  71805. ++d;
  71806. }
  71807. break;
  71808. case 'H':
  71809. case 'h':
  71810. if (parseCoord (d, x, false, true))
  71811. {
  71812. if (isRelative)
  71813. x += lastX;
  71814. path.lineTo (x, lastY);
  71815. lastX2 = lastX;
  71816. lastX = x;
  71817. }
  71818. else
  71819. {
  71820. ++d;
  71821. }
  71822. break;
  71823. case 'V':
  71824. case 'v':
  71825. if (parseCoord (d, y, false, false))
  71826. {
  71827. if (isRelative)
  71828. y += lastY;
  71829. path.lineTo (lastX, y);
  71830. lastY2 = lastY;
  71831. lastY = y;
  71832. }
  71833. else
  71834. {
  71835. ++d;
  71836. }
  71837. break;
  71838. case 'C':
  71839. case 'c':
  71840. if (parseCoords (d, x, y, false)
  71841. && parseCoords (d, x2, y2, false)
  71842. && parseCoords (d, x3, y3, false))
  71843. {
  71844. if (isRelative)
  71845. {
  71846. x += lastX;
  71847. y += lastY;
  71848. x2 += lastX;
  71849. y2 += lastY;
  71850. x3 += lastX;
  71851. y3 += lastY;
  71852. }
  71853. path.cubicTo (x, y, x2, y2, x3, y3);
  71854. lastX2 = x2;
  71855. lastY2 = y2;
  71856. lastX = x3;
  71857. lastY = y3;
  71858. }
  71859. else
  71860. {
  71861. ++d;
  71862. }
  71863. break;
  71864. case 'S':
  71865. case 's':
  71866. if (parseCoords (d, x, y, false)
  71867. && parseCoords (d, x3, y3, false))
  71868. {
  71869. if (isRelative)
  71870. {
  71871. x += lastX;
  71872. y += lastY;
  71873. x3 += lastX;
  71874. y3 += lastY;
  71875. }
  71876. x2 = lastX + (lastX - lastX2);
  71877. y2 = lastY + (lastY - lastY2);
  71878. path.cubicTo (x2, y2, x, y, x3, y3);
  71879. lastX2 = x;
  71880. lastY2 = y;
  71881. lastX = x3;
  71882. lastY = y3;
  71883. }
  71884. else
  71885. {
  71886. ++d;
  71887. }
  71888. break;
  71889. case 'Q':
  71890. case 'q':
  71891. if (parseCoords (d, x, y, false)
  71892. && parseCoords (d, x2, y2, false))
  71893. {
  71894. if (isRelative)
  71895. {
  71896. x += lastX;
  71897. y += lastY;
  71898. x2 += lastX;
  71899. y2 += lastY;
  71900. }
  71901. path.quadraticTo (x, y, x2, y2);
  71902. lastX2 = x;
  71903. lastY2 = y;
  71904. lastX = x2;
  71905. lastY = y2;
  71906. }
  71907. else
  71908. {
  71909. ++d;
  71910. }
  71911. break;
  71912. case 'T':
  71913. case 't':
  71914. if (parseCoords (d, x, y, false))
  71915. {
  71916. if (isRelative)
  71917. {
  71918. x += lastX;
  71919. y += lastY;
  71920. }
  71921. x2 = lastX + (lastX - lastX2);
  71922. y2 = lastY + (lastY - lastY2);
  71923. path.quadraticTo (x2, y2, x, y);
  71924. lastX2 = x2;
  71925. lastY2 = y2;
  71926. lastX = x;
  71927. lastY = y;
  71928. }
  71929. else
  71930. {
  71931. ++d;
  71932. }
  71933. break;
  71934. case 'A':
  71935. case 'a':
  71936. if (parseCoords (d, x, y, false))
  71937. {
  71938. String num;
  71939. if (parseNextNumber (d, num, false))
  71940. {
  71941. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71942. if (parseNextNumber (d, num, false))
  71943. {
  71944. const bool largeArc = num.getIntValue() != 0;
  71945. if (parseNextNumber (d, num, false))
  71946. {
  71947. const bool sweep = num.getIntValue() != 0;
  71948. if (parseCoords (d, x2, y2, false))
  71949. {
  71950. if (isRelative)
  71951. {
  71952. x2 += lastX;
  71953. y2 += lastY;
  71954. }
  71955. if (lastX != x2 || lastY != y2)
  71956. {
  71957. double centreX, centreY, startAngle, deltaAngle;
  71958. double rx = x, ry = y;
  71959. endpointToCentreParameters (lastX, lastY, x2, y2,
  71960. angle, largeArc, sweep,
  71961. rx, ry, centreX, centreY,
  71962. startAngle, deltaAngle);
  71963. path.addCentredArc ((float) centreX, (float) centreY,
  71964. (float) rx, (float) ry,
  71965. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71966. false);
  71967. path.lineTo (x2, y2);
  71968. }
  71969. lastX2 = lastX;
  71970. lastY2 = lastY;
  71971. lastX = x2;
  71972. lastY = y2;
  71973. }
  71974. }
  71975. }
  71976. }
  71977. }
  71978. else
  71979. {
  71980. ++d;
  71981. }
  71982. break;
  71983. case 'Z':
  71984. case 'z':
  71985. path.closeSubPath();
  71986. d = d.findEndOfWhitespace();
  71987. break;
  71988. default:
  71989. carryOn = false;
  71990. break;
  71991. }
  71992. if (! carryOn)
  71993. break;
  71994. }
  71995. return parseShape (xml, path);
  71996. }
  71997. Drawable* parseRect (const XmlElement& xml) const
  71998. {
  71999. Path rect;
  72000. const bool hasRX = xml.hasAttribute ("rx");
  72001. const bool hasRY = xml.hasAttribute ("ry");
  72002. if (hasRX || hasRY)
  72003. {
  72004. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  72005. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  72006. if (! hasRX)
  72007. rx = ry;
  72008. else if (! hasRY)
  72009. ry = rx;
  72010. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  72011. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  72012. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  72013. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  72014. rx, ry);
  72015. }
  72016. else
  72017. {
  72018. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  72019. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  72020. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  72021. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  72022. }
  72023. return parseShape (xml, rect);
  72024. }
  72025. Drawable* parseCircle (const XmlElement& xml) const
  72026. {
  72027. Path circle;
  72028. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  72029. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  72030. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  72031. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  72032. return parseShape (xml, circle);
  72033. }
  72034. Drawable* parseEllipse (const XmlElement& xml) const
  72035. {
  72036. Path ellipse;
  72037. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  72038. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  72039. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  72040. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  72041. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  72042. return parseShape (xml, ellipse);
  72043. }
  72044. Drawable* parseLine (const XmlElement& xml) const
  72045. {
  72046. Path line;
  72047. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  72048. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  72049. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  72050. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  72051. line.startNewSubPath (x1, y1);
  72052. line.lineTo (x2, y2);
  72053. return parseShape (xml, line);
  72054. }
  72055. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  72056. {
  72057. const String pointsAtt (xml.getStringAttribute ("points"));
  72058. String::CharPointerType points (pointsAtt.getCharPointer());
  72059. Path path;
  72060. float x, y;
  72061. if (parseCoords (points, x, y, true))
  72062. {
  72063. float firstX = x;
  72064. float firstY = y;
  72065. float lastX = 0, lastY = 0;
  72066. path.startNewSubPath (x, y);
  72067. while (parseCoords (points, x, y, true))
  72068. {
  72069. lastX = x;
  72070. lastY = y;
  72071. path.lineTo (x, y);
  72072. }
  72073. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  72074. path.closeSubPath();
  72075. }
  72076. return parseShape (xml, path);
  72077. }
  72078. Drawable* parseShape (const XmlElement& xml, Path& path,
  72079. const bool shouldParseTransform = true) const
  72080. {
  72081. if (shouldParseTransform && xml.hasAttribute ("transform"))
  72082. {
  72083. SVGState newState (*this);
  72084. newState.addTransform (xml);
  72085. return newState.parseShape (xml, path, false);
  72086. }
  72087. DrawablePath* dp = new DrawablePath();
  72088. dp->setName (xml.getStringAttribute ("id"));
  72089. dp->setFill (Colours::transparentBlack);
  72090. path.applyTransform (transform);
  72091. dp->setPath (path);
  72092. Path::Iterator iter (path);
  72093. bool containsClosedSubPath = false;
  72094. while (iter.next())
  72095. {
  72096. if (iter.elementType == Path::Iterator::closePath)
  72097. {
  72098. containsClosedSubPath = true;
  72099. break;
  72100. }
  72101. }
  72102. dp->setFill (getPathFillType (path,
  72103. getStyleAttribute (&xml, "fill"),
  72104. getStyleAttribute (&xml, "fill-opacity"),
  72105. getStyleAttribute (&xml, "opacity"),
  72106. containsClosedSubPath ? Colours::black
  72107. : Colours::transparentBlack));
  72108. const String strokeType (getStyleAttribute (&xml, "stroke"));
  72109. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  72110. {
  72111. dp->setStrokeFill (getPathFillType (path, strokeType,
  72112. getStyleAttribute (&xml, "stroke-opacity"),
  72113. getStyleAttribute (&xml, "opacity"),
  72114. Colours::transparentBlack));
  72115. dp->setStrokeType (getStrokeFor (&xml));
  72116. }
  72117. return dp;
  72118. }
  72119. const XmlElement* findLinkedElement (const XmlElement* e) const
  72120. {
  72121. const String id (e->getStringAttribute ("xlink:href"));
  72122. if (! id.startsWithChar ('#'))
  72123. return 0;
  72124. return findElementForId (topLevelXml, id.substring (1));
  72125. }
  72126. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  72127. {
  72128. if (fillXml == 0)
  72129. return;
  72130. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  72131. {
  72132. int index = 0;
  72133. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  72134. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  72135. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  72136. double offset = e->getDoubleAttribute ("offset");
  72137. if (e->getStringAttribute ("offset").containsChar ('%'))
  72138. offset *= 0.01;
  72139. cg.addColour (jlimit (0.0, 1.0, offset), col);
  72140. }
  72141. }
  72142. const FillType getPathFillType (const Path& path,
  72143. const String& fill,
  72144. const String& fillOpacity,
  72145. const String& overallOpacity,
  72146. const Colour& defaultColour) const
  72147. {
  72148. float opacity = 1.0f;
  72149. if (overallOpacity.isNotEmpty())
  72150. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  72151. if (fillOpacity.isNotEmpty())
  72152. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  72153. if (fill.startsWithIgnoreCase ("url"))
  72154. {
  72155. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  72156. .upToLastOccurrenceOf (")", false, false).trim());
  72157. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  72158. if (fillXml != 0
  72159. && (fillXml->hasTagName ("linearGradient")
  72160. || fillXml->hasTagName ("radialGradient")))
  72161. {
  72162. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  72163. ColourGradient gradient;
  72164. addGradientStopsIn (gradient, inheritedFrom);
  72165. addGradientStopsIn (gradient, fillXml);
  72166. if (gradient.getNumColours() > 0)
  72167. {
  72168. gradient.addColour (0.0, gradient.getColour (0));
  72169. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  72170. }
  72171. else
  72172. {
  72173. gradient.addColour (0.0, Colours::black);
  72174. gradient.addColour (1.0, Colours::black);
  72175. }
  72176. if (overallOpacity.isNotEmpty())
  72177. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  72178. jassert (gradient.getNumColours() > 0);
  72179. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  72180. float gradientWidth = viewBoxW;
  72181. float gradientHeight = viewBoxH;
  72182. float dx = 0.0f;
  72183. float dy = 0.0f;
  72184. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  72185. if (! userSpace)
  72186. {
  72187. const Rectangle<float> bounds (path.getBounds());
  72188. dx = bounds.getX();
  72189. dy = bounds.getY();
  72190. gradientWidth = bounds.getWidth();
  72191. gradientHeight = bounds.getHeight();
  72192. }
  72193. if (gradient.isRadial)
  72194. {
  72195. if (userSpace)
  72196. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  72197. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  72198. else
  72199. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  72200. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  72201. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  72202. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  72203. //xxx (the fx, fy focal point isn't handled properly here..)
  72204. }
  72205. else
  72206. {
  72207. if (userSpace)
  72208. {
  72209. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  72210. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  72211. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  72212. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  72213. }
  72214. else
  72215. {
  72216. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  72217. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  72218. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  72219. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  72220. }
  72221. if (gradient.point1 == gradient.point2)
  72222. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  72223. }
  72224. FillType type (gradient);
  72225. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  72226. .followedBy (transform);
  72227. return type;
  72228. }
  72229. }
  72230. if (fill.equalsIgnoreCase ("none"))
  72231. return Colours::transparentBlack;
  72232. int i = 0;
  72233. const Colour colour (parseColour (fill, i, defaultColour));
  72234. return colour.withMultipliedAlpha (opacity);
  72235. }
  72236. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  72237. {
  72238. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  72239. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  72240. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  72241. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  72242. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  72243. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  72244. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  72245. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  72246. if (join.equalsIgnoreCase ("round"))
  72247. joinStyle = PathStrokeType::curved;
  72248. else if (join.equalsIgnoreCase ("bevel"))
  72249. joinStyle = PathStrokeType::beveled;
  72250. if (cap.equalsIgnoreCase ("round"))
  72251. capStyle = PathStrokeType::rounded;
  72252. else if (cap.equalsIgnoreCase ("square"))
  72253. capStyle = PathStrokeType::square;
  72254. float ox = 0.0f, oy = 0.0f;
  72255. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  72256. transform.transformPoints (ox, oy, x, y);
  72257. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  72258. joinStyle, capStyle);
  72259. }
  72260. Drawable* parseText (const XmlElement& xml)
  72261. {
  72262. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  72263. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  72264. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  72265. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  72266. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  72267. //xxx not done text yet!
  72268. forEachXmlChildElement (xml, e)
  72269. {
  72270. if (e->isTextElement())
  72271. {
  72272. const String text (e->getText());
  72273. Path path;
  72274. Drawable* s = parseShape (*e, path);
  72275. delete s; // xxx not finished!
  72276. }
  72277. else if (e->hasTagName ("tspan"))
  72278. {
  72279. Drawable* s = parseText (*e);
  72280. delete s; // xxx not finished!
  72281. }
  72282. }
  72283. return 0;
  72284. }
  72285. void addTransform (const XmlElement& xml)
  72286. {
  72287. transform = parseTransform (xml.getStringAttribute ("transform"))
  72288. .followedBy (transform);
  72289. }
  72290. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  72291. {
  72292. String number;
  72293. if (! parseNextNumber (s, number, allowUnits))
  72294. {
  72295. value = 0;
  72296. return false;
  72297. }
  72298. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  72299. return true;
  72300. }
  72301. bool parseCoords (String::CharPointerType& s, float& x, float& y, const bool allowUnits) const
  72302. {
  72303. return parseCoord (s, x, allowUnits, true)
  72304. && parseCoord (s, y, allowUnits, false);
  72305. }
  72306. float getCoordLength (const String& s, const float sizeForProportions) const
  72307. {
  72308. float n = s.getFloatValue();
  72309. const int len = s.length();
  72310. if (len > 2)
  72311. {
  72312. const float dpi = 96.0f;
  72313. const juce_wchar n1 = s [len - 2];
  72314. const juce_wchar n2 = s [len - 1];
  72315. if (n1 == 'i' && n2 == 'n')
  72316. n *= dpi;
  72317. else if (n1 == 'm' && n2 == 'm')
  72318. n *= dpi / 25.4f;
  72319. else if (n1 == 'c' && n2 == 'm')
  72320. n *= dpi / 2.54f;
  72321. else if (n1 == 'p' && n2 == 'c')
  72322. n *= 15.0f;
  72323. else if (n2 == '%')
  72324. n *= 0.01f * sizeForProportions;
  72325. }
  72326. return n;
  72327. }
  72328. void getCoordList (Array <float>& coords, const String& list,
  72329. const bool allowUnits, const bool isX) const
  72330. {
  72331. String::CharPointerType text (list.getCharPointer());
  72332. float value;
  72333. while (parseCoord (text, value, allowUnits, isX))
  72334. coords.add (value);
  72335. }
  72336. void parseCSSStyle (const XmlElement& xml)
  72337. {
  72338. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  72339. }
  72340. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  72341. const String& defaultValue = String::empty) const
  72342. {
  72343. if (xml->hasAttribute (attributeName))
  72344. return xml->getStringAttribute (attributeName, defaultValue);
  72345. const String styleAtt (xml->getStringAttribute ("style"));
  72346. if (styleAtt.isNotEmpty())
  72347. {
  72348. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  72349. if (value.isNotEmpty())
  72350. return value;
  72351. }
  72352. else if (xml->hasAttribute ("class"))
  72353. {
  72354. const String className ("." + xml->getStringAttribute ("class"));
  72355. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  72356. if (index < 0)
  72357. index = cssStyleText.indexOfIgnoreCase (className + "{");
  72358. if (index >= 0)
  72359. {
  72360. const int openBracket = cssStyleText.indexOfChar (index, '{');
  72361. if (openBracket > index)
  72362. {
  72363. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  72364. if (closeBracket > openBracket)
  72365. {
  72366. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  72367. if (value.isNotEmpty())
  72368. return value;
  72369. }
  72370. }
  72371. }
  72372. }
  72373. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72374. if (xml != 0)
  72375. return getStyleAttribute (xml, attributeName, defaultValue);
  72376. return defaultValue;
  72377. }
  72378. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  72379. {
  72380. if (xml->hasAttribute (attributeName))
  72381. return xml->getStringAttribute (attributeName);
  72382. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72383. if (xml != 0)
  72384. return getInheritedAttribute (xml, attributeName);
  72385. return String::empty;
  72386. }
  72387. static bool isIdentifierChar (const juce_wchar c)
  72388. {
  72389. return CharacterFunctions::isLetter (c) || c == '-';
  72390. }
  72391. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  72392. {
  72393. int i = 0;
  72394. for (;;)
  72395. {
  72396. i = list.indexOf (i, attributeName);
  72397. if (i < 0)
  72398. break;
  72399. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  72400. && ! isIdentifierChar (list [i + attributeName.length()]))
  72401. {
  72402. i = list.indexOfChar (i, ':');
  72403. if (i < 0)
  72404. break;
  72405. int end = list.indexOfChar (i, ';');
  72406. if (end < 0)
  72407. end = 0x7ffff;
  72408. return list.substring (i + 1, end).trim();
  72409. }
  72410. ++i;
  72411. }
  72412. return defaultValue;
  72413. }
  72414. static bool parseNextNumber (String::CharPointerType& s, String& value, const bool allowUnits)
  72415. {
  72416. while (s.isWhitespace() || *s == ',')
  72417. ++s;
  72418. String::CharPointerType start (s);
  72419. int numChars = 0;
  72420. if (s.isDigit() || *s == '.' || *s == '-')
  72421. {
  72422. ++numChars;
  72423. ++s;
  72424. }
  72425. while (s.isDigit() || *s == '.')
  72426. {
  72427. ++numChars;
  72428. ++s;
  72429. }
  72430. if ((*s == 'e' || *s == 'E')
  72431. && ((s + 1).isDigit() || s[1] == '-' || s[1] == '+'))
  72432. {
  72433. s += 2;
  72434. numChars += 2;
  72435. while (s.isDigit())
  72436. {
  72437. ++numChars;
  72438. ++s;
  72439. }
  72440. }
  72441. if (allowUnits)
  72442. {
  72443. while (s.isLetter())
  72444. {
  72445. ++numChars;
  72446. ++s;
  72447. }
  72448. }
  72449. if (numChars == 0)
  72450. return false;
  72451. value = String (start, numChars);
  72452. while (s.isWhitespace() || *s == ',')
  72453. ++s;
  72454. return true;
  72455. }
  72456. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  72457. {
  72458. if (s [index] == '#')
  72459. {
  72460. uint32 hex [6];
  72461. zeromem (hex, sizeof (hex));
  72462. int numChars = 0;
  72463. for (int i = 6; --i >= 0;)
  72464. {
  72465. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  72466. if (hexValue >= 0)
  72467. hex [numChars++] = hexValue;
  72468. else
  72469. break;
  72470. }
  72471. if (numChars <= 3)
  72472. return Colour ((uint8) (hex [0] * 0x11),
  72473. (uint8) (hex [1] * 0x11),
  72474. (uint8) (hex [2] * 0x11));
  72475. else
  72476. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  72477. (uint8) ((hex [2] << 4) + hex [3]),
  72478. (uint8) ((hex [4] << 4) + hex [5]));
  72479. }
  72480. else if (s [index] == 'r'
  72481. && s [index + 1] == 'g'
  72482. && s [index + 2] == 'b')
  72483. {
  72484. const int openBracket = s.indexOfChar (index, '(');
  72485. const int closeBracket = s.indexOfChar (openBracket, ')');
  72486. if (openBracket >= 3 && closeBracket > openBracket)
  72487. {
  72488. index = closeBracket;
  72489. StringArray tokens;
  72490. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72491. tokens.trim();
  72492. tokens.removeEmptyStrings();
  72493. if (tokens[0].containsChar ('%'))
  72494. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72495. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72496. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72497. else
  72498. return Colour ((uint8) tokens[0].getIntValue(),
  72499. (uint8) tokens[1].getIntValue(),
  72500. (uint8) tokens[2].getIntValue());
  72501. }
  72502. }
  72503. return Colours::findColourForName (s, defaultColour);
  72504. }
  72505. static const AffineTransform parseTransform (String t)
  72506. {
  72507. AffineTransform result;
  72508. while (t.isNotEmpty())
  72509. {
  72510. StringArray tokens;
  72511. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72512. .upToFirstOccurrenceOf (")", false, false),
  72513. ", ", String::empty);
  72514. tokens.removeEmptyStrings (true);
  72515. float numbers [6];
  72516. for (int i = 0; i < 6; ++i)
  72517. numbers[i] = tokens[i].getFloatValue();
  72518. AffineTransform trans;
  72519. if (t.startsWithIgnoreCase ("matrix"))
  72520. {
  72521. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72522. numbers[1], numbers[3], numbers[5]);
  72523. }
  72524. else if (t.startsWithIgnoreCase ("translate"))
  72525. {
  72526. jassert (tokens.size() == 2);
  72527. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72528. }
  72529. else if (t.startsWithIgnoreCase ("scale"))
  72530. {
  72531. if (tokens.size() == 1)
  72532. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72533. else
  72534. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72535. }
  72536. else if (t.startsWithIgnoreCase ("rotate"))
  72537. {
  72538. if (tokens.size() != 3)
  72539. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72540. else
  72541. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72542. numbers[1], numbers[2]);
  72543. }
  72544. else if (t.startsWithIgnoreCase ("skewX"))
  72545. {
  72546. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72547. 0.0f, 1.0f, 0.0f);
  72548. }
  72549. else if (t.startsWithIgnoreCase ("skewY"))
  72550. {
  72551. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72552. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72553. }
  72554. result = trans.followedBy (result);
  72555. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72556. }
  72557. return result;
  72558. }
  72559. static void endpointToCentreParameters (const double x1, const double y1,
  72560. const double x2, const double y2,
  72561. const double angle,
  72562. const bool largeArc, const bool sweep,
  72563. double& rx, double& ry,
  72564. double& centreX, double& centreY,
  72565. double& startAngle, double& deltaAngle)
  72566. {
  72567. const double midX = (x1 - x2) * 0.5;
  72568. const double midY = (y1 - y2) * 0.5;
  72569. const double cosAngle = cos (angle);
  72570. const double sinAngle = sin (angle);
  72571. const double xp = cosAngle * midX + sinAngle * midY;
  72572. const double yp = cosAngle * midY - sinAngle * midX;
  72573. const double xp2 = xp * xp;
  72574. const double yp2 = yp * yp;
  72575. double rx2 = rx * rx;
  72576. double ry2 = ry * ry;
  72577. const double s = (xp2 / rx2) + (yp2 / ry2);
  72578. double c;
  72579. if (s <= 1.0)
  72580. {
  72581. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72582. / (( rx2 * yp2) + (ry2 * xp2))));
  72583. if (largeArc == sweep)
  72584. c = -c;
  72585. }
  72586. else
  72587. {
  72588. const double s2 = std::sqrt (s);
  72589. rx *= s2;
  72590. ry *= s2;
  72591. rx2 = rx * rx;
  72592. ry2 = ry * ry;
  72593. c = 0;
  72594. }
  72595. const double cpx = ((rx * yp) / ry) * c;
  72596. const double cpy = ((-ry * xp) / rx) * c;
  72597. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72598. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72599. const double ux = (xp - cpx) / rx;
  72600. const double uy = (yp - cpy) / ry;
  72601. const double vx = (-xp - cpx) / rx;
  72602. const double vy = (-yp - cpy) / ry;
  72603. const double length = juce_hypot (ux, uy);
  72604. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72605. if (uy < 0)
  72606. startAngle = -startAngle;
  72607. startAngle += double_Pi * 0.5;
  72608. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72609. / (length * juce_hypot (vx, vy))));
  72610. if ((ux * vy) - (uy * vx) < 0)
  72611. deltaAngle = -deltaAngle;
  72612. if (sweep)
  72613. {
  72614. if (deltaAngle < 0)
  72615. deltaAngle += double_Pi * 2.0;
  72616. }
  72617. else
  72618. {
  72619. if (deltaAngle > 0)
  72620. deltaAngle -= double_Pi * 2.0;
  72621. }
  72622. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72623. }
  72624. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72625. {
  72626. forEachXmlChildElement (*parent, e)
  72627. {
  72628. if (e->compareAttribute ("id", id))
  72629. return e;
  72630. const XmlElement* const found = findElementForId (e, id);
  72631. if (found != 0)
  72632. return found;
  72633. }
  72634. return 0;
  72635. }
  72636. SVGState& operator= (const SVGState&);
  72637. };
  72638. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72639. {
  72640. SVGState state (&svgDocument);
  72641. return state.parseSVGElement (svgDocument);
  72642. }
  72643. END_JUCE_NAMESPACE
  72644. /*** End of inlined file: juce_SVGParser.cpp ***/
  72645. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72646. BEGIN_JUCE_NAMESPACE
  72647. #if JUCE_MSVC && JUCE_DEBUG
  72648. #pragma optimize ("t", on)
  72649. #endif
  72650. DropShadowEffect::DropShadowEffect()
  72651. : offsetX (0),
  72652. offsetY (0),
  72653. radius (4),
  72654. opacity (0.6f)
  72655. {
  72656. }
  72657. DropShadowEffect::~DropShadowEffect()
  72658. {
  72659. }
  72660. void DropShadowEffect::setShadowProperties (const float newRadius,
  72661. const float newOpacity,
  72662. const int newShadowOffsetX,
  72663. const int newShadowOffsetY)
  72664. {
  72665. radius = jmax (1.1f, newRadius);
  72666. offsetX = newShadowOffsetX;
  72667. offsetY = newShadowOffsetY;
  72668. opacity = newOpacity;
  72669. }
  72670. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72671. {
  72672. const int w = image.getWidth();
  72673. const int h = image.getHeight();
  72674. Image shadowImage (Image::SingleChannel, w, h, false);
  72675. {
  72676. const Image::BitmapData srcData (image, Image::BitmapData::readOnly);
  72677. const Image::BitmapData destData (shadowImage, Image::BitmapData::readWrite);
  72678. const int filter = roundToInt (63.0f / radius);
  72679. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72680. for (int x = w; --x >= 0;)
  72681. {
  72682. int shadowAlpha = 0;
  72683. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72684. uint8* shadowPix = destData.data + x;
  72685. for (int y = h; --y >= 0;)
  72686. {
  72687. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72688. *shadowPix = (uint8) shadowAlpha;
  72689. src = addBytesToPointer (src, srcData.lineStride);
  72690. shadowPix += destData.lineStride;
  72691. }
  72692. }
  72693. for (int y = h; --y >= 0;)
  72694. {
  72695. int shadowAlpha = 0;
  72696. uint8* shadowPix = destData.getLinePointer (y);
  72697. for (int x = w; --x >= 0;)
  72698. {
  72699. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72700. *shadowPix++ = (uint8) shadowAlpha;
  72701. }
  72702. }
  72703. }
  72704. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72705. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72706. g.setOpacity (alpha);
  72707. g.drawImageAt (image, 0, 0);
  72708. }
  72709. #if JUCE_MSVC && JUCE_DEBUG
  72710. #pragma optimize ("", on) // resets optimisations to the project defaults
  72711. #endif
  72712. END_JUCE_NAMESPACE
  72713. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72714. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72715. BEGIN_JUCE_NAMESPACE
  72716. GlowEffect::GlowEffect()
  72717. : radius (2.0f),
  72718. colour (Colours::white)
  72719. {
  72720. }
  72721. GlowEffect::~GlowEffect()
  72722. {
  72723. }
  72724. void GlowEffect::setGlowProperties (const float newRadius,
  72725. const Colour& newColour)
  72726. {
  72727. radius = newRadius;
  72728. colour = newColour;
  72729. }
  72730. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72731. {
  72732. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72733. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72734. blurKernel.createGaussianBlur (radius);
  72735. blurKernel.rescaleAllValues (radius);
  72736. blurKernel.applyToImage (temp, image, image.getBounds());
  72737. g.setColour (colour.withMultipliedAlpha (alpha));
  72738. g.drawImageAt (temp, 0, 0, true);
  72739. g.setOpacity (alpha);
  72740. g.drawImageAt (image, 0, 0, false);
  72741. }
  72742. END_JUCE_NAMESPACE
  72743. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72744. /*** Start of inlined file: juce_Font.cpp ***/
  72745. BEGIN_JUCE_NAMESPACE
  72746. namespace FontValues
  72747. {
  72748. float limitFontHeight (const float height) throw()
  72749. {
  72750. return jlimit (0.1f, 10000.0f, height);
  72751. }
  72752. const float defaultFontHeight = 14.0f;
  72753. String fallbackFont;
  72754. }
  72755. class TypefaceCache : public DeletedAtShutdown
  72756. {
  72757. public:
  72758. TypefaceCache()
  72759. : counter (0)
  72760. {
  72761. setSize (10);
  72762. }
  72763. ~TypefaceCache()
  72764. {
  72765. clearSingletonInstance();
  72766. }
  72767. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72768. void setSize (const int numToCache)
  72769. {
  72770. faces.clear();
  72771. faces.insertMultiple (-1, CachedFace(), numToCache);
  72772. }
  72773. const Typeface::Ptr findTypefaceFor (const Font& font)
  72774. {
  72775. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72776. const String faceName (font.getTypefaceName());
  72777. int i;
  72778. for (i = faces.size(); --i >= 0;)
  72779. {
  72780. CachedFace& face = faces.getReference(i);
  72781. if (face.flags == flags
  72782. && face.typefaceName == faceName
  72783. && face.typeface->isSuitableForFont (font))
  72784. {
  72785. face.lastUsageCount = ++counter;
  72786. return face.typeface;
  72787. }
  72788. }
  72789. int replaceIndex = 0;
  72790. int bestLastUsageCount = std::numeric_limits<int>::max();
  72791. for (i = faces.size(); --i >= 0;)
  72792. {
  72793. const int lu = faces.getReference(i).lastUsageCount;
  72794. if (bestLastUsageCount > lu)
  72795. {
  72796. bestLastUsageCount = lu;
  72797. replaceIndex = i;
  72798. }
  72799. }
  72800. CachedFace& face = faces.getReference (replaceIndex);
  72801. face.typefaceName = faceName;
  72802. face.flags = flags;
  72803. face.lastUsageCount = ++counter;
  72804. face.typeface = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72805. jassert (face.typeface != 0); // the look and feel must return a typeface!
  72806. if (defaultFace == 0 && font == Font())
  72807. defaultFace = face.typeface;
  72808. return face.typeface;
  72809. }
  72810. const Typeface::Ptr getDefaultTypeface() const throw()
  72811. {
  72812. return defaultFace;
  72813. }
  72814. private:
  72815. struct CachedFace
  72816. {
  72817. CachedFace() throw()
  72818. : lastUsageCount (0), flags (-1)
  72819. {
  72820. }
  72821. // Although it seems a bit wacky to store the name here, it's because it may be a
  72822. // placeholder rather than a real one, e.g. "<Sans-Serif>" vs the actual typeface name.
  72823. // Since the typeface itself doesn't know that it may have this alias, the name under
  72824. // which it was fetched needs to be stored separately.
  72825. String typefaceName;
  72826. int lastUsageCount, flags;
  72827. Typeface::Ptr typeface;
  72828. };
  72829. Array <CachedFace> faces;
  72830. Typeface::Ptr defaultFace;
  72831. int counter;
  72832. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72833. };
  72834. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72835. void Typeface::setTypefaceCacheSize (int numFontsToCache)
  72836. {
  72837. TypefaceCache::getInstance()->setSize (numFontsToCache);
  72838. }
  72839. Font::SharedFontInternal::SharedFontInternal (const float height_, const int styleFlags_) throw()
  72840. : typefaceName (Font::getDefaultSansSerifFontName()),
  72841. height (height_),
  72842. horizontalScale (1.0f),
  72843. kerning (0),
  72844. ascent (0),
  72845. styleFlags (styleFlags_),
  72846. typeface (TypefaceCache::getInstance()->getDefaultTypeface())
  72847. {
  72848. }
  72849. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const int styleFlags_) throw()
  72850. : typefaceName (typefaceName_),
  72851. height (height_),
  72852. horizontalScale (1.0f),
  72853. kerning (0),
  72854. ascent (0),
  72855. styleFlags (styleFlags_),
  72856. typeface (0)
  72857. {
  72858. }
  72859. Font::SharedFontInternal::SharedFontInternal (const Typeface::Ptr& typeface_) throw()
  72860. : typefaceName (typeface_->getName()),
  72861. height (FontValues::defaultFontHeight),
  72862. horizontalScale (1.0f),
  72863. kerning (0),
  72864. ascent (0),
  72865. styleFlags (Font::plain),
  72866. typeface (typeface_)
  72867. {
  72868. }
  72869. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72870. : typefaceName (other.typefaceName),
  72871. height (other.height),
  72872. horizontalScale (other.horizontalScale),
  72873. kerning (other.kerning),
  72874. ascent (other.ascent),
  72875. styleFlags (other.styleFlags),
  72876. typeface (other.typeface)
  72877. {
  72878. }
  72879. bool Font::SharedFontInternal::operator== (const SharedFontInternal& other) const throw()
  72880. {
  72881. return height == other.height
  72882. && styleFlags == other.styleFlags
  72883. && horizontalScale == other.horizontalScale
  72884. && kerning == other.kerning
  72885. && typefaceName == other.typefaceName;
  72886. }
  72887. Font::Font()
  72888. : font (new SharedFontInternal (FontValues::defaultFontHeight, Font::plain))
  72889. {
  72890. }
  72891. Font::Font (const float fontHeight, const int styleFlags_)
  72892. : font (new SharedFontInternal (FontValues::limitFontHeight (fontHeight), styleFlags_))
  72893. {
  72894. }
  72895. Font::Font (const String& typefaceName_, const float fontHeight, const int styleFlags_)
  72896. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight), styleFlags_))
  72897. {
  72898. }
  72899. Font::Font (const Typeface::Ptr& typeface)
  72900. : font (new SharedFontInternal (typeface))
  72901. {
  72902. }
  72903. Font::Font (const Font& other) throw()
  72904. : font (other.font)
  72905. {
  72906. }
  72907. Font& Font::operator= (const Font& other) throw()
  72908. {
  72909. font = other.font;
  72910. return *this;
  72911. }
  72912. Font::~Font() throw()
  72913. {
  72914. }
  72915. bool Font::operator== (const Font& other) const throw()
  72916. {
  72917. return font == other.font
  72918. || *font == *other.font;
  72919. }
  72920. bool Font::operator!= (const Font& other) const throw()
  72921. {
  72922. return ! operator== (other);
  72923. }
  72924. void Font::dupeInternalIfShared()
  72925. {
  72926. if (font->getReferenceCount() > 1)
  72927. font = new SharedFontInternal (*font);
  72928. }
  72929. const String Font::getDefaultSansSerifFontName()
  72930. {
  72931. static const String name ("<Sans-Serif>");
  72932. return name;
  72933. }
  72934. const String Font::getDefaultSerifFontName()
  72935. {
  72936. static const String name ("<Serif>");
  72937. return name;
  72938. }
  72939. const String Font::getDefaultMonospacedFontName()
  72940. {
  72941. static const String name ("<Monospaced>");
  72942. return name;
  72943. }
  72944. void Font::setTypefaceName (const String& faceName)
  72945. {
  72946. if (faceName != font->typefaceName)
  72947. {
  72948. dupeInternalIfShared();
  72949. font->typefaceName = faceName;
  72950. font->typeface = 0;
  72951. font->ascent = 0;
  72952. }
  72953. }
  72954. const String Font::getFallbackFontName()
  72955. {
  72956. return FontValues::fallbackFont;
  72957. }
  72958. void Font::setFallbackFontName (const String& name)
  72959. {
  72960. FontValues::fallbackFont = name;
  72961. }
  72962. void Font::setHeight (float newHeight)
  72963. {
  72964. newHeight = FontValues::limitFontHeight (newHeight);
  72965. if (font->height != newHeight)
  72966. {
  72967. dupeInternalIfShared();
  72968. font->height = newHeight;
  72969. }
  72970. }
  72971. void Font::setHeightWithoutChangingWidth (float newHeight)
  72972. {
  72973. newHeight = FontValues::limitFontHeight (newHeight);
  72974. if (font->height != newHeight)
  72975. {
  72976. dupeInternalIfShared();
  72977. font->horizontalScale *= (font->height / newHeight);
  72978. font->height = newHeight;
  72979. }
  72980. }
  72981. void Font::setStyleFlags (const int newFlags)
  72982. {
  72983. if (font->styleFlags != newFlags)
  72984. {
  72985. dupeInternalIfShared();
  72986. font->styleFlags = newFlags;
  72987. font->typeface = 0;
  72988. font->ascent = 0;
  72989. }
  72990. }
  72991. void Font::setSizeAndStyle (float newHeight,
  72992. const int newStyleFlags,
  72993. const float newHorizontalScale,
  72994. const float newKerningAmount)
  72995. {
  72996. newHeight = FontValues::limitFontHeight (newHeight);
  72997. if (font->height != newHeight
  72998. || font->horizontalScale != newHorizontalScale
  72999. || font->kerning != newKerningAmount)
  73000. {
  73001. dupeInternalIfShared();
  73002. font->height = newHeight;
  73003. font->horizontalScale = newHorizontalScale;
  73004. font->kerning = newKerningAmount;
  73005. }
  73006. setStyleFlags (newStyleFlags);
  73007. }
  73008. void Font::setHorizontalScale (const float scaleFactor)
  73009. {
  73010. dupeInternalIfShared();
  73011. font->horizontalScale = scaleFactor;
  73012. }
  73013. void Font::setExtraKerningFactor (const float extraKerning)
  73014. {
  73015. dupeInternalIfShared();
  73016. font->kerning = extraKerning;
  73017. }
  73018. void Font::setBold (const bool shouldBeBold)
  73019. {
  73020. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  73021. : (font->styleFlags & ~bold));
  73022. }
  73023. const Font Font::boldened() const
  73024. {
  73025. Font f (*this);
  73026. f.setBold (true);
  73027. return f;
  73028. }
  73029. bool Font::isBold() const throw()
  73030. {
  73031. return (font->styleFlags & bold) != 0;
  73032. }
  73033. void Font::setItalic (const bool shouldBeItalic)
  73034. {
  73035. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  73036. : (font->styleFlags & ~italic));
  73037. }
  73038. const Font Font::italicised() const
  73039. {
  73040. Font f (*this);
  73041. f.setItalic (true);
  73042. return f;
  73043. }
  73044. bool Font::isItalic() const throw()
  73045. {
  73046. return (font->styleFlags & italic) != 0;
  73047. }
  73048. void Font::setUnderline (const bool shouldBeUnderlined)
  73049. {
  73050. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  73051. : (font->styleFlags & ~underlined));
  73052. }
  73053. bool Font::isUnderlined() const throw()
  73054. {
  73055. return (font->styleFlags & underlined) != 0;
  73056. }
  73057. float Font::getAscent() const
  73058. {
  73059. if (font->ascent == 0)
  73060. font->ascent = getTypeface()->getAscent();
  73061. return font->height * font->ascent;
  73062. }
  73063. float Font::getDescent() const
  73064. {
  73065. return font->height - getAscent();
  73066. }
  73067. int Font::getStringWidth (const String& text) const
  73068. {
  73069. return roundToInt (getStringWidthFloat (text));
  73070. }
  73071. float Font::getStringWidthFloat (const String& text) const
  73072. {
  73073. float w = getTypeface()->getStringWidth (text);
  73074. if (font->kerning != 0)
  73075. w += font->kerning * text.length();
  73076. return w * font->height * font->horizontalScale;
  73077. }
  73078. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  73079. {
  73080. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  73081. const float scale = font->height * font->horizontalScale;
  73082. const int num = xOffsets.size();
  73083. if (num > 0)
  73084. {
  73085. float* const x = &(xOffsets.getReference(0));
  73086. if (font->kerning != 0)
  73087. {
  73088. for (int i = 0; i < num; ++i)
  73089. x[i] = (x[i] + i * font->kerning) * scale;
  73090. }
  73091. else
  73092. {
  73093. for (int i = 0; i < num; ++i)
  73094. x[i] *= scale;
  73095. }
  73096. }
  73097. }
  73098. void Font::findFonts (Array<Font>& destArray)
  73099. {
  73100. const StringArray names (findAllTypefaceNames());
  73101. for (int i = 0; i < names.size(); ++i)
  73102. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  73103. }
  73104. const String Font::toString() const
  73105. {
  73106. String s (getTypefaceName());
  73107. if (s == getDefaultSansSerifFontName())
  73108. s = String::empty;
  73109. else
  73110. s += "; ";
  73111. s += String (getHeight(), 1);
  73112. if (isBold())
  73113. s += " bold";
  73114. if (isItalic())
  73115. s += " italic";
  73116. return s;
  73117. }
  73118. const Font Font::fromString (const String& fontDescription)
  73119. {
  73120. String name;
  73121. const int separator = fontDescription.indexOfChar (';');
  73122. if (separator > 0)
  73123. name = fontDescription.substring (0, separator).trim();
  73124. if (name.isEmpty())
  73125. name = getDefaultSansSerifFontName();
  73126. String sizeAndStyle (fontDescription.substring (separator + 1));
  73127. float height = sizeAndStyle.getFloatValue();
  73128. if (height <= 0)
  73129. height = 10.0f;
  73130. int flags = Font::plain;
  73131. if (sizeAndStyle.containsIgnoreCase ("bold"))
  73132. flags |= Font::bold;
  73133. if (sizeAndStyle.containsIgnoreCase ("italic"))
  73134. flags |= Font::italic;
  73135. return Font (name, height, flags);
  73136. }
  73137. Typeface* Font::getTypeface() const
  73138. {
  73139. if (font->typeface == 0)
  73140. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  73141. return font->typeface;
  73142. }
  73143. END_JUCE_NAMESPACE
  73144. /*** End of inlined file: juce_Font.cpp ***/
  73145. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  73146. BEGIN_JUCE_NAMESPACE
  73147. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  73148. const juce_wchar character_, const int glyph_)
  73149. : x (x_),
  73150. y (y_),
  73151. w (w_),
  73152. font (font_),
  73153. character (character_),
  73154. glyph (glyph_)
  73155. {
  73156. }
  73157. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  73158. : x (other.x),
  73159. y (other.y),
  73160. w (other.w),
  73161. font (other.font),
  73162. character (other.character),
  73163. glyph (other.glyph)
  73164. {
  73165. }
  73166. void PositionedGlyph::draw (const Graphics& g) const
  73167. {
  73168. if (! isWhitespace())
  73169. {
  73170. g.getInternalContext()->setFont (font);
  73171. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  73172. }
  73173. }
  73174. void PositionedGlyph::draw (const Graphics& g,
  73175. const AffineTransform& transform) const
  73176. {
  73177. if (! isWhitespace())
  73178. {
  73179. g.getInternalContext()->setFont (font);
  73180. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  73181. .followedBy (transform));
  73182. }
  73183. }
  73184. void PositionedGlyph::createPath (Path& path) const
  73185. {
  73186. if (! isWhitespace())
  73187. {
  73188. Typeface* const t = font.getTypeface();
  73189. if (t != 0)
  73190. {
  73191. Path p;
  73192. t->getOutlineForGlyph (glyph, p);
  73193. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  73194. .translated (x, y));
  73195. }
  73196. }
  73197. }
  73198. bool PositionedGlyph::hitTest (float px, float py) const
  73199. {
  73200. if (getBounds().contains (px, py) && ! isWhitespace())
  73201. {
  73202. Typeface* const t = font.getTypeface();
  73203. if (t != 0)
  73204. {
  73205. Path p;
  73206. t->getOutlineForGlyph (glyph, p);
  73207. AffineTransform::translation (-x, -y)
  73208. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  73209. .transformPoint (px, py);
  73210. return p.contains (px, py);
  73211. }
  73212. }
  73213. return false;
  73214. }
  73215. void PositionedGlyph::moveBy (const float deltaX,
  73216. const float deltaY)
  73217. {
  73218. x += deltaX;
  73219. y += deltaY;
  73220. }
  73221. GlyphArrangement::GlyphArrangement()
  73222. {
  73223. glyphs.ensureStorageAllocated (128);
  73224. }
  73225. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  73226. {
  73227. addGlyphArrangement (other);
  73228. }
  73229. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  73230. {
  73231. if (this != &other)
  73232. {
  73233. clear();
  73234. addGlyphArrangement (other);
  73235. }
  73236. return *this;
  73237. }
  73238. GlyphArrangement::~GlyphArrangement()
  73239. {
  73240. }
  73241. void GlyphArrangement::clear()
  73242. {
  73243. glyphs.clear();
  73244. }
  73245. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  73246. {
  73247. jassert (isPositiveAndBelow (index, glyphs.size()));
  73248. return *glyphs [index];
  73249. }
  73250. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  73251. {
  73252. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  73253. glyphs.addCopiesOf (other.glyphs);
  73254. }
  73255. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  73256. {
  73257. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  73258. }
  73259. void GlyphArrangement::addLineOfText (const Font& font,
  73260. const String& text,
  73261. const float xOffset,
  73262. const float yOffset)
  73263. {
  73264. addCurtailedLineOfText (font, text,
  73265. xOffset, yOffset,
  73266. 1.0e10f, false);
  73267. }
  73268. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  73269. const String& text,
  73270. float xOffset,
  73271. const float yOffset,
  73272. const float maxWidthPixels,
  73273. const bool useEllipsis)
  73274. {
  73275. if (text.isNotEmpty())
  73276. {
  73277. Array <int> newGlyphs;
  73278. Array <float> xOffsets;
  73279. font.getGlyphPositions (text, newGlyphs, xOffsets);
  73280. const int textLen = newGlyphs.size();
  73281. String::CharPointerType t (text.getCharPointer());
  73282. for (int i = 0; i < textLen; ++i)
  73283. {
  73284. const float thisX = xOffsets.getUnchecked (i);
  73285. const float nextX = xOffsets.getUnchecked (i + 1);
  73286. if (nextX > maxWidthPixels + 1.0f)
  73287. {
  73288. // curtail the string if it's too wide..
  73289. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  73290. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  73291. break;
  73292. }
  73293. else
  73294. {
  73295. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  73296. font, t.getAndAdvance(), newGlyphs.getUnchecked(i)));
  73297. }
  73298. }
  73299. }
  73300. }
  73301. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  73302. const int startIndex, int endIndex)
  73303. {
  73304. int numDeleted = 0;
  73305. if (glyphs.size() > 0)
  73306. {
  73307. Array<int> dotGlyphs;
  73308. Array<float> dotXs;
  73309. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  73310. const float dx = dotXs[1];
  73311. float xOffset = 0.0f, yOffset = 0.0f;
  73312. while (endIndex > startIndex)
  73313. {
  73314. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  73315. xOffset = pg->x;
  73316. yOffset = pg->y;
  73317. glyphs.remove (endIndex);
  73318. ++numDeleted;
  73319. if (xOffset + dx * 3 <= maxXPos)
  73320. break;
  73321. }
  73322. for (int i = 3; --i >= 0;)
  73323. {
  73324. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  73325. font, '.', dotGlyphs.getFirst()));
  73326. --numDeleted;
  73327. xOffset += dx;
  73328. if (xOffset > maxXPos)
  73329. break;
  73330. }
  73331. }
  73332. return numDeleted;
  73333. }
  73334. void GlyphArrangement::addJustifiedText (const Font& font,
  73335. const String& text,
  73336. float x, float y,
  73337. const float maxLineWidth,
  73338. const Justification& horizontalLayout)
  73339. {
  73340. int lineStartIndex = glyphs.size();
  73341. addLineOfText (font, text, x, y);
  73342. const float originalY = y;
  73343. while (lineStartIndex < glyphs.size())
  73344. {
  73345. int i = lineStartIndex;
  73346. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  73347. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  73348. ++i;
  73349. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  73350. int lastWordBreakIndex = -1;
  73351. while (i < glyphs.size())
  73352. {
  73353. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  73354. const juce_wchar c = pg->getCharacter();
  73355. if (c == '\r' || c == '\n')
  73356. {
  73357. ++i;
  73358. if (c == '\r' && i < glyphs.size()
  73359. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  73360. ++i;
  73361. break;
  73362. }
  73363. else if (pg->isWhitespace())
  73364. {
  73365. lastWordBreakIndex = i + 1;
  73366. }
  73367. else if (pg->getRight() - 0.0001f >= lineMaxX)
  73368. {
  73369. if (lastWordBreakIndex >= 0)
  73370. i = lastWordBreakIndex;
  73371. break;
  73372. }
  73373. ++i;
  73374. }
  73375. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  73376. float currentLineEndX = currentLineStartX;
  73377. for (int j = i; --j >= lineStartIndex;)
  73378. {
  73379. if (! glyphs.getUnchecked (j)->isWhitespace())
  73380. {
  73381. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  73382. break;
  73383. }
  73384. }
  73385. float deltaX = 0.0f;
  73386. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  73387. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  73388. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  73389. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  73390. else if (horizontalLayout.testFlags (Justification::right))
  73391. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  73392. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  73393. x + deltaX - currentLineStartX, y - originalY);
  73394. lineStartIndex = i;
  73395. y += font.getHeight();
  73396. }
  73397. }
  73398. void GlyphArrangement::addFittedText (const Font& f,
  73399. const String& text,
  73400. const float x, const float y,
  73401. const float width, const float height,
  73402. const Justification& layout,
  73403. int maximumLines,
  73404. const float minimumHorizontalScale)
  73405. {
  73406. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  73407. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  73408. if (text.containsAnyOf ("\r\n"))
  73409. {
  73410. GlyphArrangement ga;
  73411. ga.addJustifiedText (f, text, x, y, width, layout);
  73412. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  73413. float dy = y - bb.getY();
  73414. if (layout.testFlags (Justification::verticallyCentred))
  73415. dy += (height - bb.getHeight()) * 0.5f;
  73416. else if (layout.testFlags (Justification::bottom))
  73417. dy += height - bb.getHeight();
  73418. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  73419. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  73420. for (int i = 0; i < ga.glyphs.size(); ++i)
  73421. glyphs.add (ga.glyphs.getUnchecked (i));
  73422. ga.glyphs.clear (false);
  73423. return;
  73424. }
  73425. int startIndex = glyphs.size();
  73426. addLineOfText (f, text.trim(), x, y);
  73427. if (glyphs.size() > startIndex)
  73428. {
  73429. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73430. - glyphs.getUnchecked (startIndex)->getLeft();
  73431. if (lineWidth <= 0)
  73432. return;
  73433. if (lineWidth * minimumHorizontalScale < width)
  73434. {
  73435. if (lineWidth > width)
  73436. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  73437. width / lineWidth);
  73438. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  73439. x, y, width, height, layout);
  73440. }
  73441. else if (maximumLines <= 1)
  73442. {
  73443. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  73444. x, y, width, height, f, layout, minimumHorizontalScale);
  73445. }
  73446. else
  73447. {
  73448. Font font (f);
  73449. String txt (text.trim());
  73450. const int length = txt.length();
  73451. const int originalStartIndex = startIndex;
  73452. int numLines = 1;
  73453. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  73454. maximumLines = 1;
  73455. maximumLines = jmin (maximumLines, length);
  73456. while (numLines < maximumLines)
  73457. {
  73458. ++numLines;
  73459. const float newFontHeight = height / (float) numLines;
  73460. if (newFontHeight < font.getHeight())
  73461. {
  73462. font.setHeight (jmax (8.0f, newFontHeight));
  73463. removeRangeOfGlyphs (startIndex, -1);
  73464. addLineOfText (font, txt, x, y);
  73465. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73466. - glyphs.getUnchecked (startIndex)->getLeft();
  73467. }
  73468. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  73469. break;
  73470. }
  73471. if (numLines < 1)
  73472. numLines = 1;
  73473. float lineY = y;
  73474. float widthPerLine = lineWidth / numLines;
  73475. int lastLineStartIndex = 0;
  73476. for (int line = 0; line < numLines; ++line)
  73477. {
  73478. int i = startIndex;
  73479. lastLineStartIndex = i;
  73480. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  73481. if (line == numLines - 1)
  73482. {
  73483. widthPerLine = width;
  73484. i = glyphs.size();
  73485. }
  73486. else
  73487. {
  73488. while (i < glyphs.size())
  73489. {
  73490. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  73491. if (lineWidth > widthPerLine)
  73492. {
  73493. // got to a point where the line's too long, so skip forward to find a
  73494. // good place to break it..
  73495. const int searchStartIndex = i;
  73496. while (i < glyphs.size())
  73497. {
  73498. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73499. {
  73500. if (glyphs.getUnchecked (i)->isWhitespace()
  73501. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73502. {
  73503. ++i;
  73504. break;
  73505. }
  73506. }
  73507. else
  73508. {
  73509. // can't find a suitable break, so try looking backwards..
  73510. i = searchStartIndex;
  73511. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73512. {
  73513. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73514. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73515. {
  73516. i -= back - 1;
  73517. break;
  73518. }
  73519. }
  73520. break;
  73521. }
  73522. ++i;
  73523. }
  73524. break;
  73525. }
  73526. ++i;
  73527. }
  73528. int wsStart = i;
  73529. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73530. --wsStart;
  73531. int wsEnd = i;
  73532. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73533. ++wsEnd;
  73534. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73535. i = jmax (wsStart, startIndex + 1);
  73536. }
  73537. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73538. x, lineY, width, font.getHeight(), font,
  73539. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73540. minimumHorizontalScale);
  73541. startIndex = i;
  73542. lineY += font.getHeight();
  73543. if (startIndex >= glyphs.size())
  73544. break;
  73545. }
  73546. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73547. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73548. }
  73549. }
  73550. }
  73551. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73552. const float dx, const float dy)
  73553. {
  73554. jassert (startIndex >= 0);
  73555. if (dx != 0.0f || dy != 0.0f)
  73556. {
  73557. if (num < 0 || startIndex + num > glyphs.size())
  73558. num = glyphs.size() - startIndex;
  73559. while (--num >= 0)
  73560. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73561. }
  73562. }
  73563. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73564. const Justification& justification, float minimumHorizontalScale)
  73565. {
  73566. int numDeleted = 0;
  73567. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73568. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73569. if (lineWidth > w)
  73570. {
  73571. if (minimumHorizontalScale < 1.0f)
  73572. {
  73573. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73574. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73575. }
  73576. if (lineWidth > w)
  73577. {
  73578. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73579. numGlyphs -= numDeleted;
  73580. }
  73581. }
  73582. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73583. return numDeleted;
  73584. }
  73585. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73586. const float horizontalScaleFactor)
  73587. {
  73588. jassert (startIndex >= 0);
  73589. if (num < 0 || startIndex + num > glyphs.size())
  73590. num = glyphs.size() - startIndex;
  73591. if (num > 0)
  73592. {
  73593. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73594. while (--num >= 0)
  73595. {
  73596. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73597. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73598. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73599. pg->w *= horizontalScaleFactor;
  73600. }
  73601. }
  73602. }
  73603. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73604. {
  73605. jassert (startIndex >= 0);
  73606. if (num < 0 || startIndex + num > glyphs.size())
  73607. num = glyphs.size() - startIndex;
  73608. Rectangle<float> result;
  73609. while (--num >= 0)
  73610. {
  73611. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73612. if (includeWhitespace || ! pg->isWhitespace())
  73613. result = result.getUnion (pg->getBounds());
  73614. }
  73615. return result;
  73616. }
  73617. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73618. const float x, const float y, const float width, const float height,
  73619. const Justification& justification)
  73620. {
  73621. jassert (num >= 0 && startIndex >= 0);
  73622. if (glyphs.size() > 0 && num > 0)
  73623. {
  73624. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73625. | Justification::horizontallyCentred)));
  73626. float deltaX = 0.0f;
  73627. if (justification.testFlags (Justification::horizontallyJustified))
  73628. deltaX = x - bb.getX();
  73629. else if (justification.testFlags (Justification::horizontallyCentred))
  73630. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73631. else if (justification.testFlags (Justification::right))
  73632. deltaX = (x + width) - bb.getRight();
  73633. else
  73634. deltaX = x - bb.getX();
  73635. float deltaY = 0.0f;
  73636. if (justification.testFlags (Justification::top))
  73637. deltaY = y - bb.getY();
  73638. else if (justification.testFlags (Justification::bottom))
  73639. deltaY = (y + height) - bb.getBottom();
  73640. else
  73641. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73642. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73643. if (justification.testFlags (Justification::horizontallyJustified))
  73644. {
  73645. int lineStart = 0;
  73646. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73647. int i;
  73648. for (i = 0; i < num; ++i)
  73649. {
  73650. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73651. if (glyphY != baseY)
  73652. {
  73653. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73654. lineStart = i;
  73655. baseY = glyphY;
  73656. }
  73657. }
  73658. if (i > lineStart)
  73659. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73660. }
  73661. }
  73662. }
  73663. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73664. {
  73665. if (start + num < glyphs.size()
  73666. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73667. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73668. {
  73669. int numSpaces = 0;
  73670. int spacesAtEnd = 0;
  73671. for (int i = 0; i < num; ++i)
  73672. {
  73673. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73674. {
  73675. ++spacesAtEnd;
  73676. ++numSpaces;
  73677. }
  73678. else
  73679. {
  73680. spacesAtEnd = 0;
  73681. }
  73682. }
  73683. numSpaces -= spacesAtEnd;
  73684. if (numSpaces > 0)
  73685. {
  73686. const float startX = glyphs.getUnchecked (start)->getLeft();
  73687. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73688. const float extraPaddingBetweenWords
  73689. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73690. float deltaX = 0.0f;
  73691. for (int i = 0; i < num; ++i)
  73692. {
  73693. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73694. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73695. deltaX += extraPaddingBetweenWords;
  73696. }
  73697. }
  73698. }
  73699. }
  73700. void GlyphArrangement::draw (const Graphics& g) const
  73701. {
  73702. for (int i = 0; i < glyphs.size(); ++i)
  73703. {
  73704. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73705. if (pg->font.isUnderlined())
  73706. {
  73707. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73708. float nextX = pg->x + pg->w;
  73709. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73710. nextX = glyphs.getUnchecked (i + 1)->x;
  73711. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73712. nextX - pg->x, lineThickness);
  73713. }
  73714. pg->draw (g);
  73715. }
  73716. }
  73717. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73718. {
  73719. for (int i = 0; i < glyphs.size(); ++i)
  73720. {
  73721. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73722. if (pg->font.isUnderlined())
  73723. {
  73724. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73725. float nextX = pg->x + pg->w;
  73726. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73727. nextX = glyphs.getUnchecked (i + 1)->x;
  73728. Path p;
  73729. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73730. nextX, pg->y + lineThickness * 2.0f),
  73731. lineThickness);
  73732. g.fillPath (p, transform);
  73733. }
  73734. pg->draw (g, transform);
  73735. }
  73736. }
  73737. void GlyphArrangement::createPath (Path& path) const
  73738. {
  73739. for (int i = 0; i < glyphs.size(); ++i)
  73740. glyphs.getUnchecked (i)->createPath (path);
  73741. }
  73742. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73743. {
  73744. for (int i = 0; i < glyphs.size(); ++i)
  73745. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73746. return i;
  73747. return -1;
  73748. }
  73749. END_JUCE_NAMESPACE
  73750. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73751. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73752. BEGIN_JUCE_NAMESPACE
  73753. class TextLayout::Token
  73754. {
  73755. public:
  73756. Token (const String& t,
  73757. const Font& f,
  73758. const bool isWhitespace_)
  73759. : text (t),
  73760. font (f),
  73761. x(0),
  73762. y(0),
  73763. isWhitespace (isWhitespace_)
  73764. {
  73765. w = font.getStringWidth (t);
  73766. h = roundToInt (f.getHeight());
  73767. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73768. }
  73769. Token (const Token& other)
  73770. : text (other.text),
  73771. font (other.font),
  73772. x (other.x),
  73773. y (other.y),
  73774. w (other.w),
  73775. h (other.h),
  73776. line (other.line),
  73777. lineHeight (other.lineHeight),
  73778. isWhitespace (other.isWhitespace),
  73779. isNewLine (other.isNewLine)
  73780. {
  73781. }
  73782. void draw (Graphics& g,
  73783. const int xOffset,
  73784. const int yOffset)
  73785. {
  73786. if (! isWhitespace)
  73787. {
  73788. g.setFont (font);
  73789. g.drawSingleLineText (text.trimEnd(),
  73790. xOffset + x,
  73791. yOffset + y + (lineHeight - h)
  73792. + roundToInt (font.getAscent()));
  73793. }
  73794. }
  73795. String text;
  73796. Font font;
  73797. int x, y, w, h;
  73798. int line, lineHeight;
  73799. bool isWhitespace, isNewLine;
  73800. private:
  73801. JUCE_LEAK_DETECTOR (Token);
  73802. };
  73803. TextLayout::TextLayout()
  73804. : totalLines (0)
  73805. {
  73806. tokens.ensureStorageAllocated (64);
  73807. }
  73808. TextLayout::TextLayout (const String& text, const Font& font)
  73809. : totalLines (0)
  73810. {
  73811. tokens.ensureStorageAllocated (64);
  73812. appendText (text, font);
  73813. }
  73814. TextLayout::TextLayout (const TextLayout& other)
  73815. : totalLines (0)
  73816. {
  73817. *this = other;
  73818. }
  73819. TextLayout& TextLayout::operator= (const TextLayout& other)
  73820. {
  73821. if (this != &other)
  73822. {
  73823. clear();
  73824. totalLines = other.totalLines;
  73825. tokens.addCopiesOf (other.tokens);
  73826. }
  73827. return *this;
  73828. }
  73829. TextLayout::~TextLayout()
  73830. {
  73831. clear();
  73832. }
  73833. void TextLayout::clear()
  73834. {
  73835. tokens.clear();
  73836. totalLines = 0;
  73837. }
  73838. bool TextLayout::isEmpty() const
  73839. {
  73840. return tokens.size() == 0;
  73841. }
  73842. void TextLayout::appendText (const String& text, const Font& font)
  73843. {
  73844. String::CharPointerType t (text.getCharPointer());
  73845. String currentString;
  73846. int lastCharType = 0;
  73847. for (;;)
  73848. {
  73849. const juce_wchar c = t.getAndAdvance();
  73850. if (c == 0)
  73851. break;
  73852. int charType;
  73853. if (c == '\r' || c == '\n')
  73854. {
  73855. charType = 0;
  73856. }
  73857. else if (CharacterFunctions::isWhitespace (c))
  73858. {
  73859. charType = 2;
  73860. }
  73861. else
  73862. {
  73863. charType = 1;
  73864. }
  73865. if (charType == 0 || charType != lastCharType)
  73866. {
  73867. if (currentString.isNotEmpty())
  73868. {
  73869. tokens.add (new Token (currentString, font,
  73870. lastCharType == 2 || lastCharType == 0));
  73871. }
  73872. currentString = String::charToString (c);
  73873. if (c == '\r' && *t == '\n')
  73874. currentString += t.getAndAdvance();
  73875. }
  73876. else
  73877. {
  73878. currentString += c;
  73879. }
  73880. lastCharType = charType;
  73881. }
  73882. if (currentString.isNotEmpty())
  73883. tokens.add (new Token (currentString, font, lastCharType == 2));
  73884. }
  73885. void TextLayout::setText (const String& text, const Font& font)
  73886. {
  73887. clear();
  73888. appendText (text, font);
  73889. }
  73890. void TextLayout::layout (int maxWidth,
  73891. const Justification& justification,
  73892. const bool attemptToBalanceLineLengths)
  73893. {
  73894. if (attemptToBalanceLineLengths)
  73895. {
  73896. const int originalW = maxWidth;
  73897. int bestWidth = maxWidth;
  73898. float bestLineProportion = 0.0f;
  73899. while (maxWidth > originalW / 2)
  73900. {
  73901. layout (maxWidth, justification, false);
  73902. if (getNumLines() <= 1)
  73903. return;
  73904. const int lastLineW = getLineWidth (getNumLines() - 1);
  73905. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73906. const float prop = lastLineW / (float) lastButOneLineW;
  73907. if (prop > 0.9f)
  73908. return;
  73909. if (prop > bestLineProportion)
  73910. {
  73911. bestLineProportion = prop;
  73912. bestWidth = maxWidth;
  73913. }
  73914. maxWidth -= 10;
  73915. }
  73916. layout (bestWidth, justification, false);
  73917. }
  73918. else
  73919. {
  73920. int x = 0;
  73921. int y = 0;
  73922. int h = 0;
  73923. totalLines = 0;
  73924. int i;
  73925. for (i = 0; i < tokens.size(); ++i)
  73926. {
  73927. Token* const t = tokens.getUnchecked(i);
  73928. t->x = x;
  73929. t->y = y;
  73930. t->line = totalLines;
  73931. x += t->w;
  73932. h = jmax (h, t->h);
  73933. const Token* nextTok = tokens [i + 1];
  73934. if (nextTok == 0)
  73935. break;
  73936. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73937. {
  73938. // finished a line, so go back and update the heights of the things on it
  73939. for (int j = i; j >= 0; --j)
  73940. {
  73941. Token* const tok = tokens.getUnchecked(j);
  73942. if (tok->line == totalLines)
  73943. tok->lineHeight = h;
  73944. else
  73945. break;
  73946. }
  73947. x = 0;
  73948. y += h;
  73949. h = 0;
  73950. ++totalLines;
  73951. }
  73952. }
  73953. // finished a line, so go back and update the heights of the things on it
  73954. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73955. {
  73956. Token* const t = tokens.getUnchecked(j);
  73957. if (t->line == totalLines)
  73958. t->lineHeight = h;
  73959. else
  73960. break;
  73961. }
  73962. ++totalLines;
  73963. if (! justification.testFlags (Justification::left))
  73964. {
  73965. int totalW = getWidth();
  73966. for (i = totalLines; --i >= 0;)
  73967. {
  73968. const int lineW = getLineWidth (i);
  73969. int dx = 0;
  73970. if (justification.testFlags (Justification::horizontallyCentred))
  73971. dx = (totalW - lineW) / 2;
  73972. else if (justification.testFlags (Justification::right))
  73973. dx = totalW - lineW;
  73974. for (int j = tokens.size(); --j >= 0;)
  73975. {
  73976. Token* const t = tokens.getUnchecked(j);
  73977. if (t->line == i)
  73978. t->x += dx;
  73979. }
  73980. }
  73981. }
  73982. }
  73983. }
  73984. int TextLayout::getLineWidth (const int lineNumber) const
  73985. {
  73986. int maxW = 0;
  73987. for (int i = tokens.size(); --i >= 0;)
  73988. {
  73989. const Token* const t = tokens.getUnchecked(i);
  73990. if (t->line == lineNumber && ! t->isWhitespace)
  73991. maxW = jmax (maxW, t->x + t->w);
  73992. }
  73993. return maxW;
  73994. }
  73995. int TextLayout::getWidth() const
  73996. {
  73997. int maxW = 0;
  73998. for (int i = tokens.size(); --i >= 0;)
  73999. {
  74000. const Token* const t = tokens.getUnchecked(i);
  74001. if (! t->isWhitespace)
  74002. maxW = jmax (maxW, t->x + t->w);
  74003. }
  74004. return maxW;
  74005. }
  74006. int TextLayout::getHeight() const
  74007. {
  74008. int maxH = 0;
  74009. for (int i = tokens.size(); --i >= 0;)
  74010. {
  74011. const Token* const t = tokens.getUnchecked(i);
  74012. if (! t->isWhitespace)
  74013. maxH = jmax (maxH, t->y + t->h);
  74014. }
  74015. return maxH;
  74016. }
  74017. void TextLayout::draw (Graphics& g,
  74018. const int xOffset,
  74019. const int yOffset) const
  74020. {
  74021. for (int i = tokens.size(); --i >= 0;)
  74022. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  74023. }
  74024. void TextLayout::drawWithin (Graphics& g,
  74025. int x, int y, int w, int h,
  74026. const Justification& justification) const
  74027. {
  74028. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  74029. x, y, w, h);
  74030. draw (g, x, y);
  74031. }
  74032. END_JUCE_NAMESPACE
  74033. /*** End of inlined file: juce_TextLayout.cpp ***/
  74034. /*** Start of inlined file: juce_Typeface.cpp ***/
  74035. BEGIN_JUCE_NAMESPACE
  74036. Typeface::Typeface (const String& name_) throw()
  74037. : name (name_), isFallbackFont (false)
  74038. {
  74039. }
  74040. Typeface::~Typeface()
  74041. {
  74042. }
  74043. const Typeface::Ptr Typeface::getFallbackTypeface()
  74044. {
  74045. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  74046. Typeface* t = fallbackFont.getTypeface();
  74047. t->isFallbackFont = true;
  74048. return t;
  74049. }
  74050. class CustomTypeface::GlyphInfo
  74051. {
  74052. public:
  74053. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  74054. : character (character_), path (path_), width (width_)
  74055. {
  74056. }
  74057. struct KerningPair
  74058. {
  74059. juce_wchar character2;
  74060. float kerningAmount;
  74061. };
  74062. void addKerningPair (const juce_wchar subsequentCharacter,
  74063. const float extraKerningAmount) throw()
  74064. {
  74065. KerningPair kp;
  74066. kp.character2 = subsequentCharacter;
  74067. kp.kerningAmount = extraKerningAmount;
  74068. kerningPairs.add (kp);
  74069. }
  74070. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  74071. {
  74072. if (subsequentCharacter != 0)
  74073. {
  74074. for (int i = kerningPairs.size(); --i >= 0;)
  74075. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  74076. return width + kerningPairs.getReference(i).kerningAmount;
  74077. }
  74078. return width;
  74079. }
  74080. const juce_wchar character;
  74081. const Path path;
  74082. float width;
  74083. Array <KerningPair> kerningPairs;
  74084. private:
  74085. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  74086. };
  74087. CustomTypeface::CustomTypeface()
  74088. : Typeface (String::empty)
  74089. {
  74090. clear();
  74091. }
  74092. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  74093. : Typeface (String::empty)
  74094. {
  74095. clear();
  74096. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  74097. BufferedInputStream in (gzin, 32768);
  74098. name = in.readString();
  74099. isBold = in.readBool();
  74100. isItalic = in.readBool();
  74101. ascent = in.readFloat();
  74102. defaultCharacter = (juce_wchar) in.readShort();
  74103. int i, numChars = in.readInt();
  74104. for (i = 0; i < numChars; ++i)
  74105. {
  74106. const juce_wchar c = (juce_wchar) in.readShort();
  74107. const float width = in.readFloat();
  74108. Path p;
  74109. p.loadPathFromStream (in);
  74110. addGlyph (c, p, width);
  74111. }
  74112. const int numKerningPairs = in.readInt();
  74113. for (i = 0; i < numKerningPairs; ++i)
  74114. {
  74115. const juce_wchar char1 = (juce_wchar) in.readShort();
  74116. const juce_wchar char2 = (juce_wchar) in.readShort();
  74117. addKerningPair (char1, char2, in.readFloat());
  74118. }
  74119. }
  74120. CustomTypeface::~CustomTypeface()
  74121. {
  74122. }
  74123. void CustomTypeface::clear()
  74124. {
  74125. defaultCharacter = 0;
  74126. ascent = 1.0f;
  74127. isBold = isItalic = false;
  74128. zeromem (lookupTable, sizeof (lookupTable));
  74129. glyphs.clear();
  74130. }
  74131. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  74132. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  74133. {
  74134. name = name_;
  74135. defaultCharacter = defaultCharacter_;
  74136. ascent = ascent_;
  74137. isBold = isBold_;
  74138. isItalic = isItalic_;
  74139. }
  74140. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  74141. {
  74142. // Check that you're not trying to add the same character twice..
  74143. jassert (findGlyph (character, false) == 0);
  74144. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  74145. lookupTable [character] = (short) glyphs.size();
  74146. glyphs.add (new GlyphInfo (character, path, width));
  74147. }
  74148. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  74149. {
  74150. if (extraAmount != 0)
  74151. {
  74152. GlyphInfo* const g = findGlyph (char1, true);
  74153. jassert (g != 0); // can only add kerning pairs for characters that exist!
  74154. if (g != 0)
  74155. g->addKerningPair (char2, extraAmount);
  74156. }
  74157. }
  74158. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  74159. {
  74160. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  74161. return glyphs [(int) lookupTable [(int) character]];
  74162. for (int i = 0; i < glyphs.size(); ++i)
  74163. {
  74164. GlyphInfo* const g = glyphs.getUnchecked(i);
  74165. if (g->character == character)
  74166. return g;
  74167. }
  74168. if (loadIfNeeded && loadGlyphIfPossible (character))
  74169. return findGlyph (character, false);
  74170. return 0;
  74171. }
  74172. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  74173. {
  74174. GlyphInfo* glyph = findGlyph (character, true);
  74175. if (glyph == 0)
  74176. {
  74177. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  74178. glyph = findGlyph (L' ', true);
  74179. if (glyph == 0)
  74180. {
  74181. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  74182. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  74183. if (fallbackTypeface != 0 && fallbackTypeface != this)
  74184. {
  74185. Path path;
  74186. fallbackTypeface->getOutlineForGlyph (character, path);
  74187. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  74188. }
  74189. if (glyph == 0)
  74190. glyph = findGlyph (defaultCharacter, true);
  74191. }
  74192. }
  74193. return glyph;
  74194. }
  74195. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  74196. {
  74197. return false;
  74198. }
  74199. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  74200. {
  74201. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  74202. for (int i = 0; i < numCharacters; ++i)
  74203. {
  74204. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  74205. Array <int> glyphIndexes;
  74206. Array <float> offsets;
  74207. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  74208. const int glyphIndex = glyphIndexes.getFirst();
  74209. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  74210. {
  74211. const float glyphWidth = offsets[1];
  74212. Path p;
  74213. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  74214. addGlyph (c, p, glyphWidth);
  74215. for (int j = glyphs.size() - 1; --j >= 0;)
  74216. {
  74217. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  74218. glyphIndexes.clearQuick();
  74219. offsets.clearQuick();
  74220. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  74221. if (offsets.size() > 1)
  74222. addKerningPair (c, char2, offsets[1] - glyphWidth);
  74223. }
  74224. }
  74225. }
  74226. }
  74227. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  74228. {
  74229. GZIPCompressorOutputStream out (&outputStream);
  74230. out.writeString (name);
  74231. out.writeBool (isBold);
  74232. out.writeBool (isItalic);
  74233. out.writeFloat (ascent);
  74234. out.writeShort ((short) (unsigned short) defaultCharacter);
  74235. out.writeInt (glyphs.size());
  74236. int i, numKerningPairs = 0;
  74237. for (i = 0; i < glyphs.size(); ++i)
  74238. {
  74239. const GlyphInfo* const g = glyphs.getUnchecked (i);
  74240. out.writeShort ((short) (unsigned short) g->character);
  74241. out.writeFloat (g->width);
  74242. g->path.writePathToStream (out);
  74243. numKerningPairs += g->kerningPairs.size();
  74244. }
  74245. out.writeInt (numKerningPairs);
  74246. for (i = 0; i < glyphs.size(); ++i)
  74247. {
  74248. const GlyphInfo* const g = glyphs.getUnchecked (i);
  74249. for (int j = 0; j < g->kerningPairs.size(); ++j)
  74250. {
  74251. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  74252. out.writeShort ((short) (unsigned short) g->character);
  74253. out.writeShort ((short) (unsigned short) p.character2);
  74254. out.writeFloat (p.kerningAmount);
  74255. }
  74256. }
  74257. return true;
  74258. }
  74259. float CustomTypeface::getAscent() const
  74260. {
  74261. return ascent;
  74262. }
  74263. float CustomTypeface::getDescent() const
  74264. {
  74265. return 1.0f - ascent;
  74266. }
  74267. float CustomTypeface::getStringWidth (const String& text)
  74268. {
  74269. float x = 0;
  74270. String::CharPointerType t (text.getCharPointer());
  74271. while (! t.isEmpty())
  74272. {
  74273. const GlyphInfo* const glyph = findGlyphSubstituting (t.getAndAdvance());
  74274. if (glyph == 0 && ! isFallbackFont)
  74275. {
  74276. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  74277. if (fallbackTypeface != 0)
  74278. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  74279. }
  74280. if (glyph != 0)
  74281. x += glyph->getHorizontalSpacing (*t);
  74282. }
  74283. return x;
  74284. }
  74285. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  74286. {
  74287. xOffsets.add (0);
  74288. float x = 0;
  74289. String::CharPointerType t (text.getCharPointer());
  74290. while (! t.isEmpty())
  74291. {
  74292. const juce_wchar c = t.getAndAdvance();
  74293. const GlyphInfo* const glyph = findGlyph (c, true);
  74294. if (glyph == 0 && ! isFallbackFont)
  74295. {
  74296. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  74297. if (fallbackTypeface != 0)
  74298. {
  74299. Array <int> subGlyphs;
  74300. Array <float> subOffsets;
  74301. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  74302. if (subGlyphs.size() > 0)
  74303. {
  74304. resultGlyphs.add (subGlyphs.getFirst());
  74305. x += subOffsets[1];
  74306. xOffsets.add (x);
  74307. }
  74308. }
  74309. }
  74310. if (glyph != 0)
  74311. {
  74312. x += glyph->getHorizontalSpacing (*t);
  74313. resultGlyphs.add ((int) glyph->character);
  74314. xOffsets.add (x);
  74315. }
  74316. }
  74317. }
  74318. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  74319. {
  74320. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  74321. if (glyph == 0 && ! isFallbackFont)
  74322. {
  74323. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  74324. if (fallbackTypeface != 0)
  74325. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  74326. }
  74327. if (glyph != 0)
  74328. {
  74329. path = glyph->path;
  74330. return true;
  74331. }
  74332. return false;
  74333. }
  74334. EdgeTable* CustomTypeface::getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform)
  74335. {
  74336. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  74337. if (glyph == 0 && ! isFallbackFont)
  74338. {
  74339. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  74340. if (fallbackTypeface != 0)
  74341. return fallbackTypeface->getEdgeTableForGlyph (glyphNumber, transform);
  74342. }
  74343. if (glyph != 0 && ! glyph->path.isEmpty())
  74344. return new EdgeTable (glyph->path.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  74345. glyph->path, transform);
  74346. return 0;
  74347. }
  74348. END_JUCE_NAMESPACE
  74349. /*** End of inlined file: juce_Typeface.cpp ***/
  74350. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  74351. BEGIN_JUCE_NAMESPACE
  74352. AffineTransform::AffineTransform() throw()
  74353. : mat00 (1.0f), mat01 (0), mat02 (0),
  74354. mat10 (0), mat11 (1.0f), mat12 (0)
  74355. {
  74356. }
  74357. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  74358. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  74359. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  74360. {
  74361. }
  74362. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  74363. const float mat10_, const float mat11_, const float mat12_) throw()
  74364. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  74365. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  74366. {
  74367. }
  74368. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  74369. {
  74370. mat00 = other.mat00;
  74371. mat01 = other.mat01;
  74372. mat02 = other.mat02;
  74373. mat10 = other.mat10;
  74374. mat11 = other.mat11;
  74375. mat12 = other.mat12;
  74376. return *this;
  74377. }
  74378. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  74379. {
  74380. return mat00 == other.mat00
  74381. && mat01 == other.mat01
  74382. && mat02 == other.mat02
  74383. && mat10 == other.mat10
  74384. && mat11 == other.mat11
  74385. && mat12 == other.mat12;
  74386. }
  74387. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  74388. {
  74389. return ! operator== (other);
  74390. }
  74391. bool AffineTransform::isIdentity() const throw()
  74392. {
  74393. return (mat01 == 0)
  74394. && (mat02 == 0)
  74395. && (mat10 == 0)
  74396. && (mat12 == 0)
  74397. && (mat00 == 1.0f)
  74398. && (mat11 == 1.0f);
  74399. }
  74400. const AffineTransform AffineTransform::identity;
  74401. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  74402. {
  74403. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  74404. other.mat00 * mat01 + other.mat01 * mat11,
  74405. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  74406. other.mat10 * mat00 + other.mat11 * mat10,
  74407. other.mat10 * mat01 + other.mat11 * mat11,
  74408. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  74409. }
  74410. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  74411. {
  74412. return AffineTransform (mat00, mat01, mat02 + dx,
  74413. mat10, mat11, mat12 + dy);
  74414. }
  74415. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  74416. {
  74417. return AffineTransform (1.0f, 0, dx,
  74418. 0, 1.0f, dy);
  74419. }
  74420. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  74421. {
  74422. const float cosRad = std::cos (rad);
  74423. const float sinRad = std::sin (rad);
  74424. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  74425. cosRad * mat01 + -sinRad * mat11,
  74426. cosRad * mat02 + -sinRad * mat12,
  74427. sinRad * mat00 + cosRad * mat10,
  74428. sinRad * mat01 + cosRad * mat11,
  74429. sinRad * mat02 + cosRad * mat12);
  74430. }
  74431. const AffineTransform AffineTransform::rotation (const float rad) throw()
  74432. {
  74433. const float cosRad = std::cos (rad);
  74434. const float sinRad = std::sin (rad);
  74435. return AffineTransform (cosRad, -sinRad, 0,
  74436. sinRad, cosRad, 0);
  74437. }
  74438. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  74439. {
  74440. const float cosRad = std::cos (rad);
  74441. const float sinRad = std::sin (rad);
  74442. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  74443. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  74444. }
  74445. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  74446. {
  74447. return followedBy (rotation (angle, pivotX, pivotY));
  74448. }
  74449. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  74450. {
  74451. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  74452. factorY * mat10, factorY * mat11, factorY * mat12);
  74453. }
  74454. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  74455. {
  74456. return AffineTransform (factorX, 0, 0,
  74457. 0, factorY, 0);
  74458. }
  74459. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  74460. const float pivotX, const float pivotY) const throw()
  74461. {
  74462. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  74463. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  74464. }
  74465. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  74466. const float pivotX, const float pivotY) throw()
  74467. {
  74468. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  74469. 0, factorY, pivotY * (1.0f - factorY));
  74470. }
  74471. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  74472. {
  74473. return AffineTransform (1.0f, shearX, 0,
  74474. shearY, 1.0f, 0);
  74475. }
  74476. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  74477. {
  74478. return AffineTransform (mat00 + shearX * mat10,
  74479. mat01 + shearX * mat11,
  74480. mat02 + shearX * mat12,
  74481. shearY * mat00 + mat10,
  74482. shearY * mat01 + mat11,
  74483. shearY * mat02 + mat12);
  74484. }
  74485. const AffineTransform AffineTransform::inverted() const throw()
  74486. {
  74487. double determinant = (mat00 * mat11 - mat10 * mat01);
  74488. if (determinant != 0.0)
  74489. {
  74490. determinant = 1.0 / determinant;
  74491. const float dst00 = (float) (mat11 * determinant);
  74492. const float dst10 = (float) (-mat10 * determinant);
  74493. const float dst01 = (float) (-mat01 * determinant);
  74494. const float dst11 = (float) (mat00 * determinant);
  74495. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  74496. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  74497. }
  74498. else
  74499. {
  74500. // singularity..
  74501. return *this;
  74502. }
  74503. }
  74504. bool AffineTransform::isSingularity() const throw()
  74505. {
  74506. return (mat00 * mat11 - mat10 * mat01) == 0;
  74507. }
  74508. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  74509. const float x10, const float y10,
  74510. const float x01, const float y01) throw()
  74511. {
  74512. return AffineTransform (x10 - x00, x01 - x00, x00,
  74513. y10 - y00, y01 - y00, y00);
  74514. }
  74515. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74516. const float sx2, const float sy2, const float tx2, const float ty2,
  74517. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74518. {
  74519. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74520. .inverted()
  74521. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74522. }
  74523. bool AffineTransform::isOnlyTranslation() const throw()
  74524. {
  74525. return (mat01 == 0)
  74526. && (mat10 == 0)
  74527. && (mat00 == 1.0f)
  74528. && (mat11 == 1.0f);
  74529. }
  74530. float AffineTransform::getScaleFactor() const throw()
  74531. {
  74532. return juce_hypot (mat00 + mat01, mat10 + mat11);
  74533. }
  74534. END_JUCE_NAMESPACE
  74535. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74536. /*** Start of inlined file: juce_Path.cpp ***/
  74537. BEGIN_JUCE_NAMESPACE
  74538. // tests that some co-ords aren't NaNs
  74539. #define CHECK_COORDS_ARE_VALID(x, y) \
  74540. jassert (x == x && y == y);
  74541. namespace PathHelpers
  74542. {
  74543. const float ellipseAngularIncrement = 0.05f;
  74544. const String nextToken (String::CharPointerType& t)
  74545. {
  74546. t = t.findEndOfWhitespace();
  74547. String::CharPointerType start (t);
  74548. int numChars = 0;
  74549. while (! (t.isEmpty() || t.isWhitespace()))
  74550. {
  74551. ++t;
  74552. ++numChars;
  74553. }
  74554. return String (start, numChars);
  74555. }
  74556. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  74557. {
  74558. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  74559. }
  74560. }
  74561. const float Path::lineMarker = 100001.0f;
  74562. const float Path::moveMarker = 100002.0f;
  74563. const float Path::quadMarker = 100003.0f;
  74564. const float Path::cubicMarker = 100004.0f;
  74565. const float Path::closeSubPathMarker = 100005.0f;
  74566. Path::Path()
  74567. : numElements (0),
  74568. pathXMin (0),
  74569. pathXMax (0),
  74570. pathYMin (0),
  74571. pathYMax (0),
  74572. useNonZeroWinding (true)
  74573. {
  74574. }
  74575. Path::~Path()
  74576. {
  74577. }
  74578. Path::Path (const Path& other)
  74579. : numElements (other.numElements),
  74580. pathXMin (other.pathXMin),
  74581. pathXMax (other.pathXMax),
  74582. pathYMin (other.pathYMin),
  74583. pathYMax (other.pathYMax),
  74584. useNonZeroWinding (other.useNonZeroWinding)
  74585. {
  74586. if (numElements > 0)
  74587. {
  74588. data.setAllocatedSize ((int) numElements);
  74589. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74590. }
  74591. }
  74592. Path& Path::operator= (const Path& other)
  74593. {
  74594. if (this != &other)
  74595. {
  74596. data.ensureAllocatedSize ((int) other.numElements);
  74597. numElements = other.numElements;
  74598. pathXMin = other.pathXMin;
  74599. pathXMax = other.pathXMax;
  74600. pathYMin = other.pathYMin;
  74601. pathYMax = other.pathYMax;
  74602. useNonZeroWinding = other.useNonZeroWinding;
  74603. if (numElements > 0)
  74604. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74605. }
  74606. return *this;
  74607. }
  74608. bool Path::operator== (const Path& other) const throw()
  74609. {
  74610. return ! operator!= (other);
  74611. }
  74612. bool Path::operator!= (const Path& other) const throw()
  74613. {
  74614. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74615. return true;
  74616. for (size_t i = 0; i < numElements; ++i)
  74617. if (data.elements[i] != other.data.elements[i])
  74618. return true;
  74619. return false;
  74620. }
  74621. void Path::clear() throw()
  74622. {
  74623. numElements = 0;
  74624. pathXMin = 0;
  74625. pathYMin = 0;
  74626. pathYMax = 0;
  74627. pathXMax = 0;
  74628. }
  74629. void Path::swapWithPath (Path& other) throw()
  74630. {
  74631. data.swapWith (other.data);
  74632. swapVariables <size_t> (numElements, other.numElements);
  74633. swapVariables <float> (pathXMin, other.pathXMin);
  74634. swapVariables <float> (pathXMax, other.pathXMax);
  74635. swapVariables <float> (pathYMin, other.pathYMin);
  74636. swapVariables <float> (pathYMax, other.pathYMax);
  74637. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74638. }
  74639. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74640. {
  74641. useNonZeroWinding = isNonZero;
  74642. }
  74643. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74644. const bool preserveProportions) throw()
  74645. {
  74646. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74647. }
  74648. bool Path::isEmpty() const throw()
  74649. {
  74650. size_t i = 0;
  74651. while (i < numElements)
  74652. {
  74653. const float type = data.elements [i++];
  74654. if (type == moveMarker)
  74655. {
  74656. i += 2;
  74657. }
  74658. else if (type == lineMarker
  74659. || type == quadMarker
  74660. || type == cubicMarker)
  74661. {
  74662. return false;
  74663. }
  74664. }
  74665. return true;
  74666. }
  74667. const Rectangle<float> Path::getBounds() const throw()
  74668. {
  74669. return Rectangle<float> (pathXMin, pathYMin,
  74670. pathXMax - pathXMin,
  74671. pathYMax - pathYMin);
  74672. }
  74673. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74674. {
  74675. return getBounds().transformed (transform);
  74676. }
  74677. void Path::startNewSubPath (const float x, const float y)
  74678. {
  74679. CHECK_COORDS_ARE_VALID (x, y);
  74680. if (numElements == 0)
  74681. {
  74682. pathXMin = pathXMax = x;
  74683. pathYMin = pathYMax = y;
  74684. }
  74685. else
  74686. {
  74687. pathXMin = jmin (pathXMin, x);
  74688. pathXMax = jmax (pathXMax, x);
  74689. pathYMin = jmin (pathYMin, y);
  74690. pathYMax = jmax (pathYMax, y);
  74691. }
  74692. data.ensureAllocatedSize ((int) numElements + 3);
  74693. data.elements [numElements++] = moveMarker;
  74694. data.elements [numElements++] = x;
  74695. data.elements [numElements++] = y;
  74696. }
  74697. void Path::startNewSubPath (const Point<float>& start)
  74698. {
  74699. startNewSubPath (start.getX(), start.getY());
  74700. }
  74701. void Path::lineTo (const float x, const float y)
  74702. {
  74703. CHECK_COORDS_ARE_VALID (x, y);
  74704. if (numElements == 0)
  74705. startNewSubPath (0, 0);
  74706. data.ensureAllocatedSize ((int) numElements + 3);
  74707. data.elements [numElements++] = lineMarker;
  74708. data.elements [numElements++] = x;
  74709. data.elements [numElements++] = y;
  74710. pathXMin = jmin (pathXMin, x);
  74711. pathXMax = jmax (pathXMax, x);
  74712. pathYMin = jmin (pathYMin, y);
  74713. pathYMax = jmax (pathYMax, y);
  74714. }
  74715. void Path::lineTo (const Point<float>& end)
  74716. {
  74717. lineTo (end.getX(), end.getY());
  74718. }
  74719. void Path::quadraticTo (const float x1, const float y1,
  74720. const float x2, const float y2)
  74721. {
  74722. CHECK_COORDS_ARE_VALID (x1, y1);
  74723. CHECK_COORDS_ARE_VALID (x2, y2);
  74724. if (numElements == 0)
  74725. startNewSubPath (0, 0);
  74726. data.ensureAllocatedSize ((int) numElements + 5);
  74727. data.elements [numElements++] = quadMarker;
  74728. data.elements [numElements++] = x1;
  74729. data.elements [numElements++] = y1;
  74730. data.elements [numElements++] = x2;
  74731. data.elements [numElements++] = y2;
  74732. pathXMin = jmin (pathXMin, x1, x2);
  74733. pathXMax = jmax (pathXMax, x1, x2);
  74734. pathYMin = jmin (pathYMin, y1, y2);
  74735. pathYMax = jmax (pathYMax, y1, y2);
  74736. }
  74737. void Path::quadraticTo (const Point<float>& controlPoint,
  74738. const Point<float>& endPoint)
  74739. {
  74740. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74741. endPoint.getX(), endPoint.getY());
  74742. }
  74743. void Path::cubicTo (const float x1, const float y1,
  74744. const float x2, const float y2,
  74745. const float x3, const float y3)
  74746. {
  74747. CHECK_COORDS_ARE_VALID (x1, y1);
  74748. CHECK_COORDS_ARE_VALID (x2, y2);
  74749. CHECK_COORDS_ARE_VALID (x3, y3);
  74750. if (numElements == 0)
  74751. startNewSubPath (0, 0);
  74752. data.ensureAllocatedSize ((int) numElements + 7);
  74753. data.elements [numElements++] = cubicMarker;
  74754. data.elements [numElements++] = x1;
  74755. data.elements [numElements++] = y1;
  74756. data.elements [numElements++] = x2;
  74757. data.elements [numElements++] = y2;
  74758. data.elements [numElements++] = x3;
  74759. data.elements [numElements++] = y3;
  74760. pathXMin = jmin (pathXMin, x1, x2, x3);
  74761. pathXMax = jmax (pathXMax, x1, x2, x3);
  74762. pathYMin = jmin (pathYMin, y1, y2, y3);
  74763. pathYMax = jmax (pathYMax, y1, y2, y3);
  74764. }
  74765. void Path::cubicTo (const Point<float>& controlPoint1,
  74766. const Point<float>& controlPoint2,
  74767. const Point<float>& endPoint)
  74768. {
  74769. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74770. controlPoint2.getX(), controlPoint2.getY(),
  74771. endPoint.getX(), endPoint.getY());
  74772. }
  74773. void Path::closeSubPath()
  74774. {
  74775. if (numElements > 0
  74776. && data.elements [numElements - 1] != closeSubPathMarker)
  74777. {
  74778. data.ensureAllocatedSize ((int) numElements + 1);
  74779. data.elements [numElements++] = closeSubPathMarker;
  74780. }
  74781. }
  74782. const Point<float> Path::getCurrentPosition() const
  74783. {
  74784. int i = (int) numElements - 1;
  74785. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74786. {
  74787. while (i >= 0)
  74788. {
  74789. if (data.elements[i] == moveMarker)
  74790. {
  74791. i += 2;
  74792. break;
  74793. }
  74794. --i;
  74795. }
  74796. }
  74797. if (i > 0)
  74798. return Point<float> (data.elements [i - 1], data.elements [i]);
  74799. return Point<float>();
  74800. }
  74801. void Path::addRectangle (const float x, const float y,
  74802. const float w, const float h)
  74803. {
  74804. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74805. if (w < 0)
  74806. swapVariables (x1, x2);
  74807. if (h < 0)
  74808. swapVariables (y1, y2);
  74809. data.ensureAllocatedSize ((int) numElements + 13);
  74810. if (numElements == 0)
  74811. {
  74812. pathXMin = x1;
  74813. pathXMax = x2;
  74814. pathYMin = y1;
  74815. pathYMax = y2;
  74816. }
  74817. else
  74818. {
  74819. pathXMin = jmin (pathXMin, x1);
  74820. pathXMax = jmax (pathXMax, x2);
  74821. pathYMin = jmin (pathYMin, y1);
  74822. pathYMax = jmax (pathYMax, y2);
  74823. }
  74824. data.elements [numElements++] = moveMarker;
  74825. data.elements [numElements++] = x1;
  74826. data.elements [numElements++] = y2;
  74827. data.elements [numElements++] = lineMarker;
  74828. data.elements [numElements++] = x1;
  74829. data.elements [numElements++] = y1;
  74830. data.elements [numElements++] = lineMarker;
  74831. data.elements [numElements++] = x2;
  74832. data.elements [numElements++] = y1;
  74833. data.elements [numElements++] = lineMarker;
  74834. data.elements [numElements++] = x2;
  74835. data.elements [numElements++] = y2;
  74836. data.elements [numElements++] = closeSubPathMarker;
  74837. }
  74838. void Path::addRoundedRectangle (const float x, const float y,
  74839. const float w, const float h,
  74840. float csx,
  74841. float csy)
  74842. {
  74843. csx = jmin (csx, w * 0.5f);
  74844. csy = jmin (csy, h * 0.5f);
  74845. const float cs45x = csx * 0.45f;
  74846. const float cs45y = csy * 0.45f;
  74847. const float x2 = x + w;
  74848. const float y2 = y + h;
  74849. startNewSubPath (x + csx, y);
  74850. lineTo (x2 - csx, y);
  74851. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74852. lineTo (x2, y2 - csy);
  74853. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74854. lineTo (x + csx, y2);
  74855. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74856. lineTo (x, y + csy);
  74857. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74858. closeSubPath();
  74859. }
  74860. void Path::addRoundedRectangle (const float x, const float y,
  74861. const float w, const float h,
  74862. float cs)
  74863. {
  74864. addRoundedRectangle (x, y, w, h, cs, cs);
  74865. }
  74866. void Path::addTriangle (const float x1, const float y1,
  74867. const float x2, const float y2,
  74868. const float x3, const float y3)
  74869. {
  74870. startNewSubPath (x1, y1);
  74871. lineTo (x2, y2);
  74872. lineTo (x3, y3);
  74873. closeSubPath();
  74874. }
  74875. void Path::addQuadrilateral (const float x1, const float y1,
  74876. const float x2, const float y2,
  74877. const float x3, const float y3,
  74878. const float x4, const float y4)
  74879. {
  74880. startNewSubPath (x1, y1);
  74881. lineTo (x2, y2);
  74882. lineTo (x3, y3);
  74883. lineTo (x4, y4);
  74884. closeSubPath();
  74885. }
  74886. void Path::addEllipse (const float x, const float y,
  74887. const float w, const float h)
  74888. {
  74889. const float hw = w * 0.5f;
  74890. const float hw55 = hw * 0.55f;
  74891. const float hh = h * 0.5f;
  74892. const float hh55 = hh * 0.55f;
  74893. const float cx = x + hw;
  74894. const float cy = y + hh;
  74895. startNewSubPath (cx, cy - hh);
  74896. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74897. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74898. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74899. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74900. closeSubPath();
  74901. }
  74902. void Path::addArc (const float x, const float y,
  74903. const float w, const float h,
  74904. const float fromRadians,
  74905. const float toRadians,
  74906. const bool startAsNewSubPath)
  74907. {
  74908. const float radiusX = w / 2.0f;
  74909. const float radiusY = h / 2.0f;
  74910. addCentredArc (x + radiusX,
  74911. y + radiusY,
  74912. radiusX, radiusY,
  74913. 0.0f,
  74914. fromRadians, toRadians,
  74915. startAsNewSubPath);
  74916. }
  74917. void Path::addCentredArc (const float centreX, const float centreY,
  74918. const float radiusX, const float radiusY,
  74919. const float rotationOfEllipse,
  74920. const float fromRadians,
  74921. const float toRadians,
  74922. const bool startAsNewSubPath)
  74923. {
  74924. if (radiusX > 0.0f && radiusY > 0.0f)
  74925. {
  74926. const Point<float> centre (centreX, centreY);
  74927. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74928. float angle = fromRadians;
  74929. if (startAsNewSubPath)
  74930. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74931. if (fromRadians < toRadians)
  74932. {
  74933. if (startAsNewSubPath)
  74934. angle += PathHelpers::ellipseAngularIncrement;
  74935. while (angle < toRadians)
  74936. {
  74937. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74938. angle += PathHelpers::ellipseAngularIncrement;
  74939. }
  74940. }
  74941. else
  74942. {
  74943. if (startAsNewSubPath)
  74944. angle -= PathHelpers::ellipseAngularIncrement;
  74945. while (angle > toRadians)
  74946. {
  74947. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74948. angle -= PathHelpers::ellipseAngularIncrement;
  74949. }
  74950. }
  74951. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74952. }
  74953. }
  74954. void Path::addPieSegment (const float x, const float y,
  74955. const float width, const float height,
  74956. const float fromRadians,
  74957. const float toRadians,
  74958. const float innerCircleProportionalSize)
  74959. {
  74960. float radiusX = width * 0.5f;
  74961. float radiusY = height * 0.5f;
  74962. const Point<float> centre (x + radiusX, y + radiusY);
  74963. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74964. addArc (x, y, width, height, fromRadians, toRadians);
  74965. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74966. {
  74967. closeSubPath();
  74968. if (innerCircleProportionalSize > 0)
  74969. {
  74970. radiusX *= innerCircleProportionalSize;
  74971. radiusY *= innerCircleProportionalSize;
  74972. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74973. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74974. }
  74975. }
  74976. else
  74977. {
  74978. if (innerCircleProportionalSize > 0)
  74979. {
  74980. radiusX *= innerCircleProportionalSize;
  74981. radiusY *= innerCircleProportionalSize;
  74982. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74983. }
  74984. else
  74985. {
  74986. lineTo (centre);
  74987. }
  74988. }
  74989. closeSubPath();
  74990. }
  74991. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74992. {
  74993. const Line<float> reversed (line.reversed());
  74994. lineThickness *= 0.5f;
  74995. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74996. lineTo (line.getPointAlongLine (0, -lineThickness));
  74997. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74998. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74999. closeSubPath();
  75000. }
  75001. void Path::addArrow (const Line<float>& line, float lineThickness,
  75002. float arrowheadWidth, float arrowheadLength)
  75003. {
  75004. const Line<float> reversed (line.reversed());
  75005. lineThickness *= 0.5f;
  75006. arrowheadWidth *= 0.5f;
  75007. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  75008. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  75009. lineTo (line.getPointAlongLine (0, -lineThickness));
  75010. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  75011. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  75012. lineTo (line.getEnd());
  75013. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  75014. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  75015. closeSubPath();
  75016. }
  75017. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  75018. const float radius, const float startAngle)
  75019. {
  75020. jassert (numberOfSides > 1); // this would be silly.
  75021. if (numberOfSides > 1)
  75022. {
  75023. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  75024. for (int i = 0; i < numberOfSides; ++i)
  75025. {
  75026. const float angle = startAngle + i * angleBetweenPoints;
  75027. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  75028. if (i == 0)
  75029. startNewSubPath (p);
  75030. else
  75031. lineTo (p);
  75032. }
  75033. closeSubPath();
  75034. }
  75035. }
  75036. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  75037. const float innerRadius, const float outerRadius, const float startAngle)
  75038. {
  75039. jassert (numberOfPoints > 1); // this would be silly.
  75040. if (numberOfPoints > 1)
  75041. {
  75042. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  75043. for (int i = 0; i < numberOfPoints; ++i)
  75044. {
  75045. const float angle = startAngle + i * angleBetweenPoints;
  75046. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  75047. if (i == 0)
  75048. startNewSubPath (p);
  75049. else
  75050. lineTo (p);
  75051. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  75052. }
  75053. closeSubPath();
  75054. }
  75055. }
  75056. void Path::addBubble (float x, float y,
  75057. float w, float h,
  75058. float cs,
  75059. float tipX,
  75060. float tipY,
  75061. int whichSide,
  75062. float arrowPos,
  75063. float arrowWidth)
  75064. {
  75065. if (w > 1.0f && h > 1.0f)
  75066. {
  75067. cs = jmin (cs, w * 0.5f, h * 0.5f);
  75068. const float cs2 = 2.0f * cs;
  75069. startNewSubPath (x + cs, y);
  75070. if (whichSide == 0)
  75071. {
  75072. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  75073. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  75074. lineTo (arrowX1, y);
  75075. lineTo (tipX, tipY);
  75076. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  75077. }
  75078. lineTo (x + w - cs, y);
  75079. if (cs > 0.0f)
  75080. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  75081. if (whichSide == 3)
  75082. {
  75083. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  75084. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  75085. lineTo (x + w, arrowY1);
  75086. lineTo (tipX, tipY);
  75087. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  75088. }
  75089. lineTo (x + w, y + h - cs);
  75090. if (cs > 0.0f)
  75091. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  75092. if (whichSide == 2)
  75093. {
  75094. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  75095. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  75096. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  75097. lineTo (tipX, tipY);
  75098. lineTo (arrowX1, y + h);
  75099. }
  75100. lineTo (x + cs, y + h);
  75101. if (cs > 0.0f)
  75102. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  75103. if (whichSide == 1)
  75104. {
  75105. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  75106. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  75107. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  75108. lineTo (tipX, tipY);
  75109. lineTo (x, arrowY1);
  75110. }
  75111. lineTo (x, y + cs);
  75112. if (cs > 0.0f)
  75113. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  75114. closeSubPath();
  75115. }
  75116. }
  75117. void Path::addPath (const Path& other)
  75118. {
  75119. size_t i = 0;
  75120. while (i < other.numElements)
  75121. {
  75122. const float type = other.data.elements [i++];
  75123. if (type == moveMarker)
  75124. {
  75125. startNewSubPath (other.data.elements [i],
  75126. other.data.elements [i + 1]);
  75127. i += 2;
  75128. }
  75129. else if (type == lineMarker)
  75130. {
  75131. lineTo (other.data.elements [i],
  75132. other.data.elements [i + 1]);
  75133. i += 2;
  75134. }
  75135. else if (type == quadMarker)
  75136. {
  75137. quadraticTo (other.data.elements [i],
  75138. other.data.elements [i + 1],
  75139. other.data.elements [i + 2],
  75140. other.data.elements [i + 3]);
  75141. i += 4;
  75142. }
  75143. else if (type == cubicMarker)
  75144. {
  75145. cubicTo (other.data.elements [i],
  75146. other.data.elements [i + 1],
  75147. other.data.elements [i + 2],
  75148. other.data.elements [i + 3],
  75149. other.data.elements [i + 4],
  75150. other.data.elements [i + 5]);
  75151. i += 6;
  75152. }
  75153. else if (type == closeSubPathMarker)
  75154. {
  75155. closeSubPath();
  75156. }
  75157. else
  75158. {
  75159. // something's gone wrong with the element list!
  75160. jassertfalse;
  75161. }
  75162. }
  75163. }
  75164. void Path::addPath (const Path& other,
  75165. const AffineTransform& transformToApply)
  75166. {
  75167. size_t i = 0;
  75168. while (i < other.numElements)
  75169. {
  75170. const float type = other.data.elements [i++];
  75171. if (type == closeSubPathMarker)
  75172. {
  75173. closeSubPath();
  75174. }
  75175. else
  75176. {
  75177. float x = other.data.elements [i++];
  75178. float y = other.data.elements [i++];
  75179. transformToApply.transformPoint (x, y);
  75180. if (type == moveMarker)
  75181. {
  75182. startNewSubPath (x, y);
  75183. }
  75184. else if (type == lineMarker)
  75185. {
  75186. lineTo (x, y);
  75187. }
  75188. else if (type == quadMarker)
  75189. {
  75190. float x2 = other.data.elements [i++];
  75191. float y2 = other.data.elements [i++];
  75192. transformToApply.transformPoint (x2, y2);
  75193. quadraticTo (x, y, x2, y2);
  75194. }
  75195. else if (type == cubicMarker)
  75196. {
  75197. float x2 = other.data.elements [i++];
  75198. float y2 = other.data.elements [i++];
  75199. float x3 = other.data.elements [i++];
  75200. float y3 = other.data.elements [i++];
  75201. transformToApply.transformPoints (x2, y2, x3, y3);
  75202. cubicTo (x, y, x2, y2, x3, y3);
  75203. }
  75204. else
  75205. {
  75206. // something's gone wrong with the element list!
  75207. jassertfalse;
  75208. }
  75209. }
  75210. }
  75211. }
  75212. void Path::applyTransform (const AffineTransform& transform) throw()
  75213. {
  75214. size_t i = 0;
  75215. pathYMin = pathXMin = 0;
  75216. pathYMax = pathXMax = 0;
  75217. bool setMaxMin = false;
  75218. while (i < numElements)
  75219. {
  75220. const float type = data.elements [i++];
  75221. if (type == moveMarker)
  75222. {
  75223. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  75224. if (setMaxMin)
  75225. {
  75226. pathXMin = jmin (pathXMin, data.elements [i]);
  75227. pathXMax = jmax (pathXMax, data.elements [i]);
  75228. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  75229. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  75230. }
  75231. else
  75232. {
  75233. pathXMin = pathXMax = data.elements [i];
  75234. pathYMin = pathYMax = data.elements [i + 1];
  75235. setMaxMin = true;
  75236. }
  75237. i += 2;
  75238. }
  75239. else if (type == lineMarker)
  75240. {
  75241. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  75242. pathXMin = jmin (pathXMin, data.elements [i]);
  75243. pathXMax = jmax (pathXMax, data.elements [i]);
  75244. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  75245. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  75246. i += 2;
  75247. }
  75248. else if (type == quadMarker)
  75249. {
  75250. transform.transformPoints (data.elements [i], data.elements [i + 1],
  75251. data.elements [i + 2], data.elements [i + 3]);
  75252. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  75253. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  75254. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  75255. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  75256. i += 4;
  75257. }
  75258. else if (type == cubicMarker)
  75259. {
  75260. transform.transformPoints (data.elements [i], data.elements [i + 1],
  75261. data.elements [i + 2], data.elements [i + 3],
  75262. data.elements [i + 4], data.elements [i + 5]);
  75263. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  75264. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  75265. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  75266. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  75267. i += 6;
  75268. }
  75269. }
  75270. }
  75271. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  75272. const float w, const float h,
  75273. const bool preserveProportions,
  75274. const Justification& justification) const
  75275. {
  75276. Rectangle<float> bounds (getBounds());
  75277. if (preserveProportions)
  75278. {
  75279. if (w <= 0 || h <= 0 || bounds.isEmpty())
  75280. return AffineTransform::identity;
  75281. float newW, newH;
  75282. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  75283. if (srcRatio > h / w)
  75284. {
  75285. newW = h / srcRatio;
  75286. newH = h;
  75287. }
  75288. else
  75289. {
  75290. newW = w;
  75291. newH = w * srcRatio;
  75292. }
  75293. float newXCentre = x;
  75294. float newYCentre = y;
  75295. if (justification.testFlags (Justification::left))
  75296. newXCentre += newW * 0.5f;
  75297. else if (justification.testFlags (Justification::right))
  75298. newXCentre += w - newW * 0.5f;
  75299. else
  75300. newXCentre += w * 0.5f;
  75301. if (justification.testFlags (Justification::top))
  75302. newYCentre += newH * 0.5f;
  75303. else if (justification.testFlags (Justification::bottom))
  75304. newYCentre += h - newH * 0.5f;
  75305. else
  75306. newYCentre += h * 0.5f;
  75307. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  75308. bounds.getHeight() * -0.5f - bounds.getY())
  75309. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  75310. .translated (newXCentre, newYCentre);
  75311. }
  75312. else
  75313. {
  75314. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  75315. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  75316. .translated (x, y);
  75317. }
  75318. }
  75319. bool Path::contains (const float x, const float y, const float tolerance) const
  75320. {
  75321. if (x <= pathXMin || x >= pathXMax
  75322. || y <= pathYMin || y >= pathYMax)
  75323. return false;
  75324. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  75325. int positiveCrossings = 0;
  75326. int negativeCrossings = 0;
  75327. while (i.next())
  75328. {
  75329. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  75330. {
  75331. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  75332. if (intersectX <= x)
  75333. {
  75334. if (i.y1 < i.y2)
  75335. ++positiveCrossings;
  75336. else
  75337. ++negativeCrossings;
  75338. }
  75339. }
  75340. }
  75341. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  75342. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  75343. }
  75344. bool Path::contains (const Point<float>& point, const float tolerance) const
  75345. {
  75346. return contains (point.getX(), point.getY(), tolerance);
  75347. }
  75348. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  75349. {
  75350. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  75351. Point<float> intersection;
  75352. while (i.next())
  75353. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75354. return true;
  75355. return false;
  75356. }
  75357. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  75358. {
  75359. Line<float> result (line);
  75360. const bool startInside = contains (line.getStart());
  75361. const bool endInside = contains (line.getEnd());
  75362. if (startInside == endInside)
  75363. {
  75364. if (keepSectionOutsidePath == startInside)
  75365. result = Line<float>();
  75366. }
  75367. else
  75368. {
  75369. PathFlatteningIterator i (*this, AffineTransform::identity);
  75370. Point<float> intersection;
  75371. while (i.next())
  75372. {
  75373. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75374. {
  75375. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  75376. result.setStart (intersection);
  75377. else
  75378. result.setEnd (intersection);
  75379. }
  75380. }
  75381. }
  75382. return result;
  75383. }
  75384. float Path::getLength (const AffineTransform& transform) const
  75385. {
  75386. float length = 0;
  75387. PathFlatteningIterator i (*this, transform);
  75388. while (i.next())
  75389. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  75390. return length;
  75391. }
  75392. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  75393. {
  75394. PathFlatteningIterator i (*this, transform);
  75395. while (i.next())
  75396. {
  75397. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75398. const float lineLength = line.getLength();
  75399. if (distanceFromStart <= lineLength)
  75400. return line.getPointAlongLine (distanceFromStart);
  75401. distanceFromStart -= lineLength;
  75402. }
  75403. return Point<float> (i.x2, i.y2);
  75404. }
  75405. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  75406. const AffineTransform& transform) const
  75407. {
  75408. PathFlatteningIterator i (*this, transform);
  75409. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  75410. float length = 0;
  75411. Point<float> pointOnLine;
  75412. while (i.next())
  75413. {
  75414. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75415. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  75416. if (distance < bestDistance)
  75417. {
  75418. bestDistance = distance;
  75419. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  75420. pointOnPath = pointOnLine;
  75421. }
  75422. length += line.getLength();
  75423. }
  75424. return bestPosition;
  75425. }
  75426. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  75427. {
  75428. if (cornerRadius <= 0.01f)
  75429. return *this;
  75430. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  75431. size_t n = 0;
  75432. bool lastWasLine = false, firstWasLine = false;
  75433. Path p;
  75434. while (n < numElements)
  75435. {
  75436. const float type = data.elements [n++];
  75437. if (type == moveMarker)
  75438. {
  75439. indexOfPathStart = p.numElements;
  75440. indexOfPathStartThis = n - 1;
  75441. const float x = data.elements [n++];
  75442. const float y = data.elements [n++];
  75443. p.startNewSubPath (x, y);
  75444. lastWasLine = false;
  75445. firstWasLine = (data.elements [n] == lineMarker);
  75446. }
  75447. else if (type == lineMarker || type == closeSubPathMarker)
  75448. {
  75449. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  75450. if (type == lineMarker)
  75451. {
  75452. endX = data.elements [n++];
  75453. endY = data.elements [n++];
  75454. if (n > 8)
  75455. {
  75456. startX = data.elements [n - 8];
  75457. startY = data.elements [n - 7];
  75458. joinX = data.elements [n - 5];
  75459. joinY = data.elements [n - 4];
  75460. }
  75461. }
  75462. else
  75463. {
  75464. endX = data.elements [indexOfPathStartThis + 1];
  75465. endY = data.elements [indexOfPathStartThis + 2];
  75466. if (n > 6)
  75467. {
  75468. startX = data.elements [n - 6];
  75469. startY = data.elements [n - 5];
  75470. joinX = data.elements [n - 3];
  75471. joinY = data.elements [n - 2];
  75472. }
  75473. }
  75474. if (lastWasLine)
  75475. {
  75476. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75477. if (len1 > 0)
  75478. {
  75479. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75480. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75481. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75482. }
  75483. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75484. if (len2 > 0)
  75485. {
  75486. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75487. p.quadraticTo (joinX, joinY,
  75488. (float) (joinX + (endX - joinX) * propNeeded),
  75489. (float) (joinY + (endY - joinY) * propNeeded));
  75490. }
  75491. p.lineTo (endX, endY);
  75492. }
  75493. else if (type == lineMarker)
  75494. {
  75495. p.lineTo (endX, endY);
  75496. lastWasLine = true;
  75497. }
  75498. if (type == closeSubPathMarker)
  75499. {
  75500. if (firstWasLine)
  75501. {
  75502. startX = data.elements [n - 3];
  75503. startY = data.elements [n - 2];
  75504. joinX = endX;
  75505. joinY = endY;
  75506. endX = data.elements [indexOfPathStartThis + 4];
  75507. endY = data.elements [indexOfPathStartThis + 5];
  75508. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75509. if (len1 > 0)
  75510. {
  75511. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75512. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75513. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75514. }
  75515. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75516. if (len2 > 0)
  75517. {
  75518. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75519. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75520. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75521. p.quadraticTo (joinX, joinY, endX, endY);
  75522. p.data.elements [indexOfPathStart + 1] = endX;
  75523. p.data.elements [indexOfPathStart + 2] = endY;
  75524. }
  75525. }
  75526. p.closeSubPath();
  75527. }
  75528. }
  75529. else if (type == quadMarker)
  75530. {
  75531. lastWasLine = false;
  75532. const float x1 = data.elements [n++];
  75533. const float y1 = data.elements [n++];
  75534. const float x2 = data.elements [n++];
  75535. const float y2 = data.elements [n++];
  75536. p.quadraticTo (x1, y1, x2, y2);
  75537. }
  75538. else if (type == cubicMarker)
  75539. {
  75540. lastWasLine = false;
  75541. const float x1 = data.elements [n++];
  75542. const float y1 = data.elements [n++];
  75543. const float x2 = data.elements [n++];
  75544. const float y2 = data.elements [n++];
  75545. const float x3 = data.elements [n++];
  75546. const float y3 = data.elements [n++];
  75547. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75548. }
  75549. }
  75550. return p;
  75551. }
  75552. void Path::loadPathFromStream (InputStream& source)
  75553. {
  75554. while (! source.isExhausted())
  75555. {
  75556. switch (source.readByte())
  75557. {
  75558. case 'm':
  75559. {
  75560. const float x = source.readFloat();
  75561. const float y = source.readFloat();
  75562. startNewSubPath (x, y);
  75563. break;
  75564. }
  75565. case 'l':
  75566. {
  75567. const float x = source.readFloat();
  75568. const float y = source.readFloat();
  75569. lineTo (x, y);
  75570. break;
  75571. }
  75572. case 'q':
  75573. {
  75574. const float x1 = source.readFloat();
  75575. const float y1 = source.readFloat();
  75576. const float x2 = source.readFloat();
  75577. const float y2 = source.readFloat();
  75578. quadraticTo (x1, y1, x2, y2);
  75579. break;
  75580. }
  75581. case 'b':
  75582. {
  75583. const float x1 = source.readFloat();
  75584. const float y1 = source.readFloat();
  75585. const float x2 = source.readFloat();
  75586. const float y2 = source.readFloat();
  75587. const float x3 = source.readFloat();
  75588. const float y3 = source.readFloat();
  75589. cubicTo (x1, y1, x2, y2, x3, y3);
  75590. break;
  75591. }
  75592. case 'c':
  75593. closeSubPath();
  75594. break;
  75595. case 'n':
  75596. useNonZeroWinding = true;
  75597. break;
  75598. case 'z':
  75599. useNonZeroWinding = false;
  75600. break;
  75601. case 'e':
  75602. return; // end of path marker
  75603. default:
  75604. jassertfalse; // illegal char in the stream
  75605. break;
  75606. }
  75607. }
  75608. }
  75609. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75610. {
  75611. MemoryInputStream in (pathData, numberOfBytes, false);
  75612. loadPathFromStream (in);
  75613. }
  75614. void Path::writePathToStream (OutputStream& dest) const
  75615. {
  75616. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75617. size_t i = 0;
  75618. while (i < numElements)
  75619. {
  75620. const float type = data.elements [i++];
  75621. if (type == moveMarker)
  75622. {
  75623. dest.writeByte ('m');
  75624. dest.writeFloat (data.elements [i++]);
  75625. dest.writeFloat (data.elements [i++]);
  75626. }
  75627. else if (type == lineMarker)
  75628. {
  75629. dest.writeByte ('l');
  75630. dest.writeFloat (data.elements [i++]);
  75631. dest.writeFloat (data.elements [i++]);
  75632. }
  75633. else if (type == quadMarker)
  75634. {
  75635. dest.writeByte ('q');
  75636. dest.writeFloat (data.elements [i++]);
  75637. dest.writeFloat (data.elements [i++]);
  75638. dest.writeFloat (data.elements [i++]);
  75639. dest.writeFloat (data.elements [i++]);
  75640. }
  75641. else if (type == cubicMarker)
  75642. {
  75643. dest.writeByte ('b');
  75644. dest.writeFloat (data.elements [i++]);
  75645. dest.writeFloat (data.elements [i++]);
  75646. dest.writeFloat (data.elements [i++]);
  75647. dest.writeFloat (data.elements [i++]);
  75648. dest.writeFloat (data.elements [i++]);
  75649. dest.writeFloat (data.elements [i++]);
  75650. }
  75651. else if (type == closeSubPathMarker)
  75652. {
  75653. dest.writeByte ('c');
  75654. }
  75655. }
  75656. dest.writeByte ('e'); // marks the end-of-path
  75657. }
  75658. const String Path::toString() const
  75659. {
  75660. MemoryOutputStream s (2048);
  75661. if (! useNonZeroWinding)
  75662. s << 'a';
  75663. size_t i = 0;
  75664. float lastMarker = 0.0f;
  75665. while (i < numElements)
  75666. {
  75667. const float marker = data.elements [i++];
  75668. char markerChar = 0;
  75669. int numCoords = 0;
  75670. if (marker == moveMarker)
  75671. {
  75672. markerChar = 'm';
  75673. numCoords = 2;
  75674. }
  75675. else if (marker == lineMarker)
  75676. {
  75677. markerChar = 'l';
  75678. numCoords = 2;
  75679. }
  75680. else if (marker == quadMarker)
  75681. {
  75682. markerChar = 'q';
  75683. numCoords = 4;
  75684. }
  75685. else if (marker == cubicMarker)
  75686. {
  75687. markerChar = 'c';
  75688. numCoords = 6;
  75689. }
  75690. else
  75691. {
  75692. jassert (marker == closeSubPathMarker);
  75693. markerChar = 'z';
  75694. }
  75695. if (marker != lastMarker)
  75696. {
  75697. if (s.getDataSize() != 0)
  75698. s << ' ';
  75699. s << markerChar;
  75700. lastMarker = marker;
  75701. }
  75702. while (--numCoords >= 0 && i < numElements)
  75703. {
  75704. String coord (data.elements [i++], 3);
  75705. while (coord.endsWithChar ('0') && coord != "0")
  75706. coord = coord.dropLastCharacters (1);
  75707. if (coord.endsWithChar ('.'))
  75708. coord = coord.dropLastCharacters (1);
  75709. if (s.getDataSize() != 0)
  75710. s << ' ';
  75711. s << coord;
  75712. }
  75713. }
  75714. return s.toUTF8();
  75715. }
  75716. void Path::restoreFromString (const String& stringVersion)
  75717. {
  75718. clear();
  75719. setUsingNonZeroWinding (true);
  75720. String::CharPointerType t (stringVersion.getCharPointer());
  75721. juce_wchar marker = 'm';
  75722. int numValues = 2;
  75723. float values [6];
  75724. for (;;)
  75725. {
  75726. const String token (PathHelpers::nextToken (t));
  75727. const juce_wchar firstChar = token[0];
  75728. int startNum = 0;
  75729. if (firstChar == 0)
  75730. break;
  75731. if (firstChar == 'm' || firstChar == 'l')
  75732. {
  75733. marker = firstChar;
  75734. numValues = 2;
  75735. }
  75736. else if (firstChar == 'q')
  75737. {
  75738. marker = firstChar;
  75739. numValues = 4;
  75740. }
  75741. else if (firstChar == 'c')
  75742. {
  75743. marker = firstChar;
  75744. numValues = 6;
  75745. }
  75746. else if (firstChar == 'z')
  75747. {
  75748. marker = firstChar;
  75749. numValues = 0;
  75750. }
  75751. else if (firstChar == 'a')
  75752. {
  75753. setUsingNonZeroWinding (false);
  75754. continue;
  75755. }
  75756. else
  75757. {
  75758. ++startNum;
  75759. values [0] = token.getFloatValue();
  75760. }
  75761. for (int i = startNum; i < numValues; ++i)
  75762. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75763. switch (marker)
  75764. {
  75765. case 'm': startNewSubPath (values[0], values[1]); break;
  75766. case 'l': lineTo (values[0], values[1]); break;
  75767. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75768. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75769. case 'z': closeSubPath(); break;
  75770. default: jassertfalse; break; // illegal string format?
  75771. }
  75772. }
  75773. }
  75774. Path::Iterator::Iterator (const Path& path_)
  75775. : path (path_),
  75776. index (0)
  75777. {
  75778. }
  75779. Path::Iterator::~Iterator()
  75780. {
  75781. }
  75782. bool Path::Iterator::next()
  75783. {
  75784. const float* const elements = path.data.elements;
  75785. if (index < path.numElements)
  75786. {
  75787. const float type = elements [index++];
  75788. if (type == moveMarker)
  75789. {
  75790. elementType = startNewSubPath;
  75791. x1 = elements [index++];
  75792. y1 = elements [index++];
  75793. }
  75794. else if (type == lineMarker)
  75795. {
  75796. elementType = lineTo;
  75797. x1 = elements [index++];
  75798. y1 = elements [index++];
  75799. }
  75800. else if (type == quadMarker)
  75801. {
  75802. elementType = quadraticTo;
  75803. x1 = elements [index++];
  75804. y1 = elements [index++];
  75805. x2 = elements [index++];
  75806. y2 = elements [index++];
  75807. }
  75808. else if (type == cubicMarker)
  75809. {
  75810. elementType = cubicTo;
  75811. x1 = elements [index++];
  75812. y1 = elements [index++];
  75813. x2 = elements [index++];
  75814. y2 = elements [index++];
  75815. x3 = elements [index++];
  75816. y3 = elements [index++];
  75817. }
  75818. else if (type == closeSubPathMarker)
  75819. {
  75820. elementType = closePath;
  75821. }
  75822. return true;
  75823. }
  75824. return false;
  75825. }
  75826. END_JUCE_NAMESPACE
  75827. /*** End of inlined file: juce_Path.cpp ***/
  75828. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75829. BEGIN_JUCE_NAMESPACE
  75830. #if JUCE_MSVC && JUCE_DEBUG
  75831. #pragma optimize ("t", on)
  75832. #endif
  75833. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75834. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75835. const AffineTransform& transform_,
  75836. const float tolerance)
  75837. : x2 (0),
  75838. y2 (0),
  75839. closesSubPath (false),
  75840. subPathIndex (-1),
  75841. path (path_),
  75842. transform (transform_),
  75843. points (path_.data.elements),
  75844. toleranceSquared (tolerance * tolerance),
  75845. subPathCloseX (0),
  75846. subPathCloseY (0),
  75847. isIdentityTransform (transform_.isIdentity()),
  75848. stackBase (32),
  75849. index (0),
  75850. stackSize (32)
  75851. {
  75852. stackPos = stackBase;
  75853. }
  75854. PathFlatteningIterator::~PathFlatteningIterator()
  75855. {
  75856. }
  75857. bool PathFlatteningIterator::isLastInSubpath() const throw()
  75858. {
  75859. return stackPos == stackBase.getData()
  75860. && (index >= path.numElements || points [index] == Path::moveMarker);
  75861. }
  75862. bool PathFlatteningIterator::next()
  75863. {
  75864. x1 = x2;
  75865. y1 = y2;
  75866. float x3 = 0;
  75867. float y3 = 0;
  75868. float x4 = 0;
  75869. float y4 = 0;
  75870. float type;
  75871. for (;;)
  75872. {
  75873. if (stackPos == stackBase)
  75874. {
  75875. if (index >= path.numElements)
  75876. {
  75877. return false;
  75878. }
  75879. else
  75880. {
  75881. type = points [index++];
  75882. if (type != Path::closeSubPathMarker)
  75883. {
  75884. x2 = points [index++];
  75885. y2 = points [index++];
  75886. if (type == Path::quadMarker)
  75887. {
  75888. x3 = points [index++];
  75889. y3 = points [index++];
  75890. if (! isIdentityTransform)
  75891. transform.transformPoints (x2, y2, x3, y3);
  75892. }
  75893. else if (type == Path::cubicMarker)
  75894. {
  75895. x3 = points [index++];
  75896. y3 = points [index++];
  75897. x4 = points [index++];
  75898. y4 = points [index++];
  75899. if (! isIdentityTransform)
  75900. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75901. }
  75902. else
  75903. {
  75904. if (! isIdentityTransform)
  75905. transform.transformPoint (x2, y2);
  75906. }
  75907. }
  75908. }
  75909. }
  75910. else
  75911. {
  75912. type = *--stackPos;
  75913. if (type != Path::closeSubPathMarker)
  75914. {
  75915. x2 = *--stackPos;
  75916. y2 = *--stackPos;
  75917. if (type == Path::quadMarker)
  75918. {
  75919. x3 = *--stackPos;
  75920. y3 = *--stackPos;
  75921. }
  75922. else if (type == Path::cubicMarker)
  75923. {
  75924. x3 = *--stackPos;
  75925. y3 = *--stackPos;
  75926. x4 = *--stackPos;
  75927. y4 = *--stackPos;
  75928. }
  75929. }
  75930. }
  75931. if (type == Path::lineMarker)
  75932. {
  75933. ++subPathIndex;
  75934. closesSubPath = (stackPos == stackBase)
  75935. && (index < path.numElements)
  75936. && (points [index] == Path::closeSubPathMarker)
  75937. && x2 == subPathCloseX
  75938. && y2 == subPathCloseY;
  75939. return true;
  75940. }
  75941. else if (type == Path::quadMarker)
  75942. {
  75943. const size_t offset = (size_t) (stackPos - stackBase);
  75944. if (offset >= stackSize - 10)
  75945. {
  75946. stackSize <<= 1;
  75947. stackBase.realloc (stackSize);
  75948. stackPos = stackBase + offset;
  75949. }
  75950. const float m1x = (x1 + x2) * 0.5f;
  75951. const float m1y = (y1 + y2) * 0.5f;
  75952. const float m2x = (x2 + x3) * 0.5f;
  75953. const float m2y = (y2 + y3) * 0.5f;
  75954. const float m3x = (m1x + m2x) * 0.5f;
  75955. const float m3y = (m1y + m2y) * 0.5f;
  75956. const float errorX = m3x - x2;
  75957. const float errorY = m3y - y2;
  75958. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75959. {
  75960. *stackPos++ = y3;
  75961. *stackPos++ = x3;
  75962. *stackPos++ = m2y;
  75963. *stackPos++ = m2x;
  75964. *stackPos++ = Path::quadMarker;
  75965. *stackPos++ = m3y;
  75966. *stackPos++ = m3x;
  75967. *stackPos++ = m1y;
  75968. *stackPos++ = m1x;
  75969. *stackPos++ = Path::quadMarker;
  75970. }
  75971. else
  75972. {
  75973. *stackPos++ = y3;
  75974. *stackPos++ = x3;
  75975. *stackPos++ = Path::lineMarker;
  75976. *stackPos++ = m3y;
  75977. *stackPos++ = m3x;
  75978. *stackPos++ = Path::lineMarker;
  75979. }
  75980. jassert (stackPos < stackBase + stackSize);
  75981. }
  75982. else if (type == Path::cubicMarker)
  75983. {
  75984. const size_t offset = (size_t) (stackPos - stackBase);
  75985. if (offset >= stackSize - 16)
  75986. {
  75987. stackSize <<= 1;
  75988. stackBase.realloc (stackSize);
  75989. stackPos = stackBase + offset;
  75990. }
  75991. const float m1x = (x1 + x2) * 0.5f;
  75992. const float m1y = (y1 + y2) * 0.5f;
  75993. const float m2x = (x3 + x2) * 0.5f;
  75994. const float m2y = (y3 + y2) * 0.5f;
  75995. const float m3x = (x3 + x4) * 0.5f;
  75996. const float m3y = (y3 + y4) * 0.5f;
  75997. const float m4x = (m1x + m2x) * 0.5f;
  75998. const float m4y = (m1y + m2y) * 0.5f;
  75999. const float m5x = (m3x + m2x) * 0.5f;
  76000. const float m5y = (m3y + m2y) * 0.5f;
  76001. const float error1X = m4x - x2;
  76002. const float error1Y = m4y - y2;
  76003. const float error2X = m5x - x3;
  76004. const float error2Y = m5y - y3;
  76005. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  76006. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  76007. {
  76008. *stackPos++ = y4;
  76009. *stackPos++ = x4;
  76010. *stackPos++ = m3y;
  76011. *stackPos++ = m3x;
  76012. *stackPos++ = m5y;
  76013. *stackPos++ = m5x;
  76014. *stackPos++ = Path::cubicMarker;
  76015. *stackPos++ = (m4y + m5y) * 0.5f;
  76016. *stackPos++ = (m4x + m5x) * 0.5f;
  76017. *stackPos++ = m4y;
  76018. *stackPos++ = m4x;
  76019. *stackPos++ = m1y;
  76020. *stackPos++ = m1x;
  76021. *stackPos++ = Path::cubicMarker;
  76022. }
  76023. else
  76024. {
  76025. *stackPos++ = y4;
  76026. *stackPos++ = x4;
  76027. *stackPos++ = Path::lineMarker;
  76028. *stackPos++ = m5y;
  76029. *stackPos++ = m5x;
  76030. *stackPos++ = Path::lineMarker;
  76031. *stackPos++ = m4y;
  76032. *stackPos++ = m4x;
  76033. *stackPos++ = Path::lineMarker;
  76034. }
  76035. }
  76036. else if (type == Path::closeSubPathMarker)
  76037. {
  76038. if (x2 != subPathCloseX || y2 != subPathCloseY)
  76039. {
  76040. x1 = x2;
  76041. y1 = y2;
  76042. x2 = subPathCloseX;
  76043. y2 = subPathCloseY;
  76044. closesSubPath = true;
  76045. return true;
  76046. }
  76047. }
  76048. else
  76049. {
  76050. jassert (type == Path::moveMarker);
  76051. subPathIndex = -1;
  76052. subPathCloseX = x1 = x2;
  76053. subPathCloseY = y1 = y2;
  76054. }
  76055. }
  76056. }
  76057. #if JUCE_MSVC && JUCE_DEBUG
  76058. #pragma optimize ("", on) // resets optimisations to the project defaults
  76059. #endif
  76060. END_JUCE_NAMESPACE
  76061. /*** End of inlined file: juce_PathIterator.cpp ***/
  76062. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  76063. BEGIN_JUCE_NAMESPACE
  76064. PathStrokeType::PathStrokeType (const float strokeThickness,
  76065. const JointStyle jointStyle_,
  76066. const EndCapStyle endStyle_) throw()
  76067. : thickness (strokeThickness),
  76068. jointStyle (jointStyle_),
  76069. endStyle (endStyle_)
  76070. {
  76071. }
  76072. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  76073. : thickness (other.thickness),
  76074. jointStyle (other.jointStyle),
  76075. endStyle (other.endStyle)
  76076. {
  76077. }
  76078. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  76079. {
  76080. thickness = other.thickness;
  76081. jointStyle = other.jointStyle;
  76082. endStyle = other.endStyle;
  76083. return *this;
  76084. }
  76085. PathStrokeType::~PathStrokeType() throw()
  76086. {
  76087. }
  76088. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  76089. {
  76090. return thickness == other.thickness
  76091. && jointStyle == other.jointStyle
  76092. && endStyle == other.endStyle;
  76093. }
  76094. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  76095. {
  76096. return ! operator== (other);
  76097. }
  76098. namespace PathStrokeHelpers
  76099. {
  76100. bool lineIntersection (const float x1, const float y1,
  76101. const float x2, const float y2,
  76102. const float x3, const float y3,
  76103. const float x4, const float y4,
  76104. float& intersectionX,
  76105. float& intersectionY,
  76106. float& distanceBeyondLine1EndSquared) throw()
  76107. {
  76108. if (x2 != x3 || y2 != y3)
  76109. {
  76110. const float dx1 = x2 - x1;
  76111. const float dy1 = y2 - y1;
  76112. const float dx2 = x4 - x3;
  76113. const float dy2 = y4 - y3;
  76114. const float divisor = dx1 * dy2 - dx2 * dy1;
  76115. if (divisor == 0)
  76116. {
  76117. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  76118. {
  76119. if (dy1 == 0 && dy2 != 0)
  76120. {
  76121. const float along = (y1 - y3) / dy2;
  76122. intersectionX = x3 + along * dx2;
  76123. intersectionY = y1;
  76124. distanceBeyondLine1EndSquared = intersectionX - x2;
  76125. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  76126. if ((x2 > x1) == (intersectionX < x2))
  76127. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  76128. return along >= 0 && along <= 1.0f;
  76129. }
  76130. else if (dy2 == 0 && dy1 != 0)
  76131. {
  76132. const float along = (y3 - y1) / dy1;
  76133. intersectionX = x1 + along * dx1;
  76134. intersectionY = y3;
  76135. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  76136. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  76137. if (along < 1.0f)
  76138. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  76139. return along >= 0 && along <= 1.0f;
  76140. }
  76141. else if (dx1 == 0 && dx2 != 0)
  76142. {
  76143. const float along = (x1 - x3) / dx2;
  76144. intersectionX = x1;
  76145. intersectionY = y3 + along * dy2;
  76146. distanceBeyondLine1EndSquared = intersectionY - y2;
  76147. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  76148. if ((y2 > y1) == (intersectionY < y2))
  76149. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  76150. return along >= 0 && along <= 1.0f;
  76151. }
  76152. else if (dx2 == 0 && dx1 != 0)
  76153. {
  76154. const float along = (x3 - x1) / dx1;
  76155. intersectionX = x3;
  76156. intersectionY = y1 + along * dy1;
  76157. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  76158. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  76159. if (along < 1.0f)
  76160. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  76161. return along >= 0 && along <= 1.0f;
  76162. }
  76163. }
  76164. intersectionX = 0.5f * (x2 + x3);
  76165. intersectionY = 0.5f * (y2 + y3);
  76166. distanceBeyondLine1EndSquared = 0.0f;
  76167. return false;
  76168. }
  76169. else
  76170. {
  76171. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  76172. intersectionX = x1 + along1 * dx1;
  76173. intersectionY = y1 + along1 * dy1;
  76174. if (along1 >= 0 && along1 <= 1.0f)
  76175. {
  76176. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  76177. if (along2 >= 0 && along2 <= divisor)
  76178. {
  76179. distanceBeyondLine1EndSquared = 0.0f;
  76180. return true;
  76181. }
  76182. }
  76183. distanceBeyondLine1EndSquared = along1 - 1.0f;
  76184. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  76185. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  76186. if (along1 < 1.0f)
  76187. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  76188. return false;
  76189. }
  76190. }
  76191. intersectionX = x2;
  76192. intersectionY = y2;
  76193. distanceBeyondLine1EndSquared = 0.0f;
  76194. return true;
  76195. }
  76196. void addEdgeAndJoint (Path& destPath,
  76197. const PathStrokeType::JointStyle style,
  76198. const float maxMiterExtensionSquared, const float width,
  76199. const float x1, const float y1,
  76200. const float x2, const float y2,
  76201. const float x3, const float y3,
  76202. const float x4, const float y4,
  76203. const float midX, const float midY)
  76204. {
  76205. if (style == PathStrokeType::beveled
  76206. || (x3 == x4 && y3 == y4)
  76207. || (x1 == x2 && y1 == y2))
  76208. {
  76209. destPath.lineTo (x2, y2);
  76210. destPath.lineTo (x3, y3);
  76211. }
  76212. else
  76213. {
  76214. float jx, jy, distanceBeyondLine1EndSquared;
  76215. // if they intersect, use this point..
  76216. if (lineIntersection (x1, y1, x2, y2,
  76217. x3, y3, x4, y4,
  76218. jx, jy, distanceBeyondLine1EndSquared))
  76219. {
  76220. destPath.lineTo (jx, jy);
  76221. }
  76222. else
  76223. {
  76224. if (style == PathStrokeType::mitered)
  76225. {
  76226. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  76227. && distanceBeyondLine1EndSquared > 0.0f)
  76228. {
  76229. destPath.lineTo (jx, jy);
  76230. }
  76231. else
  76232. {
  76233. // the end sticks out too far, so just use a blunt joint
  76234. destPath.lineTo (x2, y2);
  76235. destPath.lineTo (x3, y3);
  76236. }
  76237. }
  76238. else
  76239. {
  76240. // curved joints
  76241. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  76242. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  76243. const float angleIncrement = 0.1f;
  76244. destPath.lineTo (x2, y2);
  76245. if (std::abs (angle1 - angle2) > angleIncrement)
  76246. {
  76247. if (angle2 > angle1 + float_Pi
  76248. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  76249. {
  76250. if (angle2 > angle1)
  76251. angle2 -= float_Pi * 2.0f;
  76252. jassert (angle1 <= angle2 + float_Pi);
  76253. angle1 -= angleIncrement;
  76254. while (angle1 > angle2)
  76255. {
  76256. destPath.lineTo (midX + width * std::sin (angle1),
  76257. midY + width * std::cos (angle1));
  76258. angle1 -= angleIncrement;
  76259. }
  76260. }
  76261. else
  76262. {
  76263. if (angle1 > angle2)
  76264. angle1 -= float_Pi * 2.0f;
  76265. jassert (angle1 >= angle2 - float_Pi);
  76266. angle1 += angleIncrement;
  76267. while (angle1 < angle2)
  76268. {
  76269. destPath.lineTo (midX + width * std::sin (angle1),
  76270. midY + width * std::cos (angle1));
  76271. angle1 += angleIncrement;
  76272. }
  76273. }
  76274. }
  76275. destPath.lineTo (x3, y3);
  76276. }
  76277. }
  76278. }
  76279. }
  76280. void addLineEnd (Path& destPath,
  76281. const PathStrokeType::EndCapStyle style,
  76282. const float x1, const float y1,
  76283. const float x2, const float y2,
  76284. const float width)
  76285. {
  76286. if (style == PathStrokeType::butt)
  76287. {
  76288. destPath.lineTo (x2, y2);
  76289. }
  76290. else
  76291. {
  76292. float offx1, offy1, offx2, offy2;
  76293. float dx = x2 - x1;
  76294. float dy = y2 - y1;
  76295. const float len = juce_hypot (dx, dy);
  76296. if (len == 0)
  76297. {
  76298. offx1 = offx2 = x1;
  76299. offy1 = offy2 = y1;
  76300. }
  76301. else
  76302. {
  76303. const float offset = width / len;
  76304. dx *= offset;
  76305. dy *= offset;
  76306. offx1 = x1 + dy;
  76307. offy1 = y1 - dx;
  76308. offx2 = x2 + dy;
  76309. offy2 = y2 - dx;
  76310. }
  76311. if (style == PathStrokeType::square)
  76312. {
  76313. // sqaure ends
  76314. destPath.lineTo (offx1, offy1);
  76315. destPath.lineTo (offx2, offy2);
  76316. destPath.lineTo (x2, y2);
  76317. }
  76318. else
  76319. {
  76320. // rounded ends
  76321. const float midx = (offx1 + offx2) * 0.5f;
  76322. const float midy = (offy1 + offy2) * 0.5f;
  76323. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  76324. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  76325. midx, midy);
  76326. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  76327. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  76328. x2, y2);
  76329. }
  76330. }
  76331. }
  76332. struct Arrowhead
  76333. {
  76334. float startWidth, startLength;
  76335. float endWidth, endLength;
  76336. };
  76337. void addArrowhead (Path& destPath,
  76338. const float x1, const float y1,
  76339. const float x2, const float y2,
  76340. const float tipX, const float tipY,
  76341. const float width,
  76342. const float arrowheadWidth)
  76343. {
  76344. Line<float> line (x1, y1, x2, y2);
  76345. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  76346. destPath.lineTo (tipX, tipY);
  76347. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  76348. destPath.lineTo (x2, y2);
  76349. }
  76350. struct LineSection
  76351. {
  76352. float x1, y1, x2, y2; // original line
  76353. float lx1, ly1, lx2, ly2; // the left-hand stroke
  76354. float rx1, ry1, rx2, ry2; // the right-hand stroke
  76355. };
  76356. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  76357. {
  76358. while (amountAtEnd > 0 && subPath.size() > 0)
  76359. {
  76360. LineSection& l = subPath.getReference (subPath.size() - 1);
  76361. float dx = l.rx2 - l.rx1;
  76362. float dy = l.ry2 - l.ry1;
  76363. const float len = juce_hypot (dx, dy);
  76364. if (len <= amountAtEnd && subPath.size() > 1)
  76365. {
  76366. LineSection& prev = subPath.getReference (subPath.size() - 2);
  76367. prev.x2 = l.x2;
  76368. prev.y2 = l.y2;
  76369. subPath.removeLast();
  76370. amountAtEnd -= len;
  76371. }
  76372. else
  76373. {
  76374. const float prop = jmin (0.9999f, amountAtEnd / len);
  76375. dx *= prop;
  76376. dy *= prop;
  76377. l.rx1 += dx;
  76378. l.ry1 += dy;
  76379. l.lx2 += dx;
  76380. l.ly2 += dy;
  76381. break;
  76382. }
  76383. }
  76384. while (amountAtStart > 0 && subPath.size() > 0)
  76385. {
  76386. LineSection& l = subPath.getReference (0);
  76387. float dx = l.rx2 - l.rx1;
  76388. float dy = l.ry2 - l.ry1;
  76389. const float len = juce_hypot (dx, dy);
  76390. if (len <= amountAtStart && subPath.size() > 1)
  76391. {
  76392. LineSection& next = subPath.getReference (1);
  76393. next.x1 = l.x1;
  76394. next.y1 = l.y1;
  76395. subPath.remove (0);
  76396. amountAtStart -= len;
  76397. }
  76398. else
  76399. {
  76400. const float prop = jmin (0.9999f, amountAtStart / len);
  76401. dx *= prop;
  76402. dy *= prop;
  76403. l.rx2 -= dx;
  76404. l.ry2 -= dy;
  76405. l.lx1 -= dx;
  76406. l.ly1 -= dy;
  76407. break;
  76408. }
  76409. }
  76410. }
  76411. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  76412. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  76413. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  76414. const Arrowhead* const arrowhead)
  76415. {
  76416. jassert (subPath.size() > 0);
  76417. if (arrowhead != 0)
  76418. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  76419. const LineSection& firstLine = subPath.getReference (0);
  76420. float lastX1 = firstLine.lx1;
  76421. float lastY1 = firstLine.ly1;
  76422. float lastX2 = firstLine.lx2;
  76423. float lastY2 = firstLine.ly2;
  76424. if (isClosed)
  76425. {
  76426. destPath.startNewSubPath (lastX1, lastY1);
  76427. }
  76428. else
  76429. {
  76430. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  76431. if (arrowhead != 0)
  76432. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  76433. width, arrowhead->startWidth);
  76434. else
  76435. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  76436. }
  76437. int i;
  76438. for (i = 1; i < subPath.size(); ++i)
  76439. {
  76440. const LineSection& l = subPath.getReference (i);
  76441. addEdgeAndJoint (destPath, jointStyle,
  76442. maxMiterExtensionSquared, width,
  76443. lastX1, lastY1, lastX2, lastY2,
  76444. l.lx1, l.ly1, l.lx2, l.ly2,
  76445. l.x1, l.y1);
  76446. lastX1 = l.lx1;
  76447. lastY1 = l.ly1;
  76448. lastX2 = l.lx2;
  76449. lastY2 = l.ly2;
  76450. }
  76451. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  76452. if (isClosed)
  76453. {
  76454. const LineSection& l = subPath.getReference (0);
  76455. addEdgeAndJoint (destPath, jointStyle,
  76456. maxMiterExtensionSquared, width,
  76457. lastX1, lastY1, lastX2, lastY2,
  76458. l.lx1, l.ly1, l.lx2, l.ly2,
  76459. l.x1, l.y1);
  76460. destPath.closeSubPath();
  76461. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  76462. }
  76463. else
  76464. {
  76465. destPath.lineTo (lastX2, lastY2);
  76466. if (arrowhead != 0)
  76467. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  76468. width, arrowhead->endWidth);
  76469. else
  76470. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  76471. }
  76472. lastX1 = lastLine.rx1;
  76473. lastY1 = lastLine.ry1;
  76474. lastX2 = lastLine.rx2;
  76475. lastY2 = lastLine.ry2;
  76476. for (i = subPath.size() - 1; --i >= 0;)
  76477. {
  76478. const LineSection& l = subPath.getReference (i);
  76479. addEdgeAndJoint (destPath, jointStyle,
  76480. maxMiterExtensionSquared, width,
  76481. lastX1, lastY1, lastX2, lastY2,
  76482. l.rx1, l.ry1, l.rx2, l.ry2,
  76483. l.x2, l.y2);
  76484. lastX1 = l.rx1;
  76485. lastY1 = l.ry1;
  76486. lastX2 = l.rx2;
  76487. lastY2 = l.ry2;
  76488. }
  76489. if (isClosed)
  76490. {
  76491. addEdgeAndJoint (destPath, jointStyle,
  76492. maxMiterExtensionSquared, width,
  76493. lastX1, lastY1, lastX2, lastY2,
  76494. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76495. lastLine.x2, lastLine.y2);
  76496. }
  76497. else
  76498. {
  76499. // do the last line
  76500. destPath.lineTo (lastX2, lastY2);
  76501. }
  76502. destPath.closeSubPath();
  76503. }
  76504. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76505. const PathStrokeType::EndCapStyle endStyle,
  76506. Path& destPath, const Path& source,
  76507. const AffineTransform& transform,
  76508. const float extraAccuracy, const Arrowhead* const arrowhead)
  76509. {
  76510. jassert (extraAccuracy > 0);
  76511. if (thickness <= 0)
  76512. {
  76513. destPath.clear();
  76514. return;
  76515. }
  76516. const Path* sourcePath = &source;
  76517. Path temp;
  76518. if (sourcePath == &destPath)
  76519. {
  76520. destPath.swapWithPath (temp);
  76521. sourcePath = &temp;
  76522. }
  76523. else
  76524. {
  76525. destPath.clear();
  76526. }
  76527. destPath.setUsingNonZeroWinding (true);
  76528. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76529. const float width = 0.5f * thickness;
  76530. // Iterate the path, creating a list of the
  76531. // left/right-hand lines along either side of it...
  76532. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76533. Array <LineSection> subPath;
  76534. subPath.ensureStorageAllocated (512);
  76535. LineSection l;
  76536. l.x1 = 0;
  76537. l.y1 = 0;
  76538. const float minSegmentLength = 0.0001f;
  76539. while (it.next())
  76540. {
  76541. if (it.subPathIndex == 0)
  76542. {
  76543. if (subPath.size() > 0)
  76544. {
  76545. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76546. subPath.clearQuick();
  76547. }
  76548. l.x1 = it.x1;
  76549. l.y1 = it.y1;
  76550. }
  76551. l.x2 = it.x2;
  76552. l.y2 = it.y2;
  76553. float dx = l.x2 - l.x1;
  76554. float dy = l.y2 - l.y1;
  76555. const float hypotSquared = dx*dx + dy*dy;
  76556. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76557. {
  76558. const float len = std::sqrt (hypotSquared);
  76559. if (len == 0)
  76560. {
  76561. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76562. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76563. }
  76564. else
  76565. {
  76566. const float offset = width / len;
  76567. dx *= offset;
  76568. dy *= offset;
  76569. l.rx2 = l.x1 - dy;
  76570. l.ry2 = l.y1 + dx;
  76571. l.lx1 = l.x1 + dy;
  76572. l.ly1 = l.y1 - dx;
  76573. l.lx2 = l.x2 + dy;
  76574. l.ly2 = l.y2 - dx;
  76575. l.rx1 = l.x2 - dy;
  76576. l.ry1 = l.y2 + dx;
  76577. }
  76578. subPath.add (l);
  76579. if (it.closesSubPath)
  76580. {
  76581. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76582. subPath.clearQuick();
  76583. }
  76584. else
  76585. {
  76586. l.x1 = it.x2;
  76587. l.y1 = it.y2;
  76588. }
  76589. }
  76590. }
  76591. if (subPath.size() > 0)
  76592. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76593. }
  76594. }
  76595. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76596. const AffineTransform& transform, const float extraAccuracy) const
  76597. {
  76598. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76599. transform, extraAccuracy, 0);
  76600. }
  76601. void PathStrokeType::createDashedStroke (Path& destPath,
  76602. const Path& sourcePath,
  76603. const float* dashLengths,
  76604. int numDashLengths,
  76605. const AffineTransform& transform,
  76606. const float extraAccuracy) const
  76607. {
  76608. jassert (extraAccuracy > 0);
  76609. if (thickness <= 0)
  76610. return;
  76611. // this should really be an even number..
  76612. jassert ((numDashLengths & 1) == 0);
  76613. Path newDestPath;
  76614. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76615. bool first = true;
  76616. int dashNum = 0;
  76617. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76618. float dx = 0.0f, dy = 0.0f;
  76619. for (;;)
  76620. {
  76621. const bool isSolid = ((dashNum & 1) == 0);
  76622. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76623. jassert (dashLen > 0); // must be a positive increment!
  76624. if (dashLen <= 0)
  76625. break;
  76626. pos += dashLen;
  76627. while (pos > lineEndPos)
  76628. {
  76629. if (! it.next())
  76630. {
  76631. if (isSolid && ! first)
  76632. newDestPath.lineTo (it.x2, it.y2);
  76633. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76634. return;
  76635. }
  76636. if (isSolid && ! first)
  76637. newDestPath.lineTo (it.x1, it.y1);
  76638. else
  76639. newDestPath.startNewSubPath (it.x1, it.y1);
  76640. dx = it.x2 - it.x1;
  76641. dy = it.y2 - it.y1;
  76642. lineLen = juce_hypot (dx, dy);
  76643. lineEndPos += lineLen;
  76644. first = it.closesSubPath;
  76645. }
  76646. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76647. if (isSolid)
  76648. newDestPath.lineTo (it.x1 + dx * alpha,
  76649. it.y1 + dy * alpha);
  76650. else
  76651. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76652. it.y1 + dy * alpha);
  76653. }
  76654. }
  76655. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76656. const Path& sourcePath,
  76657. const float arrowheadStartWidth, const float arrowheadStartLength,
  76658. const float arrowheadEndWidth, const float arrowheadEndLength,
  76659. const AffineTransform& transform,
  76660. const float extraAccuracy) const
  76661. {
  76662. PathStrokeHelpers::Arrowhead head;
  76663. head.startWidth = arrowheadStartWidth;
  76664. head.startLength = arrowheadStartLength;
  76665. head.endWidth = arrowheadEndWidth;
  76666. head.endLength = arrowheadEndLength;
  76667. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76668. destPath, sourcePath, transform, extraAccuracy, &head);
  76669. }
  76670. END_JUCE_NAMESPACE
  76671. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76672. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76673. BEGIN_JUCE_NAMESPACE
  76674. RectangleList::RectangleList() throw()
  76675. {
  76676. }
  76677. RectangleList::RectangleList (const Rectangle<int>& rect)
  76678. {
  76679. if (! rect.isEmpty())
  76680. rects.add (rect);
  76681. }
  76682. RectangleList::RectangleList (const RectangleList& other)
  76683. : rects (other.rects)
  76684. {
  76685. }
  76686. RectangleList& RectangleList::operator= (const RectangleList& other)
  76687. {
  76688. rects = other.rects;
  76689. return *this;
  76690. }
  76691. RectangleList::~RectangleList()
  76692. {
  76693. }
  76694. void RectangleList::clear()
  76695. {
  76696. rects.clearQuick();
  76697. }
  76698. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76699. {
  76700. if (isPositiveAndBelow (index, rects.size()))
  76701. return rects.getReference (index);
  76702. return Rectangle<int>();
  76703. }
  76704. bool RectangleList::isEmpty() const throw()
  76705. {
  76706. return rects.size() == 0;
  76707. }
  76708. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76709. : current (0),
  76710. owner (list),
  76711. index (list.rects.size())
  76712. {
  76713. }
  76714. RectangleList::Iterator::~Iterator()
  76715. {
  76716. }
  76717. bool RectangleList::Iterator::next() throw()
  76718. {
  76719. if (--index >= 0)
  76720. {
  76721. current = & (owner.rects.getReference (index));
  76722. return true;
  76723. }
  76724. return false;
  76725. }
  76726. void RectangleList::add (const Rectangle<int>& rect)
  76727. {
  76728. if (! rect.isEmpty())
  76729. {
  76730. if (rects.size() == 0)
  76731. {
  76732. rects.add (rect);
  76733. }
  76734. else
  76735. {
  76736. bool anyOverlaps = false;
  76737. int i;
  76738. for (i = rects.size(); --i >= 0;)
  76739. {
  76740. Rectangle<int>& ourRect = rects.getReference (i);
  76741. if (rect.intersects (ourRect))
  76742. {
  76743. if (rect.contains (ourRect))
  76744. rects.remove (i);
  76745. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76746. anyOverlaps = true;
  76747. }
  76748. }
  76749. if (anyOverlaps && rects.size() > 0)
  76750. {
  76751. RectangleList r (rect);
  76752. for (i = rects.size(); --i >= 0;)
  76753. {
  76754. const Rectangle<int>& ourRect = rects.getReference (i);
  76755. if (rect.intersects (ourRect))
  76756. {
  76757. r.subtract (ourRect);
  76758. if (r.rects.size() == 0)
  76759. return;
  76760. }
  76761. }
  76762. for (i = r.getNumRectangles(); --i >= 0;)
  76763. rects.add (r.rects.getReference (i));
  76764. }
  76765. else
  76766. {
  76767. rects.add (rect);
  76768. }
  76769. }
  76770. }
  76771. }
  76772. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76773. {
  76774. if (! rect.isEmpty())
  76775. rects.add (rect);
  76776. }
  76777. void RectangleList::add (const int x, const int y, const int w, const int h)
  76778. {
  76779. if (rects.size() == 0)
  76780. {
  76781. if (w > 0 && h > 0)
  76782. rects.add (Rectangle<int> (x, y, w, h));
  76783. }
  76784. else
  76785. {
  76786. add (Rectangle<int> (x, y, w, h));
  76787. }
  76788. }
  76789. void RectangleList::add (const RectangleList& other)
  76790. {
  76791. for (int i = 0; i < other.rects.size(); ++i)
  76792. add (other.rects.getReference (i));
  76793. }
  76794. void RectangleList::subtract (const Rectangle<int>& rect)
  76795. {
  76796. const int originalNumRects = rects.size();
  76797. if (originalNumRects > 0)
  76798. {
  76799. const int x1 = rect.x;
  76800. const int y1 = rect.y;
  76801. const int x2 = x1 + rect.w;
  76802. const int y2 = y1 + rect.h;
  76803. for (int i = getNumRectangles(); --i >= 0;)
  76804. {
  76805. Rectangle<int>& r = rects.getReference (i);
  76806. const int rx1 = r.x;
  76807. const int ry1 = r.y;
  76808. const int rx2 = rx1 + r.w;
  76809. const int ry2 = ry1 + r.h;
  76810. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76811. {
  76812. if (x1 > rx1 && x1 < rx2)
  76813. {
  76814. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76815. {
  76816. r.w = x1 - rx1;
  76817. }
  76818. else
  76819. {
  76820. r.x = x1;
  76821. r.w = rx2 - x1;
  76822. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76823. i += 2;
  76824. }
  76825. }
  76826. else if (x2 > rx1 && x2 < rx2)
  76827. {
  76828. r.x = x2;
  76829. r.w = rx2 - x2;
  76830. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76831. {
  76832. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76833. i += 2;
  76834. }
  76835. }
  76836. else if (y1 > ry1 && y1 < ry2)
  76837. {
  76838. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76839. {
  76840. r.h = y1 - ry1;
  76841. }
  76842. else
  76843. {
  76844. r.y = y1;
  76845. r.h = ry2 - y1;
  76846. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76847. i += 2;
  76848. }
  76849. }
  76850. else if (y2 > ry1 && y2 < ry2)
  76851. {
  76852. r.y = y2;
  76853. r.h = ry2 - y2;
  76854. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76855. {
  76856. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76857. i += 2;
  76858. }
  76859. }
  76860. else
  76861. {
  76862. rects.remove (i);
  76863. }
  76864. }
  76865. }
  76866. }
  76867. }
  76868. bool RectangleList::subtract (const RectangleList& otherList)
  76869. {
  76870. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76871. subtract (otherList.rects.getReference (i));
  76872. return rects.size() > 0;
  76873. }
  76874. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76875. {
  76876. bool notEmpty = false;
  76877. if (rect.isEmpty())
  76878. {
  76879. clear();
  76880. }
  76881. else
  76882. {
  76883. for (int i = rects.size(); --i >= 0;)
  76884. {
  76885. Rectangle<int>& r = rects.getReference (i);
  76886. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76887. rects.remove (i);
  76888. else
  76889. notEmpty = true;
  76890. }
  76891. }
  76892. return notEmpty;
  76893. }
  76894. bool RectangleList::clipTo (const RectangleList& other)
  76895. {
  76896. if (rects.size() == 0)
  76897. return false;
  76898. RectangleList result;
  76899. for (int j = 0; j < rects.size(); ++j)
  76900. {
  76901. const Rectangle<int>& rect = rects.getReference (j);
  76902. for (int i = other.rects.size(); --i >= 0;)
  76903. {
  76904. Rectangle<int> r (other.rects.getReference (i));
  76905. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76906. result.rects.add (r);
  76907. }
  76908. }
  76909. swapWith (result);
  76910. return ! isEmpty();
  76911. }
  76912. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76913. {
  76914. destRegion.clear();
  76915. if (! rect.isEmpty())
  76916. {
  76917. for (int i = rects.size(); --i >= 0;)
  76918. {
  76919. Rectangle<int> r (rects.getReference (i));
  76920. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76921. destRegion.rects.add (r);
  76922. }
  76923. }
  76924. return destRegion.rects.size() > 0;
  76925. }
  76926. void RectangleList::swapWith (RectangleList& otherList) throw()
  76927. {
  76928. rects.swapWithArray (otherList.rects);
  76929. }
  76930. void RectangleList::consolidate()
  76931. {
  76932. int i;
  76933. for (i = 0; i < getNumRectangles() - 1; ++i)
  76934. {
  76935. Rectangle<int>& r = rects.getReference (i);
  76936. const int rx1 = r.x;
  76937. const int ry1 = r.y;
  76938. const int rx2 = rx1 + r.w;
  76939. const int ry2 = ry1 + r.h;
  76940. for (int j = rects.size(); --j > i;)
  76941. {
  76942. Rectangle<int>& r2 = rects.getReference (j);
  76943. const int jrx1 = r2.x;
  76944. const int jry1 = r2.y;
  76945. const int jrx2 = jrx1 + r2.w;
  76946. const int jry2 = jry1 + r2.h;
  76947. // if the vertical edges of any blocks are touching and their horizontals don't
  76948. // line up, split them horizontally..
  76949. if (jrx1 == rx2 || jrx2 == rx1)
  76950. {
  76951. if (jry1 > ry1 && jry1 < ry2)
  76952. {
  76953. r.h = jry1 - ry1;
  76954. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76955. i = -1;
  76956. break;
  76957. }
  76958. if (jry2 > ry1 && jry2 < ry2)
  76959. {
  76960. r.h = jry2 - ry1;
  76961. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76962. i = -1;
  76963. break;
  76964. }
  76965. else if (ry1 > jry1 && ry1 < jry2)
  76966. {
  76967. r2.h = ry1 - jry1;
  76968. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76969. i = -1;
  76970. break;
  76971. }
  76972. else if (ry2 > jry1 && ry2 < jry2)
  76973. {
  76974. r2.h = ry2 - jry1;
  76975. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76976. i = -1;
  76977. break;
  76978. }
  76979. }
  76980. }
  76981. }
  76982. for (i = 0; i < rects.size() - 1; ++i)
  76983. {
  76984. Rectangle<int>& r = rects.getReference (i);
  76985. for (int j = rects.size(); --j > i;)
  76986. {
  76987. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76988. {
  76989. rects.remove (j);
  76990. i = -1;
  76991. break;
  76992. }
  76993. }
  76994. }
  76995. }
  76996. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76997. {
  76998. for (int i = getNumRectangles(); --i >= 0;)
  76999. if (rects.getReference (i).contains (x, y))
  77000. return true;
  77001. return false;
  77002. }
  77003. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  77004. {
  77005. if (rects.size() > 1)
  77006. {
  77007. RectangleList r (rectangleToCheck);
  77008. for (int i = rects.size(); --i >= 0;)
  77009. {
  77010. r.subtract (rects.getReference (i));
  77011. if (r.rects.size() == 0)
  77012. return true;
  77013. }
  77014. }
  77015. else if (rects.size() > 0)
  77016. {
  77017. return rects.getReference (0).contains (rectangleToCheck);
  77018. }
  77019. return false;
  77020. }
  77021. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  77022. {
  77023. for (int i = rects.size(); --i >= 0;)
  77024. if (rects.getReference (i).intersects (rectangleToCheck))
  77025. return true;
  77026. return false;
  77027. }
  77028. bool RectangleList::intersects (const RectangleList& other) const throw()
  77029. {
  77030. for (int i = rects.size(); --i >= 0;)
  77031. if (other.intersectsRectangle (rects.getReference (i)))
  77032. return true;
  77033. return false;
  77034. }
  77035. const Rectangle<int> RectangleList::getBounds() const throw()
  77036. {
  77037. if (rects.size() <= 1)
  77038. {
  77039. if (rects.size() == 0)
  77040. return Rectangle<int>();
  77041. else
  77042. return rects.getReference (0);
  77043. }
  77044. else
  77045. {
  77046. const Rectangle<int>& r = rects.getReference (0);
  77047. int minX = r.x;
  77048. int minY = r.y;
  77049. int maxX = minX + r.w;
  77050. int maxY = minY + r.h;
  77051. for (int i = rects.size(); --i > 0;)
  77052. {
  77053. const Rectangle<int>& r2 = rects.getReference (i);
  77054. minX = jmin (minX, r2.x);
  77055. minY = jmin (minY, r2.y);
  77056. maxX = jmax (maxX, r2.getRight());
  77057. maxY = jmax (maxY, r2.getBottom());
  77058. }
  77059. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  77060. }
  77061. }
  77062. void RectangleList::offsetAll (const int dx, const int dy) throw()
  77063. {
  77064. for (int i = rects.size(); --i >= 0;)
  77065. {
  77066. Rectangle<int>& r = rects.getReference (i);
  77067. r.x += dx;
  77068. r.y += dy;
  77069. }
  77070. }
  77071. const Path RectangleList::toPath() const
  77072. {
  77073. Path p;
  77074. for (int i = rects.size(); --i >= 0;)
  77075. {
  77076. const Rectangle<int>& r = rects.getReference (i);
  77077. p.addRectangle ((float) r.x,
  77078. (float) r.y,
  77079. (float) r.w,
  77080. (float) r.h);
  77081. }
  77082. return p;
  77083. }
  77084. END_JUCE_NAMESPACE
  77085. /*** End of inlined file: juce_RectangleList.cpp ***/
  77086. /*** Start of inlined file: juce_Image.cpp ***/
  77087. BEGIN_JUCE_NAMESPACE
  77088. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  77089. : format (format_), width (width_), height (height_)
  77090. {
  77091. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  77092. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  77093. }
  77094. Image::SharedImage::~SharedImage()
  77095. {
  77096. }
  77097. class SoftwareSharedImage : public Image::SharedImage
  77098. {
  77099. public:
  77100. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  77101. : Image::SharedImage (format_, width_, height_),
  77102. pixelStride (format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1)),
  77103. lineStride ((pixelStride * jmax (1, width_) + 3) & ~3)
  77104. {
  77105. imageData.allocate (lineStride * jmax (1, height_), clearImage);
  77106. }
  77107. Image::ImageType getType() const
  77108. {
  77109. return Image::SoftwareImage;
  77110. }
  77111. LowLevelGraphicsContext* createLowLevelContext()
  77112. {
  77113. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  77114. }
  77115. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  77116. {
  77117. bitmap.data = imageData + x * pixelStride + y * lineStride;
  77118. bitmap.pixelFormat = format;
  77119. bitmap.lineStride = lineStride;
  77120. bitmap.pixelStride = pixelStride;
  77121. }
  77122. Image::SharedImage* clone()
  77123. {
  77124. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  77125. memcpy (s->imageData, imageData, lineStride * height);
  77126. return s;
  77127. }
  77128. private:
  77129. HeapBlock<uint8> imageData;
  77130. const int pixelStride, lineStride;
  77131. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  77132. };
  77133. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  77134. {
  77135. return new SoftwareSharedImage (format, width, height, clearImage);
  77136. }
  77137. class SubsectionSharedImage : public Image::SharedImage
  77138. {
  77139. public:
  77140. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  77141. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  77142. image (image_), area (area_)
  77143. {
  77144. }
  77145. Image::ImageType getType() const
  77146. {
  77147. return Image::SoftwareImage;
  77148. }
  77149. LowLevelGraphicsContext* createLowLevelContext()
  77150. {
  77151. LowLevelGraphicsContext* g = image->createLowLevelContext();
  77152. g->clipToRectangle (area);
  77153. g->setOrigin (area.getX(), area.getY());
  77154. return g;
  77155. }
  77156. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode)
  77157. {
  77158. image->initialiseBitmapData (bitmap, x + area.getX(), y + area.getY(), mode);
  77159. }
  77160. Image::SharedImage* clone()
  77161. {
  77162. return new SubsectionSharedImage (image->clone(), area);
  77163. }
  77164. private:
  77165. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  77166. const Rectangle<int> area;
  77167. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  77168. };
  77169. const Image Image::getClippedImage (const Rectangle<int>& area) const
  77170. {
  77171. if (area.contains (getBounds()))
  77172. return *this;
  77173. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  77174. if (validArea.isEmpty())
  77175. return Image::null;
  77176. return Image (new SubsectionSharedImage (image, validArea));
  77177. }
  77178. Image::Image()
  77179. {
  77180. }
  77181. Image::Image (SharedImage* const instance)
  77182. : image (instance)
  77183. {
  77184. }
  77185. Image::Image (const PixelFormat format,
  77186. const int width, const int height,
  77187. const bool clearImage, const ImageType type)
  77188. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77189. : new SoftwareSharedImage (format, width, height, clearImage))
  77190. {
  77191. }
  77192. Image::Image (const Image& other)
  77193. : image (other.image)
  77194. {
  77195. }
  77196. Image& Image::operator= (const Image& other)
  77197. {
  77198. image = other.image;
  77199. return *this;
  77200. }
  77201. Image::~Image()
  77202. {
  77203. }
  77204. const Image Image::null;
  77205. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77206. {
  77207. return image == 0 ? 0 : image->createLowLevelContext();
  77208. }
  77209. void Image::duplicateIfShared()
  77210. {
  77211. if (image != 0 && image->getReferenceCount() > 1)
  77212. image = image->clone();
  77213. }
  77214. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77215. {
  77216. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77217. return *this;
  77218. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77219. Graphics g (newImage);
  77220. g.setImageResamplingQuality (quality);
  77221. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77222. return newImage;
  77223. }
  77224. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77225. {
  77226. if (image == 0 || newFormat == image->format)
  77227. return *this;
  77228. const int w = image->width, h = image->height;
  77229. Image newImage (newFormat, w, h, false, image->getType());
  77230. if (newFormat == SingleChannel)
  77231. {
  77232. if (! hasAlphaChannel())
  77233. {
  77234. newImage.clear (getBounds(), Colours::black);
  77235. }
  77236. else
  77237. {
  77238. const BitmapData destData (newImage, 0, 0, w, h, BitmapData::writeOnly);
  77239. const BitmapData srcData (*this, 0, 0, w, h);
  77240. for (int y = 0; y < h; ++y)
  77241. {
  77242. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77243. uint8* dst = destData.getLinePointer (y);
  77244. for (int x = w; --x >= 0;)
  77245. {
  77246. *dst++ = src->getAlpha();
  77247. ++src;
  77248. }
  77249. }
  77250. }
  77251. }
  77252. else
  77253. {
  77254. if (hasAlphaChannel())
  77255. newImage.clear (getBounds());
  77256. Graphics g (newImage);
  77257. g.drawImageAt (*this, 0, 0);
  77258. }
  77259. return newImage;
  77260. }
  77261. NamedValueSet* Image::getProperties() const
  77262. {
  77263. return image == 0 ? 0 : &(image->userData);
  77264. }
  77265. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, BitmapData::ReadWriteMode mode)
  77266. : width (w),
  77267. height (h)
  77268. {
  77269. // The BitmapData class must be given a valid image, and a valid rectangle within it!
  77270. jassert (image.image != 0);
  77271. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77272. image.image->initialiseBitmapData (*this, x, y, mode);
  77273. jassert (data != 0 && pixelStride > 0 && lineStride != 0);
  77274. }
  77275. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77276. : width (w),
  77277. height (h)
  77278. {
  77279. // The BitmapData class must be given a valid image, and a valid rectangle within it!
  77280. jassert (image.image != 0);
  77281. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77282. image.image->initialiseBitmapData (*this, x, y, readOnly);
  77283. jassert (data != 0 && pixelStride > 0 && lineStride != 0);
  77284. }
  77285. Image::BitmapData::BitmapData (const Image& image, BitmapData::ReadWriteMode mode)
  77286. : width (image.getWidth()),
  77287. height (image.getHeight())
  77288. {
  77289. // The BitmapData class must be given a valid image!
  77290. jassert (image.image != 0);
  77291. image.image->initialiseBitmapData (*this, 0, 0, mode);
  77292. jassert (data != 0 && pixelStride > 0 && lineStride != 0);
  77293. }
  77294. Image::BitmapData::~BitmapData()
  77295. {
  77296. }
  77297. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77298. {
  77299. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77300. const uint8* const pixel = getPixelPointer (x, y);
  77301. switch (pixelFormat)
  77302. {
  77303. case Image::ARGB: return Colour (((const PixelARGB*) pixel)->getUnpremultipliedARGB());
  77304. case Image::RGB: return Colour (((const PixelRGB*) pixel)->getUnpremultipliedARGB());
  77305. case Image::SingleChannel: return Colour (((const PixelAlpha*) pixel)->getUnpremultipliedARGB());
  77306. default: jassertfalse; break;
  77307. }
  77308. return Colour();
  77309. }
  77310. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77311. {
  77312. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77313. uint8* const pixel = getPixelPointer (x, y);
  77314. const PixelARGB col (colour.getPixelARGB());
  77315. switch (pixelFormat)
  77316. {
  77317. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77318. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77319. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77320. default: jassertfalse; break;
  77321. }
  77322. }
  77323. void Image::setPixelData (int x, int y, int w, int h,
  77324. const uint8* const sourcePixelData, const int sourceLineStride)
  77325. {
  77326. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77327. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77328. {
  77329. const BitmapData dest (*this, x, y, w, h, BitmapData::writeOnly);
  77330. for (int i = 0; i < h; ++i)
  77331. {
  77332. memcpy (dest.getLinePointer(i),
  77333. sourcePixelData + sourceLineStride * i,
  77334. w * dest.pixelStride);
  77335. }
  77336. }
  77337. }
  77338. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77339. {
  77340. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77341. if (! clipped.isEmpty())
  77342. {
  77343. const PixelARGB col (colourToClearTo.getPixelARGB());
  77344. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), BitmapData::writeOnly);
  77345. uint8* dest = destData.data;
  77346. int dh = clipped.getHeight();
  77347. while (--dh >= 0)
  77348. {
  77349. uint8* line = dest;
  77350. dest += destData.lineStride;
  77351. if (isARGB())
  77352. {
  77353. for (int x = clipped.getWidth(); --x >= 0;)
  77354. {
  77355. ((PixelARGB*) line)->set (col);
  77356. line += destData.pixelStride;
  77357. }
  77358. }
  77359. else if (isRGB())
  77360. {
  77361. for (int x = clipped.getWidth(); --x >= 0;)
  77362. {
  77363. ((PixelRGB*) line)->set (col);
  77364. line += destData.pixelStride;
  77365. }
  77366. }
  77367. else
  77368. {
  77369. for (int x = clipped.getWidth(); --x >= 0;)
  77370. {
  77371. *line = col.getAlpha();
  77372. line += destData.pixelStride;
  77373. }
  77374. }
  77375. }
  77376. }
  77377. }
  77378. const Colour Image::getPixelAt (const int x, const int y) const
  77379. {
  77380. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77381. {
  77382. const BitmapData srcData (*this, x, y, 1, 1);
  77383. return srcData.getPixelColour (0, 0);
  77384. }
  77385. return Colour();
  77386. }
  77387. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77388. {
  77389. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77390. {
  77391. const BitmapData destData (*this, x, y, 1, 1, BitmapData::writeOnly);
  77392. destData.setPixelColour (0, 0, colour);
  77393. }
  77394. }
  77395. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77396. {
  77397. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  77398. && hasAlphaChannel())
  77399. {
  77400. const BitmapData destData (*this, x, y, 1, 1, BitmapData::readWrite);
  77401. if (isARGB())
  77402. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77403. else
  77404. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77405. }
  77406. }
  77407. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77408. {
  77409. if (hasAlphaChannel())
  77410. {
  77411. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), BitmapData::readWrite);
  77412. if (isARGB())
  77413. {
  77414. for (int y = 0; y < destData.height; ++y)
  77415. {
  77416. uint8* p = destData.getLinePointer (y);
  77417. for (int x = 0; x < destData.width; ++x)
  77418. {
  77419. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77420. p += destData.pixelStride;
  77421. }
  77422. }
  77423. }
  77424. else
  77425. {
  77426. for (int y = 0; y < destData.height; ++y)
  77427. {
  77428. uint8* p = destData.getLinePointer (y);
  77429. for (int x = 0; x < destData.width; ++x)
  77430. {
  77431. *p = (uint8) (*p * amountToMultiplyBy);
  77432. p += destData.pixelStride;
  77433. }
  77434. }
  77435. }
  77436. }
  77437. else
  77438. {
  77439. jassertfalse; // can't do this without an alpha-channel!
  77440. }
  77441. }
  77442. void Image::desaturate()
  77443. {
  77444. if (isARGB() || isRGB())
  77445. {
  77446. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), BitmapData::readWrite);
  77447. if (isARGB())
  77448. {
  77449. for (int y = 0; y < destData.height; ++y)
  77450. {
  77451. uint8* p = destData.getLinePointer (y);
  77452. for (int x = 0; x < destData.width; ++x)
  77453. {
  77454. ((PixelARGB*) p)->desaturate();
  77455. p += destData.pixelStride;
  77456. }
  77457. }
  77458. }
  77459. else
  77460. {
  77461. for (int y = 0; y < destData.height; ++y)
  77462. {
  77463. uint8* p = destData.getLinePointer (y);
  77464. for (int x = 0; x < destData.width; ++x)
  77465. {
  77466. ((PixelRGB*) p)->desaturate();
  77467. p += destData.pixelStride;
  77468. }
  77469. }
  77470. }
  77471. }
  77472. }
  77473. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77474. {
  77475. if (hasAlphaChannel())
  77476. {
  77477. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77478. SparseSet<int> pixelsOnRow;
  77479. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77480. for (int y = 0; y < srcData.height; ++y)
  77481. {
  77482. pixelsOnRow.clear();
  77483. const uint8* lineData = srcData.getLinePointer (y);
  77484. if (isARGB())
  77485. {
  77486. for (int x = 0; x < srcData.width; ++x)
  77487. {
  77488. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77489. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77490. lineData += srcData.pixelStride;
  77491. }
  77492. }
  77493. else
  77494. {
  77495. for (int x = 0; x < srcData.width; ++x)
  77496. {
  77497. if (*lineData >= threshold)
  77498. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77499. lineData += srcData.pixelStride;
  77500. }
  77501. }
  77502. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77503. {
  77504. const Range<int> range (pixelsOnRow.getRange (i));
  77505. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77506. }
  77507. result.consolidate();
  77508. }
  77509. }
  77510. else
  77511. {
  77512. result.add (0, 0, getWidth(), getHeight());
  77513. }
  77514. }
  77515. void Image::moveImageSection (int dx, int dy,
  77516. int sx, int sy,
  77517. int w, int h)
  77518. {
  77519. if (dx < 0)
  77520. {
  77521. w += dx;
  77522. sx -= dx;
  77523. dx = 0;
  77524. }
  77525. if (dy < 0)
  77526. {
  77527. h += dy;
  77528. sy -= dy;
  77529. dy = 0;
  77530. }
  77531. if (sx < 0)
  77532. {
  77533. w += sx;
  77534. dx -= sx;
  77535. sx = 0;
  77536. }
  77537. if (sy < 0)
  77538. {
  77539. h += sy;
  77540. dy -= sy;
  77541. sy = 0;
  77542. }
  77543. const int minX = jmin (dx, sx);
  77544. const int minY = jmin (dy, sy);
  77545. w = jmin (w, getWidth() - jmax (sx, dx));
  77546. h = jmin (h, getHeight() - jmax (sy, dy));
  77547. if (w > 0 && h > 0)
  77548. {
  77549. const int maxX = jmax (dx, sx) + w;
  77550. const int maxY = jmax (dy, sy) + h;
  77551. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, BitmapData::readWrite);
  77552. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77553. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77554. const int lineSize = destData.pixelStride * w;
  77555. if (dy > sy)
  77556. {
  77557. while (--h >= 0)
  77558. {
  77559. const int offset = h * destData.lineStride;
  77560. memmove (dst + offset, src + offset, lineSize);
  77561. }
  77562. }
  77563. else if (dst != src)
  77564. {
  77565. while (--h >= 0)
  77566. {
  77567. memmove (dst, src, lineSize);
  77568. dst += destData.lineStride;
  77569. src += destData.lineStride;
  77570. }
  77571. }
  77572. }
  77573. }
  77574. END_JUCE_NAMESPACE
  77575. /*** End of inlined file: juce_Image.cpp ***/
  77576. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77577. BEGIN_JUCE_NAMESPACE
  77578. class ImageCache::Pimpl : public Timer,
  77579. public DeletedAtShutdown
  77580. {
  77581. public:
  77582. Pimpl()
  77583. : cacheTimeout (5000)
  77584. {
  77585. }
  77586. ~Pimpl()
  77587. {
  77588. clearSingletonInstance();
  77589. }
  77590. const Image getFromHashCode (const int64 hashCode)
  77591. {
  77592. const ScopedLock sl (lock);
  77593. for (int i = images.size(); --i >= 0;)
  77594. {
  77595. Item* const item = images.getUnchecked(i);
  77596. if (item->hashCode == hashCode)
  77597. return item->image;
  77598. }
  77599. return Image::null;
  77600. }
  77601. void addImageToCache (const Image& image, const int64 hashCode)
  77602. {
  77603. if (image.isValid())
  77604. {
  77605. if (! isTimerRunning())
  77606. startTimer (2000);
  77607. Item* const item = new Item();
  77608. item->hashCode = hashCode;
  77609. item->image = image;
  77610. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77611. const ScopedLock sl (lock);
  77612. images.add (item);
  77613. }
  77614. }
  77615. void timerCallback()
  77616. {
  77617. const uint32 now = Time::getApproximateMillisecondCounter();
  77618. const ScopedLock sl (lock);
  77619. for (int i = images.size(); --i >= 0;)
  77620. {
  77621. Item* const item = images.getUnchecked(i);
  77622. if (item->image.getReferenceCount() <= 1)
  77623. {
  77624. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77625. images.remove (i);
  77626. }
  77627. else
  77628. {
  77629. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77630. }
  77631. }
  77632. if (images.size() == 0)
  77633. stopTimer();
  77634. }
  77635. struct Item
  77636. {
  77637. Image image;
  77638. int64 hashCode;
  77639. uint32 lastUseTime;
  77640. };
  77641. int cacheTimeout;
  77642. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77643. private:
  77644. OwnedArray<Item> images;
  77645. CriticalSection lock;
  77646. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77647. };
  77648. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77649. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77650. {
  77651. if (Pimpl::getInstanceWithoutCreating() != 0)
  77652. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77653. return Image::null;
  77654. }
  77655. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77656. {
  77657. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77658. }
  77659. const Image ImageCache::getFromFile (const File& file)
  77660. {
  77661. const int64 hashCode = file.hashCode64();
  77662. Image image (getFromHashCode (hashCode));
  77663. if (image.isNull())
  77664. {
  77665. image = ImageFileFormat::loadFrom (file);
  77666. addImageToCache (image, hashCode);
  77667. }
  77668. return image;
  77669. }
  77670. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77671. {
  77672. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77673. Image image (getFromHashCode (hashCode));
  77674. if (image.isNull())
  77675. {
  77676. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77677. addImageToCache (image, hashCode);
  77678. }
  77679. return image;
  77680. }
  77681. void ImageCache::setCacheTimeout (const int millisecs)
  77682. {
  77683. Pimpl::getInstance()->cacheTimeout = millisecs;
  77684. }
  77685. END_JUCE_NAMESPACE
  77686. /*** End of inlined file: juce_ImageCache.cpp ***/
  77687. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77688. BEGIN_JUCE_NAMESPACE
  77689. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77690. : values (size_ * size_),
  77691. size (size_)
  77692. {
  77693. clear();
  77694. }
  77695. ImageConvolutionKernel::~ImageConvolutionKernel()
  77696. {
  77697. }
  77698. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77699. {
  77700. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77701. return values [x + y * size];
  77702. jassertfalse;
  77703. return 0;
  77704. }
  77705. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77706. {
  77707. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77708. {
  77709. values [x + y * size] = value;
  77710. }
  77711. else
  77712. {
  77713. jassertfalse;
  77714. }
  77715. }
  77716. void ImageConvolutionKernel::clear()
  77717. {
  77718. for (int i = size * size; --i >= 0;)
  77719. values[i] = 0;
  77720. }
  77721. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77722. {
  77723. double currentTotal = 0.0;
  77724. for (int i = size * size; --i >= 0;)
  77725. currentTotal += values[i];
  77726. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77727. }
  77728. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77729. {
  77730. for (int i = size * size; --i >= 0;)
  77731. values[i] *= multiplier;
  77732. }
  77733. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77734. {
  77735. const double radiusFactor = -1.0 / (radius * radius * 2);
  77736. const int centre = size >> 1;
  77737. for (int y = size; --y >= 0;)
  77738. {
  77739. for (int x = size; --x >= 0;)
  77740. {
  77741. const int cx = x - centre;
  77742. const int cy = y - centre;
  77743. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77744. }
  77745. }
  77746. setOverallSum (1.0f);
  77747. }
  77748. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77749. const Image& sourceImage,
  77750. const Rectangle<int>& destinationArea) const
  77751. {
  77752. if (sourceImage == destImage)
  77753. {
  77754. destImage.duplicateIfShared();
  77755. }
  77756. else
  77757. {
  77758. if (sourceImage.getWidth() != destImage.getWidth()
  77759. || sourceImage.getHeight() != destImage.getHeight()
  77760. || sourceImage.getFormat() != destImage.getFormat())
  77761. {
  77762. jassertfalse;
  77763. return;
  77764. }
  77765. }
  77766. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77767. if (area.isEmpty())
  77768. return;
  77769. const int right = area.getRight();
  77770. const int bottom = area.getBottom();
  77771. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(),
  77772. Image::BitmapData::writeOnly);
  77773. uint8* line = destData.data;
  77774. const Image::BitmapData srcData (sourceImage, Image::BitmapData::readOnly);
  77775. if (destData.pixelStride == 4)
  77776. {
  77777. for (int y = area.getY(); y < bottom; ++y)
  77778. {
  77779. uint8* dest = line;
  77780. line += destData.lineStride;
  77781. for (int x = area.getX(); x < right; ++x)
  77782. {
  77783. float c1 = 0;
  77784. float c2 = 0;
  77785. float c3 = 0;
  77786. float c4 = 0;
  77787. for (int yy = 0; yy < size; ++yy)
  77788. {
  77789. const int sy = y + yy - (size >> 1);
  77790. if (sy >= srcData.height)
  77791. break;
  77792. if (sy >= 0)
  77793. {
  77794. int sx = x - (size >> 1);
  77795. const uint8* src = srcData.getPixelPointer (sx, sy);
  77796. for (int xx = 0; xx < size; ++xx)
  77797. {
  77798. if (sx >= srcData.width)
  77799. break;
  77800. if (sx >= 0)
  77801. {
  77802. const float kernelMult = values [xx + yy * size];
  77803. c1 += kernelMult * *src++;
  77804. c2 += kernelMult * *src++;
  77805. c3 += kernelMult * *src++;
  77806. c4 += kernelMult * *src++;
  77807. }
  77808. else
  77809. {
  77810. src += 4;
  77811. }
  77812. ++sx;
  77813. }
  77814. }
  77815. }
  77816. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77817. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77818. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77819. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77820. }
  77821. }
  77822. }
  77823. else if (destData.pixelStride == 3)
  77824. {
  77825. for (int y = area.getY(); y < bottom; ++y)
  77826. {
  77827. uint8* dest = line;
  77828. line += destData.lineStride;
  77829. for (int x = area.getX(); x < right; ++x)
  77830. {
  77831. float c1 = 0;
  77832. float c2 = 0;
  77833. float c3 = 0;
  77834. for (int yy = 0; yy < size; ++yy)
  77835. {
  77836. const int sy = y + yy - (size >> 1);
  77837. if (sy >= srcData.height)
  77838. break;
  77839. if (sy >= 0)
  77840. {
  77841. int sx = x - (size >> 1);
  77842. const uint8* src = srcData.getPixelPointer (sx, sy);
  77843. for (int xx = 0; xx < size; ++xx)
  77844. {
  77845. if (sx >= srcData.width)
  77846. break;
  77847. if (sx >= 0)
  77848. {
  77849. const float kernelMult = values [xx + yy * size];
  77850. c1 += kernelMult * *src++;
  77851. c2 += kernelMult * *src++;
  77852. c3 += kernelMult * *src++;
  77853. }
  77854. else
  77855. {
  77856. src += 3;
  77857. }
  77858. ++sx;
  77859. }
  77860. }
  77861. }
  77862. *dest++ = (uint8) roundToInt (c1);
  77863. *dest++ = (uint8) roundToInt (c2);
  77864. *dest++ = (uint8) roundToInt (c3);
  77865. }
  77866. }
  77867. }
  77868. }
  77869. END_JUCE_NAMESPACE
  77870. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77871. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77872. BEGIN_JUCE_NAMESPACE
  77873. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77874. {
  77875. static PNGImageFormat png;
  77876. static JPEGImageFormat jpg;
  77877. static GIFImageFormat gif;
  77878. ImageFileFormat* formats[4];
  77879. int numFormats = 0;
  77880. formats [numFormats++] = &png;
  77881. formats [numFormats++] = &jpg;
  77882. formats [numFormats++] = &gif;
  77883. const int64 streamPos = input.getPosition();
  77884. for (int i = 0; i < numFormats; ++i)
  77885. {
  77886. const bool found = formats[i]->canUnderstand (input);
  77887. input.setPosition (streamPos);
  77888. if (found)
  77889. return formats[i];
  77890. }
  77891. return 0;
  77892. }
  77893. const Image ImageFileFormat::loadFrom (InputStream& input)
  77894. {
  77895. ImageFileFormat* const format = findImageFormatForStream (input);
  77896. if (format != 0)
  77897. return format->decodeImage (input);
  77898. return Image::null;
  77899. }
  77900. const Image ImageFileFormat::loadFrom (const File& file)
  77901. {
  77902. InputStream* const in = file.createInputStream();
  77903. if (in != 0)
  77904. {
  77905. BufferedInputStream b (in, 8192, true);
  77906. return loadFrom (b);
  77907. }
  77908. return Image::null;
  77909. }
  77910. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77911. {
  77912. if (rawData != 0 && numBytes > 4)
  77913. {
  77914. MemoryInputStream stream (rawData, numBytes, false);
  77915. return loadFrom (stream);
  77916. }
  77917. return Image::null;
  77918. }
  77919. END_JUCE_NAMESPACE
  77920. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77921. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77922. BEGIN_JUCE_NAMESPACE
  77923. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77924. const Image juce_loadWithCoreImage (InputStream& input);
  77925. #else
  77926. class GIFLoader
  77927. {
  77928. public:
  77929. GIFLoader (InputStream& in)
  77930. : input (in),
  77931. dataBlockIsZero (false),
  77932. fresh (false),
  77933. finished (false)
  77934. {
  77935. currentBit = lastBit = lastByteIndex = 0;
  77936. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77937. firstcode = oldcode = 0;
  77938. clearCode = end_code = 0;
  77939. int imageWidth, imageHeight;
  77940. int transparent = -1;
  77941. if (! getSizeFromHeader (imageWidth, imageHeight))
  77942. return;
  77943. if ((imageWidth <= 0) || (imageHeight <= 0))
  77944. return;
  77945. unsigned char buf [16];
  77946. if (in.read (buf, 3) != 3)
  77947. return;
  77948. int numColours = 2 << (buf[0] & 7);
  77949. if ((buf[0] & 0x80) != 0)
  77950. readPalette (numColours);
  77951. for (;;)
  77952. {
  77953. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77954. break;
  77955. if (buf[0] == '!')
  77956. {
  77957. if (input.read (buf, 1) != 1)
  77958. break;
  77959. if (processExtension (buf[0], transparent) < 0)
  77960. break;
  77961. continue;
  77962. }
  77963. if (buf[0] != ',')
  77964. continue;
  77965. if (input.read (buf, 9) != 9)
  77966. break;
  77967. imageWidth = makeWord (buf[4], buf[5]);
  77968. imageHeight = makeWord (buf[6], buf[7]);
  77969. numColours = 2 << (buf[8] & 7);
  77970. if ((buf[8] & 0x80) != 0)
  77971. if (! readPalette (numColours))
  77972. break;
  77973. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77974. imageWidth, imageHeight, (transparent >= 0));
  77975. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77976. readImage ((buf[8] & 0x40) != 0, transparent);
  77977. break;
  77978. }
  77979. }
  77980. ~GIFLoader() {}
  77981. Image image;
  77982. private:
  77983. InputStream& input;
  77984. uint8 buffer [300];
  77985. uint8 palette [256][4];
  77986. bool dataBlockIsZero, fresh, finished;
  77987. int currentBit, lastBit, lastByteIndex;
  77988. int codeSize, setCodeSize;
  77989. int maxCode, maxCodeSize;
  77990. int firstcode, oldcode;
  77991. int clearCode, end_code;
  77992. enum { maxGifCode = 1 << 12 };
  77993. int table [2] [maxGifCode];
  77994. int stack [2 * maxGifCode];
  77995. int *sp;
  77996. bool getSizeFromHeader (int& w, int& h)
  77997. {
  77998. char b[8];
  77999. if (input.read (b, 6) == 6)
  78000. {
  78001. if ((strncmp ("GIF87a", b, 6) == 0)
  78002. || (strncmp ("GIF89a", b, 6) == 0))
  78003. {
  78004. if (input.read (b, 4) == 4)
  78005. {
  78006. w = makeWord (b[0], b[1]);
  78007. h = makeWord (b[2], b[3]);
  78008. return true;
  78009. }
  78010. }
  78011. }
  78012. return false;
  78013. }
  78014. bool readPalette (const int numCols)
  78015. {
  78016. unsigned char rgb[4];
  78017. for (int i = 0; i < numCols; ++i)
  78018. {
  78019. input.read (rgb, 3);
  78020. palette [i][0] = rgb[0];
  78021. palette [i][1] = rgb[1];
  78022. palette [i][2] = rgb[2];
  78023. palette [i][3] = 0xff;
  78024. }
  78025. return true;
  78026. }
  78027. int readDataBlock (unsigned char* dest)
  78028. {
  78029. unsigned char n;
  78030. if (input.read (&n, 1) == 1)
  78031. {
  78032. dataBlockIsZero = (n == 0);
  78033. if (dataBlockIsZero || (input.read (dest, n) == n))
  78034. return n;
  78035. }
  78036. return -1;
  78037. }
  78038. int processExtension (const int type, int& transparent)
  78039. {
  78040. unsigned char b [300];
  78041. int n = 0;
  78042. if (type == 0xf9)
  78043. {
  78044. n = readDataBlock (b);
  78045. if (n < 0)
  78046. return 1;
  78047. if ((b[0] & 0x1) != 0)
  78048. transparent = b[3];
  78049. }
  78050. do
  78051. {
  78052. n = readDataBlock (b);
  78053. }
  78054. while (n > 0);
  78055. return n;
  78056. }
  78057. int readLZWByte (const bool initialise, const int inputCodeSize)
  78058. {
  78059. int code, incode, i;
  78060. if (initialise)
  78061. {
  78062. setCodeSize = inputCodeSize;
  78063. codeSize = setCodeSize + 1;
  78064. clearCode = 1 << setCodeSize;
  78065. end_code = clearCode + 1;
  78066. maxCodeSize = 2 * clearCode;
  78067. maxCode = clearCode + 2;
  78068. getCode (0, true);
  78069. fresh = true;
  78070. for (i = 0; i < clearCode; ++i)
  78071. {
  78072. table[0][i] = 0;
  78073. table[1][i] = i;
  78074. }
  78075. for (; i < maxGifCode; ++i)
  78076. {
  78077. table[0][i] = 0;
  78078. table[1][i] = 0;
  78079. }
  78080. sp = stack;
  78081. return 0;
  78082. }
  78083. else if (fresh)
  78084. {
  78085. fresh = false;
  78086. do
  78087. {
  78088. firstcode = oldcode
  78089. = getCode (codeSize, false);
  78090. }
  78091. while (firstcode == clearCode);
  78092. return firstcode;
  78093. }
  78094. if (sp > stack)
  78095. return *--sp;
  78096. while ((code = getCode (codeSize, false)) >= 0)
  78097. {
  78098. if (code == clearCode)
  78099. {
  78100. for (i = 0; i < clearCode; ++i)
  78101. {
  78102. table[0][i] = 0;
  78103. table[1][i] = i;
  78104. }
  78105. for (; i < maxGifCode; ++i)
  78106. {
  78107. table[0][i] = 0;
  78108. table[1][i] = 0;
  78109. }
  78110. codeSize = setCodeSize + 1;
  78111. maxCodeSize = 2 * clearCode;
  78112. maxCode = clearCode + 2;
  78113. sp = stack;
  78114. firstcode = oldcode = getCode (codeSize, false);
  78115. return firstcode;
  78116. }
  78117. else if (code == end_code)
  78118. {
  78119. if (dataBlockIsZero)
  78120. return -2;
  78121. unsigned char buf [260];
  78122. int n;
  78123. while ((n = readDataBlock (buf)) > 0)
  78124. {}
  78125. if (n != 0)
  78126. return -2;
  78127. }
  78128. incode = code;
  78129. if (code >= maxCode)
  78130. {
  78131. *sp++ = firstcode;
  78132. code = oldcode;
  78133. }
  78134. while (code >= clearCode)
  78135. {
  78136. *sp++ = table[1][code];
  78137. if (code == table[0][code])
  78138. return -2;
  78139. code = table[0][code];
  78140. }
  78141. *sp++ = firstcode = table[1][code];
  78142. if ((code = maxCode) < maxGifCode)
  78143. {
  78144. table[0][code] = oldcode;
  78145. table[1][code] = firstcode;
  78146. ++maxCode;
  78147. if ((maxCode >= maxCodeSize)
  78148. && (maxCodeSize < maxGifCode))
  78149. {
  78150. maxCodeSize <<= 1;
  78151. ++codeSize;
  78152. }
  78153. }
  78154. oldcode = incode;
  78155. if (sp > stack)
  78156. return *--sp;
  78157. }
  78158. return code;
  78159. }
  78160. int getCode (const int codeSize_, const bool initialise)
  78161. {
  78162. if (initialise)
  78163. {
  78164. currentBit = 0;
  78165. lastBit = 0;
  78166. finished = false;
  78167. return 0;
  78168. }
  78169. if ((currentBit + codeSize_) >= lastBit)
  78170. {
  78171. if (finished)
  78172. return -1;
  78173. buffer[0] = buffer [lastByteIndex - 2];
  78174. buffer[1] = buffer [lastByteIndex - 1];
  78175. const int n = readDataBlock (&buffer[2]);
  78176. if (n == 0)
  78177. finished = true;
  78178. lastByteIndex = 2 + n;
  78179. currentBit = (currentBit - lastBit) + 16;
  78180. lastBit = (2 + n) * 8 ;
  78181. }
  78182. int result = 0;
  78183. int i = currentBit;
  78184. for (int j = 0; j < codeSize_; ++j)
  78185. {
  78186. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78187. ++i;
  78188. }
  78189. currentBit += codeSize_;
  78190. return result;
  78191. }
  78192. bool readImage (const int interlace, const int transparent)
  78193. {
  78194. unsigned char c;
  78195. if (input.read (&c, 1) != 1
  78196. || readLZWByte (true, c) < 0)
  78197. return false;
  78198. if (transparent >= 0)
  78199. {
  78200. palette [transparent][0] = 0;
  78201. palette [transparent][1] = 0;
  78202. palette [transparent][2] = 0;
  78203. palette [transparent][3] = 0;
  78204. }
  78205. int index;
  78206. int xpos = 0, ypos = 0, pass = 0;
  78207. const Image::BitmapData destData (image, Image::BitmapData::writeOnly);
  78208. uint8* p = destData.data;
  78209. const bool hasAlpha = image.hasAlphaChannel();
  78210. while ((index = readLZWByte (false, c)) >= 0)
  78211. {
  78212. const uint8* const paletteEntry = palette [index];
  78213. if (hasAlpha)
  78214. {
  78215. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78216. paletteEntry[0],
  78217. paletteEntry[1],
  78218. paletteEntry[2]);
  78219. ((PixelARGB*) p)->premultiply();
  78220. }
  78221. else
  78222. {
  78223. ((PixelRGB*) p)->setARGB (0,
  78224. paletteEntry[0],
  78225. paletteEntry[1],
  78226. paletteEntry[2]);
  78227. }
  78228. p += destData.pixelStride;
  78229. ++xpos;
  78230. if (xpos == destData.width)
  78231. {
  78232. xpos = 0;
  78233. if (interlace)
  78234. {
  78235. switch (pass)
  78236. {
  78237. case 0:
  78238. case 1: ypos += 8; break;
  78239. case 2: ypos += 4; break;
  78240. case 3: ypos += 2; break;
  78241. }
  78242. while (ypos >= destData.height)
  78243. {
  78244. ++pass;
  78245. switch (pass)
  78246. {
  78247. case 1: ypos = 4; break;
  78248. case 2: ypos = 2; break;
  78249. case 3: ypos = 1; break;
  78250. default: return true;
  78251. }
  78252. }
  78253. }
  78254. else
  78255. {
  78256. ++ypos;
  78257. }
  78258. p = destData.getPixelPointer (xpos, ypos);
  78259. }
  78260. if (ypos >= destData.height)
  78261. break;
  78262. }
  78263. return true;
  78264. }
  78265. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78266. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  78267. };
  78268. #endif
  78269. GIFImageFormat::GIFImageFormat() {}
  78270. GIFImageFormat::~GIFImageFormat() {}
  78271. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78272. bool GIFImageFormat::canUnderstand (InputStream& in)
  78273. {
  78274. char header [4];
  78275. return (in.read (header, sizeof (header)) == sizeof (header))
  78276. && header[0] == 'G'
  78277. && header[1] == 'I'
  78278. && header[2] == 'F';
  78279. }
  78280. const Image GIFImageFormat::decodeImage (InputStream& in)
  78281. {
  78282. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78283. return juce_loadWithCoreImage (in);
  78284. #else
  78285. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78286. return loader->image;
  78287. #endif
  78288. }
  78289. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78290. {
  78291. jassertfalse; // writing isn't implemented for GIFs!
  78292. return false;
  78293. }
  78294. END_JUCE_NAMESPACE
  78295. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78296. #endif
  78297. //==============================================================================
  78298. // some files include lots of library code, so leave them to the end to avoid cluttering
  78299. // up the build for the clean files.
  78300. #if JUCE_BUILD_CORE
  78301. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78302. namespace zlibNamespace
  78303. {
  78304. #if JUCE_INCLUDE_ZLIB_CODE
  78305. #undef OS_CODE
  78306. #undef fdopen
  78307. /*** Start of inlined file: zlib.h ***/
  78308. #ifndef ZLIB_H
  78309. #define ZLIB_H
  78310. /*** Start of inlined file: zconf.h ***/
  78311. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78312. #ifndef ZCONF_H
  78313. #define ZCONF_H
  78314. // *** Just a few hacks here to make it compile nicely with Juce..
  78315. #define Z_PREFIX 1
  78316. #undef __MACTYPES__
  78317. #ifdef _MSC_VER
  78318. #pragma warning (disable : 4131 4127 4244 4267)
  78319. #endif
  78320. /*
  78321. * If you *really* need a unique prefix for all types and library functions,
  78322. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78323. */
  78324. #ifdef Z_PREFIX
  78325. # define deflateInit_ z_deflateInit_
  78326. # define deflate z_deflate
  78327. # define deflateEnd z_deflateEnd
  78328. # define inflateInit_ z_inflateInit_
  78329. # define inflate z_inflate
  78330. # define inflateEnd z_inflateEnd
  78331. # define inflatePrime z_inflatePrime
  78332. # define inflateGetHeader z_inflateGetHeader
  78333. # define adler32_combine z_adler32_combine
  78334. # define crc32_combine z_crc32_combine
  78335. # define deflateInit2_ z_deflateInit2_
  78336. # define deflateSetDictionary z_deflateSetDictionary
  78337. # define deflateCopy z_deflateCopy
  78338. # define deflateReset z_deflateReset
  78339. # define deflateParams z_deflateParams
  78340. # define deflateBound z_deflateBound
  78341. # define deflatePrime z_deflatePrime
  78342. # define inflateInit2_ z_inflateInit2_
  78343. # define inflateSetDictionary z_inflateSetDictionary
  78344. # define inflateSync z_inflateSync
  78345. # define inflateSyncPoint z_inflateSyncPoint
  78346. # define inflateCopy z_inflateCopy
  78347. # define inflateReset z_inflateReset
  78348. # define inflateBack z_inflateBack
  78349. # define inflateBackEnd z_inflateBackEnd
  78350. # define compress z_compress
  78351. # define compress2 z_compress2
  78352. # define compressBound z_compressBound
  78353. # define uncompress z_uncompress
  78354. # define adler32 z_adler32
  78355. # define crc32 z_crc32
  78356. # define get_crc_table z_get_crc_table
  78357. # define zError z_zError
  78358. # define alloc_func z_alloc_func
  78359. # define free_func z_free_func
  78360. # define in_func z_in_func
  78361. # define out_func z_out_func
  78362. # define Byte z_Byte
  78363. # define uInt z_uInt
  78364. # define uLong z_uLong
  78365. # define Bytef z_Bytef
  78366. # define charf z_charf
  78367. # define intf z_intf
  78368. # define uIntf z_uIntf
  78369. # define uLongf z_uLongf
  78370. # define voidpf z_voidpf
  78371. # define voidp z_voidp
  78372. #endif
  78373. #if defined(__MSDOS__) && !defined(MSDOS)
  78374. # define MSDOS
  78375. #endif
  78376. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78377. # define OS2
  78378. #endif
  78379. #if defined(_WINDOWS) && !defined(WINDOWS)
  78380. # define WINDOWS
  78381. #endif
  78382. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78383. # ifndef WIN32
  78384. # define WIN32
  78385. # endif
  78386. #endif
  78387. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78388. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78389. # ifndef SYS16BIT
  78390. # define SYS16BIT
  78391. # endif
  78392. # endif
  78393. #endif
  78394. /*
  78395. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78396. * than 64k bytes at a time (needed on systems with 16-bit int).
  78397. */
  78398. #ifdef SYS16BIT
  78399. # define MAXSEG_64K
  78400. #endif
  78401. #ifdef MSDOS
  78402. # define UNALIGNED_OK
  78403. #endif
  78404. #ifdef __STDC_VERSION__
  78405. # ifndef STDC
  78406. # define STDC
  78407. # endif
  78408. # if __STDC_VERSION__ >= 199901L
  78409. # ifndef STDC99
  78410. # define STDC99
  78411. # endif
  78412. # endif
  78413. #endif
  78414. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78415. # define STDC
  78416. #endif
  78417. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78418. # define STDC
  78419. #endif
  78420. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78421. # define STDC
  78422. #endif
  78423. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78424. # define STDC
  78425. #endif
  78426. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78427. # define STDC
  78428. #endif
  78429. #ifndef STDC
  78430. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78431. # define const /* note: need a more gentle solution here */
  78432. # endif
  78433. #endif
  78434. /* Some Mac compilers merge all .h files incorrectly: */
  78435. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78436. # define NO_DUMMY_DECL
  78437. #endif
  78438. /* Maximum value for memLevel in deflateInit2 */
  78439. #ifndef MAX_MEM_LEVEL
  78440. # ifdef MAXSEG_64K
  78441. # define MAX_MEM_LEVEL 8
  78442. # else
  78443. # define MAX_MEM_LEVEL 9
  78444. # endif
  78445. #endif
  78446. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78447. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78448. * created by gzip. (Files created by minigzip can still be extracted by
  78449. * gzip.)
  78450. */
  78451. #ifndef MAX_WBITS
  78452. # define MAX_WBITS 15 /* 32K LZ77 window */
  78453. #endif
  78454. /* The memory requirements for deflate are (in bytes):
  78455. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78456. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78457. plus a few kilobytes for small objects. For example, if you want to reduce
  78458. the default memory requirements from 256K to 128K, compile with
  78459. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78460. Of course this will generally degrade compression (there's no free lunch).
  78461. The memory requirements for inflate are (in bytes) 1 << windowBits
  78462. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78463. for small objects.
  78464. */
  78465. /* Type declarations */
  78466. #ifndef OF /* function prototypes */
  78467. # ifdef STDC
  78468. # define OF(args) args
  78469. # else
  78470. # define OF(args) ()
  78471. # endif
  78472. #endif
  78473. /* The following definitions for FAR are needed only for MSDOS mixed
  78474. * model programming (small or medium model with some far allocations).
  78475. * This was tested only with MSC; for other MSDOS compilers you may have
  78476. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78477. * just define FAR to be empty.
  78478. */
  78479. #ifdef SYS16BIT
  78480. # if defined(M_I86SM) || defined(M_I86MM)
  78481. /* MSC small or medium model */
  78482. # define SMALL_MEDIUM
  78483. # ifdef _MSC_VER
  78484. # define FAR _far
  78485. # else
  78486. # define FAR far
  78487. # endif
  78488. # endif
  78489. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78490. /* Turbo C small or medium model */
  78491. # define SMALL_MEDIUM
  78492. # ifdef __BORLANDC__
  78493. # define FAR _far
  78494. # else
  78495. # define FAR far
  78496. # endif
  78497. # endif
  78498. #endif
  78499. #if defined(WINDOWS) || defined(WIN32)
  78500. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78501. * This is not mandatory, but it offers a little performance increase.
  78502. */
  78503. # ifdef ZLIB_DLL
  78504. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78505. # ifdef ZLIB_INTERNAL
  78506. # define ZEXTERN extern __declspec(dllexport)
  78507. # else
  78508. # define ZEXTERN extern __declspec(dllimport)
  78509. # endif
  78510. # endif
  78511. # endif /* ZLIB_DLL */
  78512. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78513. * define ZLIB_WINAPI.
  78514. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78515. */
  78516. # ifdef ZLIB_WINAPI
  78517. # ifdef FAR
  78518. # undef FAR
  78519. # endif
  78520. # include <windows.h>
  78521. /* No need for _export, use ZLIB.DEF instead. */
  78522. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78523. # define ZEXPORT WINAPI
  78524. # ifdef WIN32
  78525. # define ZEXPORTVA WINAPIV
  78526. # else
  78527. # define ZEXPORTVA FAR CDECL
  78528. # endif
  78529. # endif
  78530. #endif
  78531. #if defined (__BEOS__)
  78532. # ifdef ZLIB_DLL
  78533. # ifdef ZLIB_INTERNAL
  78534. # define ZEXPORT __declspec(dllexport)
  78535. # define ZEXPORTVA __declspec(dllexport)
  78536. # else
  78537. # define ZEXPORT __declspec(dllimport)
  78538. # define ZEXPORTVA __declspec(dllimport)
  78539. # endif
  78540. # endif
  78541. #endif
  78542. #ifndef ZEXTERN
  78543. # define ZEXTERN extern
  78544. #endif
  78545. #ifndef ZEXPORT
  78546. # define ZEXPORT
  78547. #endif
  78548. #ifndef ZEXPORTVA
  78549. # define ZEXPORTVA
  78550. #endif
  78551. #ifndef FAR
  78552. # define FAR
  78553. #endif
  78554. #if !defined(__MACTYPES__)
  78555. typedef unsigned char Byte; /* 8 bits */
  78556. #endif
  78557. typedef unsigned int uInt; /* 16 bits or more */
  78558. typedef unsigned long uLong; /* 32 bits or more */
  78559. #ifdef SMALL_MEDIUM
  78560. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78561. # define Bytef Byte FAR
  78562. #else
  78563. typedef Byte FAR Bytef;
  78564. #endif
  78565. typedef char FAR charf;
  78566. typedef int FAR intf;
  78567. typedef uInt FAR uIntf;
  78568. typedef uLong FAR uLongf;
  78569. #ifdef STDC
  78570. typedef void const *voidpc;
  78571. typedef void FAR *voidpf;
  78572. typedef void *voidp;
  78573. #else
  78574. typedef Byte const *voidpc;
  78575. typedef Byte FAR *voidpf;
  78576. typedef Byte *voidp;
  78577. #endif
  78578. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78579. # include <sys/types.h> /* for off_t */
  78580. # include <unistd.h> /* for SEEK_* and off_t */
  78581. # ifdef VMS
  78582. # include <unixio.h> /* for off_t */
  78583. # endif
  78584. # define z_off_t off_t
  78585. #endif
  78586. #ifndef SEEK_SET
  78587. # define SEEK_SET 0 /* Seek from beginning of file. */
  78588. # define SEEK_CUR 1 /* Seek from current position. */
  78589. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78590. #endif
  78591. #ifndef z_off_t
  78592. # define z_off_t long
  78593. #endif
  78594. #if defined(__OS400__)
  78595. # define NO_vsnprintf
  78596. #endif
  78597. #if defined(__MVS__)
  78598. # define NO_vsnprintf
  78599. # ifdef FAR
  78600. # undef FAR
  78601. # endif
  78602. #endif
  78603. /* MVS linker does not support external names larger than 8 bytes */
  78604. #if defined(__MVS__)
  78605. # pragma map(deflateInit_,"DEIN")
  78606. # pragma map(deflateInit2_,"DEIN2")
  78607. # pragma map(deflateEnd,"DEEND")
  78608. # pragma map(deflateBound,"DEBND")
  78609. # pragma map(inflateInit_,"ININ")
  78610. # pragma map(inflateInit2_,"ININ2")
  78611. # pragma map(inflateEnd,"INEND")
  78612. # pragma map(inflateSync,"INSY")
  78613. # pragma map(inflateSetDictionary,"INSEDI")
  78614. # pragma map(compressBound,"CMBND")
  78615. # pragma map(inflate_table,"INTABL")
  78616. # pragma map(inflate_fast,"INFA")
  78617. # pragma map(inflate_copyright,"INCOPY")
  78618. #endif
  78619. #endif /* ZCONF_H */
  78620. /*** End of inlined file: zconf.h ***/
  78621. #ifdef __cplusplus
  78622. //extern "C" {
  78623. #endif
  78624. #define ZLIB_VERSION "1.2.3"
  78625. #define ZLIB_VERNUM 0x1230
  78626. /*
  78627. The 'zlib' compression library provides in-memory compression and
  78628. decompression functions, including integrity checks of the uncompressed
  78629. data. This version of the library supports only one compression method
  78630. (deflation) but other algorithms will be added later and will have the same
  78631. stream interface.
  78632. Compression can be done in a single step if the buffers are large
  78633. enough (for example if an input file is mmap'ed), or can be done by
  78634. repeated calls of the compression function. In the latter case, the
  78635. application must provide more input and/or consume the output
  78636. (providing more output space) before each call.
  78637. The compressed data format used by default by the in-memory functions is
  78638. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78639. around a deflate stream, which is itself documented in RFC 1951.
  78640. The library also supports reading and writing files in gzip (.gz) format
  78641. with an interface similar to that of stdio using the functions that start
  78642. with "gz". The gzip format is different from the zlib format. gzip is a
  78643. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78644. This library can optionally read and write gzip streams in memory as well.
  78645. The zlib format was designed to be compact and fast for use in memory
  78646. and on communications channels. The gzip format was designed for single-
  78647. file compression on file systems, has a larger header than zlib to maintain
  78648. directory information, and uses a different, slower check method than zlib.
  78649. The library does not install any signal handler. The decoder checks
  78650. the consistency of the compressed data, so the library should never
  78651. crash even in case of corrupted input.
  78652. */
  78653. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78654. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78655. struct internal_state;
  78656. typedef struct z_stream_s {
  78657. Bytef *next_in; /* next input byte */
  78658. uInt avail_in; /* number of bytes available at next_in */
  78659. uLong total_in; /* total nb of input bytes read so far */
  78660. Bytef *next_out; /* next output byte should be put there */
  78661. uInt avail_out; /* remaining free space at next_out */
  78662. uLong total_out; /* total nb of bytes output so far */
  78663. char *msg; /* last error message, NULL if no error */
  78664. struct internal_state FAR *state; /* not visible by applications */
  78665. alloc_func zalloc; /* used to allocate the internal state */
  78666. free_func zfree; /* used to free the internal state */
  78667. voidpf opaque; /* private data object passed to zalloc and zfree */
  78668. int data_type; /* best guess about the data type: binary or text */
  78669. uLong adler; /* adler32 value of the uncompressed data */
  78670. uLong reserved; /* reserved for future use */
  78671. } z_stream;
  78672. typedef z_stream FAR *z_streamp;
  78673. /*
  78674. gzip header information passed to and from zlib routines. See RFC 1952
  78675. for more details on the meanings of these fields.
  78676. */
  78677. typedef struct gz_header_s {
  78678. int text; /* true if compressed data believed to be text */
  78679. uLong time; /* modification time */
  78680. int xflags; /* extra flags (not used when writing a gzip file) */
  78681. int os; /* operating system */
  78682. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78683. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78684. uInt extra_max; /* space at extra (only when reading header) */
  78685. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78686. uInt name_max; /* space at name (only when reading header) */
  78687. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78688. uInt comm_max; /* space at comment (only when reading header) */
  78689. int hcrc; /* true if there was or will be a header crc */
  78690. int done; /* true when done reading gzip header (not used
  78691. when writing a gzip file) */
  78692. } gz_header;
  78693. typedef gz_header FAR *gz_headerp;
  78694. /*
  78695. The application must update next_in and avail_in when avail_in has
  78696. dropped to zero. It must update next_out and avail_out when avail_out
  78697. has dropped to zero. The application must initialize zalloc, zfree and
  78698. opaque before calling the init function. All other fields are set by the
  78699. compression library and must not be updated by the application.
  78700. The opaque value provided by the application will be passed as the first
  78701. parameter for calls of zalloc and zfree. This can be useful for custom
  78702. memory management. The compression library attaches no meaning to the
  78703. opaque value.
  78704. zalloc must return Z_NULL if there is not enough memory for the object.
  78705. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78706. thread safe.
  78707. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78708. exactly 65536 bytes, but will not be required to allocate more than this
  78709. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78710. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78711. have their offset normalized to zero. The default allocation function
  78712. provided by this library ensures this (see zutil.c). To reduce memory
  78713. requirements and avoid any allocation of 64K objects, at the expense of
  78714. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78715. The fields total_in and total_out can be used for statistics or
  78716. progress reports. After compression, total_in holds the total size of
  78717. the uncompressed data and may be saved for use in the decompressor
  78718. (particularly if the decompressor wants to decompress everything in
  78719. a single step).
  78720. */
  78721. /* constants */
  78722. #define Z_NO_FLUSH 0
  78723. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78724. #define Z_SYNC_FLUSH 2
  78725. #define Z_FULL_FLUSH 3
  78726. #define Z_FINISH 4
  78727. #define Z_BLOCK 5
  78728. /* Allowed flush values; see deflate() and inflate() below for details */
  78729. #define Z_OK 0
  78730. #define Z_STREAM_END 1
  78731. #define Z_NEED_DICT 2
  78732. #define Z_ERRNO (-1)
  78733. #define Z_STREAM_ERROR (-2)
  78734. #define Z_DATA_ERROR (-3)
  78735. #define Z_MEM_ERROR (-4)
  78736. #define Z_BUF_ERROR (-5)
  78737. #define Z_VERSION_ERROR (-6)
  78738. /* Return codes for the compression/decompression functions. Negative
  78739. * values are errors, positive values are used for special but normal events.
  78740. */
  78741. #define Z_NO_COMPRESSION 0
  78742. #define Z_BEST_SPEED 1
  78743. #define Z_BEST_COMPRESSION 9
  78744. #define Z_DEFAULT_COMPRESSION (-1)
  78745. /* compression levels */
  78746. #define Z_FILTERED 1
  78747. #define Z_HUFFMAN_ONLY 2
  78748. #define Z_RLE 3
  78749. #define Z_FIXED 4
  78750. #define Z_DEFAULT_STRATEGY 0
  78751. /* compression strategy; see deflateInit2() below for details */
  78752. #define Z_BINARY 0
  78753. #define Z_TEXT 1
  78754. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78755. #define Z_UNKNOWN 2
  78756. /* Possible values of the data_type field (though see inflate()) */
  78757. #define Z_DEFLATED 8
  78758. /* The deflate compression method (the only one supported in this version) */
  78759. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78760. #define zlib_version zlibVersion()
  78761. /* for compatibility with versions < 1.0.2 */
  78762. /* basic functions */
  78763. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78764. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78765. If the first character differs, the library code actually used is
  78766. not compatible with the zlib.h header file used by the application.
  78767. This check is automatically made by deflateInit and inflateInit.
  78768. */
  78769. /*
  78770. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78771. Initializes the internal stream state for compression. The fields
  78772. zalloc, zfree and opaque must be initialized before by the caller.
  78773. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78774. use default allocation functions.
  78775. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78776. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78777. all (the input data is simply copied a block at a time).
  78778. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78779. compression (currently equivalent to level 6).
  78780. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78781. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78782. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78783. with the version assumed by the caller (ZLIB_VERSION).
  78784. msg is set to null if there is no error message. deflateInit does not
  78785. perform any compression: this will be done by deflate().
  78786. */
  78787. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78788. /*
  78789. deflate compresses as much data as possible, and stops when the input
  78790. buffer becomes empty or the output buffer becomes full. It may introduce some
  78791. output latency (reading input without producing any output) except when
  78792. forced to flush.
  78793. The detailed semantics are as follows. deflate performs one or both of the
  78794. following actions:
  78795. - Compress more input starting at next_in and update next_in and avail_in
  78796. accordingly. If not all input can be processed (because there is not
  78797. enough room in the output buffer), next_in and avail_in are updated and
  78798. processing will resume at this point for the next call of deflate().
  78799. - Provide more output starting at next_out and update next_out and avail_out
  78800. accordingly. This action is forced if the parameter flush is non zero.
  78801. Forcing flush frequently degrades the compression ratio, so this parameter
  78802. should be set only when necessary (in interactive applications).
  78803. Some output may be provided even if flush is not set.
  78804. Before the call of deflate(), the application should ensure that at least
  78805. one of the actions is possible, by providing more input and/or consuming
  78806. more output, and updating avail_in or avail_out accordingly; avail_out
  78807. should never be zero before the call. The application can consume the
  78808. compressed output when it wants, for example when the output buffer is full
  78809. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78810. and with zero avail_out, it must be called again after making room in the
  78811. output buffer because there might be more output pending.
  78812. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78813. decide how much data to accumualte before producing output, in order to
  78814. maximize compression.
  78815. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78816. flushed to the output buffer and the output is aligned on a byte boundary, so
  78817. that the decompressor can get all input data available so far. (In particular
  78818. avail_in is zero after the call if enough output space has been provided
  78819. before the call.) Flushing may degrade compression for some compression
  78820. algorithms and so it should be used only when necessary.
  78821. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78822. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78823. restart from this point if previous compressed data has been damaged or if
  78824. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78825. compression.
  78826. If deflate returns with avail_out == 0, this function must be called again
  78827. with the same value of the flush parameter and more output space (updated
  78828. avail_out), until the flush is complete (deflate returns with non-zero
  78829. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78830. avail_out is greater than six to avoid repeated flush markers due to
  78831. avail_out == 0 on return.
  78832. If the parameter flush is set to Z_FINISH, pending input is processed,
  78833. pending output is flushed and deflate returns with Z_STREAM_END if there
  78834. was enough output space; if deflate returns with Z_OK, this function must be
  78835. called again with Z_FINISH and more output space (updated avail_out) but no
  78836. more input data, until it returns with Z_STREAM_END or an error. After
  78837. deflate has returned Z_STREAM_END, the only possible operations on the
  78838. stream are deflateReset or deflateEnd.
  78839. Z_FINISH can be used immediately after deflateInit if all the compression
  78840. is to be done in a single step. In this case, avail_out must be at least
  78841. the value returned by deflateBound (see below). If deflate does not return
  78842. Z_STREAM_END, then it must be called again as described above.
  78843. deflate() sets strm->adler to the adler32 checksum of all input read
  78844. so far (that is, total_in bytes).
  78845. deflate() may update strm->data_type if it can make a good guess about
  78846. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78847. binary. This field is only for information purposes and does not affect
  78848. the compression algorithm in any manner.
  78849. deflate() returns Z_OK if some progress has been made (more input
  78850. processed or more output produced), Z_STREAM_END if all input has been
  78851. consumed and all output has been produced (only when flush is set to
  78852. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78853. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78854. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78855. fatal, and deflate() can be called again with more input and more output
  78856. space to continue compressing.
  78857. */
  78858. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78859. /*
  78860. All dynamically allocated data structures for this stream are freed.
  78861. This function discards any unprocessed input and does not flush any
  78862. pending output.
  78863. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78864. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78865. prematurely (some input or output was discarded). In the error case,
  78866. msg may be set but then points to a static string (which must not be
  78867. deallocated).
  78868. */
  78869. /*
  78870. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78871. Initializes the internal stream state for decompression. The fields
  78872. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78873. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78874. value depends on the compression method), inflateInit determines the
  78875. compression method from the zlib header and allocates all data structures
  78876. accordingly; otherwise the allocation will be deferred to the first call of
  78877. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78878. use default allocation functions.
  78879. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78880. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78881. version assumed by the caller. msg is set to null if there is no error
  78882. message. inflateInit does not perform any decompression apart from reading
  78883. the zlib header if present: this will be done by inflate(). (So next_in and
  78884. avail_in may be modified, but next_out and avail_out are unchanged.)
  78885. */
  78886. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78887. /*
  78888. inflate decompresses as much data as possible, and stops when the input
  78889. buffer becomes empty or the output buffer becomes full. It may introduce
  78890. some output latency (reading input without producing any output) except when
  78891. forced to flush.
  78892. The detailed semantics are as follows. inflate performs one or both of the
  78893. following actions:
  78894. - Decompress more input starting at next_in and update next_in and avail_in
  78895. accordingly. If not all input can be processed (because there is not
  78896. enough room in the output buffer), next_in is updated and processing
  78897. will resume at this point for the next call of inflate().
  78898. - Provide more output starting at next_out and update next_out and avail_out
  78899. accordingly. inflate() provides as much output as possible, until there
  78900. is no more input data or no more space in the output buffer (see below
  78901. about the flush parameter).
  78902. Before the call of inflate(), the application should ensure that at least
  78903. one of the actions is possible, by providing more input and/or consuming
  78904. more output, and updating the next_* and avail_* values accordingly.
  78905. The application can consume the uncompressed output when it wants, for
  78906. example when the output buffer is full (avail_out == 0), or after each
  78907. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78908. must be called again after making room in the output buffer because there
  78909. might be more output pending.
  78910. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78911. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78912. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78913. if and when it gets to the next deflate block boundary. When decoding the
  78914. zlib or gzip format, this will cause inflate() to return immediately after
  78915. the header and before the first block. When doing a raw inflate, inflate()
  78916. will go ahead and process the first block, and will return when it gets to
  78917. the end of that block, or when it runs out of data.
  78918. The Z_BLOCK option assists in appending to or combining deflate streams.
  78919. Also to assist in this, on return inflate() will set strm->data_type to the
  78920. number of unused bits in the last byte taken from strm->next_in, plus 64
  78921. if inflate() is currently decoding the last block in the deflate stream,
  78922. plus 128 if inflate() returned immediately after decoding an end-of-block
  78923. code or decoding the complete header up to just before the first byte of the
  78924. deflate stream. The end-of-block will not be indicated until all of the
  78925. uncompressed data from that block has been written to strm->next_out. The
  78926. number of unused bits may in general be greater than seven, except when
  78927. bit 7 of data_type is set, in which case the number of unused bits will be
  78928. less than eight.
  78929. inflate() should normally be called until it returns Z_STREAM_END or an
  78930. error. However if all decompression is to be performed in a single step
  78931. (a single call of inflate), the parameter flush should be set to
  78932. Z_FINISH. In this case all pending input is processed and all pending
  78933. output is flushed; avail_out must be large enough to hold all the
  78934. uncompressed data. (The size of the uncompressed data may have been saved
  78935. by the compressor for this purpose.) The next operation on this stream must
  78936. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78937. is never required, but can be used to inform inflate that a faster approach
  78938. may be used for the single inflate() call.
  78939. In this implementation, inflate() always flushes as much output as
  78940. possible to the output buffer, and always uses the faster approach on the
  78941. first call. So the only effect of the flush parameter in this implementation
  78942. is on the return value of inflate(), as noted below, or when it returns early
  78943. because Z_BLOCK is used.
  78944. If a preset dictionary is needed after this call (see inflateSetDictionary
  78945. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78946. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78947. strm->adler to the adler32 checksum of all output produced so far (that is,
  78948. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78949. below. At the end of the stream, inflate() checks that its computed adler32
  78950. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78951. only if the checksum is correct.
  78952. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78953. deflate data. The header type is detected automatically. Any information
  78954. contained in the gzip header is not retained, so applications that need that
  78955. information should instead use raw inflate, see inflateInit2() below, or
  78956. inflateBack() and perform their own processing of the gzip header and
  78957. trailer.
  78958. inflate() returns Z_OK if some progress has been made (more input processed
  78959. or more output produced), Z_STREAM_END if the end of the compressed data has
  78960. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78961. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78962. corrupted (input stream not conforming to the zlib format or incorrect check
  78963. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78964. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78965. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78966. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78967. inflate() can be called again with more input and more output space to
  78968. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78969. call inflateSync() to look for a good compression block if a partial recovery
  78970. of the data is desired.
  78971. */
  78972. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78973. /*
  78974. All dynamically allocated data structures for this stream are freed.
  78975. This function discards any unprocessed input and does not flush any
  78976. pending output.
  78977. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78978. was inconsistent. In the error case, msg may be set but then points to a
  78979. static string (which must not be deallocated).
  78980. */
  78981. /* Advanced functions */
  78982. /*
  78983. The following functions are needed only in some special applications.
  78984. */
  78985. /*
  78986. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78987. int level,
  78988. int method,
  78989. int windowBits,
  78990. int memLevel,
  78991. int strategy));
  78992. This is another version of deflateInit with more compression options. The
  78993. fields next_in, zalloc, zfree and opaque must be initialized before by
  78994. the caller.
  78995. The method parameter is the compression method. It must be Z_DEFLATED in
  78996. this version of the library.
  78997. The windowBits parameter is the base two logarithm of the window size
  78998. (the size of the history buffer). It should be in the range 8..15 for this
  78999. version of the library. Larger values of this parameter result in better
  79000. compression at the expense of memory usage. The default value is 15 if
  79001. deflateInit is used instead.
  79002. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  79003. determines the window size. deflate() will then generate raw deflate data
  79004. with no zlib header or trailer, and will not compute an adler32 check value.
  79005. windowBits can also be greater than 15 for optional gzip encoding. Add
  79006. 16 to windowBits to write a simple gzip header and trailer around the
  79007. compressed data instead of a zlib wrapper. The gzip header will have no
  79008. file name, no extra data, no comment, no modification time (set to zero),
  79009. no header crc, and the operating system will be set to 255 (unknown). If a
  79010. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  79011. The memLevel parameter specifies how much memory should be allocated
  79012. for the internal compression state. memLevel=1 uses minimum memory but
  79013. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  79014. for optimal speed. The default value is 8. See zconf.h for total memory
  79015. usage as a function of windowBits and memLevel.
  79016. The strategy parameter is used to tune the compression algorithm. Use the
  79017. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  79018. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  79019. string match), or Z_RLE to limit match distances to one (run-length
  79020. encoding). Filtered data consists mostly of small values with a somewhat
  79021. random distribution. In this case, the compression algorithm is tuned to
  79022. compress them better. The effect of Z_FILTERED is to force more Huffman
  79023. coding and less string matching; it is somewhat intermediate between
  79024. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  79025. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  79026. parameter only affects the compression ratio but not the correctness of the
  79027. compressed output even if it is not set appropriately. Z_FIXED prevents the
  79028. use of dynamic Huffman codes, allowing for a simpler decoder for special
  79029. applications.
  79030. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79031. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  79032. method). msg is set to null if there is no error message. deflateInit2 does
  79033. not perform any compression: this will be done by deflate().
  79034. */
  79035. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  79036. const Bytef *dictionary,
  79037. uInt dictLength));
  79038. /*
  79039. Initializes the compression dictionary from the given byte sequence
  79040. without producing any compressed output. This function must be called
  79041. immediately after deflateInit, deflateInit2 or deflateReset, before any
  79042. call of deflate. The compressor and decompressor must use exactly the same
  79043. dictionary (see inflateSetDictionary).
  79044. The dictionary should consist of strings (byte sequences) that are likely
  79045. to be encountered later in the data to be compressed, with the most commonly
  79046. used strings preferably put towards the end of the dictionary. Using a
  79047. dictionary is most useful when the data to be compressed is short and can be
  79048. predicted with good accuracy; the data can then be compressed better than
  79049. with the default empty dictionary.
  79050. Depending on the size of the compression data structures selected by
  79051. deflateInit or deflateInit2, a part of the dictionary may in effect be
  79052. discarded, for example if the dictionary is larger than the window size in
  79053. deflate or deflate2. Thus the strings most likely to be useful should be
  79054. put at the end of the dictionary, not at the front. In addition, the
  79055. current implementation of deflate will use at most the window size minus
  79056. 262 bytes of the provided dictionary.
  79057. Upon return of this function, strm->adler is set to the adler32 value
  79058. of the dictionary; the decompressor may later use this value to determine
  79059. which dictionary has been used by the compressor. (The adler32 value
  79060. applies to the whole dictionary even if only a subset of the dictionary is
  79061. actually used by the compressor.) If a raw deflate was requested, then the
  79062. adler32 value is not computed and strm->adler is not set.
  79063. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  79064. parameter is invalid (such as NULL dictionary) or the stream state is
  79065. inconsistent (for example if deflate has already been called for this stream
  79066. or if the compression method is bsort). deflateSetDictionary does not
  79067. perform any compression: this will be done by deflate().
  79068. */
  79069. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  79070. z_streamp source));
  79071. /*
  79072. Sets the destination stream as a complete copy of the source stream.
  79073. This function can be useful when several compression strategies will be
  79074. tried, for example when there are several ways of pre-processing the input
  79075. data with a filter. The streams that will be discarded should then be freed
  79076. by calling deflateEnd. Note that deflateCopy duplicates the internal
  79077. compression state which can be quite large, so this strategy is slow and
  79078. can consume lots of memory.
  79079. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79080. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79081. (such as zalloc being NULL). msg is left unchanged in both source and
  79082. destination.
  79083. */
  79084. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  79085. /*
  79086. This function is equivalent to deflateEnd followed by deflateInit,
  79087. but does not free and reallocate all the internal compression state.
  79088. The stream will keep the same compression level and any other attributes
  79089. that may have been set by deflateInit2.
  79090. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79091. stream state was inconsistent (such as zalloc or state being NULL).
  79092. */
  79093. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  79094. int level,
  79095. int strategy));
  79096. /*
  79097. Dynamically update the compression level and compression strategy. The
  79098. interpretation of level and strategy is as in deflateInit2. This can be
  79099. used to switch between compression and straight copy of the input data, or
  79100. to switch to a different kind of input data requiring a different
  79101. strategy. If the compression level is changed, the input available so far
  79102. is compressed with the old level (and may be flushed); the new level will
  79103. take effect only at the next call of deflate().
  79104. Before the call of deflateParams, the stream state must be set as for
  79105. a call of deflate(), since the currently available input may have to
  79106. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  79107. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  79108. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  79109. if strm->avail_out was zero.
  79110. */
  79111. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  79112. int good_length,
  79113. int max_lazy,
  79114. int nice_length,
  79115. int max_chain));
  79116. /*
  79117. Fine tune deflate's internal compression parameters. This should only be
  79118. used by someone who understands the algorithm used by zlib's deflate for
  79119. searching for the best matching string, and even then only by the most
  79120. fanatic optimizer trying to squeeze out the last compressed bit for their
  79121. specific input data. Read the deflate.c source code for the meaning of the
  79122. max_lazy, good_length, nice_length, and max_chain parameters.
  79123. deflateTune() can be called after deflateInit() or deflateInit2(), and
  79124. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  79125. */
  79126. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  79127. uLong sourceLen));
  79128. /*
  79129. deflateBound() returns an upper bound on the compressed size after
  79130. deflation of sourceLen bytes. It must be called after deflateInit()
  79131. or deflateInit2(). This would be used to allocate an output buffer
  79132. for deflation in a single pass, and so would be called before deflate().
  79133. */
  79134. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  79135. int bits,
  79136. int value));
  79137. /*
  79138. deflatePrime() inserts bits in the deflate output stream. The intent
  79139. is that this function is used to start off the deflate output with the
  79140. bits leftover from a previous deflate stream when appending to it. As such,
  79141. this function can only be used for raw deflate, and must be used before the
  79142. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  79143. less than or equal to 16, and that many of the least significant bits of
  79144. value will be inserted in the output.
  79145. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79146. stream state was inconsistent.
  79147. */
  79148. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  79149. gz_headerp head));
  79150. /*
  79151. deflateSetHeader() provides gzip header information for when a gzip
  79152. stream is requested by deflateInit2(). deflateSetHeader() may be called
  79153. after deflateInit2() or deflateReset() and before the first call of
  79154. deflate(). The text, time, os, extra field, name, and comment information
  79155. in the provided gz_header structure are written to the gzip header (xflag is
  79156. ignored -- the extra flags are set according to the compression level). The
  79157. caller must assure that, if not Z_NULL, name and comment are terminated with
  79158. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  79159. available there. If hcrc is true, a gzip header crc is included. Note that
  79160. the current versions of the command-line version of gzip (up through version
  79161. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  79162. gzip file" and give up.
  79163. If deflateSetHeader is not used, the default gzip header has text false,
  79164. the time set to zero, and os set to 255, with no extra, name, or comment
  79165. fields. The gzip header is returned to the default state by deflateReset().
  79166. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79167. stream state was inconsistent.
  79168. */
  79169. /*
  79170. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79171. int windowBits));
  79172. This is another version of inflateInit with an extra parameter. The
  79173. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79174. before by the caller.
  79175. The windowBits parameter is the base two logarithm of the maximum window
  79176. size (the size of the history buffer). It should be in the range 8..15 for
  79177. this version of the library. The default value is 15 if inflateInit is used
  79178. instead. windowBits must be greater than or equal to the windowBits value
  79179. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79180. deflateInit2() was not used. If a compressed stream with a larger window
  79181. size is given as input, inflate() will return with the error code
  79182. Z_DATA_ERROR instead of trying to allocate a larger window.
  79183. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79184. determines the window size. inflate() will then process raw deflate data,
  79185. not looking for a zlib or gzip header, not generating a check value, and not
  79186. looking for any check values for comparison at the end of the stream. This
  79187. is for use with other formats that use the deflate compressed data format
  79188. such as zip. Those formats provide their own check values. If a custom
  79189. format is developed using the raw deflate format for compressed data, it is
  79190. recommended that a check value such as an adler32 or a crc32 be applied to
  79191. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79192. most applications, the zlib format should be used as is. Note that comments
  79193. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79194. windowBits can also be greater than 15 for optional gzip decoding. Add
  79195. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79196. detection, or add 16 to decode only the gzip format (the zlib format will
  79197. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79198. a crc32 instead of an adler32.
  79199. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79200. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79201. is set to null if there is no error message. inflateInit2 does not perform
  79202. any decompression apart from reading the zlib header if present: this will
  79203. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79204. and avail_out are unchanged.)
  79205. */
  79206. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79207. const Bytef *dictionary,
  79208. uInt dictLength));
  79209. /*
  79210. Initializes the decompression dictionary from the given uncompressed byte
  79211. sequence. This function must be called immediately after a call of inflate,
  79212. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79213. can be determined from the adler32 value returned by that call of inflate.
  79214. The compressor and decompressor must use exactly the same dictionary (see
  79215. deflateSetDictionary). For raw inflate, this function can be called
  79216. immediately after inflateInit2() or inflateReset() and before any call of
  79217. inflate() to set the dictionary. The application must insure that the
  79218. dictionary that was used for compression is provided.
  79219. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79220. parameter is invalid (such as NULL dictionary) or the stream state is
  79221. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79222. expected one (incorrect adler32 value). inflateSetDictionary does not
  79223. perform any decompression: this will be done by subsequent calls of
  79224. inflate().
  79225. */
  79226. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79227. /*
  79228. Skips invalid compressed data until a full flush point (see above the
  79229. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79230. available input is skipped. No output is provided.
  79231. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79232. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79233. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79234. case, the application may save the current current value of total_in which
  79235. indicates where valid compressed data was found. In the error case, the
  79236. application may repeatedly call inflateSync, providing more input each time,
  79237. until success or end of the input data.
  79238. */
  79239. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79240. z_streamp source));
  79241. /*
  79242. Sets the destination stream as a complete copy of the source stream.
  79243. This function can be useful when randomly accessing a large stream. The
  79244. first pass through the stream can periodically record the inflate state,
  79245. allowing restarting inflate at those points when randomly accessing the
  79246. stream.
  79247. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79248. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79249. (such as zalloc being NULL). msg is left unchanged in both source and
  79250. destination.
  79251. */
  79252. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79253. /*
  79254. This function is equivalent to inflateEnd followed by inflateInit,
  79255. but does not free and reallocate all the internal decompression state.
  79256. The stream will keep attributes that may have been set by inflateInit2.
  79257. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79258. stream state was inconsistent (such as zalloc or state being NULL).
  79259. */
  79260. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79261. int bits,
  79262. int value));
  79263. /*
  79264. This function inserts bits in the inflate input stream. The intent is
  79265. that this function is used to start inflating at a bit position in the
  79266. middle of a byte. The provided bits will be used before any bytes are used
  79267. from next_in. This function should only be used with raw inflate, and
  79268. should be used before the first inflate() call after inflateInit2() or
  79269. inflateReset(). bits must be less than or equal to 16, and that many of the
  79270. least significant bits of value will be inserted in the input.
  79271. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79272. stream state was inconsistent.
  79273. */
  79274. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79275. gz_headerp head));
  79276. /*
  79277. inflateGetHeader() requests that gzip header information be stored in the
  79278. provided gz_header structure. inflateGetHeader() may be called after
  79279. inflateInit2() or inflateReset(), and before the first call of inflate().
  79280. As inflate() processes the gzip stream, head->done is zero until the header
  79281. is completed, at which time head->done is set to one. If a zlib stream is
  79282. being decoded, then head->done is set to -1 to indicate that there will be
  79283. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79284. force inflate() to return immediately after header processing is complete
  79285. and before any actual data is decompressed.
  79286. The text, time, xflags, and os fields are filled in with the gzip header
  79287. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79288. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79289. contains the maximum number of bytes to write to extra. Once done is true,
  79290. extra_len contains the actual extra field length, and extra contains the
  79291. extra field, or that field truncated if extra_max is less than extra_len.
  79292. If name is not Z_NULL, then up to name_max characters are written there,
  79293. terminated with a zero unless the length is greater than name_max. If
  79294. comment is not Z_NULL, then up to comm_max characters are written there,
  79295. terminated with a zero unless the length is greater than comm_max. When
  79296. any of extra, name, or comment are not Z_NULL and the respective field is
  79297. not present in the header, then that field is set to Z_NULL to signal its
  79298. absence. This allows the use of deflateSetHeader() with the returned
  79299. structure to duplicate the header. However if those fields are set to
  79300. allocated memory, then the application will need to save those pointers
  79301. elsewhere so that they can be eventually freed.
  79302. If inflateGetHeader is not used, then the header information is simply
  79303. discarded. The header is always checked for validity, including the header
  79304. CRC if present. inflateReset() will reset the process to discard the header
  79305. information. The application would need to call inflateGetHeader() again to
  79306. retrieve the header from the next gzip stream.
  79307. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79308. stream state was inconsistent.
  79309. */
  79310. /*
  79311. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79312. unsigned char FAR *window));
  79313. Initialize the internal stream state for decompression using inflateBack()
  79314. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79315. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79316. derived memory allocation routines are used. windowBits is the base two
  79317. logarithm of the window size, in the range 8..15. window is a caller
  79318. supplied buffer of that size. Except for special applications where it is
  79319. assured that deflate was used with small window sizes, windowBits must be 15
  79320. and a 32K byte window must be supplied to be able to decompress general
  79321. deflate streams.
  79322. See inflateBack() for the usage of these routines.
  79323. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79324. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79325. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79326. match the version of the header file.
  79327. */
  79328. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79329. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79330. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79331. in_func in, void FAR *in_desc,
  79332. out_func out, void FAR *out_desc));
  79333. /*
  79334. inflateBack() does a raw inflate with a single call using a call-back
  79335. interface for input and output. This is more efficient than inflate() for
  79336. file i/o applications in that it avoids copying between the output and the
  79337. sliding window by simply making the window itself the output buffer. This
  79338. function trusts the application to not change the output buffer passed by
  79339. the output function, at least until inflateBack() returns.
  79340. inflateBackInit() must be called first to allocate the internal state
  79341. and to initialize the state with the user-provided window buffer.
  79342. inflateBack() may then be used multiple times to inflate a complete, raw
  79343. deflate stream with each call. inflateBackEnd() is then called to free
  79344. the allocated state.
  79345. A raw deflate stream is one with no zlib or gzip header or trailer.
  79346. This routine would normally be used in a utility that reads zip or gzip
  79347. files and writes out uncompressed files. The utility would decode the
  79348. header and process the trailer on its own, hence this routine expects
  79349. only the raw deflate stream to decompress. This is different from the
  79350. normal behavior of inflate(), which expects either a zlib or gzip header and
  79351. trailer around the deflate stream.
  79352. inflateBack() uses two subroutines supplied by the caller that are then
  79353. called by inflateBack() for input and output. inflateBack() calls those
  79354. routines until it reads a complete deflate stream and writes out all of the
  79355. uncompressed data, or until it encounters an error. The function's
  79356. parameters and return types are defined above in the in_func and out_func
  79357. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79358. number of bytes of provided input, and a pointer to that input in buf. If
  79359. there is no input available, in() must return zero--buf is ignored in that
  79360. case--and inflateBack() will return a buffer error. inflateBack() will call
  79361. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79362. should return zero on success, or non-zero on failure. If out() returns
  79363. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79364. are permitted to change the contents of the window provided to
  79365. inflateBackInit(), which is also the buffer that out() uses to write from.
  79366. The length written by out() will be at most the window size. Any non-zero
  79367. amount of input may be provided by in().
  79368. For convenience, inflateBack() can be provided input on the first call by
  79369. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79370. in() will be called. Therefore strm->next_in must be initialized before
  79371. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79372. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79373. must also be initialized, and then if strm->avail_in is not zero, input will
  79374. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79375. The in_desc and out_desc parameters of inflateBack() is passed as the
  79376. first parameter of in() and out() respectively when they are called. These
  79377. descriptors can be optionally used to pass any information that the caller-
  79378. supplied in() and out() functions need to do their job.
  79379. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79380. pass back any unused input that was provided by the last in() call. The
  79381. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79382. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79383. error in the deflate stream (in which case strm->msg is set to indicate the
  79384. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79385. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79386. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79387. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79388. out() returning non-zero. (in() will always be called before out(), so
  79389. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79390. that inflateBack() cannot return Z_OK.
  79391. */
  79392. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79393. /*
  79394. All memory allocated by inflateBackInit() is freed.
  79395. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79396. state was inconsistent.
  79397. */
  79398. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79399. /* Return flags indicating compile-time options.
  79400. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79401. 1.0: size of uInt
  79402. 3.2: size of uLong
  79403. 5.4: size of voidpf (pointer)
  79404. 7.6: size of z_off_t
  79405. Compiler, assembler, and debug options:
  79406. 8: DEBUG
  79407. 9: ASMV or ASMINF -- use ASM code
  79408. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79409. 11: 0 (reserved)
  79410. One-time table building (smaller code, but not thread-safe if true):
  79411. 12: BUILDFIXED -- build static block decoding tables when needed
  79412. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79413. 14,15: 0 (reserved)
  79414. Library content (indicates missing functionality):
  79415. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79416. deflate code when not needed)
  79417. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79418. and decode gzip streams (to avoid linking crc code)
  79419. 18-19: 0 (reserved)
  79420. Operation variations (changes in library functionality):
  79421. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79422. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79423. 22,23: 0 (reserved)
  79424. The sprintf variant used by gzprintf (zero is best):
  79425. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79426. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79427. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79428. Remainder:
  79429. 27-31: 0 (reserved)
  79430. */
  79431. /* utility functions */
  79432. /*
  79433. The following utility functions are implemented on top of the
  79434. basic stream-oriented functions. To simplify the interface, some
  79435. default options are assumed (compression level and memory usage,
  79436. standard memory allocation functions). The source code of these
  79437. utility functions can easily be modified if you need special options.
  79438. */
  79439. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79440. const Bytef *source, uLong sourceLen));
  79441. /*
  79442. Compresses the source buffer into the destination buffer. sourceLen is
  79443. the byte length of the source buffer. Upon entry, destLen is the total
  79444. size of the destination buffer, which must be at least the value returned
  79445. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79446. compressed buffer.
  79447. This function can be used to compress a whole file at once if the
  79448. input file is mmap'ed.
  79449. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79450. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79451. buffer.
  79452. */
  79453. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79454. const Bytef *source, uLong sourceLen,
  79455. int level));
  79456. /*
  79457. Compresses the source buffer into the destination buffer. The level
  79458. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79459. length of the source buffer. Upon entry, destLen is the total size of the
  79460. destination buffer, which must be at least the value returned by
  79461. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79462. compressed buffer.
  79463. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79464. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79465. Z_STREAM_ERROR if the level parameter is invalid.
  79466. */
  79467. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79468. /*
  79469. compressBound() returns an upper bound on the compressed size after
  79470. compress() or compress2() on sourceLen bytes. It would be used before
  79471. a compress() or compress2() call to allocate the destination buffer.
  79472. */
  79473. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79474. const Bytef *source, uLong sourceLen));
  79475. /*
  79476. Decompresses the source buffer into the destination buffer. sourceLen is
  79477. the byte length of the source buffer. Upon entry, destLen is the total
  79478. size of the destination buffer, which must be large enough to hold the
  79479. entire uncompressed data. (The size of the uncompressed data must have
  79480. been saved previously by the compressor and transmitted to the decompressor
  79481. by some mechanism outside the scope of this compression library.)
  79482. Upon exit, destLen is the actual size of the compressed buffer.
  79483. This function can be used to decompress a whole file at once if the
  79484. input file is mmap'ed.
  79485. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79486. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79487. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79488. */
  79489. typedef voidp gzFile;
  79490. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79491. /*
  79492. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79493. is as in fopen ("rb" or "wb") but can also include a compression level
  79494. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79495. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79496. as in "wb1R". (See the description of deflateInit2 for more information
  79497. about the strategy parameter.)
  79498. gzopen can be used to read a file which is not in gzip format; in this
  79499. case gzread will directly read from the file without decompression.
  79500. gzopen returns NULL if the file could not be opened or if there was
  79501. insufficient memory to allocate the (de)compression state; errno
  79502. can be checked to distinguish the two cases (if errno is zero, the
  79503. zlib error is Z_MEM_ERROR). */
  79504. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79505. /*
  79506. gzdopen() associates a gzFile with the file descriptor fd. File
  79507. descriptors are obtained from calls like open, dup, creat, pipe or
  79508. fileno (in the file has been previously opened with fopen).
  79509. The mode parameter is as in gzopen.
  79510. The next call of gzclose on the returned gzFile will also close the
  79511. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79512. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79513. gzdopen returns NULL if there was insufficient memory to allocate
  79514. the (de)compression state.
  79515. */
  79516. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79517. /*
  79518. Dynamically update the compression level or strategy. See the description
  79519. of deflateInit2 for the meaning of these parameters.
  79520. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79521. opened for writing.
  79522. */
  79523. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79524. /*
  79525. Reads the given number of uncompressed bytes from the compressed file.
  79526. If the input file was not in gzip format, gzread copies the given number
  79527. of bytes into the buffer.
  79528. gzread returns the number of uncompressed bytes actually read (0 for
  79529. end of file, -1 for error). */
  79530. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79531. voidpc buf, unsigned len));
  79532. /*
  79533. Writes the given number of uncompressed bytes into the compressed file.
  79534. gzwrite returns the number of uncompressed bytes actually written
  79535. (0 in case of error).
  79536. */
  79537. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79538. /*
  79539. Converts, formats, and writes the args to the compressed file under
  79540. control of the format string, as in fprintf. gzprintf returns the number of
  79541. uncompressed bytes actually written (0 in case of error). The number of
  79542. uncompressed bytes written is limited to 4095. The caller should assure that
  79543. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79544. return an error (0) with nothing written. In this case, there may also be a
  79545. buffer overflow with unpredictable consequences, which is possible only if
  79546. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79547. because the secure snprintf() or vsnprintf() functions were not available.
  79548. */
  79549. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79550. /*
  79551. Writes the given null-terminated string to the compressed file, excluding
  79552. the terminating null character.
  79553. gzputs returns the number of characters written, or -1 in case of error.
  79554. */
  79555. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79556. /*
  79557. Reads bytes from the compressed file until len-1 characters are read, or
  79558. a newline character is read and transferred to buf, or an end-of-file
  79559. condition is encountered. The string is then terminated with a null
  79560. character.
  79561. gzgets returns buf, or Z_NULL in case of error.
  79562. */
  79563. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79564. /*
  79565. Writes c, converted to an unsigned char, into the compressed file.
  79566. gzputc returns the value that was written, or -1 in case of error.
  79567. */
  79568. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79569. /*
  79570. Reads one byte from the compressed file. gzgetc returns this byte
  79571. or -1 in case of end of file or error.
  79572. */
  79573. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79574. /*
  79575. Push one character back onto the stream to be read again later.
  79576. Only one character of push-back is allowed. gzungetc() returns the
  79577. character pushed, or -1 on failure. gzungetc() will fail if a
  79578. character has been pushed but not read yet, or if c is -1. The pushed
  79579. character will be discarded if the stream is repositioned with gzseek()
  79580. or gzrewind().
  79581. */
  79582. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79583. /*
  79584. Flushes all pending output into the compressed file. The parameter
  79585. flush is as in the deflate() function. The return value is the zlib
  79586. error number (see function gzerror below). gzflush returns Z_OK if
  79587. the flush parameter is Z_FINISH and all output could be flushed.
  79588. gzflush should be called only when strictly necessary because it can
  79589. degrade compression.
  79590. */
  79591. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79592. z_off_t offset, int whence));
  79593. /*
  79594. Sets the starting position for the next gzread or gzwrite on the
  79595. given compressed file. The offset represents a number of bytes in the
  79596. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79597. the value SEEK_END is not supported.
  79598. If the file is opened for reading, this function is emulated but can be
  79599. extremely slow. If the file is opened for writing, only forward seeks are
  79600. supported; gzseek then compresses a sequence of zeroes up to the new
  79601. starting position.
  79602. gzseek returns the resulting offset location as measured in bytes from
  79603. the beginning of the uncompressed stream, or -1 in case of error, in
  79604. particular if the file is opened for writing and the new starting position
  79605. would be before the current position.
  79606. */
  79607. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79608. /*
  79609. Rewinds the given file. This function is supported only for reading.
  79610. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79611. */
  79612. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79613. /*
  79614. Returns the starting position for the next gzread or gzwrite on the
  79615. given compressed file. This position represents a number of bytes in the
  79616. uncompressed data stream.
  79617. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79618. */
  79619. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79620. /*
  79621. Returns 1 when EOF has previously been detected reading the given
  79622. input stream, otherwise zero.
  79623. */
  79624. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79625. /*
  79626. Returns 1 if file is being read directly without decompression, otherwise
  79627. zero.
  79628. */
  79629. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79630. /*
  79631. Flushes all pending output if necessary, closes the compressed file
  79632. and deallocates all the (de)compression state. The return value is the zlib
  79633. error number (see function gzerror below).
  79634. */
  79635. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79636. /*
  79637. Returns the error message for the last error which occurred on the
  79638. given compressed file. errnum is set to zlib error number. If an
  79639. error occurred in the file system and not in the compression library,
  79640. errnum is set to Z_ERRNO and the application may consult errno
  79641. to get the exact error code.
  79642. */
  79643. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79644. /*
  79645. Clears the error and end-of-file flags for file. This is analogous to the
  79646. clearerr() function in stdio. This is useful for continuing to read a gzip
  79647. file that is being written concurrently.
  79648. */
  79649. /* checksum functions */
  79650. /*
  79651. These functions are not related to compression but are exported
  79652. anyway because they might be useful in applications using the
  79653. compression library.
  79654. */
  79655. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79656. /*
  79657. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79658. return the updated checksum. If buf is NULL, this function returns
  79659. the required initial value for the checksum.
  79660. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79661. much faster. Usage example:
  79662. uLong adler = adler32(0L, Z_NULL, 0);
  79663. while (read_buffer(buffer, length) != EOF) {
  79664. adler = adler32(adler, buffer, length);
  79665. }
  79666. if (adler != original_adler) error();
  79667. */
  79668. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79669. z_off_t len2));
  79670. /*
  79671. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79672. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79673. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79674. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79675. */
  79676. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79677. /*
  79678. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79679. updated CRC-32. If buf is NULL, this function returns the required initial
  79680. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79681. performed within this function so it shouldn't be done by the application.
  79682. Usage example:
  79683. uLong crc = crc32(0L, Z_NULL, 0);
  79684. while (read_buffer(buffer, length) != EOF) {
  79685. crc = crc32(crc, buffer, length);
  79686. }
  79687. if (crc != original_crc) error();
  79688. */
  79689. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79690. /*
  79691. Combine two CRC-32 check values into one. For two sequences of bytes,
  79692. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79693. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79694. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79695. len2.
  79696. */
  79697. /* various hacks, don't look :) */
  79698. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79699. * and the compiler's view of z_stream:
  79700. */
  79701. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79702. const char *version, int stream_size));
  79703. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79704. const char *version, int stream_size));
  79705. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79706. int windowBits, int memLevel,
  79707. int strategy, const char *version,
  79708. int stream_size));
  79709. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79710. const char *version, int stream_size));
  79711. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79712. unsigned char FAR *window,
  79713. const char *version,
  79714. int stream_size));
  79715. #define deflateInit(strm, level) \
  79716. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79717. #define inflateInit(strm) \
  79718. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79719. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79720. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79721. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79722. #define inflateInit2(strm, windowBits) \
  79723. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79724. #define inflateBackInit(strm, windowBits, window) \
  79725. inflateBackInit_((strm), (windowBits), (window), \
  79726. ZLIB_VERSION, sizeof(z_stream))
  79727. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79728. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79729. #endif
  79730. ZEXTERN const char * ZEXPORT zError OF((int));
  79731. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79732. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79733. #ifdef __cplusplus
  79734. //}
  79735. #endif
  79736. #endif /* ZLIB_H */
  79737. /*** End of inlined file: zlib.h ***/
  79738. #undef OS_CODE
  79739. #else
  79740. #include <zlib.h>
  79741. #endif
  79742. }
  79743. BEGIN_JUCE_NAMESPACE
  79744. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79745. {
  79746. public:
  79747. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79748. : data (0),
  79749. dataSize (0),
  79750. compLevel (compressionLevel),
  79751. strategy (0),
  79752. setParams (true),
  79753. streamIsValid (false),
  79754. finished (false),
  79755. shouldFinish (false)
  79756. {
  79757. using namespace zlibNamespace;
  79758. zerostruct (stream);
  79759. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79760. windowBits != 0 ? windowBits : MAX_WBITS,
  79761. 8, strategy) == Z_OK);
  79762. }
  79763. ~GZIPCompressorHelper()
  79764. {
  79765. using namespace zlibNamespace;
  79766. if (streamIsValid)
  79767. deflateEnd (&stream);
  79768. }
  79769. bool needsInput() const throw()
  79770. {
  79771. return dataSize <= 0;
  79772. }
  79773. void setInput (const uint8* const newData, const int size) throw()
  79774. {
  79775. data = newData;
  79776. dataSize = size;
  79777. }
  79778. int doNextBlock (uint8* const dest, const int destSize) throw()
  79779. {
  79780. using namespace zlibNamespace;
  79781. if (streamIsValid)
  79782. {
  79783. stream.next_in = const_cast <uint8*> (data);
  79784. stream.next_out = dest;
  79785. stream.avail_in = dataSize;
  79786. stream.avail_out = destSize;
  79787. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79788. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79789. setParams = false;
  79790. switch (result)
  79791. {
  79792. case Z_STREAM_END:
  79793. finished = true;
  79794. // Deliberate fall-through..
  79795. case Z_OK:
  79796. data += dataSize - stream.avail_in;
  79797. dataSize = stream.avail_in;
  79798. return destSize - stream.avail_out;
  79799. default:
  79800. break;
  79801. }
  79802. }
  79803. return 0;
  79804. }
  79805. enum { gzipCompBufferSize = 32768 };
  79806. private:
  79807. zlibNamespace::z_stream stream;
  79808. const uint8* data;
  79809. int dataSize, compLevel, strategy;
  79810. bool setParams, streamIsValid;
  79811. public:
  79812. bool finished, shouldFinish;
  79813. };
  79814. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79815. int compressionLevel,
  79816. const bool deleteDestStream,
  79817. const int windowBits)
  79818. : destStream (destStream_, deleteDestStream),
  79819. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79820. {
  79821. if (compressionLevel < 1 || compressionLevel > 9)
  79822. compressionLevel = -1;
  79823. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79824. }
  79825. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79826. {
  79827. flush();
  79828. }
  79829. void GZIPCompressorOutputStream::flush()
  79830. {
  79831. if (! helper->finished)
  79832. {
  79833. helper->shouldFinish = true;
  79834. while (! helper->finished)
  79835. doNextBlock();
  79836. }
  79837. destStream->flush();
  79838. }
  79839. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79840. {
  79841. if (! helper->finished)
  79842. {
  79843. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79844. while (! helper->needsInput())
  79845. {
  79846. if (! doNextBlock())
  79847. return false;
  79848. }
  79849. }
  79850. return true;
  79851. }
  79852. bool GZIPCompressorOutputStream::doNextBlock()
  79853. {
  79854. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79855. return len <= 0 || destStream->write (buffer, len);
  79856. }
  79857. int64 GZIPCompressorOutputStream::getPosition()
  79858. {
  79859. return destStream->getPosition();
  79860. }
  79861. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79862. {
  79863. jassertfalse; // can't do it!
  79864. return false;
  79865. }
  79866. END_JUCE_NAMESPACE
  79867. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79868. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79869. #if JUCE_MSVC
  79870. #pragma warning (push)
  79871. #pragma warning (disable: 4309 4305)
  79872. #endif
  79873. namespace zlibNamespace
  79874. {
  79875. #if JUCE_INCLUDE_ZLIB_CODE
  79876. #undef OS_CODE
  79877. #undef fdopen
  79878. #define ZLIB_INTERNAL
  79879. #define NO_DUMMY_DECL
  79880. /*** Start of inlined file: adler32.c ***/
  79881. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79882. #define ZLIB_INTERNAL
  79883. #define BASE 65521UL /* largest prime smaller than 65536 */
  79884. #define NMAX 5552
  79885. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79886. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79887. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79888. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79889. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79890. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79891. /* use NO_DIVIDE if your processor does not do division in hardware */
  79892. #ifdef NO_DIVIDE
  79893. # define MOD(a) \
  79894. do { \
  79895. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79896. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79897. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79898. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79899. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79900. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79901. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79902. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79903. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79904. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79905. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79906. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79907. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79908. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79909. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79910. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79911. if (a >= BASE) a -= BASE; \
  79912. } while (0)
  79913. # define MOD4(a) \
  79914. do { \
  79915. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79916. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79917. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79918. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79919. if (a >= BASE) a -= BASE; \
  79920. } while (0)
  79921. #else
  79922. # define MOD(a) a %= BASE
  79923. # define MOD4(a) a %= BASE
  79924. #endif
  79925. /* ========================================================================= */
  79926. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79927. {
  79928. unsigned long sum2;
  79929. unsigned n;
  79930. /* split Adler-32 into component sums */
  79931. sum2 = (adler >> 16) & 0xffff;
  79932. adler &= 0xffff;
  79933. /* in case user likes doing a byte at a time, keep it fast */
  79934. if (len == 1) {
  79935. adler += buf[0];
  79936. if (adler >= BASE)
  79937. adler -= BASE;
  79938. sum2 += adler;
  79939. if (sum2 >= BASE)
  79940. sum2 -= BASE;
  79941. return adler | (sum2 << 16);
  79942. }
  79943. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79944. if (buf == Z_NULL)
  79945. return 1L;
  79946. /* in case short lengths are provided, keep it somewhat fast */
  79947. if (len < 16) {
  79948. while (len--) {
  79949. adler += *buf++;
  79950. sum2 += adler;
  79951. }
  79952. if (adler >= BASE)
  79953. adler -= BASE;
  79954. MOD4(sum2); /* only added so many BASE's */
  79955. return adler | (sum2 << 16);
  79956. }
  79957. /* do length NMAX blocks -- requires just one modulo operation */
  79958. while (len >= NMAX) {
  79959. len -= NMAX;
  79960. n = NMAX / 16; /* NMAX is divisible by 16 */
  79961. do {
  79962. DO16(buf); /* 16 sums unrolled */
  79963. buf += 16;
  79964. } while (--n);
  79965. MOD(adler);
  79966. MOD(sum2);
  79967. }
  79968. /* do remaining bytes (less than NMAX, still just one modulo) */
  79969. if (len) { /* avoid modulos if none remaining */
  79970. while (len >= 16) {
  79971. len -= 16;
  79972. DO16(buf);
  79973. buf += 16;
  79974. }
  79975. while (len--) {
  79976. adler += *buf++;
  79977. sum2 += adler;
  79978. }
  79979. MOD(adler);
  79980. MOD(sum2);
  79981. }
  79982. /* return recombined sums */
  79983. return adler | (sum2 << 16);
  79984. }
  79985. /* ========================================================================= */
  79986. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79987. {
  79988. unsigned long sum1;
  79989. unsigned long sum2;
  79990. unsigned rem;
  79991. /* the derivation of this formula is left as an exercise for the reader */
  79992. rem = (unsigned)(len2 % BASE);
  79993. sum1 = adler1 & 0xffff;
  79994. sum2 = rem * sum1;
  79995. MOD(sum2);
  79996. sum1 += (adler2 & 0xffff) + BASE - 1;
  79997. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79998. if (sum1 > BASE) sum1 -= BASE;
  79999. if (sum1 > BASE) sum1 -= BASE;
  80000. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  80001. if (sum2 > BASE) sum2 -= BASE;
  80002. return sum1 | (sum2 << 16);
  80003. }
  80004. /*** End of inlined file: adler32.c ***/
  80005. /*** Start of inlined file: compress.c ***/
  80006. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80007. #define ZLIB_INTERNAL
  80008. /* ===========================================================================
  80009. Compresses the source buffer into the destination buffer. The level
  80010. parameter has the same meaning as in deflateInit. sourceLen is the byte
  80011. length of the source buffer. Upon entry, destLen is the total size of the
  80012. destination buffer, which must be at least 0.1% larger than sourceLen plus
  80013. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  80014. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  80015. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  80016. Z_STREAM_ERROR if the level parameter is invalid.
  80017. */
  80018. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  80019. uLong sourceLen, int level)
  80020. {
  80021. z_stream stream;
  80022. int err;
  80023. stream.next_in = (Bytef*)source;
  80024. stream.avail_in = (uInt)sourceLen;
  80025. #ifdef MAXSEG_64K
  80026. /* Check for source > 64K on 16-bit machine: */
  80027. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  80028. #endif
  80029. stream.next_out = dest;
  80030. stream.avail_out = (uInt)*destLen;
  80031. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  80032. stream.zalloc = (alloc_func)0;
  80033. stream.zfree = (free_func)0;
  80034. stream.opaque = (voidpf)0;
  80035. err = deflateInit(&stream, level);
  80036. if (err != Z_OK) return err;
  80037. err = deflate(&stream, Z_FINISH);
  80038. if (err != Z_STREAM_END) {
  80039. deflateEnd(&stream);
  80040. return err == Z_OK ? Z_BUF_ERROR : err;
  80041. }
  80042. *destLen = stream.total_out;
  80043. err = deflateEnd(&stream);
  80044. return err;
  80045. }
  80046. /* ===========================================================================
  80047. */
  80048. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  80049. {
  80050. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  80051. }
  80052. /* ===========================================================================
  80053. If the default memLevel or windowBits for deflateInit() is changed, then
  80054. this function needs to be updated.
  80055. */
  80056. uLong ZEXPORT compressBound (uLong sourceLen)
  80057. {
  80058. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  80059. }
  80060. /*** End of inlined file: compress.c ***/
  80061. #undef DO1
  80062. #undef DO8
  80063. /*** Start of inlined file: crc32.c ***/
  80064. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80065. /*
  80066. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  80067. protection on the static variables used to control the first-use generation
  80068. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  80069. first call get_crc_table() to initialize the tables before allowing more than
  80070. one thread to use crc32().
  80071. */
  80072. #ifdef MAKECRCH
  80073. # include <stdio.h>
  80074. # ifndef DYNAMIC_CRC_TABLE
  80075. # define DYNAMIC_CRC_TABLE
  80076. # endif /* !DYNAMIC_CRC_TABLE */
  80077. #endif /* MAKECRCH */
  80078. /*** Start of inlined file: zutil.h ***/
  80079. /* WARNING: this file should *not* be used by applications. It is
  80080. part of the implementation of the compression library and is
  80081. subject to change. Applications should only use zlib.h.
  80082. */
  80083. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80084. #ifndef ZUTIL_H
  80085. #define ZUTIL_H
  80086. #define ZLIB_INTERNAL
  80087. #ifdef STDC
  80088. # ifndef _WIN32_WCE
  80089. # include <stddef.h>
  80090. # endif
  80091. # include <string.h>
  80092. # include <stdlib.h>
  80093. #endif
  80094. #ifdef NO_ERRNO_H
  80095. # ifdef _WIN32_WCE
  80096. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80097. * errno. We define it as a global variable to simplify porting.
  80098. * Its value is always 0 and should not be used. We rename it to
  80099. * avoid conflict with other libraries that use the same workaround.
  80100. */
  80101. # define errno z_errno
  80102. # endif
  80103. extern int errno;
  80104. #else
  80105. # ifndef _WIN32_WCE
  80106. # include <errno.h>
  80107. # endif
  80108. #endif
  80109. #ifndef local
  80110. # define local static
  80111. #endif
  80112. /* compile with -Dlocal if your debugger can't find static symbols */
  80113. typedef unsigned char uch;
  80114. typedef uch FAR uchf;
  80115. typedef unsigned short ush;
  80116. typedef ush FAR ushf;
  80117. typedef unsigned long ulg;
  80118. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  80119. /* (size given to avoid silly warnings with Visual C++) */
  80120. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  80121. #define ERR_RETURN(strm,err) \
  80122. return (strm->msg = (char*)ERR_MSG(err), (err))
  80123. /* To be used only when the state is known to be valid */
  80124. /* common constants */
  80125. #ifndef DEF_WBITS
  80126. # define DEF_WBITS MAX_WBITS
  80127. #endif
  80128. /* default windowBits for decompression. MAX_WBITS is for compression only */
  80129. #if MAX_MEM_LEVEL >= 8
  80130. # define DEF_MEM_LEVEL 8
  80131. #else
  80132. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  80133. #endif
  80134. /* default memLevel */
  80135. #define STORED_BLOCK 0
  80136. #define STATIC_TREES 1
  80137. #define DYN_TREES 2
  80138. /* The three kinds of block type */
  80139. #define MIN_MATCH 3
  80140. #define MAX_MATCH 258
  80141. /* The minimum and maximum match lengths */
  80142. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  80143. /* target dependencies */
  80144. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  80145. # define OS_CODE 0x00
  80146. # if defined(__TURBOC__) || defined(__BORLANDC__)
  80147. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  80148. /* Allow compilation with ANSI keywords only enabled */
  80149. void _Cdecl farfree( void *block );
  80150. void *_Cdecl farmalloc( unsigned long nbytes );
  80151. # else
  80152. # include <alloc.h>
  80153. # endif
  80154. # else /* MSC or DJGPP */
  80155. # include <malloc.h>
  80156. # endif
  80157. #endif
  80158. #ifdef AMIGA
  80159. # define OS_CODE 0x01
  80160. #endif
  80161. #if defined(VAXC) || defined(VMS)
  80162. # define OS_CODE 0x02
  80163. # define F_OPEN(name, mode) \
  80164. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80165. #endif
  80166. #if defined(ATARI) || defined(atarist)
  80167. # define OS_CODE 0x05
  80168. #endif
  80169. #ifdef OS2
  80170. # define OS_CODE 0x06
  80171. # ifdef M_I86
  80172. #include <malloc.h>
  80173. # endif
  80174. #endif
  80175. #if defined(MACOS) || TARGET_OS_MAC
  80176. # define OS_CODE 0x07
  80177. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80178. # include <unix.h> /* for fdopen */
  80179. # else
  80180. # ifndef fdopen
  80181. # define fdopen(fd,mode) NULL /* No fdopen() */
  80182. # endif
  80183. # endif
  80184. #endif
  80185. #ifdef TOPS20
  80186. # define OS_CODE 0x0a
  80187. #endif
  80188. #ifdef WIN32
  80189. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80190. # define OS_CODE 0x0b
  80191. # endif
  80192. #endif
  80193. #ifdef __50SERIES /* Prime/PRIMOS */
  80194. # define OS_CODE 0x0f
  80195. #endif
  80196. #if defined(_BEOS_) || defined(RISCOS)
  80197. # define fdopen(fd,mode) NULL /* No fdopen() */
  80198. #endif
  80199. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80200. # if defined(_WIN32_WCE)
  80201. # define fdopen(fd,mode) NULL /* No fdopen() */
  80202. # ifndef _PTRDIFF_T_DEFINED
  80203. typedef int ptrdiff_t;
  80204. # define _PTRDIFF_T_DEFINED
  80205. # endif
  80206. # else
  80207. # define fdopen(fd,type) _fdopen(fd,type)
  80208. # endif
  80209. #endif
  80210. /* common defaults */
  80211. #ifndef OS_CODE
  80212. # define OS_CODE 0x03 /* assume Unix */
  80213. #endif
  80214. #ifndef F_OPEN
  80215. # define F_OPEN(name, mode) fopen((name), (mode))
  80216. #endif
  80217. /* functions */
  80218. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80219. # ifndef HAVE_VSNPRINTF
  80220. # define HAVE_VSNPRINTF
  80221. # endif
  80222. #endif
  80223. #if defined(__CYGWIN__)
  80224. # ifndef HAVE_VSNPRINTF
  80225. # define HAVE_VSNPRINTF
  80226. # endif
  80227. #endif
  80228. #ifndef HAVE_VSNPRINTF
  80229. # ifdef MSDOS
  80230. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80231. but for now we just assume it doesn't. */
  80232. # define NO_vsnprintf
  80233. # endif
  80234. # ifdef __TURBOC__
  80235. # define NO_vsnprintf
  80236. # endif
  80237. # ifdef WIN32
  80238. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80239. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80240. # define vsnprintf _vsnprintf
  80241. # endif
  80242. # endif
  80243. # ifdef __SASC
  80244. # define NO_vsnprintf
  80245. # endif
  80246. #endif
  80247. #ifdef VMS
  80248. # define NO_vsnprintf
  80249. #endif
  80250. #if defined(pyr)
  80251. # define NO_MEMCPY
  80252. #endif
  80253. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80254. /* Use our own functions for small and medium model with MSC <= 5.0.
  80255. * You may have to use the same strategy for Borland C (untested).
  80256. * The __SC__ check is for Symantec.
  80257. */
  80258. # define NO_MEMCPY
  80259. #endif
  80260. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80261. # define HAVE_MEMCPY
  80262. #endif
  80263. #ifdef HAVE_MEMCPY
  80264. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80265. # define zmemcpy _fmemcpy
  80266. # define zmemcmp _fmemcmp
  80267. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80268. # else
  80269. # define zmemcpy memcpy
  80270. # define zmemcmp memcmp
  80271. # define zmemzero(dest, len) memset(dest, 0, len)
  80272. # endif
  80273. #else
  80274. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80275. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80276. extern void zmemzero OF((Bytef* dest, uInt len));
  80277. #endif
  80278. /* Diagnostic functions */
  80279. #ifdef DEBUG
  80280. # include <stdio.h>
  80281. extern int z_verbose;
  80282. extern void z_error OF((const char *m));
  80283. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80284. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80285. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80286. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80287. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80288. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80289. #else
  80290. # define Assert(cond,msg)
  80291. # define Trace(x)
  80292. # define Tracev(x)
  80293. # define Tracevv(x)
  80294. # define Tracec(c,x)
  80295. # define Tracecv(c,x)
  80296. #endif
  80297. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80298. void zcfree OF((voidpf opaque, voidpf ptr));
  80299. #define ZALLOC(strm, items, size) \
  80300. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80301. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80302. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80303. #endif /* ZUTIL_H */
  80304. /*** End of inlined file: zutil.h ***/
  80305. /* for STDC and FAR definitions */
  80306. #define local static
  80307. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80308. #ifndef NOBYFOUR
  80309. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80310. # include <limits.h>
  80311. # define BYFOUR
  80312. # if (UINT_MAX == 0xffffffffUL)
  80313. typedef unsigned int u4;
  80314. # else
  80315. # if (ULONG_MAX == 0xffffffffUL)
  80316. typedef unsigned long u4;
  80317. # else
  80318. # if (USHRT_MAX == 0xffffffffUL)
  80319. typedef unsigned short u4;
  80320. # else
  80321. # undef BYFOUR /* can't find a four-byte integer type! */
  80322. # endif
  80323. # endif
  80324. # endif
  80325. # endif /* STDC */
  80326. #endif /* !NOBYFOUR */
  80327. /* Definitions for doing the crc four data bytes at a time. */
  80328. #ifdef BYFOUR
  80329. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80330. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80331. local unsigned long crc32_little OF((unsigned long,
  80332. const unsigned char FAR *, unsigned));
  80333. local unsigned long crc32_big OF((unsigned long,
  80334. const unsigned char FAR *, unsigned));
  80335. # define TBLS 8
  80336. #else
  80337. # define TBLS 1
  80338. #endif /* BYFOUR */
  80339. /* Local functions for crc concatenation */
  80340. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80341. unsigned long vec));
  80342. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80343. #ifdef DYNAMIC_CRC_TABLE
  80344. local volatile int crc_table_empty = 1;
  80345. local unsigned long FAR crc_table[TBLS][256];
  80346. local void make_crc_table OF((void));
  80347. #ifdef MAKECRCH
  80348. local void write_table OF((FILE *, const unsigned long FAR *));
  80349. #endif /* MAKECRCH */
  80350. /*
  80351. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80352. 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.
  80353. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80354. with the lowest powers in the most significant bit. Then adding polynomials
  80355. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80356. one. If we call the above polynomial p, and represent a byte as the
  80357. polynomial q, also with the lowest power in the most significant bit (so the
  80358. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80359. where a mod b means the remainder after dividing a by b.
  80360. This calculation is done using the shift-register method of multiplying and
  80361. taking the remainder. The register is initialized to zero, and for each
  80362. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80363. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80364. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80365. out is a one). We start with the highest power (least significant bit) of
  80366. q and repeat for all eight bits of q.
  80367. The first table is simply the CRC of all possible eight bit values. This is
  80368. all the information needed to generate CRCs on data a byte at a time for all
  80369. combinations of CRC register values and incoming bytes. The remaining tables
  80370. allow for word-at-a-time CRC calculation for both big-endian and little-
  80371. endian machines, where a word is four bytes.
  80372. */
  80373. local void make_crc_table()
  80374. {
  80375. unsigned long c;
  80376. int n, k;
  80377. unsigned long poly; /* polynomial exclusive-or pattern */
  80378. /* terms of polynomial defining this crc (except x^32): */
  80379. static volatile int first = 1; /* flag to limit concurrent making */
  80380. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80381. /* See if another task is already doing this (not thread-safe, but better
  80382. than nothing -- significantly reduces duration of vulnerability in
  80383. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80384. if (first) {
  80385. first = 0;
  80386. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80387. poly = 0UL;
  80388. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80389. poly |= 1UL << (31 - p[n]);
  80390. /* generate a crc for every 8-bit value */
  80391. for (n = 0; n < 256; n++) {
  80392. c = (unsigned long)n;
  80393. for (k = 0; k < 8; k++)
  80394. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80395. crc_table[0][n] = c;
  80396. }
  80397. #ifdef BYFOUR
  80398. /* generate crc for each value followed by one, two, and three zeros,
  80399. and then the byte reversal of those as well as the first table */
  80400. for (n = 0; n < 256; n++) {
  80401. c = crc_table[0][n];
  80402. crc_table[4][n] = REV(c);
  80403. for (k = 1; k < 4; k++) {
  80404. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80405. crc_table[k][n] = c;
  80406. crc_table[k + 4][n] = REV(c);
  80407. }
  80408. }
  80409. #endif /* BYFOUR */
  80410. crc_table_empty = 0;
  80411. }
  80412. else { /* not first */
  80413. /* wait for the other guy to finish (not efficient, but rare) */
  80414. while (crc_table_empty)
  80415. ;
  80416. }
  80417. #ifdef MAKECRCH
  80418. /* write out CRC tables to crc32.h */
  80419. {
  80420. FILE *out;
  80421. out = fopen("crc32.h", "w");
  80422. if (out == NULL) return;
  80423. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80424. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80425. fprintf(out, "local const unsigned long FAR ");
  80426. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80427. write_table(out, crc_table[0]);
  80428. # ifdef BYFOUR
  80429. fprintf(out, "#ifdef BYFOUR\n");
  80430. for (k = 1; k < 8; k++) {
  80431. fprintf(out, " },\n {\n");
  80432. write_table(out, crc_table[k]);
  80433. }
  80434. fprintf(out, "#endif\n");
  80435. # endif /* BYFOUR */
  80436. fprintf(out, " }\n};\n");
  80437. fclose(out);
  80438. }
  80439. #endif /* MAKECRCH */
  80440. }
  80441. #ifdef MAKECRCH
  80442. local void write_table(out, table)
  80443. FILE *out;
  80444. const unsigned long FAR *table;
  80445. {
  80446. int n;
  80447. for (n = 0; n < 256; n++)
  80448. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80449. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80450. }
  80451. #endif /* MAKECRCH */
  80452. #else /* !DYNAMIC_CRC_TABLE */
  80453. /* ========================================================================
  80454. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80455. */
  80456. /*** Start of inlined file: crc32.h ***/
  80457. local const unsigned long FAR crc_table[TBLS][256] =
  80458. {
  80459. {
  80460. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80461. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80462. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80463. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80464. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80465. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80466. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80467. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80468. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80469. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80470. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80471. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80472. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80473. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80474. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80475. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80476. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80477. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80478. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80479. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80480. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80481. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80482. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80483. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80484. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80485. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80486. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80487. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80488. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80489. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80490. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80491. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80492. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80493. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80494. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80495. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80496. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80497. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80498. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80499. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80500. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80501. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80502. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80503. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80504. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80505. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80506. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80507. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80508. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80509. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80510. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80511. 0x2d02ef8dUL
  80512. #ifdef BYFOUR
  80513. },
  80514. {
  80515. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80516. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80517. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80518. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80519. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80520. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80521. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80522. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80523. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80524. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80525. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80526. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80527. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80528. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80529. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80530. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80531. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80532. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80533. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80534. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80535. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80536. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80537. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80538. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80539. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80540. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80541. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80542. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80543. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80544. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80545. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80546. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80547. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80548. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80549. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80550. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80551. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80552. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80553. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80554. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80555. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80556. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80557. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80558. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80559. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80560. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80561. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80562. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80563. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80564. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80565. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80566. 0x9324fd72UL
  80567. },
  80568. {
  80569. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80570. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80571. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80572. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80573. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80574. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80575. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80576. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80577. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80578. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80579. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80580. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80581. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80582. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80583. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80584. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80585. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80586. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80587. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80588. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80589. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80590. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80591. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80592. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80593. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80594. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80595. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80596. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80597. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80598. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80599. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80600. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80601. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80602. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80603. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80604. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80605. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80606. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80607. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80608. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80609. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80610. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80611. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80612. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80613. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80614. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80615. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80616. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80617. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80618. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80619. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80620. 0xbe9834edUL
  80621. },
  80622. {
  80623. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80624. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80625. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80626. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80627. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80628. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80629. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80630. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80631. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80632. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80633. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80634. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80635. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80636. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80637. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80638. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80639. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80640. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80641. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80642. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80643. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80644. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80645. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80646. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80647. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80648. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80649. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80650. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80651. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80652. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80653. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80654. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80655. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80656. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80657. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80658. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80659. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80660. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80661. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80662. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80663. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80664. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80665. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80666. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80667. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80668. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80669. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80670. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80671. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80672. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80673. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80674. 0xde0506f1UL
  80675. },
  80676. {
  80677. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80678. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80679. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80680. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80681. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80682. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80683. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80684. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80685. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80686. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80687. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80688. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80689. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80690. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80691. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80692. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80693. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80694. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80695. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80696. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80697. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80698. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80699. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80700. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80701. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80702. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80703. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80704. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80705. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80706. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80707. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80708. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80709. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80710. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80711. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80712. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80713. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80714. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80715. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80716. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80717. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80718. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80719. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80720. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80721. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80722. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80723. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80724. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80725. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80726. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80727. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80728. 0x8def022dUL
  80729. },
  80730. {
  80731. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80732. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80733. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80734. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80735. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80736. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80737. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80738. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80739. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80740. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80741. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80742. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80743. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80744. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80745. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80746. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80747. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80748. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80749. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80750. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80751. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80752. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80753. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80754. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80755. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80756. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80757. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80758. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80759. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80760. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80761. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80762. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80763. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80764. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80765. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80766. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80767. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80768. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80769. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80770. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80771. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80772. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80773. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80774. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80775. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80776. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80777. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80778. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80779. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80780. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80781. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80782. 0x72fd2493UL
  80783. },
  80784. {
  80785. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80786. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80787. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80788. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80789. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80790. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80791. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80792. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80793. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80794. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80795. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80796. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80797. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80798. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80799. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80800. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80801. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80802. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80803. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80804. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80805. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80806. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80807. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80808. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80809. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80810. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80811. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80812. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80813. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80814. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80815. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80816. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80817. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80818. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80819. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80820. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80821. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80822. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80823. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80824. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80825. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80826. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80827. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80828. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80829. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80830. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80831. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80832. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80833. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80834. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80835. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80836. 0xed3498beUL
  80837. },
  80838. {
  80839. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80840. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80841. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80842. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80843. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80844. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80845. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80846. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80847. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80848. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80849. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80850. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80851. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80852. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80853. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80854. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80855. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80856. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80857. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80858. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80859. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80860. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80861. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80862. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80863. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80864. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80865. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80866. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80867. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80868. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80869. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80870. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80871. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80872. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80873. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80874. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80875. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80876. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80877. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80878. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80879. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80880. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80881. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80882. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80883. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80884. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80885. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80886. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80887. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80888. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80889. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80890. 0xf10605deUL
  80891. #endif
  80892. }
  80893. };
  80894. /*** End of inlined file: crc32.h ***/
  80895. #endif /* DYNAMIC_CRC_TABLE */
  80896. /* =========================================================================
  80897. * This function can be used by asm versions of crc32()
  80898. */
  80899. const unsigned long FAR * ZEXPORT get_crc_table()
  80900. {
  80901. #ifdef DYNAMIC_CRC_TABLE
  80902. if (crc_table_empty)
  80903. make_crc_table();
  80904. #endif /* DYNAMIC_CRC_TABLE */
  80905. return (const unsigned long FAR *)crc_table;
  80906. }
  80907. /* ========================================================================= */
  80908. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80909. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80910. /* ========================================================================= */
  80911. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80912. {
  80913. if (buf == Z_NULL) return 0UL;
  80914. #ifdef DYNAMIC_CRC_TABLE
  80915. if (crc_table_empty)
  80916. make_crc_table();
  80917. #endif /* DYNAMIC_CRC_TABLE */
  80918. #ifdef BYFOUR
  80919. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80920. u4 endian;
  80921. endian = 1;
  80922. if (*((unsigned char *)(&endian)))
  80923. return crc32_little(crc, buf, len);
  80924. else
  80925. return crc32_big(crc, buf, len);
  80926. }
  80927. #endif /* BYFOUR */
  80928. crc = crc ^ 0xffffffffUL;
  80929. while (len >= 8) {
  80930. DO8;
  80931. len -= 8;
  80932. }
  80933. if (len) do {
  80934. DO1;
  80935. } while (--len);
  80936. return crc ^ 0xffffffffUL;
  80937. }
  80938. #ifdef BYFOUR
  80939. /* ========================================================================= */
  80940. #define DOLIT4 c ^= *buf4++; \
  80941. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80942. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80943. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80944. /* ========================================================================= */
  80945. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80946. {
  80947. register u4 c;
  80948. register const u4 FAR *buf4;
  80949. c = (u4)crc;
  80950. c = ~c;
  80951. while (len && ((ptrdiff_t)buf & 3)) {
  80952. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80953. len--;
  80954. }
  80955. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80956. while (len >= 32) {
  80957. DOLIT32;
  80958. len -= 32;
  80959. }
  80960. while (len >= 4) {
  80961. DOLIT4;
  80962. len -= 4;
  80963. }
  80964. buf = (const unsigned char FAR *)buf4;
  80965. if (len) do {
  80966. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80967. } while (--len);
  80968. c = ~c;
  80969. return (unsigned long)c;
  80970. }
  80971. /* ========================================================================= */
  80972. #define DOBIG4 c ^= *++buf4; \
  80973. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80974. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80975. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80976. /* ========================================================================= */
  80977. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80978. {
  80979. register u4 c;
  80980. register const u4 FAR *buf4;
  80981. c = REV((u4)crc);
  80982. c = ~c;
  80983. while (len && ((ptrdiff_t)buf & 3)) {
  80984. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80985. len--;
  80986. }
  80987. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80988. buf4--;
  80989. while (len >= 32) {
  80990. DOBIG32;
  80991. len -= 32;
  80992. }
  80993. while (len >= 4) {
  80994. DOBIG4;
  80995. len -= 4;
  80996. }
  80997. buf4++;
  80998. buf = (const unsigned char FAR *)buf4;
  80999. if (len) do {
  81000. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  81001. } while (--len);
  81002. c = ~c;
  81003. return (unsigned long)(REV(c));
  81004. }
  81005. #endif /* BYFOUR */
  81006. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  81007. /* ========================================================================= */
  81008. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  81009. {
  81010. unsigned long sum;
  81011. sum = 0;
  81012. while (vec) {
  81013. if (vec & 1)
  81014. sum ^= *mat;
  81015. vec >>= 1;
  81016. mat++;
  81017. }
  81018. return sum;
  81019. }
  81020. /* ========================================================================= */
  81021. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  81022. {
  81023. int n;
  81024. for (n = 0; n < GF2_DIM; n++)
  81025. square[n] = gf2_matrix_times(mat, mat[n]);
  81026. }
  81027. /* ========================================================================= */
  81028. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  81029. {
  81030. int n;
  81031. unsigned long row;
  81032. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  81033. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  81034. /* degenerate case */
  81035. if (len2 == 0)
  81036. return crc1;
  81037. /* put operator for one zero bit in odd */
  81038. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  81039. row = 1;
  81040. for (n = 1; n < GF2_DIM; n++) {
  81041. odd[n] = row;
  81042. row <<= 1;
  81043. }
  81044. /* put operator for two zero bits in even */
  81045. gf2_matrix_square(even, odd);
  81046. /* put operator for four zero bits in odd */
  81047. gf2_matrix_square(odd, even);
  81048. /* apply len2 zeros to crc1 (first square will put the operator for one
  81049. zero byte, eight zero bits, in even) */
  81050. do {
  81051. /* apply zeros operator for this bit of len2 */
  81052. gf2_matrix_square(even, odd);
  81053. if (len2 & 1)
  81054. crc1 = gf2_matrix_times(even, crc1);
  81055. len2 >>= 1;
  81056. /* if no more bits set, then done */
  81057. if (len2 == 0)
  81058. break;
  81059. /* another iteration of the loop with odd and even swapped */
  81060. gf2_matrix_square(odd, even);
  81061. if (len2 & 1)
  81062. crc1 = gf2_matrix_times(odd, crc1);
  81063. len2 >>= 1;
  81064. /* if no more bits set, then done */
  81065. } while (len2 != 0);
  81066. /* return combined crc */
  81067. crc1 ^= crc2;
  81068. return crc1;
  81069. }
  81070. /*** End of inlined file: crc32.c ***/
  81071. /*** Start of inlined file: deflate.c ***/
  81072. /*
  81073. * ALGORITHM
  81074. *
  81075. * The "deflation" process depends on being able to identify portions
  81076. * of the input text which are identical to earlier input (within a
  81077. * sliding window trailing behind the input currently being processed).
  81078. *
  81079. * The most straightforward technique turns out to be the fastest for
  81080. * most input files: try all possible matches and select the longest.
  81081. * The key feature of this algorithm is that insertions into the string
  81082. * dictionary are very simple and thus fast, and deletions are avoided
  81083. * completely. Insertions are performed at each input character, whereas
  81084. * string matches are performed only when the previous match ends. So it
  81085. * is preferable to spend more time in matches to allow very fast string
  81086. * insertions and avoid deletions. The matching algorithm for small
  81087. * strings is inspired from that of Rabin & Karp. A brute force approach
  81088. * is used to find longer strings when a small match has been found.
  81089. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  81090. * (by Leonid Broukhis).
  81091. * A previous version of this file used a more sophisticated algorithm
  81092. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  81093. * time, but has a larger average cost, uses more memory and is patented.
  81094. * However the F&G algorithm may be faster for some highly redundant
  81095. * files if the parameter max_chain_length (described below) is too large.
  81096. *
  81097. * ACKNOWLEDGEMENTS
  81098. *
  81099. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  81100. * I found it in 'freeze' written by Leonid Broukhis.
  81101. * Thanks to many people for bug reports and testing.
  81102. *
  81103. * REFERENCES
  81104. *
  81105. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  81106. * Available in http://www.ietf.org/rfc/rfc1951.txt
  81107. *
  81108. * A description of the Rabin and Karp algorithm is given in the book
  81109. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  81110. *
  81111. * Fiala,E.R., and Greene,D.H.
  81112. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  81113. *
  81114. */
  81115. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81116. /*** Start of inlined file: deflate.h ***/
  81117. /* WARNING: this file should *not* be used by applications. It is
  81118. part of the implementation of the compression library and is
  81119. subject to change. Applications should only use zlib.h.
  81120. */
  81121. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81122. #ifndef DEFLATE_H
  81123. #define DEFLATE_H
  81124. /* define NO_GZIP when compiling if you want to disable gzip header and
  81125. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  81126. the crc code when it is not needed. For shared libraries, gzip encoding
  81127. should be left enabled. */
  81128. #ifndef NO_GZIP
  81129. # define GZIP
  81130. #endif
  81131. #define NO_DUMMY_DECL
  81132. /* ===========================================================================
  81133. * Internal compression state.
  81134. */
  81135. #define LENGTH_CODES 29
  81136. /* number of length codes, not counting the special END_BLOCK code */
  81137. #define LITERALS 256
  81138. /* number of literal bytes 0..255 */
  81139. #define L_CODES (LITERALS+1+LENGTH_CODES)
  81140. /* number of Literal or Length codes, including the END_BLOCK code */
  81141. #define D_CODES 30
  81142. /* number of distance codes */
  81143. #define BL_CODES 19
  81144. /* number of codes used to transfer the bit lengths */
  81145. #define HEAP_SIZE (2*L_CODES+1)
  81146. /* maximum heap size */
  81147. #define MAX_BITS 15
  81148. /* All codes must not exceed MAX_BITS bits */
  81149. #define INIT_STATE 42
  81150. #define EXTRA_STATE 69
  81151. #define NAME_STATE 73
  81152. #define COMMENT_STATE 91
  81153. #define HCRC_STATE 103
  81154. #define BUSY_STATE 113
  81155. #define FINISH_STATE 666
  81156. /* Stream status */
  81157. /* Data structure describing a single value and its code string. */
  81158. typedef struct ct_data_s {
  81159. union {
  81160. ush freq; /* frequency count */
  81161. ush code; /* bit string */
  81162. } fc;
  81163. union {
  81164. ush dad; /* father node in Huffman tree */
  81165. ush len; /* length of bit string */
  81166. } dl;
  81167. } FAR ct_data;
  81168. #define Freq fc.freq
  81169. #define Code fc.code
  81170. #define Dad dl.dad
  81171. #define Len dl.len
  81172. typedef struct static_tree_desc_s static_tree_desc;
  81173. typedef struct tree_desc_s {
  81174. ct_data *dyn_tree; /* the dynamic tree */
  81175. int max_code; /* largest code with non zero frequency */
  81176. static_tree_desc *stat_desc; /* the corresponding static tree */
  81177. } FAR tree_desc;
  81178. typedef ush Pos;
  81179. typedef Pos FAR Posf;
  81180. typedef unsigned IPos;
  81181. /* A Pos is an index in the character window. We use short instead of int to
  81182. * save space in the various tables. IPos is used only for parameter passing.
  81183. */
  81184. typedef struct internal_state {
  81185. z_streamp strm; /* pointer back to this zlib stream */
  81186. int status; /* as the name implies */
  81187. Bytef *pending_buf; /* output still pending */
  81188. ulg pending_buf_size; /* size of pending_buf */
  81189. Bytef *pending_out; /* next pending byte to output to the stream */
  81190. uInt pending; /* nb of bytes in the pending buffer */
  81191. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81192. gz_headerp gzhead; /* gzip header information to write */
  81193. uInt gzindex; /* where in extra, name, or comment */
  81194. Byte method; /* STORED (for zip only) or DEFLATED */
  81195. int last_flush; /* value of flush param for previous deflate call */
  81196. /* used by deflate.c: */
  81197. uInt w_size; /* LZ77 window size (32K by default) */
  81198. uInt w_bits; /* log2(w_size) (8..16) */
  81199. uInt w_mask; /* w_size - 1 */
  81200. Bytef *window;
  81201. /* Sliding window. Input bytes are read into the second half of the window,
  81202. * and move to the first half later to keep a dictionary of at least wSize
  81203. * bytes. With this organization, matches are limited to a distance of
  81204. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81205. * performed with a length multiple of the block size. Also, it limits
  81206. * the window size to 64K, which is quite useful on MSDOS.
  81207. * To do: use the user input buffer as sliding window.
  81208. */
  81209. ulg window_size;
  81210. /* Actual size of window: 2*wSize, except when the user input buffer
  81211. * is directly used as sliding window.
  81212. */
  81213. Posf *prev;
  81214. /* Link to older string with same hash index. To limit the size of this
  81215. * array to 64K, this link is maintained only for the last 32K strings.
  81216. * An index in this array is thus a window index modulo 32K.
  81217. */
  81218. Posf *head; /* Heads of the hash chains or NIL. */
  81219. uInt ins_h; /* hash index of string to be inserted */
  81220. uInt hash_size; /* number of elements in hash table */
  81221. uInt hash_bits; /* log2(hash_size) */
  81222. uInt hash_mask; /* hash_size-1 */
  81223. uInt hash_shift;
  81224. /* Number of bits by which ins_h must be shifted at each input
  81225. * step. It must be such that after MIN_MATCH steps, the oldest
  81226. * byte no longer takes part in the hash key, that is:
  81227. * hash_shift * MIN_MATCH >= hash_bits
  81228. */
  81229. long block_start;
  81230. /* Window position at the beginning of the current output block. Gets
  81231. * negative when the window is moved backwards.
  81232. */
  81233. uInt match_length; /* length of best match */
  81234. IPos prev_match; /* previous match */
  81235. int match_available; /* set if previous match exists */
  81236. uInt strstart; /* start of string to insert */
  81237. uInt match_start; /* start of matching string */
  81238. uInt lookahead; /* number of valid bytes ahead in window */
  81239. uInt prev_length;
  81240. /* Length of the best match at previous step. Matches not greater than this
  81241. * are discarded. This is used in the lazy match evaluation.
  81242. */
  81243. uInt max_chain_length;
  81244. /* To speed up deflation, hash chains are never searched beyond this
  81245. * length. A higher limit improves compression ratio but degrades the
  81246. * speed.
  81247. */
  81248. uInt max_lazy_match;
  81249. /* Attempt to find a better match only when the current match is strictly
  81250. * smaller than this value. This mechanism is used only for compression
  81251. * levels >= 4.
  81252. */
  81253. # define max_insert_length max_lazy_match
  81254. /* Insert new strings in the hash table only if the match length is not
  81255. * greater than this length. This saves time but degrades compression.
  81256. * max_insert_length is used only for compression levels <= 3.
  81257. */
  81258. int level; /* compression level (1..9) */
  81259. int strategy; /* favor or force Huffman coding*/
  81260. uInt good_match;
  81261. /* Use a faster search when the previous match is longer than this */
  81262. int nice_match; /* Stop searching when current match exceeds this */
  81263. /* used by trees.c: */
  81264. /* Didn't use ct_data typedef below to supress compiler warning */
  81265. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81266. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81267. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81268. struct tree_desc_s l_desc; /* desc. for literal tree */
  81269. struct tree_desc_s d_desc; /* desc. for distance tree */
  81270. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81271. ush bl_count[MAX_BITS+1];
  81272. /* number of codes at each bit length for an optimal tree */
  81273. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81274. int heap_len; /* number of elements in the heap */
  81275. int heap_max; /* element of largest frequency */
  81276. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81277. * The same heap array is used to build all trees.
  81278. */
  81279. uch depth[2*L_CODES+1];
  81280. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81281. */
  81282. uchf *l_buf; /* buffer for literals or lengths */
  81283. uInt lit_bufsize;
  81284. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81285. * limiting lit_bufsize to 64K:
  81286. * - frequencies can be kept in 16 bit counters
  81287. * - if compression is not successful for the first block, all input
  81288. * data is still in the window so we can still emit a stored block even
  81289. * when input comes from standard input. (This can also be done for
  81290. * all blocks if lit_bufsize is not greater than 32K.)
  81291. * - if compression is not successful for a file smaller than 64K, we can
  81292. * even emit a stored file instead of a stored block (saving 5 bytes).
  81293. * This is applicable only for zip (not gzip or zlib).
  81294. * - creating new Huffman trees less frequently may not provide fast
  81295. * adaptation to changes in the input data statistics. (Take for
  81296. * example a binary file with poorly compressible code followed by
  81297. * a highly compressible string table.) Smaller buffer sizes give
  81298. * fast adaptation but have of course the overhead of transmitting
  81299. * trees more frequently.
  81300. * - I can't count above 4
  81301. */
  81302. uInt last_lit; /* running index in l_buf */
  81303. ushf *d_buf;
  81304. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81305. * the same number of elements. To use different lengths, an extra flag
  81306. * array would be necessary.
  81307. */
  81308. ulg opt_len; /* bit length of current block with optimal trees */
  81309. ulg static_len; /* bit length of current block with static trees */
  81310. uInt matches; /* number of string matches in current block */
  81311. int last_eob_len; /* bit length of EOB code for last block */
  81312. #ifdef DEBUG
  81313. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81314. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81315. #endif
  81316. ush bi_buf;
  81317. /* Output buffer. bits are inserted starting at the bottom (least
  81318. * significant bits).
  81319. */
  81320. int bi_valid;
  81321. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81322. * are always zero.
  81323. */
  81324. } FAR deflate_state;
  81325. /* Output a byte on the stream.
  81326. * IN assertion: there is enough room in pending_buf.
  81327. */
  81328. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81329. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81330. /* Minimum amount of lookahead, except at the end of the input file.
  81331. * See deflate.c for comments about the MIN_MATCH+1.
  81332. */
  81333. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81334. /* In order to simplify the code, particularly on 16 bit machines, match
  81335. * distances are limited to MAX_DIST instead of WSIZE.
  81336. */
  81337. /* in trees.c */
  81338. void _tr_init OF((deflate_state *s));
  81339. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81340. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81341. int eof));
  81342. void _tr_align OF((deflate_state *s));
  81343. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81344. int eof));
  81345. #define d_code(dist) \
  81346. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81347. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81348. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81349. * used.
  81350. */
  81351. #ifndef DEBUG
  81352. /* Inline versions of _tr_tally for speed: */
  81353. #if defined(GEN_TREES_H) || !defined(STDC)
  81354. extern uch _length_code[];
  81355. extern uch _dist_code[];
  81356. #else
  81357. extern const uch _length_code[];
  81358. extern const uch _dist_code[];
  81359. #endif
  81360. # define _tr_tally_lit(s, c, flush) \
  81361. { uch cc = (c); \
  81362. s->d_buf[s->last_lit] = 0; \
  81363. s->l_buf[s->last_lit++] = cc; \
  81364. s->dyn_ltree[cc].Freq++; \
  81365. flush = (s->last_lit == s->lit_bufsize-1); \
  81366. }
  81367. # define _tr_tally_dist(s, distance, length, flush) \
  81368. { uch len = (length); \
  81369. ush dist = (distance); \
  81370. s->d_buf[s->last_lit] = dist; \
  81371. s->l_buf[s->last_lit++] = len; \
  81372. dist--; \
  81373. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81374. s->dyn_dtree[d_code(dist)].Freq++; \
  81375. flush = (s->last_lit == s->lit_bufsize-1); \
  81376. }
  81377. #else
  81378. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81379. # define _tr_tally_dist(s, distance, length, flush) \
  81380. flush = _tr_tally(s, distance, length)
  81381. #endif
  81382. #endif /* DEFLATE_H */
  81383. /*** End of inlined file: deflate.h ***/
  81384. const char deflate_copyright[] =
  81385. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81386. /*
  81387. If you use the zlib library in a product, an acknowledgment is welcome
  81388. in the documentation of your product. If for some reason you cannot
  81389. include such an acknowledgment, I would appreciate that you keep this
  81390. copyright string in the executable of your product.
  81391. */
  81392. /* ===========================================================================
  81393. * Function prototypes.
  81394. */
  81395. typedef enum {
  81396. need_more, /* block not completed, need more input or more output */
  81397. block_done, /* block flush performed */
  81398. finish_started, /* finish started, need only more output at next deflate */
  81399. finish_done /* finish done, accept no more input or output */
  81400. } block_state;
  81401. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81402. /* Compression function. Returns the block state after the call. */
  81403. local void fill_window OF((deflate_state *s));
  81404. local block_state deflate_stored OF((deflate_state *s, int flush));
  81405. local block_state deflate_fast OF((deflate_state *s, int flush));
  81406. #ifndef FASTEST
  81407. local block_state deflate_slow OF((deflate_state *s, int flush));
  81408. #endif
  81409. local void lm_init OF((deflate_state *s));
  81410. local void putShortMSB OF((deflate_state *s, uInt b));
  81411. local void flush_pending OF((z_streamp strm));
  81412. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81413. #ifndef FASTEST
  81414. #ifdef ASMV
  81415. void match_init OF((void)); /* asm code initialization */
  81416. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81417. #else
  81418. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81419. #endif
  81420. #endif
  81421. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81422. #ifdef DEBUG
  81423. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81424. int length));
  81425. #endif
  81426. /* ===========================================================================
  81427. * Local data
  81428. */
  81429. #define NIL 0
  81430. /* Tail of hash chains */
  81431. #ifndef TOO_FAR
  81432. # define TOO_FAR 4096
  81433. #endif
  81434. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81435. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81436. /* Minimum amount of lookahead, except at the end of the input file.
  81437. * See deflate.c for comments about the MIN_MATCH+1.
  81438. */
  81439. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81440. * the desired pack level (0..9). The values given below have been tuned to
  81441. * exclude worst case performance for pathological files. Better values may be
  81442. * found for specific files.
  81443. */
  81444. typedef struct config_s {
  81445. ush good_length; /* reduce lazy search above this match length */
  81446. ush max_lazy; /* do not perform lazy search above this match length */
  81447. ush nice_length; /* quit search above this match length */
  81448. ush max_chain;
  81449. compress_func func;
  81450. } config;
  81451. #ifdef FASTEST
  81452. local const config configuration_table[2] = {
  81453. /* good lazy nice chain */
  81454. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81455. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81456. #else
  81457. local const config configuration_table[10] = {
  81458. /* good lazy nice chain */
  81459. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81460. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81461. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81462. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81463. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81464. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81465. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81466. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81467. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81468. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81469. #endif
  81470. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81471. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81472. * meaning.
  81473. */
  81474. #define EQUAL 0
  81475. /* result of memcmp for equal strings */
  81476. #ifndef NO_DUMMY_DECL
  81477. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81478. #endif
  81479. /* ===========================================================================
  81480. * Update a hash value with the given input byte
  81481. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81482. * input characters, so that a running hash key can be computed from the
  81483. * previous key instead of complete recalculation each time.
  81484. */
  81485. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81486. /* ===========================================================================
  81487. * Insert string str in the dictionary and set match_head to the previous head
  81488. * of the hash chain (the most recent string with same hash key). Return
  81489. * the previous length of the hash chain.
  81490. * If this file is compiled with -DFASTEST, the compression level is forced
  81491. * to 1, and no hash chains are maintained.
  81492. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81493. * input characters and the first MIN_MATCH bytes of str are valid
  81494. * (except for the last MIN_MATCH-1 bytes of the input file).
  81495. */
  81496. #ifdef FASTEST
  81497. #define INSERT_STRING(s, str, match_head) \
  81498. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81499. match_head = s->head[s->ins_h], \
  81500. s->head[s->ins_h] = (Pos)(str))
  81501. #else
  81502. #define INSERT_STRING(s, str, match_head) \
  81503. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81504. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81505. s->head[s->ins_h] = (Pos)(str))
  81506. #endif
  81507. /* ===========================================================================
  81508. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81509. * prev[] will be initialized on the fly.
  81510. */
  81511. #define CLEAR_HASH(s) \
  81512. s->head[s->hash_size-1] = NIL; \
  81513. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81514. /* ========================================================================= */
  81515. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81516. {
  81517. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81518. Z_DEFAULT_STRATEGY, version, stream_size);
  81519. /* To do: ignore strm->next_in if we use it as window */
  81520. }
  81521. /* ========================================================================= */
  81522. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81523. {
  81524. deflate_state *s;
  81525. int wrap = 1;
  81526. static const char my_version[] = ZLIB_VERSION;
  81527. ushf *overlay;
  81528. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81529. * output size for (length,distance) codes is <= 24 bits.
  81530. */
  81531. if (version == Z_NULL || version[0] != my_version[0] ||
  81532. stream_size != sizeof(z_stream)) {
  81533. return Z_VERSION_ERROR;
  81534. }
  81535. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81536. strm->msg = Z_NULL;
  81537. if (strm->zalloc == (alloc_func)0) {
  81538. strm->zalloc = zcalloc;
  81539. strm->opaque = (voidpf)0;
  81540. }
  81541. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81542. #ifdef FASTEST
  81543. if (level != 0) level = 1;
  81544. #else
  81545. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81546. #endif
  81547. if (windowBits < 0) { /* suppress zlib wrapper */
  81548. wrap = 0;
  81549. windowBits = -windowBits;
  81550. }
  81551. #ifdef GZIP
  81552. else if (windowBits > 15) {
  81553. wrap = 2; /* write gzip wrapper instead */
  81554. windowBits -= 16;
  81555. }
  81556. #endif
  81557. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81558. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81559. strategy < 0 || strategy > Z_FIXED) {
  81560. return Z_STREAM_ERROR;
  81561. }
  81562. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81563. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81564. if (s == Z_NULL) return Z_MEM_ERROR;
  81565. strm->state = (struct internal_state FAR *)s;
  81566. s->strm = strm;
  81567. s->wrap = wrap;
  81568. s->gzhead = Z_NULL;
  81569. s->w_bits = windowBits;
  81570. s->w_size = 1 << s->w_bits;
  81571. s->w_mask = s->w_size - 1;
  81572. s->hash_bits = memLevel + 7;
  81573. s->hash_size = 1 << s->hash_bits;
  81574. s->hash_mask = s->hash_size - 1;
  81575. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81576. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81577. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81578. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81579. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81580. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81581. s->pending_buf = (uchf *) overlay;
  81582. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81583. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81584. s->pending_buf == Z_NULL) {
  81585. s->status = FINISH_STATE;
  81586. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81587. deflateEnd (strm);
  81588. return Z_MEM_ERROR;
  81589. }
  81590. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81591. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81592. s->level = level;
  81593. s->strategy = strategy;
  81594. s->method = (Byte)method;
  81595. return deflateReset(strm);
  81596. }
  81597. /* ========================================================================= */
  81598. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81599. {
  81600. deflate_state *s;
  81601. uInt length = dictLength;
  81602. uInt n;
  81603. IPos hash_head = 0;
  81604. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81605. strm->state->wrap == 2 ||
  81606. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81607. return Z_STREAM_ERROR;
  81608. s = strm->state;
  81609. if (s->wrap)
  81610. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81611. if (length < MIN_MATCH) return Z_OK;
  81612. if (length > MAX_DIST(s)) {
  81613. length = MAX_DIST(s);
  81614. dictionary += dictLength - length; /* use the tail of the dictionary */
  81615. }
  81616. zmemcpy(s->window, dictionary, length);
  81617. s->strstart = length;
  81618. s->block_start = (long)length;
  81619. /* Insert all strings in the hash table (except for the last two bytes).
  81620. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81621. * call of fill_window.
  81622. */
  81623. s->ins_h = s->window[0];
  81624. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81625. for (n = 0; n <= length - MIN_MATCH; n++) {
  81626. INSERT_STRING(s, n, hash_head);
  81627. }
  81628. if (hash_head) hash_head = 0; /* to make compiler happy */
  81629. return Z_OK;
  81630. }
  81631. /* ========================================================================= */
  81632. int ZEXPORT deflateReset (z_streamp strm)
  81633. {
  81634. deflate_state *s;
  81635. if (strm == Z_NULL || strm->state == Z_NULL ||
  81636. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81637. return Z_STREAM_ERROR;
  81638. }
  81639. strm->total_in = strm->total_out = 0;
  81640. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81641. strm->data_type = Z_UNKNOWN;
  81642. s = (deflate_state *)strm->state;
  81643. s->pending = 0;
  81644. s->pending_out = s->pending_buf;
  81645. if (s->wrap < 0) {
  81646. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81647. }
  81648. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81649. strm->adler =
  81650. #ifdef GZIP
  81651. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81652. #endif
  81653. adler32(0L, Z_NULL, 0);
  81654. s->last_flush = Z_NO_FLUSH;
  81655. _tr_init(s);
  81656. lm_init(s);
  81657. return Z_OK;
  81658. }
  81659. /* ========================================================================= */
  81660. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81661. {
  81662. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81663. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81664. strm->state->gzhead = head;
  81665. return Z_OK;
  81666. }
  81667. /* ========================================================================= */
  81668. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81669. {
  81670. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81671. strm->state->bi_valid = bits;
  81672. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81673. return Z_OK;
  81674. }
  81675. /* ========================================================================= */
  81676. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81677. {
  81678. deflate_state *s;
  81679. compress_func func;
  81680. int err = Z_OK;
  81681. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81682. s = strm->state;
  81683. #ifdef FASTEST
  81684. if (level != 0) level = 1;
  81685. #else
  81686. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81687. #endif
  81688. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81689. return Z_STREAM_ERROR;
  81690. }
  81691. func = configuration_table[s->level].func;
  81692. if (func != configuration_table[level].func && strm->total_in != 0) {
  81693. /* Flush the last buffer: */
  81694. err = deflate(strm, Z_PARTIAL_FLUSH);
  81695. }
  81696. if (s->level != level) {
  81697. s->level = level;
  81698. s->max_lazy_match = configuration_table[level].max_lazy;
  81699. s->good_match = configuration_table[level].good_length;
  81700. s->nice_match = configuration_table[level].nice_length;
  81701. s->max_chain_length = configuration_table[level].max_chain;
  81702. }
  81703. s->strategy = strategy;
  81704. return err;
  81705. }
  81706. /* ========================================================================= */
  81707. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81708. {
  81709. deflate_state *s;
  81710. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81711. s = strm->state;
  81712. s->good_match = good_length;
  81713. s->max_lazy_match = max_lazy;
  81714. s->nice_match = nice_length;
  81715. s->max_chain_length = max_chain;
  81716. return Z_OK;
  81717. }
  81718. /* =========================================================================
  81719. * For the default windowBits of 15 and memLevel of 8, this function returns
  81720. * a close to exact, as well as small, upper bound on the compressed size.
  81721. * They are coded as constants here for a reason--if the #define's are
  81722. * changed, then this function needs to be changed as well. The return
  81723. * value for 15 and 8 only works for those exact settings.
  81724. *
  81725. * For any setting other than those defaults for windowBits and memLevel,
  81726. * the value returned is a conservative worst case for the maximum expansion
  81727. * resulting from using fixed blocks instead of stored blocks, which deflate
  81728. * can emit on compressed data for some combinations of the parameters.
  81729. *
  81730. * This function could be more sophisticated to provide closer upper bounds
  81731. * for every combination of windowBits and memLevel, as well as wrap.
  81732. * But even the conservative upper bound of about 14% expansion does not
  81733. * seem onerous for output buffer allocation.
  81734. */
  81735. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81736. {
  81737. deflate_state *s;
  81738. uLong destLen;
  81739. /* conservative upper bound */
  81740. destLen = sourceLen +
  81741. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81742. /* if can't get parameters, return conservative bound */
  81743. if (strm == Z_NULL || strm->state == Z_NULL)
  81744. return destLen;
  81745. /* if not default parameters, return conservative bound */
  81746. s = strm->state;
  81747. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81748. return destLen;
  81749. /* default settings: return tight bound for that case */
  81750. return compressBound(sourceLen);
  81751. }
  81752. /* =========================================================================
  81753. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81754. * IN assertion: the stream state is correct and there is enough room in
  81755. * pending_buf.
  81756. */
  81757. local void putShortMSB (deflate_state *s, uInt b)
  81758. {
  81759. put_byte(s, (Byte)(b >> 8));
  81760. put_byte(s, (Byte)(b & 0xff));
  81761. }
  81762. /* =========================================================================
  81763. * Flush as much pending output as possible. All deflate() output goes
  81764. * through this function so some applications may wish to modify it
  81765. * to avoid allocating a large strm->next_out buffer and copying into it.
  81766. * (See also read_buf()).
  81767. */
  81768. local void flush_pending (z_streamp strm)
  81769. {
  81770. unsigned len = strm->state->pending;
  81771. if (len > strm->avail_out) len = strm->avail_out;
  81772. if (len == 0) return;
  81773. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81774. strm->next_out += len;
  81775. strm->state->pending_out += len;
  81776. strm->total_out += len;
  81777. strm->avail_out -= len;
  81778. strm->state->pending -= len;
  81779. if (strm->state->pending == 0) {
  81780. strm->state->pending_out = strm->state->pending_buf;
  81781. }
  81782. }
  81783. /* ========================================================================= */
  81784. int ZEXPORT deflate (z_streamp strm, int flush)
  81785. {
  81786. int old_flush; /* value of flush param for previous deflate call */
  81787. deflate_state *s;
  81788. if (strm == Z_NULL || strm->state == Z_NULL ||
  81789. flush > Z_FINISH || flush < 0) {
  81790. return Z_STREAM_ERROR;
  81791. }
  81792. s = strm->state;
  81793. if (strm->next_out == Z_NULL ||
  81794. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81795. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81796. ERR_RETURN(strm, Z_STREAM_ERROR);
  81797. }
  81798. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81799. s->strm = strm; /* just in case */
  81800. old_flush = s->last_flush;
  81801. s->last_flush = flush;
  81802. /* Write the header */
  81803. if (s->status == INIT_STATE) {
  81804. #ifdef GZIP
  81805. if (s->wrap == 2) {
  81806. strm->adler = crc32(0L, Z_NULL, 0);
  81807. put_byte(s, 31);
  81808. put_byte(s, 139);
  81809. put_byte(s, 8);
  81810. if (s->gzhead == NULL) {
  81811. put_byte(s, 0);
  81812. put_byte(s, 0);
  81813. put_byte(s, 0);
  81814. put_byte(s, 0);
  81815. put_byte(s, 0);
  81816. put_byte(s, s->level == 9 ? 2 :
  81817. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81818. 4 : 0));
  81819. put_byte(s, OS_CODE);
  81820. s->status = BUSY_STATE;
  81821. }
  81822. else {
  81823. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81824. (s->gzhead->hcrc ? 2 : 0) +
  81825. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81826. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81827. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81828. );
  81829. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81830. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81831. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81832. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81833. put_byte(s, s->level == 9 ? 2 :
  81834. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81835. 4 : 0));
  81836. put_byte(s, s->gzhead->os & 0xff);
  81837. if (s->gzhead->extra != NULL) {
  81838. put_byte(s, s->gzhead->extra_len & 0xff);
  81839. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81840. }
  81841. if (s->gzhead->hcrc)
  81842. strm->adler = crc32(strm->adler, s->pending_buf,
  81843. s->pending);
  81844. s->gzindex = 0;
  81845. s->status = EXTRA_STATE;
  81846. }
  81847. }
  81848. else
  81849. #endif
  81850. {
  81851. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81852. uInt level_flags;
  81853. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81854. level_flags = 0;
  81855. else if (s->level < 6)
  81856. level_flags = 1;
  81857. else if (s->level == 6)
  81858. level_flags = 2;
  81859. else
  81860. level_flags = 3;
  81861. header |= (level_flags << 6);
  81862. if (s->strstart != 0) header |= PRESET_DICT;
  81863. header += 31 - (header % 31);
  81864. s->status = BUSY_STATE;
  81865. putShortMSB(s, header);
  81866. /* Save the adler32 of the preset dictionary: */
  81867. if (s->strstart != 0) {
  81868. putShortMSB(s, (uInt)(strm->adler >> 16));
  81869. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81870. }
  81871. strm->adler = adler32(0L, Z_NULL, 0);
  81872. }
  81873. }
  81874. #ifdef GZIP
  81875. if (s->status == EXTRA_STATE) {
  81876. if (s->gzhead->extra != NULL) {
  81877. uInt beg = s->pending; /* start of bytes to update crc */
  81878. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81879. if (s->pending == s->pending_buf_size) {
  81880. if (s->gzhead->hcrc && s->pending > beg)
  81881. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81882. s->pending - beg);
  81883. flush_pending(strm);
  81884. beg = s->pending;
  81885. if (s->pending == s->pending_buf_size)
  81886. break;
  81887. }
  81888. put_byte(s, s->gzhead->extra[s->gzindex]);
  81889. s->gzindex++;
  81890. }
  81891. if (s->gzhead->hcrc && s->pending > beg)
  81892. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81893. s->pending - beg);
  81894. if (s->gzindex == s->gzhead->extra_len) {
  81895. s->gzindex = 0;
  81896. s->status = NAME_STATE;
  81897. }
  81898. }
  81899. else
  81900. s->status = NAME_STATE;
  81901. }
  81902. if (s->status == NAME_STATE) {
  81903. if (s->gzhead->name != NULL) {
  81904. uInt beg = s->pending; /* start of bytes to update crc */
  81905. int val;
  81906. do {
  81907. if (s->pending == s->pending_buf_size) {
  81908. if (s->gzhead->hcrc && s->pending > beg)
  81909. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81910. s->pending - beg);
  81911. flush_pending(strm);
  81912. beg = s->pending;
  81913. if (s->pending == s->pending_buf_size) {
  81914. val = 1;
  81915. break;
  81916. }
  81917. }
  81918. val = s->gzhead->name[s->gzindex++];
  81919. put_byte(s, val);
  81920. } while (val != 0);
  81921. if (s->gzhead->hcrc && s->pending > beg)
  81922. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81923. s->pending - beg);
  81924. if (val == 0) {
  81925. s->gzindex = 0;
  81926. s->status = COMMENT_STATE;
  81927. }
  81928. }
  81929. else
  81930. s->status = COMMENT_STATE;
  81931. }
  81932. if (s->status == COMMENT_STATE) {
  81933. if (s->gzhead->comment != NULL) {
  81934. uInt beg = s->pending; /* start of bytes to update crc */
  81935. int val;
  81936. do {
  81937. if (s->pending == s->pending_buf_size) {
  81938. if (s->gzhead->hcrc && s->pending > beg)
  81939. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81940. s->pending - beg);
  81941. flush_pending(strm);
  81942. beg = s->pending;
  81943. if (s->pending == s->pending_buf_size) {
  81944. val = 1;
  81945. break;
  81946. }
  81947. }
  81948. val = s->gzhead->comment[s->gzindex++];
  81949. put_byte(s, val);
  81950. } while (val != 0);
  81951. if (s->gzhead->hcrc && s->pending > beg)
  81952. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81953. s->pending - beg);
  81954. if (val == 0)
  81955. s->status = HCRC_STATE;
  81956. }
  81957. else
  81958. s->status = HCRC_STATE;
  81959. }
  81960. if (s->status == HCRC_STATE) {
  81961. if (s->gzhead->hcrc) {
  81962. if (s->pending + 2 > s->pending_buf_size)
  81963. flush_pending(strm);
  81964. if (s->pending + 2 <= s->pending_buf_size) {
  81965. put_byte(s, (Byte)(strm->adler & 0xff));
  81966. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81967. strm->adler = crc32(0L, Z_NULL, 0);
  81968. s->status = BUSY_STATE;
  81969. }
  81970. }
  81971. else
  81972. s->status = BUSY_STATE;
  81973. }
  81974. #endif
  81975. /* Flush as much pending output as possible */
  81976. if (s->pending != 0) {
  81977. flush_pending(strm);
  81978. if (strm->avail_out == 0) {
  81979. /* Since avail_out is 0, deflate will be called again with
  81980. * more output space, but possibly with both pending and
  81981. * avail_in equal to zero. There won't be anything to do,
  81982. * but this is not an error situation so make sure we
  81983. * return OK instead of BUF_ERROR at next call of deflate:
  81984. */
  81985. s->last_flush = -1;
  81986. return Z_OK;
  81987. }
  81988. /* Make sure there is something to do and avoid duplicate consecutive
  81989. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81990. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81991. */
  81992. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81993. flush != Z_FINISH) {
  81994. ERR_RETURN(strm, Z_BUF_ERROR);
  81995. }
  81996. /* User must not provide more input after the first FINISH: */
  81997. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81998. ERR_RETURN(strm, Z_BUF_ERROR);
  81999. }
  82000. /* Start a new block or continue the current one.
  82001. */
  82002. if (strm->avail_in != 0 || s->lookahead != 0 ||
  82003. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  82004. block_state bstate;
  82005. bstate = (*(configuration_table[s->level].func))(s, flush);
  82006. if (bstate == finish_started || bstate == finish_done) {
  82007. s->status = FINISH_STATE;
  82008. }
  82009. if (bstate == need_more || bstate == finish_started) {
  82010. if (strm->avail_out == 0) {
  82011. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  82012. }
  82013. return Z_OK;
  82014. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  82015. * of deflate should use the same flush parameter to make sure
  82016. * that the flush is complete. So we don't have to output an
  82017. * empty block here, this will be done at next call. This also
  82018. * ensures that for a very small output buffer, we emit at most
  82019. * one empty block.
  82020. */
  82021. }
  82022. if (bstate == block_done) {
  82023. if (flush == Z_PARTIAL_FLUSH) {
  82024. _tr_align(s);
  82025. } else { /* FULL_FLUSH or SYNC_FLUSH */
  82026. _tr_stored_block(s, (char*)0, 0L, 0);
  82027. /* For a full flush, this empty block will be recognized
  82028. * as a special marker by inflate_sync().
  82029. */
  82030. if (flush == Z_FULL_FLUSH) {
  82031. CLEAR_HASH(s); /* forget history */
  82032. }
  82033. }
  82034. flush_pending(strm);
  82035. if (strm->avail_out == 0) {
  82036. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  82037. return Z_OK;
  82038. }
  82039. }
  82040. }
  82041. Assert(strm->avail_out > 0, "bug2");
  82042. if (flush != Z_FINISH) return Z_OK;
  82043. if (s->wrap <= 0) return Z_STREAM_END;
  82044. /* Write the trailer */
  82045. #ifdef GZIP
  82046. if (s->wrap == 2) {
  82047. put_byte(s, (Byte)(strm->adler & 0xff));
  82048. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  82049. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  82050. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  82051. put_byte(s, (Byte)(strm->total_in & 0xff));
  82052. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  82053. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  82054. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  82055. }
  82056. else
  82057. #endif
  82058. {
  82059. putShortMSB(s, (uInt)(strm->adler >> 16));
  82060. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  82061. }
  82062. flush_pending(strm);
  82063. /* If avail_out is zero, the application will call deflate again
  82064. * to flush the rest.
  82065. */
  82066. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  82067. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  82068. }
  82069. /* ========================================================================= */
  82070. int ZEXPORT deflateEnd (z_streamp strm)
  82071. {
  82072. int status;
  82073. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82074. status = strm->state->status;
  82075. if (status != INIT_STATE &&
  82076. status != EXTRA_STATE &&
  82077. status != NAME_STATE &&
  82078. status != COMMENT_STATE &&
  82079. status != HCRC_STATE &&
  82080. status != BUSY_STATE &&
  82081. status != FINISH_STATE) {
  82082. return Z_STREAM_ERROR;
  82083. }
  82084. /* Deallocate in reverse order of allocations: */
  82085. TRY_FREE(strm, strm->state->pending_buf);
  82086. TRY_FREE(strm, strm->state->head);
  82087. TRY_FREE(strm, strm->state->prev);
  82088. TRY_FREE(strm, strm->state->window);
  82089. ZFREE(strm, strm->state);
  82090. strm->state = Z_NULL;
  82091. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  82092. }
  82093. /* =========================================================================
  82094. * Copy the source state to the destination state.
  82095. * To simplify the source, this is not supported for 16-bit MSDOS (which
  82096. * doesn't have enough memory anyway to duplicate compression states).
  82097. */
  82098. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  82099. {
  82100. #ifdef MAXSEG_64K
  82101. return Z_STREAM_ERROR;
  82102. #else
  82103. deflate_state *ds;
  82104. deflate_state *ss;
  82105. ushf *overlay;
  82106. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  82107. return Z_STREAM_ERROR;
  82108. }
  82109. ss = source->state;
  82110. zmemcpy(dest, source, sizeof(z_stream));
  82111. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  82112. if (ds == Z_NULL) return Z_MEM_ERROR;
  82113. dest->state = (struct internal_state FAR *) ds;
  82114. zmemcpy(ds, ss, sizeof(deflate_state));
  82115. ds->strm = dest;
  82116. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  82117. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  82118. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  82119. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  82120. ds->pending_buf = (uchf *) overlay;
  82121. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  82122. ds->pending_buf == Z_NULL) {
  82123. deflateEnd (dest);
  82124. return Z_MEM_ERROR;
  82125. }
  82126. /* following zmemcpy do not work for 16-bit MSDOS */
  82127. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  82128. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  82129. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  82130. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  82131. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  82132. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  82133. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  82134. ds->l_desc.dyn_tree = ds->dyn_ltree;
  82135. ds->d_desc.dyn_tree = ds->dyn_dtree;
  82136. ds->bl_desc.dyn_tree = ds->bl_tree;
  82137. return Z_OK;
  82138. #endif /* MAXSEG_64K */
  82139. }
  82140. /* ===========================================================================
  82141. * Read a new buffer from the current input stream, update the adler32
  82142. * and total number of bytes read. All deflate() input goes through
  82143. * this function so some applications may wish to modify it to avoid
  82144. * allocating a large strm->next_in buffer and copying from it.
  82145. * (See also flush_pending()).
  82146. */
  82147. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  82148. {
  82149. unsigned len = strm->avail_in;
  82150. if (len > size) len = size;
  82151. if (len == 0) return 0;
  82152. strm->avail_in -= len;
  82153. if (strm->state->wrap == 1) {
  82154. strm->adler = adler32(strm->adler, strm->next_in, len);
  82155. }
  82156. #ifdef GZIP
  82157. else if (strm->state->wrap == 2) {
  82158. strm->adler = crc32(strm->adler, strm->next_in, len);
  82159. }
  82160. #endif
  82161. zmemcpy(buf, strm->next_in, len);
  82162. strm->next_in += len;
  82163. strm->total_in += len;
  82164. return (int)len;
  82165. }
  82166. /* ===========================================================================
  82167. * Initialize the "longest match" routines for a new zlib stream
  82168. */
  82169. local void lm_init (deflate_state *s)
  82170. {
  82171. s->window_size = (ulg)2L*s->w_size;
  82172. CLEAR_HASH(s);
  82173. /* Set the default configuration parameters:
  82174. */
  82175. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82176. s->good_match = configuration_table[s->level].good_length;
  82177. s->nice_match = configuration_table[s->level].nice_length;
  82178. s->max_chain_length = configuration_table[s->level].max_chain;
  82179. s->strstart = 0;
  82180. s->block_start = 0L;
  82181. s->lookahead = 0;
  82182. s->match_length = s->prev_length = MIN_MATCH-1;
  82183. s->match_available = 0;
  82184. s->ins_h = 0;
  82185. #ifndef FASTEST
  82186. #ifdef ASMV
  82187. match_init(); /* initialize the asm code */
  82188. #endif
  82189. #endif
  82190. }
  82191. #ifndef FASTEST
  82192. /* ===========================================================================
  82193. * Set match_start to the longest match starting at the given string and
  82194. * return its length. Matches shorter or equal to prev_length are discarded,
  82195. * in which case the result is equal to prev_length and match_start is
  82196. * garbage.
  82197. * IN assertions: cur_match is the head of the hash chain for the current
  82198. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82199. * OUT assertion: the match length is not greater than s->lookahead.
  82200. */
  82201. #ifndef ASMV
  82202. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82203. * match.S. The code will be functionally equivalent.
  82204. */
  82205. local uInt longest_match(deflate_state *s, IPos cur_match)
  82206. {
  82207. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82208. register Bytef *scan = s->window + s->strstart; /* current string */
  82209. register Bytef *match; /* matched string */
  82210. register int len; /* length of current match */
  82211. int best_len = s->prev_length; /* best match length so far */
  82212. int nice_match = s->nice_match; /* stop if match long enough */
  82213. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82214. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82215. /* Stop when cur_match becomes <= limit. To simplify the code,
  82216. * we prevent matches with the string of window index 0.
  82217. */
  82218. Posf *prev = s->prev;
  82219. uInt wmask = s->w_mask;
  82220. #ifdef UNALIGNED_OK
  82221. /* Compare two bytes at a time. Note: this is not always beneficial.
  82222. * Try with and without -DUNALIGNED_OK to check.
  82223. */
  82224. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82225. register ush scan_start = *(ushf*)scan;
  82226. register ush scan_end = *(ushf*)(scan+best_len-1);
  82227. #else
  82228. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82229. register Byte scan_end1 = scan[best_len-1];
  82230. register Byte scan_end = scan[best_len];
  82231. #endif
  82232. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82233. * It is easy to get rid of this optimization if necessary.
  82234. */
  82235. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82236. /* Do not waste too much time if we already have a good match: */
  82237. if (s->prev_length >= s->good_match) {
  82238. chain_length >>= 2;
  82239. }
  82240. /* Do not look for matches beyond the end of the input. This is necessary
  82241. * to make deflate deterministic.
  82242. */
  82243. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82244. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82245. do {
  82246. Assert(cur_match < s->strstart, "no future");
  82247. match = s->window + cur_match;
  82248. /* Skip to next match if the match length cannot increase
  82249. * or if the match length is less than 2. Note that the checks below
  82250. * for insufficient lookahead only occur occasionally for performance
  82251. * reasons. Therefore uninitialized memory will be accessed, and
  82252. * conditional jumps will be made that depend on those values.
  82253. * However the length of the match is limited to the lookahead, so
  82254. * the output of deflate is not affected by the uninitialized values.
  82255. */
  82256. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82257. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82258. * UNALIGNED_OK if your compiler uses a different size.
  82259. */
  82260. if (*(ushf*)(match+best_len-1) != scan_end ||
  82261. *(ushf*)match != scan_start) continue;
  82262. /* It is not necessary to compare scan[2] and match[2] since they are
  82263. * always equal when the other bytes match, given that the hash keys
  82264. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82265. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82266. * lookahead only every 4th comparison; the 128th check will be made
  82267. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82268. * necessary to put more guard bytes at the end of the window, or
  82269. * to check more often for insufficient lookahead.
  82270. */
  82271. Assert(scan[2] == match[2], "scan[2]?");
  82272. scan++, match++;
  82273. do {
  82274. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82275. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82276. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82277. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82278. scan < strend);
  82279. /* The funny "do {}" generates better code on most compilers */
  82280. /* Here, scan <= window+strstart+257 */
  82281. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82282. if (*scan == *match) scan++;
  82283. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82284. scan = strend - (MAX_MATCH-1);
  82285. #else /* UNALIGNED_OK */
  82286. if (match[best_len] != scan_end ||
  82287. match[best_len-1] != scan_end1 ||
  82288. *match != *scan ||
  82289. *++match != scan[1]) continue;
  82290. /* The check at best_len-1 can be removed because it will be made
  82291. * again later. (This heuristic is not always a win.)
  82292. * It is not necessary to compare scan[2] and match[2] since they
  82293. * are always equal when the other bytes match, given that
  82294. * the hash keys are equal and that HASH_BITS >= 8.
  82295. */
  82296. scan += 2, match++;
  82297. Assert(*scan == *match, "match[2]?");
  82298. /* We check for insufficient lookahead only every 8th comparison;
  82299. * the 256th check will be made at strstart+258.
  82300. */
  82301. do {
  82302. } while (*++scan == *++match && *++scan == *++match &&
  82303. *++scan == *++match && *++scan == *++match &&
  82304. *++scan == *++match && *++scan == *++match &&
  82305. *++scan == *++match && *++scan == *++match &&
  82306. scan < strend);
  82307. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82308. len = MAX_MATCH - (int)(strend - scan);
  82309. scan = strend - MAX_MATCH;
  82310. #endif /* UNALIGNED_OK */
  82311. if (len > best_len) {
  82312. s->match_start = cur_match;
  82313. best_len = len;
  82314. if (len >= nice_match) break;
  82315. #ifdef UNALIGNED_OK
  82316. scan_end = *(ushf*)(scan+best_len-1);
  82317. #else
  82318. scan_end1 = scan[best_len-1];
  82319. scan_end = scan[best_len];
  82320. #endif
  82321. }
  82322. } while ((cur_match = prev[cur_match & wmask]) > limit
  82323. && --chain_length != 0);
  82324. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82325. return s->lookahead;
  82326. }
  82327. #endif /* ASMV */
  82328. #endif /* FASTEST */
  82329. /* ---------------------------------------------------------------------------
  82330. * Optimized version for level == 1 or strategy == Z_RLE only
  82331. */
  82332. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82333. {
  82334. register Bytef *scan = s->window + s->strstart; /* current string */
  82335. register Bytef *match; /* matched string */
  82336. register int len; /* length of current match */
  82337. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82338. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82339. * It is easy to get rid of this optimization if necessary.
  82340. */
  82341. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82342. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82343. Assert(cur_match < s->strstart, "no future");
  82344. match = s->window + cur_match;
  82345. /* Return failure if the match length is less than 2:
  82346. */
  82347. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82348. /* The check at best_len-1 can be removed because it will be made
  82349. * again later. (This heuristic is not always a win.)
  82350. * It is not necessary to compare scan[2] and match[2] since they
  82351. * are always equal when the other bytes match, given that
  82352. * the hash keys are equal and that HASH_BITS >= 8.
  82353. */
  82354. scan += 2, match += 2;
  82355. Assert(*scan == *match, "match[2]?");
  82356. /* We check for insufficient lookahead only every 8th comparison;
  82357. * the 256th check will be made at strstart+258.
  82358. */
  82359. do {
  82360. } while (*++scan == *++match && *++scan == *++match &&
  82361. *++scan == *++match && *++scan == *++match &&
  82362. *++scan == *++match && *++scan == *++match &&
  82363. *++scan == *++match && *++scan == *++match &&
  82364. scan < strend);
  82365. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82366. len = MAX_MATCH - (int)(strend - scan);
  82367. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82368. s->match_start = cur_match;
  82369. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82370. }
  82371. #ifdef DEBUG
  82372. /* ===========================================================================
  82373. * Check that the match at match_start is indeed a match.
  82374. */
  82375. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82376. {
  82377. /* check that the match is indeed a match */
  82378. if (zmemcmp(s->window + match,
  82379. s->window + start, length) != EQUAL) {
  82380. fprintf(stderr, " start %u, match %u, length %d\n",
  82381. start, match, length);
  82382. do {
  82383. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82384. } while (--length != 0);
  82385. z_error("invalid match");
  82386. }
  82387. if (z_verbose > 1) {
  82388. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82389. do { putc(s->window[start++], stderr); } while (--length != 0);
  82390. }
  82391. }
  82392. #else
  82393. # define check_match(s, start, match, length)
  82394. #endif /* DEBUG */
  82395. /* ===========================================================================
  82396. * Fill the window when the lookahead becomes insufficient.
  82397. * Updates strstart and lookahead.
  82398. *
  82399. * IN assertion: lookahead < MIN_LOOKAHEAD
  82400. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82401. * At least one byte has been read, or avail_in == 0; reads are
  82402. * performed for at least two bytes (required for the zip translate_eol
  82403. * option -- not supported here).
  82404. */
  82405. local void fill_window (deflate_state *s)
  82406. {
  82407. register unsigned n, m;
  82408. register Posf *p;
  82409. unsigned more; /* Amount of free space at the end of the window. */
  82410. uInt wsize = s->w_size;
  82411. do {
  82412. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82413. /* Deal with !@#$% 64K limit: */
  82414. if (sizeof(int) <= 2) {
  82415. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82416. more = wsize;
  82417. } else if (more == (unsigned)(-1)) {
  82418. /* Very unlikely, but possible on 16 bit machine if
  82419. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82420. */
  82421. more--;
  82422. }
  82423. }
  82424. /* If the window is almost full and there is insufficient lookahead,
  82425. * move the upper half to the lower one to make room in the upper half.
  82426. */
  82427. if (s->strstart >= wsize+MAX_DIST(s)) {
  82428. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82429. s->match_start -= wsize;
  82430. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82431. s->block_start -= (long) wsize;
  82432. /* Slide the hash table (could be avoided with 32 bit values
  82433. at the expense of memory usage). We slide even when level == 0
  82434. to keep the hash table consistent if we switch back to level > 0
  82435. later. (Using level 0 permanently is not an optimal usage of
  82436. zlib, so we don't care about this pathological case.)
  82437. */
  82438. /* %%% avoid this when Z_RLE */
  82439. n = s->hash_size;
  82440. p = &s->head[n];
  82441. do {
  82442. m = *--p;
  82443. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82444. } while (--n);
  82445. n = wsize;
  82446. #ifndef FASTEST
  82447. p = &s->prev[n];
  82448. do {
  82449. m = *--p;
  82450. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82451. /* If n is not on any hash chain, prev[n] is garbage but
  82452. * its value will never be used.
  82453. */
  82454. } while (--n);
  82455. #endif
  82456. more += wsize;
  82457. }
  82458. if (s->strm->avail_in == 0) return;
  82459. /* If there was no sliding:
  82460. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82461. * more == window_size - lookahead - strstart
  82462. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82463. * => more >= window_size - 2*WSIZE + 2
  82464. * In the BIG_MEM or MMAP case (not yet supported),
  82465. * window_size == input_size + MIN_LOOKAHEAD &&
  82466. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82467. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82468. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82469. */
  82470. Assert(more >= 2, "more < 2");
  82471. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82472. s->lookahead += n;
  82473. /* Initialize the hash value now that we have some input: */
  82474. if (s->lookahead >= MIN_MATCH) {
  82475. s->ins_h = s->window[s->strstart];
  82476. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82477. #if MIN_MATCH != 3
  82478. Call UPDATE_HASH() MIN_MATCH-3 more times
  82479. #endif
  82480. }
  82481. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82482. * but this is not important since only literal bytes will be emitted.
  82483. */
  82484. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82485. }
  82486. /* ===========================================================================
  82487. * Flush the current block, with given end-of-file flag.
  82488. * IN assertion: strstart is set to the end of the current match.
  82489. */
  82490. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82491. _tr_flush_block(s, (s->block_start >= 0L ? \
  82492. (charf *)&s->window[(unsigned)s->block_start] : \
  82493. (charf *)Z_NULL), \
  82494. (ulg)((long)s->strstart - s->block_start), \
  82495. (eof)); \
  82496. s->block_start = s->strstart; \
  82497. flush_pending(s->strm); \
  82498. Tracev((stderr,"[FLUSH]")); \
  82499. }
  82500. /* Same but force premature exit if necessary. */
  82501. #define FLUSH_BLOCK(s, eof) { \
  82502. FLUSH_BLOCK_ONLY(s, eof); \
  82503. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82504. }
  82505. /* ===========================================================================
  82506. * Copy without compression as much as possible from the input stream, return
  82507. * the current block state.
  82508. * This function does not insert new strings in the dictionary since
  82509. * uncompressible data is probably not useful. This function is used
  82510. * only for the level=0 compression option.
  82511. * NOTE: this function should be optimized to avoid extra copying from
  82512. * window to pending_buf.
  82513. */
  82514. local block_state deflate_stored(deflate_state *s, int flush)
  82515. {
  82516. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82517. * to pending_buf_size, and each stored block has a 5 byte header:
  82518. */
  82519. ulg max_block_size = 0xffff;
  82520. ulg max_start;
  82521. if (max_block_size > s->pending_buf_size - 5) {
  82522. max_block_size = s->pending_buf_size - 5;
  82523. }
  82524. /* Copy as much as possible from input to output: */
  82525. for (;;) {
  82526. /* Fill the window as much as possible: */
  82527. if (s->lookahead <= 1) {
  82528. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82529. s->block_start >= (long)s->w_size, "slide too late");
  82530. fill_window(s);
  82531. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82532. if (s->lookahead == 0) break; /* flush the current block */
  82533. }
  82534. Assert(s->block_start >= 0L, "block gone");
  82535. s->strstart += s->lookahead;
  82536. s->lookahead = 0;
  82537. /* Emit a stored block if pending_buf will be full: */
  82538. max_start = s->block_start + max_block_size;
  82539. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82540. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82541. s->lookahead = (uInt)(s->strstart - max_start);
  82542. s->strstart = (uInt)max_start;
  82543. FLUSH_BLOCK(s, 0);
  82544. }
  82545. /* Flush if we may have to slide, otherwise block_start may become
  82546. * negative and the data will be gone:
  82547. */
  82548. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82549. FLUSH_BLOCK(s, 0);
  82550. }
  82551. }
  82552. FLUSH_BLOCK(s, flush == Z_FINISH);
  82553. return flush == Z_FINISH ? finish_done : block_done;
  82554. }
  82555. /* ===========================================================================
  82556. * Compress as much as possible from the input stream, return the current
  82557. * block state.
  82558. * This function does not perform lazy evaluation of matches and inserts
  82559. * new strings in the dictionary only for unmatched strings or for short
  82560. * matches. It is used only for the fast compression options.
  82561. */
  82562. local block_state deflate_fast(deflate_state *s, int flush)
  82563. {
  82564. IPos hash_head = NIL; /* head of the hash chain */
  82565. int bflush; /* set if current block must be flushed */
  82566. for (;;) {
  82567. /* Make sure that we always have enough lookahead, except
  82568. * at the end of the input file. We need MAX_MATCH bytes
  82569. * for the next match, plus MIN_MATCH bytes to insert the
  82570. * string following the next match.
  82571. */
  82572. if (s->lookahead < MIN_LOOKAHEAD) {
  82573. fill_window(s);
  82574. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82575. return need_more;
  82576. }
  82577. if (s->lookahead == 0) break; /* flush the current block */
  82578. }
  82579. /* Insert the string window[strstart .. strstart+2] in the
  82580. * dictionary, and set hash_head to the head of the hash chain:
  82581. */
  82582. if (s->lookahead >= MIN_MATCH) {
  82583. INSERT_STRING(s, s->strstart, hash_head);
  82584. }
  82585. /* Find the longest match, discarding those <= prev_length.
  82586. * At this point we have always match_length < MIN_MATCH
  82587. */
  82588. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82589. /* To simplify the code, we prevent matches with the string
  82590. * of window index 0 (in particular we have to avoid a match
  82591. * of the string with itself at the start of the input file).
  82592. */
  82593. #ifdef FASTEST
  82594. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82595. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82596. s->match_length = longest_match_fast (s, hash_head);
  82597. }
  82598. #else
  82599. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82600. s->match_length = longest_match (s, hash_head);
  82601. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82602. s->match_length = longest_match_fast (s, hash_head);
  82603. }
  82604. #endif
  82605. /* longest_match() or longest_match_fast() sets match_start */
  82606. }
  82607. if (s->match_length >= MIN_MATCH) {
  82608. check_match(s, s->strstart, s->match_start, s->match_length);
  82609. _tr_tally_dist(s, s->strstart - s->match_start,
  82610. s->match_length - MIN_MATCH, bflush);
  82611. s->lookahead -= s->match_length;
  82612. /* Insert new strings in the hash table only if the match length
  82613. * is not too large. This saves time but degrades compression.
  82614. */
  82615. #ifndef FASTEST
  82616. if (s->match_length <= s->max_insert_length &&
  82617. s->lookahead >= MIN_MATCH) {
  82618. s->match_length--; /* string at strstart already in table */
  82619. do {
  82620. s->strstart++;
  82621. INSERT_STRING(s, s->strstart, hash_head);
  82622. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82623. * always MIN_MATCH bytes ahead.
  82624. */
  82625. } while (--s->match_length != 0);
  82626. s->strstart++;
  82627. } else
  82628. #endif
  82629. {
  82630. s->strstart += s->match_length;
  82631. s->match_length = 0;
  82632. s->ins_h = s->window[s->strstart];
  82633. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82634. #if MIN_MATCH != 3
  82635. Call UPDATE_HASH() MIN_MATCH-3 more times
  82636. #endif
  82637. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82638. * matter since it will be recomputed at next deflate call.
  82639. */
  82640. }
  82641. } else {
  82642. /* No match, output a literal byte */
  82643. Tracevv((stderr,"%c", s->window[s->strstart]));
  82644. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82645. s->lookahead--;
  82646. s->strstart++;
  82647. }
  82648. if (bflush) FLUSH_BLOCK(s, 0);
  82649. }
  82650. FLUSH_BLOCK(s, flush == Z_FINISH);
  82651. return flush == Z_FINISH ? finish_done : block_done;
  82652. }
  82653. #ifndef FASTEST
  82654. /* ===========================================================================
  82655. * Same as above, but achieves better compression. We use a lazy
  82656. * evaluation for matches: a match is finally adopted only if there is
  82657. * no better match at the next window position.
  82658. */
  82659. local block_state deflate_slow(deflate_state *s, int flush)
  82660. {
  82661. IPos hash_head = NIL; /* head of hash chain */
  82662. int bflush; /* set if current block must be flushed */
  82663. /* Process the input block. */
  82664. for (;;) {
  82665. /* Make sure that we always have enough lookahead, except
  82666. * at the end of the input file. We need MAX_MATCH bytes
  82667. * for the next match, plus MIN_MATCH bytes to insert the
  82668. * string following the next match.
  82669. */
  82670. if (s->lookahead < MIN_LOOKAHEAD) {
  82671. fill_window(s);
  82672. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82673. return need_more;
  82674. }
  82675. if (s->lookahead == 0) break; /* flush the current block */
  82676. }
  82677. /* Insert the string window[strstart .. strstart+2] in the
  82678. * dictionary, and set hash_head to the head of the hash chain:
  82679. */
  82680. if (s->lookahead >= MIN_MATCH) {
  82681. INSERT_STRING(s, s->strstart, hash_head);
  82682. }
  82683. /* Find the longest match, discarding those <= prev_length.
  82684. */
  82685. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82686. s->match_length = MIN_MATCH-1;
  82687. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82688. s->strstart - hash_head <= MAX_DIST(s)) {
  82689. /* To simplify the code, we prevent matches with the string
  82690. * of window index 0 (in particular we have to avoid a match
  82691. * of the string with itself at the start of the input file).
  82692. */
  82693. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82694. s->match_length = longest_match (s, hash_head);
  82695. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82696. s->match_length = longest_match_fast (s, hash_head);
  82697. }
  82698. /* longest_match() or longest_match_fast() sets match_start */
  82699. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82700. #if TOO_FAR <= 32767
  82701. || (s->match_length == MIN_MATCH &&
  82702. s->strstart - s->match_start > TOO_FAR)
  82703. #endif
  82704. )) {
  82705. /* If prev_match is also MIN_MATCH, match_start is garbage
  82706. * but we will ignore the current match anyway.
  82707. */
  82708. s->match_length = MIN_MATCH-1;
  82709. }
  82710. }
  82711. /* If there was a match at the previous step and the current
  82712. * match is not better, output the previous match:
  82713. */
  82714. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82715. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82716. /* Do not insert strings in hash table beyond this. */
  82717. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82718. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82719. s->prev_length - MIN_MATCH, bflush);
  82720. /* Insert in hash table all strings up to the end of the match.
  82721. * strstart-1 and strstart are already inserted. If there is not
  82722. * enough lookahead, the last two strings are not inserted in
  82723. * the hash table.
  82724. */
  82725. s->lookahead -= s->prev_length-1;
  82726. s->prev_length -= 2;
  82727. do {
  82728. if (++s->strstart <= max_insert) {
  82729. INSERT_STRING(s, s->strstart, hash_head);
  82730. }
  82731. } while (--s->prev_length != 0);
  82732. s->match_available = 0;
  82733. s->match_length = MIN_MATCH-1;
  82734. s->strstart++;
  82735. if (bflush) FLUSH_BLOCK(s, 0);
  82736. } else if (s->match_available) {
  82737. /* If there was no match at the previous position, output a
  82738. * single literal. If there was a match but the current match
  82739. * is longer, truncate the previous match to a single literal.
  82740. */
  82741. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82742. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82743. if (bflush) {
  82744. FLUSH_BLOCK_ONLY(s, 0);
  82745. }
  82746. s->strstart++;
  82747. s->lookahead--;
  82748. if (s->strm->avail_out == 0) return need_more;
  82749. } else {
  82750. /* There is no previous match to compare with, wait for
  82751. * the next step to decide.
  82752. */
  82753. s->match_available = 1;
  82754. s->strstart++;
  82755. s->lookahead--;
  82756. }
  82757. }
  82758. Assert (flush != Z_NO_FLUSH, "no flush?");
  82759. if (s->match_available) {
  82760. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82761. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82762. s->match_available = 0;
  82763. }
  82764. FLUSH_BLOCK(s, flush == Z_FINISH);
  82765. return flush == Z_FINISH ? finish_done : block_done;
  82766. }
  82767. #endif /* FASTEST */
  82768. #if 0
  82769. /* ===========================================================================
  82770. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82771. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82772. * deflate switches away from Z_RLE.)
  82773. */
  82774. local block_state deflate_rle(s, flush)
  82775. deflate_state *s;
  82776. int flush;
  82777. {
  82778. int bflush; /* set if current block must be flushed */
  82779. uInt run; /* length of run */
  82780. uInt max; /* maximum length of run */
  82781. uInt prev; /* byte at distance one to match */
  82782. Bytef *scan; /* scan for end of run */
  82783. for (;;) {
  82784. /* Make sure that we always have enough lookahead, except
  82785. * at the end of the input file. We need MAX_MATCH bytes
  82786. * for the longest encodable run.
  82787. */
  82788. if (s->lookahead < MAX_MATCH) {
  82789. fill_window(s);
  82790. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82791. return need_more;
  82792. }
  82793. if (s->lookahead == 0) break; /* flush the current block */
  82794. }
  82795. /* See how many times the previous byte repeats */
  82796. run = 0;
  82797. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82798. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82799. scan = s->window + s->strstart - 1;
  82800. prev = *scan++;
  82801. do {
  82802. if (*scan++ != prev)
  82803. break;
  82804. } while (++run < max);
  82805. }
  82806. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82807. if (run >= MIN_MATCH) {
  82808. check_match(s, s->strstart, s->strstart - 1, run);
  82809. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82810. s->lookahead -= run;
  82811. s->strstart += run;
  82812. } else {
  82813. /* No match, output a literal byte */
  82814. Tracevv((stderr,"%c", s->window[s->strstart]));
  82815. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82816. s->lookahead--;
  82817. s->strstart++;
  82818. }
  82819. if (bflush) FLUSH_BLOCK(s, 0);
  82820. }
  82821. FLUSH_BLOCK(s, flush == Z_FINISH);
  82822. return flush == Z_FINISH ? finish_done : block_done;
  82823. }
  82824. #endif
  82825. /*** End of inlined file: deflate.c ***/
  82826. /*** Start of inlined file: inffast.c ***/
  82827. /*** Start of inlined file: inftrees.h ***/
  82828. /* WARNING: this file should *not* be used by applications. It is
  82829. part of the implementation of the compression library and is
  82830. subject to change. Applications should only use zlib.h.
  82831. */
  82832. #ifndef _INFTREES_H_
  82833. #define _INFTREES_H_
  82834. /* Structure for decoding tables. Each entry provides either the
  82835. information needed to do the operation requested by the code that
  82836. indexed that table entry, or it provides a pointer to another
  82837. table that indexes more bits of the code. op indicates whether
  82838. the entry is a pointer to another table, a literal, a length or
  82839. distance, an end-of-block, or an invalid code. For a table
  82840. pointer, the low four bits of op is the number of index bits of
  82841. that table. For a length or distance, the low four bits of op
  82842. is the number of extra bits to get after the code. bits is
  82843. the number of bits in this code or part of the code to drop off
  82844. of the bit buffer. val is the actual byte to output in the case
  82845. of a literal, the base length or distance, or the offset from
  82846. the current table to the next table. Each entry is four bytes. */
  82847. typedef struct {
  82848. unsigned char op; /* operation, extra bits, table bits */
  82849. unsigned char bits; /* bits in this part of the code */
  82850. unsigned short val; /* offset in table or code value */
  82851. } code;
  82852. /* op values as set by inflate_table():
  82853. 00000000 - literal
  82854. 0000tttt - table link, tttt != 0 is the number of table index bits
  82855. 0001eeee - length or distance, eeee is the number of extra bits
  82856. 01100000 - end of block
  82857. 01000000 - invalid code
  82858. */
  82859. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82860. exhaustive search was 1444 code structures (852 for length/literals
  82861. and 592 for distances, the latter actually the result of an
  82862. exhaustive search). The true maximum is not known, but the value
  82863. below is more than safe. */
  82864. #define ENOUGH 2048
  82865. #define MAXD 592
  82866. /* Type of code to build for inftable() */
  82867. typedef enum {
  82868. CODES,
  82869. LENS,
  82870. DISTS
  82871. } codetype;
  82872. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82873. unsigned codes, code FAR * FAR *table,
  82874. unsigned FAR *bits, unsigned short FAR *work));
  82875. #endif
  82876. /*** End of inlined file: inftrees.h ***/
  82877. /*** Start of inlined file: inflate.h ***/
  82878. /* WARNING: this file should *not* be used by applications. It is
  82879. part of the implementation of the compression library and is
  82880. subject to change. Applications should only use zlib.h.
  82881. */
  82882. #ifndef _INFLATE_H_
  82883. #define _INFLATE_H_
  82884. /* define NO_GZIP when compiling if you want to disable gzip header and
  82885. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82886. the crc code when it is not needed. For shared libraries, gzip decoding
  82887. should be left enabled. */
  82888. #ifndef NO_GZIP
  82889. # define GUNZIP
  82890. #endif
  82891. /* Possible inflate modes between inflate() calls */
  82892. typedef enum {
  82893. HEAD, /* i: waiting for magic header */
  82894. FLAGS, /* i: waiting for method and flags (gzip) */
  82895. TIME, /* i: waiting for modification time (gzip) */
  82896. OS, /* i: waiting for extra flags and operating system (gzip) */
  82897. EXLEN, /* i: waiting for extra length (gzip) */
  82898. EXTRA, /* i: waiting for extra bytes (gzip) */
  82899. NAME, /* i: waiting for end of file name (gzip) */
  82900. COMMENT, /* i: waiting for end of comment (gzip) */
  82901. HCRC, /* i: waiting for header crc (gzip) */
  82902. DICTID, /* i: waiting for dictionary check value */
  82903. DICT, /* waiting for inflateSetDictionary() call */
  82904. TYPE, /* i: waiting for type bits, including last-flag bit */
  82905. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82906. STORED, /* i: waiting for stored size (length and complement) */
  82907. COPY, /* i/o: waiting for input or output to copy stored block */
  82908. TABLE, /* i: waiting for dynamic block table lengths */
  82909. LENLENS, /* i: waiting for code length code lengths */
  82910. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82911. LEN, /* i: waiting for length/lit code */
  82912. LENEXT, /* i: waiting for length extra bits */
  82913. DIST, /* i: waiting for distance code */
  82914. DISTEXT, /* i: waiting for distance extra bits */
  82915. MATCH, /* o: waiting for output space to copy string */
  82916. LIT, /* o: waiting for output space to write literal */
  82917. CHECK, /* i: waiting for 32-bit check value */
  82918. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82919. DONE, /* finished check, done -- remain here until reset */
  82920. BAD, /* got a data error -- remain here until reset */
  82921. MEM, /* got an inflate() memory error -- remain here until reset */
  82922. SYNC /* looking for synchronization bytes to restart inflate() */
  82923. } inflate_mode;
  82924. /*
  82925. State transitions between above modes -
  82926. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82927. Process header:
  82928. HEAD -> (gzip) or (zlib)
  82929. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82930. NAME -> COMMENT -> HCRC -> TYPE
  82931. (zlib) -> DICTID or TYPE
  82932. DICTID -> DICT -> TYPE
  82933. Read deflate blocks:
  82934. TYPE -> STORED or TABLE or LEN or CHECK
  82935. STORED -> COPY -> TYPE
  82936. TABLE -> LENLENS -> CODELENS -> LEN
  82937. Read deflate codes:
  82938. LEN -> LENEXT or LIT or TYPE
  82939. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82940. LIT -> LEN
  82941. Process trailer:
  82942. CHECK -> LENGTH -> DONE
  82943. */
  82944. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82945. struct inflate_state {
  82946. inflate_mode mode; /* current inflate mode */
  82947. int last; /* true if processing last block */
  82948. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82949. int havedict; /* true if dictionary provided */
  82950. int flags; /* gzip header method and flags (0 if zlib) */
  82951. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82952. unsigned long check; /* protected copy of check value */
  82953. unsigned long total; /* protected copy of output count */
  82954. gz_headerp head; /* where to save gzip header information */
  82955. /* sliding window */
  82956. unsigned wbits; /* log base 2 of requested window size */
  82957. unsigned wsize; /* window size or zero if not using window */
  82958. unsigned whave; /* valid bytes in the window */
  82959. unsigned write; /* window write index */
  82960. unsigned char FAR *window; /* allocated sliding window, if needed */
  82961. /* bit accumulator */
  82962. unsigned long hold; /* input bit accumulator */
  82963. unsigned bits; /* number of bits in "in" */
  82964. /* for string and stored block copying */
  82965. unsigned length; /* literal or length of data to copy */
  82966. unsigned offset; /* distance back to copy string from */
  82967. /* for table and code decoding */
  82968. unsigned extra; /* extra bits needed */
  82969. /* fixed and dynamic code tables */
  82970. code const FAR *lencode; /* starting table for length/literal codes */
  82971. code const FAR *distcode; /* starting table for distance codes */
  82972. unsigned lenbits; /* index bits for lencode */
  82973. unsigned distbits; /* index bits for distcode */
  82974. /* dynamic table building */
  82975. unsigned ncode; /* number of code length code lengths */
  82976. unsigned nlen; /* number of length code lengths */
  82977. unsigned ndist; /* number of distance code lengths */
  82978. unsigned have; /* number of code lengths in lens[] */
  82979. code FAR *next; /* next available space in codes[] */
  82980. unsigned short lens[320]; /* temporary storage for code lengths */
  82981. unsigned short work[288]; /* work area for code table building */
  82982. code codes[ENOUGH]; /* space for code tables */
  82983. };
  82984. #endif
  82985. /*** End of inlined file: inflate.h ***/
  82986. /*** Start of inlined file: inffast.h ***/
  82987. /* WARNING: this file should *not* be used by applications. It is
  82988. part of the implementation of the compression library and is
  82989. subject to change. Applications should only use zlib.h.
  82990. */
  82991. void inflate_fast OF((z_streamp strm, unsigned start));
  82992. /*** End of inlined file: inffast.h ***/
  82993. #ifndef ASMINF
  82994. /* Allow machine dependent optimization for post-increment or pre-increment.
  82995. Based on testing to date,
  82996. Pre-increment preferred for:
  82997. - PowerPC G3 (Adler)
  82998. - MIPS R5000 (Randers-Pehrson)
  82999. Post-increment preferred for:
  83000. - none
  83001. No measurable difference:
  83002. - Pentium III (Anderson)
  83003. - M68060 (Nikl)
  83004. */
  83005. #ifdef POSTINC
  83006. # define OFF 0
  83007. # define PUP(a) *(a)++
  83008. #else
  83009. # define OFF 1
  83010. # define PUP(a) *++(a)
  83011. #endif
  83012. /*
  83013. Decode literal, length, and distance codes and write out the resulting
  83014. literal and match bytes until either not enough input or output is
  83015. available, an end-of-block is encountered, or a data error is encountered.
  83016. When large enough input and output buffers are supplied to inflate(), for
  83017. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  83018. inflate execution time is spent in this routine.
  83019. Entry assumptions:
  83020. state->mode == LEN
  83021. strm->avail_in >= 6
  83022. strm->avail_out >= 258
  83023. start >= strm->avail_out
  83024. state->bits < 8
  83025. On return, state->mode is one of:
  83026. LEN -- ran out of enough output space or enough available input
  83027. TYPE -- reached end of block code, inflate() to interpret next block
  83028. BAD -- error in block data
  83029. Notes:
  83030. - The maximum input bits used by a length/distance pair is 15 bits for the
  83031. length code, 5 bits for the length extra, 15 bits for the distance code,
  83032. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  83033. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  83034. checking for available input while decoding.
  83035. - The maximum bytes that a single length/distance pair can output is 258
  83036. bytes, which is the maximum length that can be coded. inflate_fast()
  83037. requires strm->avail_out >= 258 for each loop to avoid checking for
  83038. output space.
  83039. */
  83040. void inflate_fast (z_streamp strm, unsigned start)
  83041. {
  83042. struct inflate_state FAR *state;
  83043. unsigned char FAR *in; /* local strm->next_in */
  83044. unsigned char FAR *last; /* while in < last, enough input available */
  83045. unsigned char FAR *out; /* local strm->next_out */
  83046. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  83047. unsigned char FAR *end; /* while out < end, enough space available */
  83048. #ifdef INFLATE_STRICT
  83049. unsigned dmax; /* maximum distance from zlib header */
  83050. #endif
  83051. unsigned wsize; /* window size or zero if not using window */
  83052. unsigned whave; /* valid bytes in the window */
  83053. unsigned write; /* window write index */
  83054. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  83055. unsigned long hold; /* local strm->hold */
  83056. unsigned bits; /* local strm->bits */
  83057. code const FAR *lcode; /* local strm->lencode */
  83058. code const FAR *dcode; /* local strm->distcode */
  83059. unsigned lmask; /* mask for first level of length codes */
  83060. unsigned dmask; /* mask for first level of distance codes */
  83061. code thisx; /* retrieved table entry */
  83062. unsigned op; /* code bits, operation, extra bits, or */
  83063. /* window position, window bytes to copy */
  83064. unsigned len; /* match length, unused bytes */
  83065. unsigned dist; /* match distance */
  83066. unsigned char FAR *from; /* where to copy match from */
  83067. /* copy state to local variables */
  83068. state = (struct inflate_state FAR *)strm->state;
  83069. in = strm->next_in - OFF;
  83070. last = in + (strm->avail_in - 5);
  83071. out = strm->next_out - OFF;
  83072. beg = out - (start - strm->avail_out);
  83073. end = out + (strm->avail_out - 257);
  83074. #ifdef INFLATE_STRICT
  83075. dmax = state->dmax;
  83076. #endif
  83077. wsize = state->wsize;
  83078. whave = state->whave;
  83079. write = state->write;
  83080. window = state->window;
  83081. hold = state->hold;
  83082. bits = state->bits;
  83083. lcode = state->lencode;
  83084. dcode = state->distcode;
  83085. lmask = (1U << state->lenbits) - 1;
  83086. dmask = (1U << state->distbits) - 1;
  83087. /* decode literals and length/distances until end-of-block or not enough
  83088. input data or output space */
  83089. do {
  83090. if (bits < 15) {
  83091. hold += (unsigned long)(PUP(in)) << bits;
  83092. bits += 8;
  83093. hold += (unsigned long)(PUP(in)) << bits;
  83094. bits += 8;
  83095. }
  83096. thisx = lcode[hold & lmask];
  83097. dolen:
  83098. op = (unsigned)(thisx.bits);
  83099. hold >>= op;
  83100. bits -= op;
  83101. op = (unsigned)(thisx.op);
  83102. if (op == 0) { /* literal */
  83103. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83104. "inflate: literal '%c'\n" :
  83105. "inflate: literal 0x%02x\n", thisx.val));
  83106. PUP(out) = (unsigned char)(thisx.val);
  83107. }
  83108. else if (op & 16) { /* length base */
  83109. len = (unsigned)(thisx.val);
  83110. op &= 15; /* number of extra bits */
  83111. if (op) {
  83112. if (bits < op) {
  83113. hold += (unsigned long)(PUP(in)) << bits;
  83114. bits += 8;
  83115. }
  83116. len += (unsigned)hold & ((1U << op) - 1);
  83117. hold >>= op;
  83118. bits -= op;
  83119. }
  83120. Tracevv((stderr, "inflate: length %u\n", len));
  83121. if (bits < 15) {
  83122. hold += (unsigned long)(PUP(in)) << bits;
  83123. bits += 8;
  83124. hold += (unsigned long)(PUP(in)) << bits;
  83125. bits += 8;
  83126. }
  83127. thisx = dcode[hold & dmask];
  83128. dodist:
  83129. op = (unsigned)(thisx.bits);
  83130. hold >>= op;
  83131. bits -= op;
  83132. op = (unsigned)(thisx.op);
  83133. if (op & 16) { /* distance base */
  83134. dist = (unsigned)(thisx.val);
  83135. op &= 15; /* number of extra bits */
  83136. if (bits < op) {
  83137. hold += (unsigned long)(PUP(in)) << bits;
  83138. bits += 8;
  83139. if (bits < op) {
  83140. hold += (unsigned long)(PUP(in)) << bits;
  83141. bits += 8;
  83142. }
  83143. }
  83144. dist += (unsigned)hold & ((1U << op) - 1);
  83145. #ifdef INFLATE_STRICT
  83146. if (dist > dmax) {
  83147. strm->msg = (char *)"invalid distance too far back";
  83148. state->mode = BAD;
  83149. break;
  83150. }
  83151. #endif
  83152. hold >>= op;
  83153. bits -= op;
  83154. Tracevv((stderr, "inflate: distance %u\n", dist));
  83155. op = (unsigned)(out - beg); /* max distance in output */
  83156. if (dist > op) { /* see if copy from window */
  83157. op = dist - op; /* distance back in window */
  83158. if (op > whave) {
  83159. strm->msg = (char *)"invalid distance too far back";
  83160. state->mode = BAD;
  83161. break;
  83162. }
  83163. from = window - OFF;
  83164. if (write == 0) { /* very common case */
  83165. from += wsize - op;
  83166. if (op < len) { /* some from window */
  83167. len -= op;
  83168. do {
  83169. PUP(out) = PUP(from);
  83170. } while (--op);
  83171. from = out - dist; /* rest from output */
  83172. }
  83173. }
  83174. else if (write < op) { /* wrap around window */
  83175. from += wsize + write - op;
  83176. op -= write;
  83177. if (op < len) { /* some from end of window */
  83178. len -= op;
  83179. do {
  83180. PUP(out) = PUP(from);
  83181. } while (--op);
  83182. from = window - OFF;
  83183. if (write < len) { /* some from start of window */
  83184. op = write;
  83185. len -= op;
  83186. do {
  83187. PUP(out) = PUP(from);
  83188. } while (--op);
  83189. from = out - dist; /* rest from output */
  83190. }
  83191. }
  83192. }
  83193. else { /* contiguous in window */
  83194. from += write - op;
  83195. if (op < len) { /* some from window */
  83196. len -= op;
  83197. do {
  83198. PUP(out) = PUP(from);
  83199. } while (--op);
  83200. from = out - dist; /* rest from output */
  83201. }
  83202. }
  83203. while (len > 2) {
  83204. PUP(out) = PUP(from);
  83205. PUP(out) = PUP(from);
  83206. PUP(out) = PUP(from);
  83207. len -= 3;
  83208. }
  83209. if (len) {
  83210. PUP(out) = PUP(from);
  83211. if (len > 1)
  83212. PUP(out) = PUP(from);
  83213. }
  83214. }
  83215. else {
  83216. from = out - dist; /* copy direct from output */
  83217. do { /* minimum length is three */
  83218. PUP(out) = PUP(from);
  83219. PUP(out) = PUP(from);
  83220. PUP(out) = PUP(from);
  83221. len -= 3;
  83222. } while (len > 2);
  83223. if (len) {
  83224. PUP(out) = PUP(from);
  83225. if (len > 1)
  83226. PUP(out) = PUP(from);
  83227. }
  83228. }
  83229. }
  83230. else if ((op & 64) == 0) { /* 2nd level distance code */
  83231. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83232. goto dodist;
  83233. }
  83234. else {
  83235. strm->msg = (char *)"invalid distance code";
  83236. state->mode = BAD;
  83237. break;
  83238. }
  83239. }
  83240. else if ((op & 64) == 0) { /* 2nd level length code */
  83241. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83242. goto dolen;
  83243. }
  83244. else if (op & 32) { /* end-of-block */
  83245. Tracevv((stderr, "inflate: end of block\n"));
  83246. state->mode = TYPE;
  83247. break;
  83248. }
  83249. else {
  83250. strm->msg = (char *)"invalid literal/length code";
  83251. state->mode = BAD;
  83252. break;
  83253. }
  83254. } while (in < last && out < end);
  83255. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83256. len = bits >> 3;
  83257. in -= len;
  83258. bits -= len << 3;
  83259. hold &= (1U << bits) - 1;
  83260. /* update state and return */
  83261. strm->next_in = in + OFF;
  83262. strm->next_out = out + OFF;
  83263. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83264. strm->avail_out = (unsigned)(out < end ?
  83265. 257 + (end - out) : 257 - (out - end));
  83266. state->hold = hold;
  83267. state->bits = bits;
  83268. return;
  83269. }
  83270. /*
  83271. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83272. - Using bit fields for code structure
  83273. - Different op definition to avoid & for extra bits (do & for table bits)
  83274. - Three separate decoding do-loops for direct, window, and write == 0
  83275. - Special case for distance > 1 copies to do overlapped load and store copy
  83276. - Explicit branch predictions (based on measured branch probabilities)
  83277. - Deferring match copy and interspersed it with decoding subsequent codes
  83278. - Swapping literal/length else
  83279. - Swapping window/direct else
  83280. - Larger unrolled copy loops (three is about right)
  83281. - Moving len -= 3 statement into middle of loop
  83282. */
  83283. #endif /* !ASMINF */
  83284. /*** End of inlined file: inffast.c ***/
  83285. #undef PULLBYTE
  83286. #undef LOAD
  83287. #undef RESTORE
  83288. #undef INITBITS
  83289. #undef NEEDBITS
  83290. #undef DROPBITS
  83291. #undef BYTEBITS
  83292. /*** Start of inlined file: inflate.c ***/
  83293. /*
  83294. * Change history:
  83295. *
  83296. * 1.2.beta0 24 Nov 2002
  83297. * - First version -- complete rewrite of inflate to simplify code, avoid
  83298. * creation of window when not needed, minimize use of window when it is
  83299. * needed, make inffast.c even faster, implement gzip decoding, and to
  83300. * improve code readability and style over the previous zlib inflate code
  83301. *
  83302. * 1.2.beta1 25 Nov 2002
  83303. * - Use pointers for available input and output checking in inffast.c
  83304. * - Remove input and output counters in inffast.c
  83305. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83306. * - Remove unnecessary second byte pull from length extra in inffast.c
  83307. * - Unroll direct copy to three copies per loop in inffast.c
  83308. *
  83309. * 1.2.beta2 4 Dec 2002
  83310. * - Change external routine names to reduce potential conflicts
  83311. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83312. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83313. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83314. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83315. *
  83316. * 1.2.beta3 22 Dec 2002
  83317. * - Add comments on state->bits assertion in inffast.c
  83318. * - Add comments on op field in inftrees.h
  83319. * - Fix bug in reuse of allocated window after inflateReset()
  83320. * - Remove bit fields--back to byte structure for speed
  83321. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83322. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83323. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83324. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83325. * - Use local copies of stream next and avail values, as well as local bit
  83326. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83327. *
  83328. * 1.2.beta4 1 Jan 2003
  83329. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83330. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83331. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83332. * - Rearrange window copies in inflate_fast() for speed and simplification
  83333. * - Unroll last copy for window match in inflate_fast()
  83334. * - Use local copies of window variables in inflate_fast() for speed
  83335. * - Pull out common write == 0 case for speed in inflate_fast()
  83336. * - Make op and len in inflate_fast() unsigned for consistency
  83337. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83338. * - Simplified bad distance check in inflate_fast()
  83339. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83340. * source file infback.c to provide a call-back interface to inflate for
  83341. * programs like gzip and unzip -- uses window as output buffer to avoid
  83342. * window copying
  83343. *
  83344. * 1.2.beta5 1 Jan 2003
  83345. * - Improved inflateBack() interface to allow the caller to provide initial
  83346. * input in strm.
  83347. * - Fixed stored blocks bug in inflateBack()
  83348. *
  83349. * 1.2.beta6 4 Jan 2003
  83350. * - Added comments in inffast.c on effectiveness of POSTINC
  83351. * - Typecasting all around to reduce compiler warnings
  83352. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83353. * make compilers happy
  83354. * - Changed type of window in inflateBackInit() to unsigned char *
  83355. *
  83356. * 1.2.beta7 27 Jan 2003
  83357. * - Changed many types to unsigned or unsigned short to avoid warnings
  83358. * - Added inflateCopy() function
  83359. *
  83360. * 1.2.0 9 Mar 2003
  83361. * - Changed inflateBack() interface to provide separate opaque descriptors
  83362. * for the in() and out() functions
  83363. * - Changed inflateBack() argument and in_func typedef to swap the length
  83364. * and buffer address return values for the input function
  83365. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83366. *
  83367. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83368. */
  83369. /*** Start of inlined file: inffast.h ***/
  83370. /* WARNING: this file should *not* be used by applications. It is
  83371. part of the implementation of the compression library and is
  83372. subject to change. Applications should only use zlib.h.
  83373. */
  83374. void inflate_fast OF((z_streamp strm, unsigned start));
  83375. /*** End of inlined file: inffast.h ***/
  83376. #ifdef MAKEFIXED
  83377. # ifndef BUILDFIXED
  83378. # define BUILDFIXED
  83379. # endif
  83380. #endif
  83381. /* function prototypes */
  83382. local void fixedtables OF((struct inflate_state FAR *state));
  83383. local int updatewindow OF((z_streamp strm, unsigned out));
  83384. #ifdef BUILDFIXED
  83385. void makefixed OF((void));
  83386. #endif
  83387. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83388. unsigned len));
  83389. int ZEXPORT inflateReset (z_streamp strm)
  83390. {
  83391. struct inflate_state FAR *state;
  83392. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83393. state = (struct inflate_state FAR *)strm->state;
  83394. strm->total_in = strm->total_out = state->total = 0;
  83395. strm->msg = Z_NULL;
  83396. strm->adler = 1; /* to support ill-conceived Java test suite */
  83397. state->mode = HEAD;
  83398. state->last = 0;
  83399. state->havedict = 0;
  83400. state->dmax = 32768U;
  83401. state->head = Z_NULL;
  83402. state->wsize = 0;
  83403. state->whave = 0;
  83404. state->write = 0;
  83405. state->hold = 0;
  83406. state->bits = 0;
  83407. state->lencode = state->distcode = state->next = state->codes;
  83408. Tracev((stderr, "inflate: reset\n"));
  83409. return Z_OK;
  83410. }
  83411. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83412. {
  83413. struct inflate_state FAR *state;
  83414. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83415. state = (struct inflate_state FAR *)strm->state;
  83416. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83417. value &= (1L << bits) - 1;
  83418. state->hold += value << state->bits;
  83419. state->bits += bits;
  83420. return Z_OK;
  83421. }
  83422. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83423. {
  83424. struct inflate_state FAR *state;
  83425. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83426. stream_size != (int)(sizeof(z_stream)))
  83427. return Z_VERSION_ERROR;
  83428. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83429. strm->msg = Z_NULL; /* in case we return an error */
  83430. if (strm->zalloc == (alloc_func)0) {
  83431. strm->zalloc = zcalloc;
  83432. strm->opaque = (voidpf)0;
  83433. }
  83434. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83435. state = (struct inflate_state FAR *)
  83436. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83437. if (state == Z_NULL) return Z_MEM_ERROR;
  83438. Tracev((stderr, "inflate: allocated\n"));
  83439. strm->state = (struct internal_state FAR *)state;
  83440. if (windowBits < 0) {
  83441. state->wrap = 0;
  83442. windowBits = -windowBits;
  83443. }
  83444. else {
  83445. state->wrap = (windowBits >> 4) + 1;
  83446. #ifdef GUNZIP
  83447. if (windowBits < 48) windowBits &= 15;
  83448. #endif
  83449. }
  83450. if (windowBits < 8 || windowBits > 15) {
  83451. ZFREE(strm, state);
  83452. strm->state = Z_NULL;
  83453. return Z_STREAM_ERROR;
  83454. }
  83455. state->wbits = (unsigned)windowBits;
  83456. state->window = Z_NULL;
  83457. return inflateReset(strm);
  83458. }
  83459. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83460. {
  83461. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83462. }
  83463. /*
  83464. Return state with length and distance decoding tables and index sizes set to
  83465. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83466. If BUILDFIXED is defined, then instead this routine builds the tables the
  83467. first time it's called, and returns those tables the first time and
  83468. thereafter. This reduces the size of the code by about 2K bytes, in
  83469. exchange for a little execution time. However, BUILDFIXED should not be
  83470. used for threaded applications, since the rewriting of the tables and virgin
  83471. may not be thread-safe.
  83472. */
  83473. local void fixedtables (struct inflate_state FAR *state)
  83474. {
  83475. #ifdef BUILDFIXED
  83476. static int virgin = 1;
  83477. static code *lenfix, *distfix;
  83478. static code fixed[544];
  83479. /* build fixed huffman tables if first call (may not be thread safe) */
  83480. if (virgin) {
  83481. unsigned sym, bits;
  83482. static code *next;
  83483. /* literal/length table */
  83484. sym = 0;
  83485. while (sym < 144) state->lens[sym++] = 8;
  83486. while (sym < 256) state->lens[sym++] = 9;
  83487. while (sym < 280) state->lens[sym++] = 7;
  83488. while (sym < 288) state->lens[sym++] = 8;
  83489. next = fixed;
  83490. lenfix = next;
  83491. bits = 9;
  83492. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83493. /* distance table */
  83494. sym = 0;
  83495. while (sym < 32) state->lens[sym++] = 5;
  83496. distfix = next;
  83497. bits = 5;
  83498. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83499. /* do this just once */
  83500. virgin = 0;
  83501. }
  83502. #else /* !BUILDFIXED */
  83503. /*** Start of inlined file: inffixed.h ***/
  83504. /* WARNING: this file should *not* be used by applications. It
  83505. is part of the implementation of the compression library and
  83506. is subject to change. Applications should only use zlib.h.
  83507. */
  83508. static const code lenfix[512] = {
  83509. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83510. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83511. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83512. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83513. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83514. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83515. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83516. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83517. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83518. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83519. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83520. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83521. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83522. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83523. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83524. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83525. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83526. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83527. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83528. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83529. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83530. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83531. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83532. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83533. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83534. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83535. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83536. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83537. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83538. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83539. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83540. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83541. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83542. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83543. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83544. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83545. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83546. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83547. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83548. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83549. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83550. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83551. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83552. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83553. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83554. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83555. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83556. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83557. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83558. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83559. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83560. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83561. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83562. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83563. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83564. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83565. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83566. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83567. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83568. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83569. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83570. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83571. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83572. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83573. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83574. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83575. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83576. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83577. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83578. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83579. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83580. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83581. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83582. {0,9,255}
  83583. };
  83584. static const code distfix[32] = {
  83585. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83586. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83587. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83588. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83589. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83590. {22,5,193},{64,5,0}
  83591. };
  83592. /*** End of inlined file: inffixed.h ***/
  83593. #endif /* BUILDFIXED */
  83594. state->lencode = lenfix;
  83595. state->lenbits = 9;
  83596. state->distcode = distfix;
  83597. state->distbits = 5;
  83598. }
  83599. #ifdef MAKEFIXED
  83600. #include <stdio.h>
  83601. /*
  83602. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83603. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83604. those tables to stdout, which would be piped to inffixed.h. A small program
  83605. can simply call makefixed to do this:
  83606. void makefixed(void);
  83607. int main(void)
  83608. {
  83609. makefixed();
  83610. return 0;
  83611. }
  83612. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83613. a.out > inffixed.h
  83614. */
  83615. void makefixed()
  83616. {
  83617. unsigned low, size;
  83618. struct inflate_state state;
  83619. fixedtables(&state);
  83620. puts(" /* inffixed.h -- table for decoding fixed codes");
  83621. puts(" * Generated automatically by makefixed().");
  83622. puts(" */");
  83623. puts("");
  83624. puts(" /* WARNING: this file should *not* be used by applications.");
  83625. puts(" It is part of the implementation of this library and is");
  83626. puts(" subject to change. Applications should only use zlib.h.");
  83627. puts(" */");
  83628. puts("");
  83629. size = 1U << 9;
  83630. printf(" static const code lenfix[%u] = {", size);
  83631. low = 0;
  83632. for (;;) {
  83633. if ((low % 7) == 0) printf("\n ");
  83634. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83635. state.lencode[low].val);
  83636. if (++low == size) break;
  83637. putchar(',');
  83638. }
  83639. puts("\n };");
  83640. size = 1U << 5;
  83641. printf("\n static const code distfix[%u] = {", size);
  83642. low = 0;
  83643. for (;;) {
  83644. if ((low % 6) == 0) printf("\n ");
  83645. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83646. state.distcode[low].val);
  83647. if (++low == size) break;
  83648. putchar(',');
  83649. }
  83650. puts("\n };");
  83651. }
  83652. #endif /* MAKEFIXED */
  83653. /*
  83654. Update the window with the last wsize (normally 32K) bytes written before
  83655. returning. If window does not exist yet, create it. This is only called
  83656. when a window is already in use, or when output has been written during this
  83657. inflate call, but the end of the deflate stream has not been reached yet.
  83658. It is also called to create a window for dictionary data when a dictionary
  83659. is loaded.
  83660. Providing output buffers larger than 32K to inflate() should provide a speed
  83661. advantage, since only the last 32K of output is copied to the sliding window
  83662. upon return from inflate(), and since all distances after the first 32K of
  83663. output will fall in the output data, making match copies simpler and faster.
  83664. The advantage may be dependent on the size of the processor's data caches.
  83665. */
  83666. local int updatewindow (z_streamp strm, unsigned out)
  83667. {
  83668. struct inflate_state FAR *state;
  83669. unsigned copy, dist;
  83670. state = (struct inflate_state FAR *)strm->state;
  83671. /* if it hasn't been done already, allocate space for the window */
  83672. if (state->window == Z_NULL) {
  83673. state->window = (unsigned char FAR *)
  83674. ZALLOC(strm, 1U << state->wbits,
  83675. sizeof(unsigned char));
  83676. if (state->window == Z_NULL) return 1;
  83677. }
  83678. /* if window not in use yet, initialize */
  83679. if (state->wsize == 0) {
  83680. state->wsize = 1U << state->wbits;
  83681. state->write = 0;
  83682. state->whave = 0;
  83683. }
  83684. /* copy state->wsize or less output bytes into the circular window */
  83685. copy = out - strm->avail_out;
  83686. if (copy >= state->wsize) {
  83687. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83688. state->write = 0;
  83689. state->whave = state->wsize;
  83690. }
  83691. else {
  83692. dist = state->wsize - state->write;
  83693. if (dist > copy) dist = copy;
  83694. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83695. copy -= dist;
  83696. if (copy) {
  83697. zmemcpy(state->window, strm->next_out - copy, copy);
  83698. state->write = copy;
  83699. state->whave = state->wsize;
  83700. }
  83701. else {
  83702. state->write += dist;
  83703. if (state->write == state->wsize) state->write = 0;
  83704. if (state->whave < state->wsize) state->whave += dist;
  83705. }
  83706. }
  83707. return 0;
  83708. }
  83709. /* Macros for inflate(): */
  83710. /* check function to use adler32() for zlib or crc32() for gzip */
  83711. #ifdef GUNZIP
  83712. # define UPDATE(check, buf, len) \
  83713. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83714. #else
  83715. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83716. #endif
  83717. /* check macros for header crc */
  83718. #ifdef GUNZIP
  83719. # define CRC2(check, word) \
  83720. do { \
  83721. hbuf[0] = (unsigned char)(word); \
  83722. hbuf[1] = (unsigned char)((word) >> 8); \
  83723. check = crc32(check, hbuf, 2); \
  83724. } while (0)
  83725. # define CRC4(check, word) \
  83726. do { \
  83727. hbuf[0] = (unsigned char)(word); \
  83728. hbuf[1] = (unsigned char)((word) >> 8); \
  83729. hbuf[2] = (unsigned char)((word) >> 16); \
  83730. hbuf[3] = (unsigned char)((word) >> 24); \
  83731. check = crc32(check, hbuf, 4); \
  83732. } while (0)
  83733. #endif
  83734. /* Load registers with state in inflate() for speed */
  83735. #define LOAD() \
  83736. do { \
  83737. put = strm->next_out; \
  83738. left = strm->avail_out; \
  83739. next = strm->next_in; \
  83740. have = strm->avail_in; \
  83741. hold = state->hold; \
  83742. bits = state->bits; \
  83743. } while (0)
  83744. /* Restore state from registers in inflate() */
  83745. #define RESTORE() \
  83746. do { \
  83747. strm->next_out = put; \
  83748. strm->avail_out = left; \
  83749. strm->next_in = next; \
  83750. strm->avail_in = have; \
  83751. state->hold = hold; \
  83752. state->bits = bits; \
  83753. } while (0)
  83754. /* Clear the input bit accumulator */
  83755. #define INITBITS() \
  83756. do { \
  83757. hold = 0; \
  83758. bits = 0; \
  83759. } while (0)
  83760. /* Get a byte of input into the bit accumulator, or return from inflate()
  83761. if there is no input available. */
  83762. #define PULLBYTE() \
  83763. do { \
  83764. if (have == 0) goto inf_leave; \
  83765. have--; \
  83766. hold += (unsigned long)(*next++) << bits; \
  83767. bits += 8; \
  83768. } while (0)
  83769. /* Assure that there are at least n bits in the bit accumulator. If there is
  83770. not enough available input to do that, then return from inflate(). */
  83771. #define NEEDBITS(n) \
  83772. do { \
  83773. while (bits < (unsigned)(n)) \
  83774. PULLBYTE(); \
  83775. } while (0)
  83776. /* Return the low n bits of the bit accumulator (n < 16) */
  83777. #define BITS(n) \
  83778. ((unsigned)hold & ((1U << (n)) - 1))
  83779. /* Remove n bits from the bit accumulator */
  83780. #define DROPBITS(n) \
  83781. do { \
  83782. hold >>= (n); \
  83783. bits -= (unsigned)(n); \
  83784. } while (0)
  83785. /* Remove zero to seven bits as needed to go to a byte boundary */
  83786. #define BYTEBITS() \
  83787. do { \
  83788. hold >>= bits & 7; \
  83789. bits -= bits & 7; \
  83790. } while (0)
  83791. /* Reverse the bytes in a 32-bit value */
  83792. #define REVERSE(q) \
  83793. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83794. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83795. /*
  83796. inflate() uses a state machine to process as much input data and generate as
  83797. much output data as possible before returning. The state machine is
  83798. structured roughly as follows:
  83799. for (;;) switch (state) {
  83800. ...
  83801. case STATEn:
  83802. if (not enough input data or output space to make progress)
  83803. return;
  83804. ... make progress ...
  83805. state = STATEm;
  83806. break;
  83807. ...
  83808. }
  83809. so when inflate() is called again, the same case is attempted again, and
  83810. if the appropriate resources are provided, the machine proceeds to the
  83811. next state. The NEEDBITS() macro is usually the way the state evaluates
  83812. whether it can proceed or should return. NEEDBITS() does the return if
  83813. the requested bits are not available. The typical use of the BITS macros
  83814. is:
  83815. NEEDBITS(n);
  83816. ... do something with BITS(n) ...
  83817. DROPBITS(n);
  83818. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83819. input left to load n bits into the accumulator, or it continues. BITS(n)
  83820. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83821. the low n bits off the accumulator. INITBITS() clears the accumulator
  83822. and sets the number of available bits to zero. BYTEBITS() discards just
  83823. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83824. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83825. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83826. if there is no input available. The decoding of variable length codes uses
  83827. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83828. code, and no more.
  83829. Some states loop until they get enough input, making sure that enough
  83830. state information is maintained to continue the loop where it left off
  83831. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83832. would all have to actually be part of the saved state in case NEEDBITS()
  83833. returns:
  83834. case STATEw:
  83835. while (want < need) {
  83836. NEEDBITS(n);
  83837. keep[want++] = BITS(n);
  83838. DROPBITS(n);
  83839. }
  83840. state = STATEx;
  83841. case STATEx:
  83842. As shown above, if the next state is also the next case, then the break
  83843. is omitted.
  83844. A state may also return if there is not enough output space available to
  83845. complete that state. Those states are copying stored data, writing a
  83846. literal byte, and copying a matching string.
  83847. When returning, a "goto inf_leave" is used to update the total counters,
  83848. update the check value, and determine whether any progress has been made
  83849. during that inflate() call in order to return the proper return code.
  83850. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83851. When there is a window, goto inf_leave will update the window with the last
  83852. output written. If a goto inf_leave occurs in the middle of decompression
  83853. and there is no window currently, goto inf_leave will create one and copy
  83854. output to the window for the next call of inflate().
  83855. In this implementation, the flush parameter of inflate() only affects the
  83856. return code (per zlib.h). inflate() always writes as much as possible to
  83857. strm->next_out, given the space available and the provided input--the effect
  83858. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83859. the allocation of and copying into a sliding window until necessary, which
  83860. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83861. stream available. So the only thing the flush parameter actually does is:
  83862. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83863. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83864. */
  83865. int ZEXPORT inflate (z_streamp strm, int flush)
  83866. {
  83867. struct inflate_state FAR *state;
  83868. unsigned char FAR *next; /* next input */
  83869. unsigned char FAR *put; /* next output */
  83870. unsigned have, left; /* available input and output */
  83871. unsigned long hold; /* bit buffer */
  83872. unsigned bits; /* bits in bit buffer */
  83873. unsigned in, out; /* save starting available input and output */
  83874. unsigned copy; /* number of stored or match bytes to copy */
  83875. unsigned char FAR *from; /* where to copy match bytes from */
  83876. code thisx; /* current decoding table entry */
  83877. code last; /* parent table entry */
  83878. unsigned len; /* length to copy for repeats, bits to drop */
  83879. int ret; /* return code */
  83880. #ifdef GUNZIP
  83881. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83882. #endif
  83883. static const unsigned short order[19] = /* permutation of code lengths */
  83884. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83885. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83886. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83887. return Z_STREAM_ERROR;
  83888. state = (struct inflate_state FAR *)strm->state;
  83889. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83890. LOAD();
  83891. in = have;
  83892. out = left;
  83893. ret = Z_OK;
  83894. for (;;)
  83895. switch (state->mode) {
  83896. case HEAD:
  83897. if (state->wrap == 0) {
  83898. state->mode = TYPEDO;
  83899. break;
  83900. }
  83901. NEEDBITS(16);
  83902. #ifdef GUNZIP
  83903. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83904. state->check = crc32(0L, Z_NULL, 0);
  83905. CRC2(state->check, hold);
  83906. INITBITS();
  83907. state->mode = FLAGS;
  83908. break;
  83909. }
  83910. state->flags = 0; /* expect zlib header */
  83911. if (state->head != Z_NULL)
  83912. state->head->done = -1;
  83913. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83914. #else
  83915. if (
  83916. #endif
  83917. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83918. strm->msg = (char *)"incorrect header check";
  83919. state->mode = BAD;
  83920. break;
  83921. }
  83922. if (BITS(4) != Z_DEFLATED) {
  83923. strm->msg = (char *)"unknown compression method";
  83924. state->mode = BAD;
  83925. break;
  83926. }
  83927. DROPBITS(4);
  83928. len = BITS(4) + 8;
  83929. if (len > state->wbits) {
  83930. strm->msg = (char *)"invalid window size";
  83931. state->mode = BAD;
  83932. break;
  83933. }
  83934. state->dmax = 1U << len;
  83935. Tracev((stderr, "inflate: zlib header ok\n"));
  83936. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83937. state->mode = hold & 0x200 ? DICTID : TYPE;
  83938. INITBITS();
  83939. break;
  83940. #ifdef GUNZIP
  83941. case FLAGS:
  83942. NEEDBITS(16);
  83943. state->flags = (int)(hold);
  83944. if ((state->flags & 0xff) != Z_DEFLATED) {
  83945. strm->msg = (char *)"unknown compression method";
  83946. state->mode = BAD;
  83947. break;
  83948. }
  83949. if (state->flags & 0xe000) {
  83950. strm->msg = (char *)"unknown header flags set";
  83951. state->mode = BAD;
  83952. break;
  83953. }
  83954. if (state->head != Z_NULL)
  83955. state->head->text = (int)((hold >> 8) & 1);
  83956. if (state->flags & 0x0200) CRC2(state->check, hold);
  83957. INITBITS();
  83958. state->mode = TIME;
  83959. case TIME:
  83960. NEEDBITS(32);
  83961. if (state->head != Z_NULL)
  83962. state->head->time = hold;
  83963. if (state->flags & 0x0200) CRC4(state->check, hold);
  83964. INITBITS();
  83965. state->mode = OS;
  83966. case OS:
  83967. NEEDBITS(16);
  83968. if (state->head != Z_NULL) {
  83969. state->head->xflags = (int)(hold & 0xff);
  83970. state->head->os = (int)(hold >> 8);
  83971. }
  83972. if (state->flags & 0x0200) CRC2(state->check, hold);
  83973. INITBITS();
  83974. state->mode = EXLEN;
  83975. case EXLEN:
  83976. if (state->flags & 0x0400) {
  83977. NEEDBITS(16);
  83978. state->length = (unsigned)(hold);
  83979. if (state->head != Z_NULL)
  83980. state->head->extra_len = (unsigned)hold;
  83981. if (state->flags & 0x0200) CRC2(state->check, hold);
  83982. INITBITS();
  83983. }
  83984. else if (state->head != Z_NULL)
  83985. state->head->extra = Z_NULL;
  83986. state->mode = EXTRA;
  83987. case EXTRA:
  83988. if (state->flags & 0x0400) {
  83989. copy = state->length;
  83990. if (copy > have) copy = have;
  83991. if (copy) {
  83992. if (state->head != Z_NULL &&
  83993. state->head->extra != Z_NULL) {
  83994. len = state->head->extra_len - state->length;
  83995. zmemcpy(state->head->extra + len, next,
  83996. len + copy > state->head->extra_max ?
  83997. state->head->extra_max - len : copy);
  83998. }
  83999. if (state->flags & 0x0200)
  84000. state->check = crc32(state->check, next, copy);
  84001. have -= copy;
  84002. next += copy;
  84003. state->length -= copy;
  84004. }
  84005. if (state->length) goto inf_leave;
  84006. }
  84007. state->length = 0;
  84008. state->mode = NAME;
  84009. case NAME:
  84010. if (state->flags & 0x0800) {
  84011. if (have == 0) goto inf_leave;
  84012. copy = 0;
  84013. do {
  84014. len = (unsigned)(next[copy++]);
  84015. if (state->head != Z_NULL &&
  84016. state->head->name != Z_NULL &&
  84017. state->length < state->head->name_max)
  84018. state->head->name[state->length++] = len;
  84019. } while (len && copy < have);
  84020. if (state->flags & 0x0200)
  84021. state->check = crc32(state->check, next, copy);
  84022. have -= copy;
  84023. next += copy;
  84024. if (len) goto inf_leave;
  84025. }
  84026. else if (state->head != Z_NULL)
  84027. state->head->name = Z_NULL;
  84028. state->length = 0;
  84029. state->mode = COMMENT;
  84030. case COMMENT:
  84031. if (state->flags & 0x1000) {
  84032. if (have == 0) goto inf_leave;
  84033. copy = 0;
  84034. do {
  84035. len = (unsigned)(next[copy++]);
  84036. if (state->head != Z_NULL &&
  84037. state->head->comment != Z_NULL &&
  84038. state->length < state->head->comm_max)
  84039. state->head->comment[state->length++] = len;
  84040. } while (len && copy < have);
  84041. if (state->flags & 0x0200)
  84042. state->check = crc32(state->check, next, copy);
  84043. have -= copy;
  84044. next += copy;
  84045. if (len) goto inf_leave;
  84046. }
  84047. else if (state->head != Z_NULL)
  84048. state->head->comment = Z_NULL;
  84049. state->mode = HCRC;
  84050. case HCRC:
  84051. if (state->flags & 0x0200) {
  84052. NEEDBITS(16);
  84053. if (hold != (state->check & 0xffff)) {
  84054. strm->msg = (char *)"header crc mismatch";
  84055. state->mode = BAD;
  84056. break;
  84057. }
  84058. INITBITS();
  84059. }
  84060. if (state->head != Z_NULL) {
  84061. state->head->hcrc = (int)((state->flags >> 9) & 1);
  84062. state->head->done = 1;
  84063. }
  84064. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  84065. state->mode = TYPE;
  84066. break;
  84067. #endif
  84068. case DICTID:
  84069. NEEDBITS(32);
  84070. strm->adler = state->check = REVERSE(hold);
  84071. INITBITS();
  84072. state->mode = DICT;
  84073. case DICT:
  84074. if (state->havedict == 0) {
  84075. RESTORE();
  84076. return Z_NEED_DICT;
  84077. }
  84078. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  84079. state->mode = TYPE;
  84080. case TYPE:
  84081. if (flush == Z_BLOCK) goto inf_leave;
  84082. case TYPEDO:
  84083. if (state->last) {
  84084. BYTEBITS();
  84085. state->mode = CHECK;
  84086. break;
  84087. }
  84088. NEEDBITS(3);
  84089. state->last = BITS(1);
  84090. DROPBITS(1);
  84091. switch (BITS(2)) {
  84092. case 0: /* stored block */
  84093. Tracev((stderr, "inflate: stored block%s\n",
  84094. state->last ? " (last)" : ""));
  84095. state->mode = STORED;
  84096. break;
  84097. case 1: /* fixed block */
  84098. fixedtables(state);
  84099. Tracev((stderr, "inflate: fixed codes block%s\n",
  84100. state->last ? " (last)" : ""));
  84101. state->mode = LEN; /* decode codes */
  84102. break;
  84103. case 2: /* dynamic block */
  84104. Tracev((stderr, "inflate: dynamic codes block%s\n",
  84105. state->last ? " (last)" : ""));
  84106. state->mode = TABLE;
  84107. break;
  84108. case 3:
  84109. strm->msg = (char *)"invalid block type";
  84110. state->mode = BAD;
  84111. }
  84112. DROPBITS(2);
  84113. break;
  84114. case STORED:
  84115. BYTEBITS(); /* go to byte boundary */
  84116. NEEDBITS(32);
  84117. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  84118. strm->msg = (char *)"invalid stored block lengths";
  84119. state->mode = BAD;
  84120. break;
  84121. }
  84122. state->length = (unsigned)hold & 0xffff;
  84123. Tracev((stderr, "inflate: stored length %u\n",
  84124. state->length));
  84125. INITBITS();
  84126. state->mode = COPY;
  84127. case COPY:
  84128. copy = state->length;
  84129. if (copy) {
  84130. if (copy > have) copy = have;
  84131. if (copy > left) copy = left;
  84132. if (copy == 0) goto inf_leave;
  84133. zmemcpy(put, next, copy);
  84134. have -= copy;
  84135. next += copy;
  84136. left -= copy;
  84137. put += copy;
  84138. state->length -= copy;
  84139. break;
  84140. }
  84141. Tracev((stderr, "inflate: stored end\n"));
  84142. state->mode = TYPE;
  84143. break;
  84144. case TABLE:
  84145. NEEDBITS(14);
  84146. state->nlen = BITS(5) + 257;
  84147. DROPBITS(5);
  84148. state->ndist = BITS(5) + 1;
  84149. DROPBITS(5);
  84150. state->ncode = BITS(4) + 4;
  84151. DROPBITS(4);
  84152. #ifndef PKZIP_BUG_WORKAROUND
  84153. if (state->nlen > 286 || state->ndist > 30) {
  84154. strm->msg = (char *)"too many length or distance symbols";
  84155. state->mode = BAD;
  84156. break;
  84157. }
  84158. #endif
  84159. Tracev((stderr, "inflate: table sizes ok\n"));
  84160. state->have = 0;
  84161. state->mode = LENLENS;
  84162. case LENLENS:
  84163. while (state->have < state->ncode) {
  84164. NEEDBITS(3);
  84165. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84166. DROPBITS(3);
  84167. }
  84168. while (state->have < 19)
  84169. state->lens[order[state->have++]] = 0;
  84170. state->next = state->codes;
  84171. state->lencode = (code const FAR *)(state->next);
  84172. state->lenbits = 7;
  84173. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84174. &(state->lenbits), state->work);
  84175. if (ret) {
  84176. strm->msg = (char *)"invalid code lengths set";
  84177. state->mode = BAD;
  84178. break;
  84179. }
  84180. Tracev((stderr, "inflate: code lengths ok\n"));
  84181. state->have = 0;
  84182. state->mode = CODELENS;
  84183. case CODELENS:
  84184. while (state->have < state->nlen + state->ndist) {
  84185. for (;;) {
  84186. thisx = state->lencode[BITS(state->lenbits)];
  84187. if ((unsigned)(thisx.bits) <= bits) break;
  84188. PULLBYTE();
  84189. }
  84190. if (thisx.val < 16) {
  84191. NEEDBITS(thisx.bits);
  84192. DROPBITS(thisx.bits);
  84193. state->lens[state->have++] = thisx.val;
  84194. }
  84195. else {
  84196. if (thisx.val == 16) {
  84197. NEEDBITS(thisx.bits + 2);
  84198. DROPBITS(thisx.bits);
  84199. if (state->have == 0) {
  84200. strm->msg = (char *)"invalid bit length repeat";
  84201. state->mode = BAD;
  84202. break;
  84203. }
  84204. len = state->lens[state->have - 1];
  84205. copy = 3 + BITS(2);
  84206. DROPBITS(2);
  84207. }
  84208. else if (thisx.val == 17) {
  84209. NEEDBITS(thisx.bits + 3);
  84210. DROPBITS(thisx.bits);
  84211. len = 0;
  84212. copy = 3 + BITS(3);
  84213. DROPBITS(3);
  84214. }
  84215. else {
  84216. NEEDBITS(thisx.bits + 7);
  84217. DROPBITS(thisx.bits);
  84218. len = 0;
  84219. copy = 11 + BITS(7);
  84220. DROPBITS(7);
  84221. }
  84222. if (state->have + copy > state->nlen + state->ndist) {
  84223. strm->msg = (char *)"invalid bit length repeat";
  84224. state->mode = BAD;
  84225. break;
  84226. }
  84227. while (copy--)
  84228. state->lens[state->have++] = (unsigned short)len;
  84229. }
  84230. }
  84231. /* handle error breaks in while */
  84232. if (state->mode == BAD) break;
  84233. /* build code tables */
  84234. state->next = state->codes;
  84235. state->lencode = (code const FAR *)(state->next);
  84236. state->lenbits = 9;
  84237. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84238. &(state->lenbits), state->work);
  84239. if (ret) {
  84240. strm->msg = (char *)"invalid literal/lengths set";
  84241. state->mode = BAD;
  84242. break;
  84243. }
  84244. state->distcode = (code const FAR *)(state->next);
  84245. state->distbits = 6;
  84246. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84247. &(state->next), &(state->distbits), state->work);
  84248. if (ret) {
  84249. strm->msg = (char *)"invalid distances set";
  84250. state->mode = BAD;
  84251. break;
  84252. }
  84253. Tracev((stderr, "inflate: codes ok\n"));
  84254. state->mode = LEN;
  84255. case LEN:
  84256. if (have >= 6 && left >= 258) {
  84257. RESTORE();
  84258. inflate_fast(strm, out);
  84259. LOAD();
  84260. break;
  84261. }
  84262. for (;;) {
  84263. thisx = state->lencode[BITS(state->lenbits)];
  84264. if ((unsigned)(thisx.bits) <= bits) break;
  84265. PULLBYTE();
  84266. }
  84267. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84268. last = thisx;
  84269. for (;;) {
  84270. thisx = state->lencode[last.val +
  84271. (BITS(last.bits + last.op) >> last.bits)];
  84272. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84273. PULLBYTE();
  84274. }
  84275. DROPBITS(last.bits);
  84276. }
  84277. DROPBITS(thisx.bits);
  84278. state->length = (unsigned)thisx.val;
  84279. if ((int)(thisx.op) == 0) {
  84280. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84281. "inflate: literal '%c'\n" :
  84282. "inflate: literal 0x%02x\n", thisx.val));
  84283. state->mode = LIT;
  84284. break;
  84285. }
  84286. if (thisx.op & 32) {
  84287. Tracevv((stderr, "inflate: end of block\n"));
  84288. state->mode = TYPE;
  84289. break;
  84290. }
  84291. if (thisx.op & 64) {
  84292. strm->msg = (char *)"invalid literal/length code";
  84293. state->mode = BAD;
  84294. break;
  84295. }
  84296. state->extra = (unsigned)(thisx.op) & 15;
  84297. state->mode = LENEXT;
  84298. case LENEXT:
  84299. if (state->extra) {
  84300. NEEDBITS(state->extra);
  84301. state->length += BITS(state->extra);
  84302. DROPBITS(state->extra);
  84303. }
  84304. Tracevv((stderr, "inflate: length %u\n", state->length));
  84305. state->mode = DIST;
  84306. case DIST:
  84307. for (;;) {
  84308. thisx = state->distcode[BITS(state->distbits)];
  84309. if ((unsigned)(thisx.bits) <= bits) break;
  84310. PULLBYTE();
  84311. }
  84312. if ((thisx.op & 0xf0) == 0) {
  84313. last = thisx;
  84314. for (;;) {
  84315. thisx = state->distcode[last.val +
  84316. (BITS(last.bits + last.op) >> last.bits)];
  84317. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84318. PULLBYTE();
  84319. }
  84320. DROPBITS(last.bits);
  84321. }
  84322. DROPBITS(thisx.bits);
  84323. if (thisx.op & 64) {
  84324. strm->msg = (char *)"invalid distance code";
  84325. state->mode = BAD;
  84326. break;
  84327. }
  84328. state->offset = (unsigned)thisx.val;
  84329. state->extra = (unsigned)(thisx.op) & 15;
  84330. state->mode = DISTEXT;
  84331. case DISTEXT:
  84332. if (state->extra) {
  84333. NEEDBITS(state->extra);
  84334. state->offset += BITS(state->extra);
  84335. DROPBITS(state->extra);
  84336. }
  84337. #ifdef INFLATE_STRICT
  84338. if (state->offset > state->dmax) {
  84339. strm->msg = (char *)"invalid distance too far back";
  84340. state->mode = BAD;
  84341. break;
  84342. }
  84343. #endif
  84344. if (state->offset > state->whave + out - left) {
  84345. strm->msg = (char *)"invalid distance too far back";
  84346. state->mode = BAD;
  84347. break;
  84348. }
  84349. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84350. state->mode = MATCH;
  84351. case MATCH:
  84352. if (left == 0) goto inf_leave;
  84353. copy = out - left;
  84354. if (state->offset > copy) { /* copy from window */
  84355. copy = state->offset - copy;
  84356. if (copy > state->write) {
  84357. copy -= state->write;
  84358. from = state->window + (state->wsize - copy);
  84359. }
  84360. else
  84361. from = state->window + (state->write - copy);
  84362. if (copy > state->length) copy = state->length;
  84363. }
  84364. else { /* copy from output */
  84365. from = put - state->offset;
  84366. copy = state->length;
  84367. }
  84368. if (copy > left) copy = left;
  84369. left -= copy;
  84370. state->length -= copy;
  84371. do {
  84372. *put++ = *from++;
  84373. } while (--copy);
  84374. if (state->length == 0) state->mode = LEN;
  84375. break;
  84376. case LIT:
  84377. if (left == 0) goto inf_leave;
  84378. *put++ = (unsigned char)(state->length);
  84379. left--;
  84380. state->mode = LEN;
  84381. break;
  84382. case CHECK:
  84383. if (state->wrap) {
  84384. NEEDBITS(32);
  84385. out -= left;
  84386. strm->total_out += out;
  84387. state->total += out;
  84388. if (out)
  84389. strm->adler = state->check =
  84390. UPDATE(state->check, put - out, out);
  84391. out = left;
  84392. if ((
  84393. #ifdef GUNZIP
  84394. state->flags ? hold :
  84395. #endif
  84396. REVERSE(hold)) != state->check) {
  84397. strm->msg = (char *)"incorrect data check";
  84398. state->mode = BAD;
  84399. break;
  84400. }
  84401. INITBITS();
  84402. Tracev((stderr, "inflate: check matches trailer\n"));
  84403. }
  84404. #ifdef GUNZIP
  84405. state->mode = LENGTH;
  84406. case LENGTH:
  84407. if (state->wrap && state->flags) {
  84408. NEEDBITS(32);
  84409. if (hold != (state->total & 0xffffffffUL)) {
  84410. strm->msg = (char *)"incorrect length check";
  84411. state->mode = BAD;
  84412. break;
  84413. }
  84414. INITBITS();
  84415. Tracev((stderr, "inflate: length matches trailer\n"));
  84416. }
  84417. #endif
  84418. state->mode = DONE;
  84419. case DONE:
  84420. ret = Z_STREAM_END;
  84421. goto inf_leave;
  84422. case BAD:
  84423. ret = Z_DATA_ERROR;
  84424. goto inf_leave;
  84425. case MEM:
  84426. return Z_MEM_ERROR;
  84427. case SYNC:
  84428. default:
  84429. return Z_STREAM_ERROR;
  84430. }
  84431. /*
  84432. Return from inflate(), updating the total counts and the check value.
  84433. If there was no progress during the inflate() call, return a buffer
  84434. error. Call updatewindow() to create and/or update the window state.
  84435. Note: a memory error from inflate() is non-recoverable.
  84436. */
  84437. inf_leave:
  84438. RESTORE();
  84439. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84440. if (updatewindow(strm, out)) {
  84441. state->mode = MEM;
  84442. return Z_MEM_ERROR;
  84443. }
  84444. in -= strm->avail_in;
  84445. out -= strm->avail_out;
  84446. strm->total_in += in;
  84447. strm->total_out += out;
  84448. state->total += out;
  84449. if (state->wrap && out)
  84450. strm->adler = state->check =
  84451. UPDATE(state->check, strm->next_out - out, out);
  84452. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84453. (state->mode == TYPE ? 128 : 0);
  84454. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84455. ret = Z_BUF_ERROR;
  84456. return ret;
  84457. }
  84458. int ZEXPORT inflateEnd (z_streamp strm)
  84459. {
  84460. struct inflate_state FAR *state;
  84461. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84462. return Z_STREAM_ERROR;
  84463. state = (struct inflate_state FAR *)strm->state;
  84464. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84465. ZFREE(strm, strm->state);
  84466. strm->state = Z_NULL;
  84467. Tracev((stderr, "inflate: end\n"));
  84468. return Z_OK;
  84469. }
  84470. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84471. {
  84472. struct inflate_state FAR *state;
  84473. unsigned long id_;
  84474. /* check state */
  84475. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84476. state = (struct inflate_state FAR *)strm->state;
  84477. if (state->wrap != 0 && state->mode != DICT)
  84478. return Z_STREAM_ERROR;
  84479. /* check for correct dictionary id */
  84480. if (state->mode == DICT) {
  84481. id_ = adler32(0L, Z_NULL, 0);
  84482. id_ = adler32(id_, dictionary, dictLength);
  84483. if (id_ != state->check)
  84484. return Z_DATA_ERROR;
  84485. }
  84486. /* copy dictionary to window */
  84487. if (updatewindow(strm, strm->avail_out)) {
  84488. state->mode = MEM;
  84489. return Z_MEM_ERROR;
  84490. }
  84491. if (dictLength > state->wsize) {
  84492. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84493. state->wsize);
  84494. state->whave = state->wsize;
  84495. }
  84496. else {
  84497. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84498. dictLength);
  84499. state->whave = dictLength;
  84500. }
  84501. state->havedict = 1;
  84502. Tracev((stderr, "inflate: dictionary set\n"));
  84503. return Z_OK;
  84504. }
  84505. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84506. {
  84507. struct inflate_state FAR *state;
  84508. /* check state */
  84509. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84510. state = (struct inflate_state FAR *)strm->state;
  84511. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84512. /* save header structure */
  84513. state->head = head;
  84514. head->done = 0;
  84515. return Z_OK;
  84516. }
  84517. /*
  84518. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84519. or when out of input. When called, *have is the number of pattern bytes
  84520. found in order so far, in 0..3. On return *have is updated to the new
  84521. state. If on return *have equals four, then the pattern was found and the
  84522. return value is how many bytes were read including the last byte of the
  84523. pattern. If *have is less than four, then the pattern has not been found
  84524. yet and the return value is len. In the latter case, syncsearch() can be
  84525. called again with more data and the *have state. *have is initialized to
  84526. zero for the first call.
  84527. */
  84528. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84529. {
  84530. unsigned got;
  84531. unsigned next;
  84532. got = *have;
  84533. next = 0;
  84534. while (next < len && got < 4) {
  84535. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84536. got++;
  84537. else if (buf[next])
  84538. got = 0;
  84539. else
  84540. got = 4 - got;
  84541. next++;
  84542. }
  84543. *have = got;
  84544. return next;
  84545. }
  84546. int ZEXPORT inflateSync (z_streamp strm)
  84547. {
  84548. unsigned len; /* number of bytes to look at or looked at */
  84549. unsigned long in, out; /* temporary to save total_in and total_out */
  84550. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84551. struct inflate_state FAR *state;
  84552. /* check parameters */
  84553. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84554. state = (struct inflate_state FAR *)strm->state;
  84555. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84556. /* if first time, start search in bit buffer */
  84557. if (state->mode != SYNC) {
  84558. state->mode = SYNC;
  84559. state->hold <<= state->bits & 7;
  84560. state->bits -= state->bits & 7;
  84561. len = 0;
  84562. while (state->bits >= 8) {
  84563. buf[len++] = (unsigned char)(state->hold);
  84564. state->hold >>= 8;
  84565. state->bits -= 8;
  84566. }
  84567. state->have = 0;
  84568. syncsearch(&(state->have), buf, len);
  84569. }
  84570. /* search available input */
  84571. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84572. strm->avail_in -= len;
  84573. strm->next_in += len;
  84574. strm->total_in += len;
  84575. /* return no joy or set up to restart inflate() on a new block */
  84576. if (state->have != 4) return Z_DATA_ERROR;
  84577. in = strm->total_in; out = strm->total_out;
  84578. inflateReset(strm);
  84579. strm->total_in = in; strm->total_out = out;
  84580. state->mode = TYPE;
  84581. return Z_OK;
  84582. }
  84583. /*
  84584. Returns true if inflate is currently at the end of a block generated by
  84585. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84586. implementation to provide an additional safety check. PPP uses
  84587. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84588. block. When decompressing, PPP checks that at the end of input packet,
  84589. inflate is waiting for these length bytes.
  84590. */
  84591. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84592. {
  84593. struct inflate_state FAR *state;
  84594. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84595. state = (struct inflate_state FAR *)strm->state;
  84596. return state->mode == STORED && state->bits == 0;
  84597. }
  84598. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84599. {
  84600. struct inflate_state FAR *state;
  84601. struct inflate_state FAR *copy;
  84602. unsigned char FAR *window;
  84603. unsigned wsize;
  84604. /* check input */
  84605. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84606. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84607. return Z_STREAM_ERROR;
  84608. state = (struct inflate_state FAR *)source->state;
  84609. /* allocate space */
  84610. copy = (struct inflate_state FAR *)
  84611. ZALLOC(source, 1, sizeof(struct inflate_state));
  84612. if (copy == Z_NULL) return Z_MEM_ERROR;
  84613. window = Z_NULL;
  84614. if (state->window != Z_NULL) {
  84615. window = (unsigned char FAR *)
  84616. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84617. if (window == Z_NULL) {
  84618. ZFREE(source, copy);
  84619. return Z_MEM_ERROR;
  84620. }
  84621. }
  84622. /* copy state */
  84623. zmemcpy(dest, source, sizeof(z_stream));
  84624. zmemcpy(copy, state, sizeof(struct inflate_state));
  84625. if (state->lencode >= state->codes &&
  84626. state->lencode <= state->codes + ENOUGH - 1) {
  84627. copy->lencode = copy->codes + (state->lencode - state->codes);
  84628. copy->distcode = copy->codes + (state->distcode - state->codes);
  84629. }
  84630. copy->next = copy->codes + (state->next - state->codes);
  84631. if (window != Z_NULL) {
  84632. wsize = 1U << state->wbits;
  84633. zmemcpy(window, state->window, wsize);
  84634. }
  84635. copy->window = window;
  84636. dest->state = (struct internal_state FAR *)copy;
  84637. return Z_OK;
  84638. }
  84639. /*** End of inlined file: inflate.c ***/
  84640. /*** Start of inlined file: inftrees.c ***/
  84641. #define MAXBITS 15
  84642. const char inflate_copyright[] =
  84643. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84644. /*
  84645. If you use the zlib library in a product, an acknowledgment is welcome
  84646. in the documentation of your product. If for some reason you cannot
  84647. include such an acknowledgment, I would appreciate that you keep this
  84648. copyright string in the executable of your product.
  84649. */
  84650. /*
  84651. Build a set of tables to decode the provided canonical Huffman code.
  84652. The code lengths are lens[0..codes-1]. The result starts at *table,
  84653. whose indices are 0..2^bits-1. work is a writable array of at least
  84654. lens shorts, which is used as a work area. type is the type of code
  84655. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84656. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84657. on return points to the next available entry's address. bits is the
  84658. requested root table index bits, and on return it is the actual root
  84659. table index bits. It will differ if the request is greater than the
  84660. longest code or if it is less than the shortest code.
  84661. */
  84662. int inflate_table (codetype type,
  84663. unsigned short FAR *lens,
  84664. unsigned codes,
  84665. code FAR * FAR *table,
  84666. unsigned FAR *bits,
  84667. unsigned short FAR *work)
  84668. {
  84669. unsigned len; /* a code's length in bits */
  84670. unsigned sym; /* index of code symbols */
  84671. unsigned min, max; /* minimum and maximum code lengths */
  84672. unsigned root; /* number of index bits for root table */
  84673. unsigned curr; /* number of index bits for current table */
  84674. unsigned drop; /* code bits to drop for sub-table */
  84675. int left; /* number of prefix codes available */
  84676. unsigned used; /* code entries in table used */
  84677. unsigned huff; /* Huffman code */
  84678. unsigned incr; /* for incrementing code, index */
  84679. unsigned fill; /* index for replicating entries */
  84680. unsigned low; /* low bits for current root entry */
  84681. unsigned mask; /* mask for low root bits */
  84682. code thisx; /* table entry for duplication */
  84683. code FAR *next; /* next available space in table */
  84684. const unsigned short FAR *base; /* base value table to use */
  84685. const unsigned short FAR *extra; /* extra bits table to use */
  84686. int end; /* use base and extra for symbol > end */
  84687. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84688. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84689. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84690. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84691. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84692. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84693. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84694. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84695. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84696. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84697. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84698. 8193, 12289, 16385, 24577, 0, 0};
  84699. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84700. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84701. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84702. 28, 28, 29, 29, 64, 64};
  84703. /*
  84704. Process a set of code lengths to create a canonical Huffman code. The
  84705. code lengths are lens[0..codes-1]. Each length corresponds to the
  84706. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84707. symbols by length from short to long, and retaining the symbol order
  84708. for codes with equal lengths. Then the code starts with all zero bits
  84709. for the first code of the shortest length, and the codes are integer
  84710. increments for the same length, and zeros are appended as the length
  84711. increases. For the deflate format, these bits are stored backwards
  84712. from their more natural integer increment ordering, and so when the
  84713. decoding tables are built in the large loop below, the integer codes
  84714. are incremented backwards.
  84715. This routine assumes, but does not check, that all of the entries in
  84716. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84717. 1..MAXBITS is interpreted as that code length. zero means that that
  84718. symbol does not occur in this code.
  84719. The codes are sorted by computing a count of codes for each length,
  84720. creating from that a table of starting indices for each length in the
  84721. sorted table, and then entering the symbols in order in the sorted
  84722. table. The sorted table is work[], with that space being provided by
  84723. the caller.
  84724. The length counts are used for other purposes as well, i.e. finding
  84725. the minimum and maximum length codes, determining if there are any
  84726. codes at all, checking for a valid set of lengths, and looking ahead
  84727. at length counts to determine sub-table sizes when building the
  84728. decoding tables.
  84729. */
  84730. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84731. for (len = 0; len <= MAXBITS; len++)
  84732. count[len] = 0;
  84733. for (sym = 0; sym < codes; sym++)
  84734. count[lens[sym]]++;
  84735. /* bound code lengths, force root to be within code lengths */
  84736. root = *bits;
  84737. for (max = MAXBITS; max >= 1; max--)
  84738. if (count[max] != 0) break;
  84739. if (root > max) root = max;
  84740. if (max == 0) { /* no symbols to code at all */
  84741. thisx.op = (unsigned char)64; /* invalid code marker */
  84742. thisx.bits = (unsigned char)1;
  84743. thisx.val = (unsigned short)0;
  84744. *(*table)++ = thisx; /* make a table to force an error */
  84745. *(*table)++ = thisx;
  84746. *bits = 1;
  84747. return 0; /* no symbols, but wait for decoding to report error */
  84748. }
  84749. for (min = 1; min <= MAXBITS; min++)
  84750. if (count[min] != 0) break;
  84751. if (root < min) root = min;
  84752. /* check for an over-subscribed or incomplete set of lengths */
  84753. left = 1;
  84754. for (len = 1; len <= MAXBITS; len++) {
  84755. left <<= 1;
  84756. left -= count[len];
  84757. if (left < 0) return -1; /* over-subscribed */
  84758. }
  84759. if (left > 0 && (type == CODES || max != 1))
  84760. return -1; /* incomplete set */
  84761. /* generate offsets into symbol table for each length for sorting */
  84762. offs[1] = 0;
  84763. for (len = 1; len < MAXBITS; len++)
  84764. offs[len + 1] = offs[len] + count[len];
  84765. /* sort symbols by length, by symbol order within each length */
  84766. for (sym = 0; sym < codes; sym++)
  84767. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84768. /*
  84769. Create and fill in decoding tables. In this loop, the table being
  84770. filled is at next and has curr index bits. The code being used is huff
  84771. with length len. That code is converted to an index by dropping drop
  84772. bits off of the bottom. For codes where len is less than drop + curr,
  84773. those top drop + curr - len bits are incremented through all values to
  84774. fill the table with replicated entries.
  84775. root is the number of index bits for the root table. When len exceeds
  84776. root, sub-tables are created pointed to by the root entry with an index
  84777. of the low root bits of huff. This is saved in low to check for when a
  84778. new sub-table should be started. drop is zero when the root table is
  84779. being filled, and drop is root when sub-tables are being filled.
  84780. When a new sub-table is needed, it is necessary to look ahead in the
  84781. code lengths to determine what size sub-table is needed. The length
  84782. counts are used for this, and so count[] is decremented as codes are
  84783. entered in the tables.
  84784. used keeps track of how many table entries have been allocated from the
  84785. provided *table space. It is checked when a LENS table is being made
  84786. against the space in *table, ENOUGH, minus the maximum space needed by
  84787. the worst case distance code, MAXD. This should never happen, but the
  84788. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84789. This assumes that when type == LENS, bits == 9.
  84790. sym increments through all symbols, and the loop terminates when
  84791. all codes of length max, i.e. all codes, have been processed. This
  84792. routine permits incomplete codes, so another loop after this one fills
  84793. in the rest of the decoding tables with invalid code markers.
  84794. */
  84795. /* set up for code type */
  84796. switch (type) {
  84797. case CODES:
  84798. base = extra = work; /* dummy value--not used */
  84799. end = 19;
  84800. break;
  84801. case LENS:
  84802. base = lbase;
  84803. base -= 257;
  84804. extra = lext;
  84805. extra -= 257;
  84806. end = 256;
  84807. break;
  84808. default: /* DISTS */
  84809. base = dbase;
  84810. extra = dext;
  84811. end = -1;
  84812. }
  84813. /* initialize state for loop */
  84814. huff = 0; /* starting code */
  84815. sym = 0; /* starting code symbol */
  84816. len = min; /* starting code length */
  84817. next = *table; /* current table to fill in */
  84818. curr = root; /* current table index bits */
  84819. drop = 0; /* current bits to drop from code for index */
  84820. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84821. used = 1U << root; /* use root table entries */
  84822. mask = used - 1; /* mask for comparing low */
  84823. /* check available table space */
  84824. if (type == LENS && used >= ENOUGH - MAXD)
  84825. return 1;
  84826. /* process all codes and make table entries */
  84827. for (;;) {
  84828. /* create table entry */
  84829. thisx.bits = (unsigned char)(len - drop);
  84830. if ((int)(work[sym]) < end) {
  84831. thisx.op = (unsigned char)0;
  84832. thisx.val = work[sym];
  84833. }
  84834. else if ((int)(work[sym]) > end) {
  84835. thisx.op = (unsigned char)(extra[work[sym]]);
  84836. thisx.val = base[work[sym]];
  84837. }
  84838. else {
  84839. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84840. thisx.val = 0;
  84841. }
  84842. /* replicate for those indices with low len bits equal to huff */
  84843. incr = 1U << (len - drop);
  84844. fill = 1U << curr;
  84845. min = fill; /* save offset to next table */
  84846. do {
  84847. fill -= incr;
  84848. next[(huff >> drop) + fill] = thisx;
  84849. } while (fill != 0);
  84850. /* backwards increment the len-bit code huff */
  84851. incr = 1U << (len - 1);
  84852. while (huff & incr)
  84853. incr >>= 1;
  84854. if (incr != 0) {
  84855. huff &= incr - 1;
  84856. huff += incr;
  84857. }
  84858. else
  84859. huff = 0;
  84860. /* go to next symbol, update count, len */
  84861. sym++;
  84862. if (--(count[len]) == 0) {
  84863. if (len == max) break;
  84864. len = lens[work[sym]];
  84865. }
  84866. /* create new sub-table if needed */
  84867. if (len > root && (huff & mask) != low) {
  84868. /* if first time, transition to sub-tables */
  84869. if (drop == 0)
  84870. drop = root;
  84871. /* increment past last table */
  84872. next += min; /* here min is 1 << curr */
  84873. /* determine length of next table */
  84874. curr = len - drop;
  84875. left = (int)(1 << curr);
  84876. while (curr + drop < max) {
  84877. left -= count[curr + drop];
  84878. if (left <= 0) break;
  84879. curr++;
  84880. left <<= 1;
  84881. }
  84882. /* check for enough space */
  84883. used += 1U << curr;
  84884. if (type == LENS && used >= ENOUGH - MAXD)
  84885. return 1;
  84886. /* point entry in root table to sub-table */
  84887. low = huff & mask;
  84888. (*table)[low].op = (unsigned char)curr;
  84889. (*table)[low].bits = (unsigned char)root;
  84890. (*table)[low].val = (unsigned short)(next - *table);
  84891. }
  84892. }
  84893. /*
  84894. Fill in rest of table for incomplete codes. This loop is similar to the
  84895. loop above in incrementing huff for table indices. It is assumed that
  84896. len is equal to curr + drop, so there is no loop needed to increment
  84897. through high index bits. When the current sub-table is filled, the loop
  84898. drops back to the root table to fill in any remaining entries there.
  84899. */
  84900. thisx.op = (unsigned char)64; /* invalid code marker */
  84901. thisx.bits = (unsigned char)(len - drop);
  84902. thisx.val = (unsigned short)0;
  84903. while (huff != 0) {
  84904. /* when done with sub-table, drop back to root table */
  84905. if (drop != 0 && (huff & mask) != low) {
  84906. drop = 0;
  84907. len = root;
  84908. next = *table;
  84909. thisx.bits = (unsigned char)len;
  84910. }
  84911. /* put invalid code marker in table */
  84912. next[huff >> drop] = thisx;
  84913. /* backwards increment the len-bit code huff */
  84914. incr = 1U << (len - 1);
  84915. while (huff & incr)
  84916. incr >>= 1;
  84917. if (incr != 0) {
  84918. huff &= incr - 1;
  84919. huff += incr;
  84920. }
  84921. else
  84922. huff = 0;
  84923. }
  84924. /* set return parameters */
  84925. *table += used;
  84926. *bits = root;
  84927. return 0;
  84928. }
  84929. /*** End of inlined file: inftrees.c ***/
  84930. /*** Start of inlined file: trees.c ***/
  84931. /*
  84932. * ALGORITHM
  84933. *
  84934. * The "deflation" process uses several Huffman trees. The more
  84935. * common source values are represented by shorter bit sequences.
  84936. *
  84937. * Each code tree is stored in a compressed form which is itself
  84938. * a Huffman encoding of the lengths of all the code strings (in
  84939. * ascending order by source values). The actual code strings are
  84940. * reconstructed from the lengths in the inflate process, as described
  84941. * in the deflate specification.
  84942. *
  84943. * REFERENCES
  84944. *
  84945. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84946. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84947. *
  84948. * Storer, James A.
  84949. * Data Compression: Methods and Theory, pp. 49-50.
  84950. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84951. *
  84952. * Sedgewick, R.
  84953. * Algorithms, p290.
  84954. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84955. */
  84956. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84957. /* #define GEN_TREES_H */
  84958. #ifdef DEBUG
  84959. # include <ctype.h>
  84960. #endif
  84961. /* ===========================================================================
  84962. * Constants
  84963. */
  84964. #define MAX_BL_BITS 7
  84965. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84966. #define END_BLOCK 256
  84967. /* end of block literal code */
  84968. #define REP_3_6 16
  84969. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84970. #define REPZ_3_10 17
  84971. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84972. #define REPZ_11_138 18
  84973. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84974. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84975. = {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};
  84976. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84977. = {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};
  84978. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84979. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84980. local const uch bl_order[BL_CODES]
  84981. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84982. /* The lengths of the bit length codes are sent in order of decreasing
  84983. * probability, to avoid transmitting the lengths for unused bit length codes.
  84984. */
  84985. #define Buf_size (8 * 2*sizeof(char))
  84986. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84987. * more than 16 bits on some systems.)
  84988. */
  84989. /* ===========================================================================
  84990. * Local data. These are initialized only once.
  84991. */
  84992. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84993. #if defined(GEN_TREES_H) || !defined(STDC)
  84994. /* non ANSI compilers may not accept trees.h */
  84995. local ct_data static_ltree[L_CODES+2];
  84996. /* The static literal tree. Since the bit lengths are imposed, there is no
  84997. * need for the L_CODES extra codes used during heap construction. However
  84998. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84999. * below).
  85000. */
  85001. local ct_data static_dtree[D_CODES];
  85002. /* The static distance tree. (Actually a trivial tree since all codes use
  85003. * 5 bits.)
  85004. */
  85005. uch _dist_code[DIST_CODE_LEN];
  85006. /* Distance codes. The first 256 values correspond to the distances
  85007. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  85008. * the 15 bit distances.
  85009. */
  85010. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  85011. /* length code for each normalized match length (0 == MIN_MATCH) */
  85012. local int base_length[LENGTH_CODES];
  85013. /* First normalized length for each code (0 = MIN_MATCH) */
  85014. local int base_dist[D_CODES];
  85015. /* First normalized distance for each code (0 = distance of 1) */
  85016. #else
  85017. /*** Start of inlined file: trees.h ***/
  85018. local const ct_data static_ltree[L_CODES+2] = {
  85019. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  85020. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  85021. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  85022. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  85023. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  85024. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  85025. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  85026. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  85027. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  85028. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  85029. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  85030. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  85031. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  85032. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  85033. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  85034. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  85035. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  85036. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  85037. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  85038. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  85039. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  85040. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  85041. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  85042. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  85043. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  85044. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  85045. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  85046. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  85047. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  85048. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  85049. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  85050. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  85051. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  85052. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  85053. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  85054. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  85055. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  85056. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  85057. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  85058. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  85059. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  85060. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  85061. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  85062. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  85063. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  85064. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  85065. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  85066. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  85067. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  85068. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  85069. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  85070. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  85071. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  85072. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  85073. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  85074. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  85075. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  85076. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  85077. };
  85078. local const ct_data static_dtree[D_CODES] = {
  85079. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  85080. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  85081. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  85082. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  85083. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  85084. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  85085. };
  85086. const uch _dist_code[DIST_CODE_LEN] = {
  85087. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  85088. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  85089. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  85090. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  85091. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  85092. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  85093. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85094. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85095. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85096. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  85097. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85098. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85099. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  85100. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  85101. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85102. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85103. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85104. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  85105. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85106. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85107. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85108. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85109. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85110. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85111. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85112. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  85113. };
  85114. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  85115. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  85116. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  85117. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  85118. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  85119. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  85120. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  85121. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85122. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85123. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85124. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  85125. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85126. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85127. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  85128. };
  85129. local const int base_length[LENGTH_CODES] = {
  85130. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  85131. 64, 80, 96, 112, 128, 160, 192, 224, 0
  85132. };
  85133. local const int base_dist[D_CODES] = {
  85134. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  85135. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  85136. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  85137. };
  85138. /*** End of inlined file: trees.h ***/
  85139. #endif /* GEN_TREES_H */
  85140. struct static_tree_desc_s {
  85141. const ct_data *static_tree; /* static tree or NULL */
  85142. const intf *extra_bits; /* extra bits for each code or NULL */
  85143. int extra_base; /* base index for extra_bits */
  85144. int elems; /* max number of elements in the tree */
  85145. int max_length; /* max bit length for the codes */
  85146. };
  85147. local static_tree_desc static_l_desc =
  85148. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  85149. local static_tree_desc static_d_desc =
  85150. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  85151. local static_tree_desc static_bl_desc =
  85152. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  85153. /* ===========================================================================
  85154. * Local (static) routines in this file.
  85155. */
  85156. local void tr_static_init OF((void));
  85157. local void init_block OF((deflate_state *s));
  85158. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  85159. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  85160. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  85161. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85162. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85163. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85164. local int build_bl_tree OF((deflate_state *s));
  85165. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85166. int blcodes));
  85167. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85168. ct_data *dtree));
  85169. local void set_data_type OF((deflate_state *s));
  85170. local unsigned bi_reverse OF((unsigned value, int length));
  85171. local void bi_windup OF((deflate_state *s));
  85172. local void bi_flush OF((deflate_state *s));
  85173. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85174. int header));
  85175. #ifdef GEN_TREES_H
  85176. local void gen_trees_header OF((void));
  85177. #endif
  85178. #ifndef DEBUG
  85179. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85180. /* Send a code of the given tree. c and tree must not have side effects */
  85181. #else /* DEBUG */
  85182. # define send_code(s, c, tree) \
  85183. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85184. send_bits(s, tree[c].Code, tree[c].Len); }
  85185. #endif
  85186. /* ===========================================================================
  85187. * Output a short LSB first on the stream.
  85188. * IN assertion: there is enough room in pendingBuf.
  85189. */
  85190. #define put_short(s, w) { \
  85191. put_byte(s, (uch)((w) & 0xff)); \
  85192. put_byte(s, (uch)((ush)(w) >> 8)); \
  85193. }
  85194. /* ===========================================================================
  85195. * Send a value on a given number of bits.
  85196. * IN assertion: length <= 16 and value fits in length bits.
  85197. */
  85198. #ifdef DEBUG
  85199. local void send_bits OF((deflate_state *s, int value, int length));
  85200. local void send_bits (deflate_state *s, int value, int length)
  85201. {
  85202. Tracevv((stderr," l %2d v %4x ", length, value));
  85203. Assert(length > 0 && length <= 15, "invalid length");
  85204. s->bits_sent += (ulg)length;
  85205. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85206. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85207. * unused bits in value.
  85208. */
  85209. if (s->bi_valid > (int)Buf_size - length) {
  85210. s->bi_buf |= (value << s->bi_valid);
  85211. put_short(s, s->bi_buf);
  85212. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85213. s->bi_valid += length - Buf_size;
  85214. } else {
  85215. s->bi_buf |= value << s->bi_valid;
  85216. s->bi_valid += length;
  85217. }
  85218. }
  85219. #else /* !DEBUG */
  85220. #define send_bits(s, value, length) \
  85221. { int len = length;\
  85222. if (s->bi_valid > (int)Buf_size - len) {\
  85223. int val = value;\
  85224. s->bi_buf |= (val << s->bi_valid);\
  85225. put_short(s, s->bi_buf);\
  85226. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85227. s->bi_valid += len - Buf_size;\
  85228. } else {\
  85229. s->bi_buf |= (value) << s->bi_valid;\
  85230. s->bi_valid += len;\
  85231. }\
  85232. }
  85233. #endif /* DEBUG */
  85234. /* the arguments must not have side effects */
  85235. /* ===========================================================================
  85236. * Initialize the various 'constant' tables.
  85237. */
  85238. local void tr_static_init()
  85239. {
  85240. #if defined(GEN_TREES_H) || !defined(STDC)
  85241. static int static_init_done = 0;
  85242. int n; /* iterates over tree elements */
  85243. int bits; /* bit counter */
  85244. int length; /* length value */
  85245. int code; /* code value */
  85246. int dist; /* distance index */
  85247. ush bl_count[MAX_BITS+1];
  85248. /* number of codes at each bit length for an optimal tree */
  85249. if (static_init_done) return;
  85250. /* For some embedded targets, global variables are not initialized: */
  85251. static_l_desc.static_tree = static_ltree;
  85252. static_l_desc.extra_bits = extra_lbits;
  85253. static_d_desc.static_tree = static_dtree;
  85254. static_d_desc.extra_bits = extra_dbits;
  85255. static_bl_desc.extra_bits = extra_blbits;
  85256. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85257. length = 0;
  85258. for (code = 0; code < LENGTH_CODES-1; code++) {
  85259. base_length[code] = length;
  85260. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85261. _length_code[length++] = (uch)code;
  85262. }
  85263. }
  85264. Assert (length == 256, "tr_static_init: length != 256");
  85265. /* Note that the length 255 (match length 258) can be represented
  85266. * in two different ways: code 284 + 5 bits or code 285, so we
  85267. * overwrite length_code[255] to use the best encoding:
  85268. */
  85269. _length_code[length-1] = (uch)code;
  85270. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85271. dist = 0;
  85272. for (code = 0 ; code < 16; code++) {
  85273. base_dist[code] = dist;
  85274. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85275. _dist_code[dist++] = (uch)code;
  85276. }
  85277. }
  85278. Assert (dist == 256, "tr_static_init: dist != 256");
  85279. dist >>= 7; /* from now on, all distances are divided by 128 */
  85280. for ( ; code < D_CODES; code++) {
  85281. base_dist[code] = dist << 7;
  85282. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85283. _dist_code[256 + dist++] = (uch)code;
  85284. }
  85285. }
  85286. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85287. /* Construct the codes of the static literal tree */
  85288. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85289. n = 0;
  85290. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85291. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85292. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85293. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85294. /* Codes 286 and 287 do not exist, but we must include them in the
  85295. * tree construction to get a canonical Huffman tree (longest code
  85296. * all ones)
  85297. */
  85298. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85299. /* The static distance tree is trivial: */
  85300. for (n = 0; n < D_CODES; n++) {
  85301. static_dtree[n].Len = 5;
  85302. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85303. }
  85304. static_init_done = 1;
  85305. # ifdef GEN_TREES_H
  85306. gen_trees_header();
  85307. # endif
  85308. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85309. }
  85310. /* ===========================================================================
  85311. * Genererate the file trees.h describing the static trees.
  85312. */
  85313. #ifdef GEN_TREES_H
  85314. # ifndef DEBUG
  85315. # include <stdio.h>
  85316. # endif
  85317. # define SEPARATOR(i, last, width) \
  85318. ((i) == (last)? "\n};\n\n" : \
  85319. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85320. void gen_trees_header()
  85321. {
  85322. FILE *header = fopen("trees.h", "w");
  85323. int i;
  85324. Assert (header != NULL, "Can't open trees.h");
  85325. fprintf(header,
  85326. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85327. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85328. for (i = 0; i < L_CODES+2; i++) {
  85329. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85330. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85331. }
  85332. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85333. for (i = 0; i < D_CODES; i++) {
  85334. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85335. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85336. }
  85337. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85338. for (i = 0; i < DIST_CODE_LEN; i++) {
  85339. fprintf(header, "%2u%s", _dist_code[i],
  85340. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85341. }
  85342. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85343. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85344. fprintf(header, "%2u%s", _length_code[i],
  85345. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85346. }
  85347. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85348. for (i = 0; i < LENGTH_CODES; i++) {
  85349. fprintf(header, "%1u%s", base_length[i],
  85350. SEPARATOR(i, LENGTH_CODES-1, 20));
  85351. }
  85352. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85353. for (i = 0; i < D_CODES; i++) {
  85354. fprintf(header, "%5u%s", base_dist[i],
  85355. SEPARATOR(i, D_CODES-1, 10));
  85356. }
  85357. fclose(header);
  85358. }
  85359. #endif /* GEN_TREES_H */
  85360. /* ===========================================================================
  85361. * Initialize the tree data structures for a new zlib stream.
  85362. */
  85363. void _tr_init(deflate_state *s)
  85364. {
  85365. tr_static_init();
  85366. s->l_desc.dyn_tree = s->dyn_ltree;
  85367. s->l_desc.stat_desc = &static_l_desc;
  85368. s->d_desc.dyn_tree = s->dyn_dtree;
  85369. s->d_desc.stat_desc = &static_d_desc;
  85370. s->bl_desc.dyn_tree = s->bl_tree;
  85371. s->bl_desc.stat_desc = &static_bl_desc;
  85372. s->bi_buf = 0;
  85373. s->bi_valid = 0;
  85374. s->last_eob_len = 8; /* enough lookahead for inflate */
  85375. #ifdef DEBUG
  85376. s->compressed_len = 0L;
  85377. s->bits_sent = 0L;
  85378. #endif
  85379. /* Initialize the first block of the first file: */
  85380. init_block(s);
  85381. }
  85382. /* ===========================================================================
  85383. * Initialize a new block.
  85384. */
  85385. local void init_block (deflate_state *s)
  85386. {
  85387. int n; /* iterates over tree elements */
  85388. /* Initialize the trees. */
  85389. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85390. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85391. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85392. s->dyn_ltree[END_BLOCK].Freq = 1;
  85393. s->opt_len = s->static_len = 0L;
  85394. s->last_lit = s->matches = 0;
  85395. }
  85396. #define SMALLEST 1
  85397. /* Index within the heap array of least frequent node in the Huffman tree */
  85398. /* ===========================================================================
  85399. * Remove the smallest element from the heap and recreate the heap with
  85400. * one less element. Updates heap and heap_len.
  85401. */
  85402. #define pqremove(s, tree, top) \
  85403. {\
  85404. top = s->heap[SMALLEST]; \
  85405. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85406. pqdownheap(s, tree, SMALLEST); \
  85407. }
  85408. /* ===========================================================================
  85409. * Compares to subtrees, using the tree depth as tie breaker when
  85410. * the subtrees have equal frequency. This minimizes the worst case length.
  85411. */
  85412. #define smaller(tree, n, m, depth) \
  85413. (tree[n].Freq < tree[m].Freq || \
  85414. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85415. /* ===========================================================================
  85416. * Restore the heap property by moving down the tree starting at node k,
  85417. * exchanging a node with the smallest of its two sons if necessary, stopping
  85418. * when the heap property is re-established (each father smaller than its
  85419. * two sons).
  85420. */
  85421. local void pqdownheap (deflate_state *s,
  85422. ct_data *tree, /* the tree to restore */
  85423. int k) /* node to move down */
  85424. {
  85425. int v = s->heap[k];
  85426. int j = k << 1; /* left son of k */
  85427. while (j <= s->heap_len) {
  85428. /* Set j to the smallest of the two sons: */
  85429. if (j < s->heap_len &&
  85430. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85431. j++;
  85432. }
  85433. /* Exit if v is smaller than both sons */
  85434. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85435. /* Exchange v with the smallest son */
  85436. s->heap[k] = s->heap[j]; k = j;
  85437. /* And continue down the tree, setting j to the left son of k */
  85438. j <<= 1;
  85439. }
  85440. s->heap[k] = v;
  85441. }
  85442. /* ===========================================================================
  85443. * Compute the optimal bit lengths for a tree and update the total bit length
  85444. * for the current block.
  85445. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85446. * above are the tree nodes sorted by increasing frequency.
  85447. * OUT assertions: the field len is set to the optimal bit length, the
  85448. * array bl_count contains the frequencies for each bit length.
  85449. * The length opt_len is updated; static_len is also updated if stree is
  85450. * not null.
  85451. */
  85452. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85453. {
  85454. ct_data *tree = desc->dyn_tree;
  85455. int max_code = desc->max_code;
  85456. const ct_data *stree = desc->stat_desc->static_tree;
  85457. const intf *extra = desc->stat_desc->extra_bits;
  85458. int base = desc->stat_desc->extra_base;
  85459. int max_length = desc->stat_desc->max_length;
  85460. int h; /* heap index */
  85461. int n, m; /* iterate over the tree elements */
  85462. int bits; /* bit length */
  85463. int xbits; /* extra bits */
  85464. ush f; /* frequency */
  85465. int overflow = 0; /* number of elements with bit length too large */
  85466. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85467. /* In a first pass, compute the optimal bit lengths (which may
  85468. * overflow in the case of the bit length tree).
  85469. */
  85470. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85471. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85472. n = s->heap[h];
  85473. bits = tree[tree[n].Dad].Len + 1;
  85474. if (bits > max_length) bits = max_length, overflow++;
  85475. tree[n].Len = (ush)bits;
  85476. /* We overwrite tree[n].Dad which is no longer needed */
  85477. if (n > max_code) continue; /* not a leaf node */
  85478. s->bl_count[bits]++;
  85479. xbits = 0;
  85480. if (n >= base) xbits = extra[n-base];
  85481. f = tree[n].Freq;
  85482. s->opt_len += (ulg)f * (bits + xbits);
  85483. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85484. }
  85485. if (overflow == 0) return;
  85486. Trace((stderr,"\nbit length overflow\n"));
  85487. /* This happens for example on obj2 and pic of the Calgary corpus */
  85488. /* Find the first bit length which could increase: */
  85489. do {
  85490. bits = max_length-1;
  85491. while (s->bl_count[bits] == 0) bits--;
  85492. s->bl_count[bits]--; /* move one leaf down the tree */
  85493. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85494. s->bl_count[max_length]--;
  85495. /* The brother of the overflow item also moves one step up,
  85496. * but this does not affect bl_count[max_length]
  85497. */
  85498. overflow -= 2;
  85499. } while (overflow > 0);
  85500. /* Now recompute all bit lengths, scanning in increasing frequency.
  85501. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85502. * lengths instead of fixing only the wrong ones. This idea is taken
  85503. * from 'ar' written by Haruhiko Okumura.)
  85504. */
  85505. for (bits = max_length; bits != 0; bits--) {
  85506. n = s->bl_count[bits];
  85507. while (n != 0) {
  85508. m = s->heap[--h];
  85509. if (m > max_code) continue;
  85510. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85511. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85512. s->opt_len += ((long)bits - (long)tree[m].Len)
  85513. *(long)tree[m].Freq;
  85514. tree[m].Len = (ush)bits;
  85515. }
  85516. n--;
  85517. }
  85518. }
  85519. }
  85520. /* ===========================================================================
  85521. * Generate the codes for a given tree and bit counts (which need not be
  85522. * optimal).
  85523. * IN assertion: the array bl_count contains the bit length statistics for
  85524. * the given tree and the field len is set for all tree elements.
  85525. * OUT assertion: the field code is set for all tree elements of non
  85526. * zero code length.
  85527. */
  85528. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85529. int max_code, /* largest code with non zero frequency */
  85530. ushf *bl_count) /* number of codes at each bit length */
  85531. {
  85532. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85533. ush code = 0; /* running code value */
  85534. int bits; /* bit index */
  85535. int n; /* code index */
  85536. /* The distribution counts are first used to generate the code values
  85537. * without bit reversal.
  85538. */
  85539. for (bits = 1; bits <= MAX_BITS; bits++) {
  85540. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85541. }
  85542. /* Check that the bit counts in bl_count are consistent. The last code
  85543. * must be all ones.
  85544. */
  85545. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85546. "inconsistent bit counts");
  85547. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85548. for (n = 0; n <= max_code; n++) {
  85549. int len = tree[n].Len;
  85550. if (len == 0) continue;
  85551. /* Now reverse the bits */
  85552. tree[n].Code = bi_reverse(next_code[len]++, len);
  85553. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85554. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85555. }
  85556. }
  85557. /* ===========================================================================
  85558. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85559. * Update the total bit length for the current block.
  85560. * IN assertion: the field freq is set for all tree elements.
  85561. * OUT assertions: the fields len and code are set to the optimal bit length
  85562. * and corresponding code. The length opt_len is updated; static_len is
  85563. * also updated if stree is not null. The field max_code is set.
  85564. */
  85565. local void build_tree (deflate_state *s,
  85566. tree_desc *desc) /* the tree descriptor */
  85567. {
  85568. ct_data *tree = desc->dyn_tree;
  85569. const ct_data *stree = desc->stat_desc->static_tree;
  85570. int elems = desc->stat_desc->elems;
  85571. int n, m; /* iterate over heap elements */
  85572. int max_code = -1; /* largest code with non zero frequency */
  85573. int node; /* new node being created */
  85574. /* Construct the initial heap, with least frequent element in
  85575. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85576. * heap[0] is not used.
  85577. */
  85578. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85579. for (n = 0; n < elems; n++) {
  85580. if (tree[n].Freq != 0) {
  85581. s->heap[++(s->heap_len)] = max_code = n;
  85582. s->depth[n] = 0;
  85583. } else {
  85584. tree[n].Len = 0;
  85585. }
  85586. }
  85587. /* The pkzip format requires that at least one distance code exists,
  85588. * and that at least one bit should be sent even if there is only one
  85589. * possible code. So to avoid special checks later on we force at least
  85590. * two codes of non zero frequency.
  85591. */
  85592. while (s->heap_len < 2) {
  85593. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85594. tree[node].Freq = 1;
  85595. s->depth[node] = 0;
  85596. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85597. /* node is 0 or 1 so it does not have extra bits */
  85598. }
  85599. desc->max_code = max_code;
  85600. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85601. * establish sub-heaps of increasing lengths:
  85602. */
  85603. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85604. /* Construct the Huffman tree by repeatedly combining the least two
  85605. * frequent nodes.
  85606. */
  85607. node = elems; /* next internal node of the tree */
  85608. do {
  85609. pqremove(s, tree, n); /* n = node of least frequency */
  85610. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85611. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85612. s->heap[--(s->heap_max)] = m;
  85613. /* Create a new node father of n and m */
  85614. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85615. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85616. s->depth[n] : s->depth[m]) + 1);
  85617. tree[n].Dad = tree[m].Dad = (ush)node;
  85618. #ifdef DUMP_BL_TREE
  85619. if (tree == s->bl_tree) {
  85620. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85621. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85622. }
  85623. #endif
  85624. /* and insert the new node in the heap */
  85625. s->heap[SMALLEST] = node++;
  85626. pqdownheap(s, tree, SMALLEST);
  85627. } while (s->heap_len >= 2);
  85628. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85629. /* At this point, the fields freq and dad are set. We can now
  85630. * generate the bit lengths.
  85631. */
  85632. gen_bitlen(s, (tree_desc *)desc);
  85633. /* The field len is now set, we can generate the bit codes */
  85634. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85635. }
  85636. /* ===========================================================================
  85637. * Scan a literal or distance tree to determine the frequencies of the codes
  85638. * in the bit length tree.
  85639. */
  85640. local void scan_tree (deflate_state *s,
  85641. ct_data *tree, /* the tree to be scanned */
  85642. int max_code) /* and its largest code of non zero frequency */
  85643. {
  85644. int n; /* iterates over all tree elements */
  85645. int prevlen = -1; /* last emitted length */
  85646. int curlen; /* length of current code */
  85647. int nextlen = tree[0].Len; /* length of next code */
  85648. int count = 0; /* repeat count of the current code */
  85649. int max_count = 7; /* max repeat count */
  85650. int min_count = 4; /* min repeat count */
  85651. if (nextlen == 0) max_count = 138, min_count = 3;
  85652. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85653. for (n = 0; n <= max_code; n++) {
  85654. curlen = nextlen; nextlen = tree[n+1].Len;
  85655. if (++count < max_count && curlen == nextlen) {
  85656. continue;
  85657. } else if (count < min_count) {
  85658. s->bl_tree[curlen].Freq += count;
  85659. } else if (curlen != 0) {
  85660. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85661. s->bl_tree[REP_3_6].Freq++;
  85662. } else if (count <= 10) {
  85663. s->bl_tree[REPZ_3_10].Freq++;
  85664. } else {
  85665. s->bl_tree[REPZ_11_138].Freq++;
  85666. }
  85667. count = 0; prevlen = curlen;
  85668. if (nextlen == 0) {
  85669. max_count = 138, min_count = 3;
  85670. } else if (curlen == nextlen) {
  85671. max_count = 6, min_count = 3;
  85672. } else {
  85673. max_count = 7, min_count = 4;
  85674. }
  85675. }
  85676. }
  85677. /* ===========================================================================
  85678. * Send a literal or distance tree in compressed form, using the codes in
  85679. * bl_tree.
  85680. */
  85681. local void send_tree (deflate_state *s,
  85682. ct_data *tree, /* the tree to be scanned */
  85683. int max_code) /* and its largest code of non zero frequency */
  85684. {
  85685. int n; /* iterates over all tree elements */
  85686. int prevlen = -1; /* last emitted length */
  85687. int curlen; /* length of current code */
  85688. int nextlen = tree[0].Len; /* length of next code */
  85689. int count = 0; /* repeat count of the current code */
  85690. int max_count = 7; /* max repeat count */
  85691. int min_count = 4; /* min repeat count */
  85692. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85693. if (nextlen == 0) max_count = 138, min_count = 3;
  85694. for (n = 0; n <= max_code; n++) {
  85695. curlen = nextlen; nextlen = tree[n+1].Len;
  85696. if (++count < max_count && curlen == nextlen) {
  85697. continue;
  85698. } else if (count < min_count) {
  85699. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85700. } else if (curlen != 0) {
  85701. if (curlen != prevlen) {
  85702. send_code(s, curlen, s->bl_tree); count--;
  85703. }
  85704. Assert(count >= 3 && count <= 6, " 3_6?");
  85705. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85706. } else if (count <= 10) {
  85707. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85708. } else {
  85709. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85710. }
  85711. count = 0; prevlen = curlen;
  85712. if (nextlen == 0) {
  85713. max_count = 138, min_count = 3;
  85714. } else if (curlen == nextlen) {
  85715. max_count = 6, min_count = 3;
  85716. } else {
  85717. max_count = 7, min_count = 4;
  85718. }
  85719. }
  85720. }
  85721. /* ===========================================================================
  85722. * Construct the Huffman tree for the bit lengths and return the index in
  85723. * bl_order of the last bit length code to send.
  85724. */
  85725. local int build_bl_tree (deflate_state *s)
  85726. {
  85727. int max_blindex; /* index of last bit length code of non zero freq */
  85728. /* Determine the bit length frequencies for literal and distance trees */
  85729. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85730. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85731. /* Build the bit length tree: */
  85732. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85733. /* opt_len now includes the length of the tree representations, except
  85734. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85735. */
  85736. /* Determine the number of bit length codes to send. The pkzip format
  85737. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85738. * 3 but the actual value used is 4.)
  85739. */
  85740. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85741. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85742. }
  85743. /* Update opt_len to include the bit length tree and counts */
  85744. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85745. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85746. s->opt_len, s->static_len));
  85747. return max_blindex;
  85748. }
  85749. /* ===========================================================================
  85750. * Send the header for a block using dynamic Huffman trees: the counts, the
  85751. * lengths of the bit length codes, the literal tree and the distance tree.
  85752. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85753. */
  85754. local void send_all_trees (deflate_state *s,
  85755. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85756. {
  85757. int rank; /* index in bl_order */
  85758. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85759. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85760. "too many codes");
  85761. Tracev((stderr, "\nbl counts: "));
  85762. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85763. send_bits(s, dcodes-1, 5);
  85764. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85765. for (rank = 0; rank < blcodes; rank++) {
  85766. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85767. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85768. }
  85769. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85770. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85771. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85772. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85773. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85774. }
  85775. /* ===========================================================================
  85776. * Send a stored block
  85777. */
  85778. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85779. {
  85780. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85781. #ifdef DEBUG
  85782. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85783. s->compressed_len += (stored_len + 4) << 3;
  85784. #endif
  85785. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85786. }
  85787. /* ===========================================================================
  85788. * Send one empty static block to give enough lookahead for inflate.
  85789. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85790. * The current inflate code requires 9 bits of lookahead. If the
  85791. * last two codes for the previous block (real code plus EOB) were coded
  85792. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85793. * the last real code. In this case we send two empty static blocks instead
  85794. * of one. (There are no problems if the previous block is stored or fixed.)
  85795. * To simplify the code, we assume the worst case of last real code encoded
  85796. * on one bit only.
  85797. */
  85798. void _tr_align (deflate_state *s)
  85799. {
  85800. send_bits(s, STATIC_TREES<<1, 3);
  85801. send_code(s, END_BLOCK, static_ltree);
  85802. #ifdef DEBUG
  85803. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85804. #endif
  85805. bi_flush(s);
  85806. /* Of the 10 bits for the empty block, we have already sent
  85807. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85808. * the EOB of the previous block) was thus at least one plus the length
  85809. * of the EOB plus what we have just sent of the empty static block.
  85810. */
  85811. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85812. send_bits(s, STATIC_TREES<<1, 3);
  85813. send_code(s, END_BLOCK, static_ltree);
  85814. #ifdef DEBUG
  85815. s->compressed_len += 10L;
  85816. #endif
  85817. bi_flush(s);
  85818. }
  85819. s->last_eob_len = 7;
  85820. }
  85821. /* ===========================================================================
  85822. * Determine the best encoding for the current block: dynamic trees, static
  85823. * trees or store, and output the encoded block to the zip file.
  85824. */
  85825. void _tr_flush_block (deflate_state *s,
  85826. charf *buf, /* input block, or NULL if too old */
  85827. ulg stored_len, /* length of input block */
  85828. int eof) /* true if this is the last block for a file */
  85829. {
  85830. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85831. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85832. /* Build the Huffman trees unless a stored block is forced */
  85833. if (s->level > 0) {
  85834. /* Check if the file is binary or text */
  85835. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85836. set_data_type(s);
  85837. /* Construct the literal and distance trees */
  85838. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85839. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85840. s->static_len));
  85841. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85842. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85843. s->static_len));
  85844. /* At this point, opt_len and static_len are the total bit lengths of
  85845. * the compressed block data, excluding the tree representations.
  85846. */
  85847. /* Build the bit length tree for the above two trees, and get the index
  85848. * in bl_order of the last bit length code to send.
  85849. */
  85850. max_blindex = build_bl_tree(s);
  85851. /* Determine the best encoding. Compute the block lengths in bytes. */
  85852. opt_lenb = (s->opt_len+3+7)>>3;
  85853. static_lenb = (s->static_len+3+7)>>3;
  85854. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85855. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85856. s->last_lit));
  85857. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85858. } else {
  85859. Assert(buf != (char*)0, "lost buf");
  85860. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85861. }
  85862. #ifdef FORCE_STORED
  85863. if (buf != (char*)0) { /* force stored block */
  85864. #else
  85865. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85866. /* 4: two words for the lengths */
  85867. #endif
  85868. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85869. * Otherwise we can't have processed more than WSIZE input bytes since
  85870. * the last block flush, because compression would have been
  85871. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85872. * transform a block into a stored block.
  85873. */
  85874. _tr_stored_block(s, buf, stored_len, eof);
  85875. #ifdef FORCE_STATIC
  85876. } else if (static_lenb >= 0) { /* force static trees */
  85877. #else
  85878. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85879. #endif
  85880. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85881. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85882. #ifdef DEBUG
  85883. s->compressed_len += 3 + s->static_len;
  85884. #endif
  85885. } else {
  85886. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85887. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85888. max_blindex+1);
  85889. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85890. #ifdef DEBUG
  85891. s->compressed_len += 3 + s->opt_len;
  85892. #endif
  85893. }
  85894. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85895. /* The above check is made mod 2^32, for files larger than 512 MB
  85896. * and uLong implemented on 32 bits.
  85897. */
  85898. init_block(s);
  85899. if (eof) {
  85900. bi_windup(s);
  85901. #ifdef DEBUG
  85902. s->compressed_len += 7; /* align on byte boundary */
  85903. #endif
  85904. }
  85905. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85906. s->compressed_len-7*eof));
  85907. }
  85908. /* ===========================================================================
  85909. * Save the match info and tally the frequency counts. Return true if
  85910. * the current block must be flushed.
  85911. */
  85912. int _tr_tally (deflate_state *s,
  85913. unsigned dist, /* distance of matched string */
  85914. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85915. {
  85916. s->d_buf[s->last_lit] = (ush)dist;
  85917. s->l_buf[s->last_lit++] = (uch)lc;
  85918. if (dist == 0) {
  85919. /* lc is the unmatched char */
  85920. s->dyn_ltree[lc].Freq++;
  85921. } else {
  85922. s->matches++;
  85923. /* Here, lc is the match length - MIN_MATCH */
  85924. dist--; /* dist = match distance - 1 */
  85925. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85926. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85927. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85928. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85929. s->dyn_dtree[d_code(dist)].Freq++;
  85930. }
  85931. #ifdef TRUNCATE_BLOCK
  85932. /* Try to guess if it is profitable to stop the current block here */
  85933. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85934. /* Compute an upper bound for the compressed length */
  85935. ulg out_length = (ulg)s->last_lit*8L;
  85936. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85937. int dcode;
  85938. for (dcode = 0; dcode < D_CODES; dcode++) {
  85939. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85940. (5L+extra_dbits[dcode]);
  85941. }
  85942. out_length >>= 3;
  85943. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85944. s->last_lit, in_length, out_length,
  85945. 100L - out_length*100L/in_length));
  85946. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85947. }
  85948. #endif
  85949. return (s->last_lit == s->lit_bufsize-1);
  85950. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85951. * on 16 bit machines and because stored blocks are restricted to
  85952. * 64K-1 bytes.
  85953. */
  85954. }
  85955. /* ===========================================================================
  85956. * Send the block data compressed using the given Huffman trees
  85957. */
  85958. local void compress_block (deflate_state *s,
  85959. ct_data *ltree, /* literal tree */
  85960. ct_data *dtree) /* distance tree */
  85961. {
  85962. unsigned dist; /* distance of matched string */
  85963. int lc; /* match length or unmatched char (if dist == 0) */
  85964. unsigned lx = 0; /* running index in l_buf */
  85965. unsigned code; /* the code to send */
  85966. int extra; /* number of extra bits to send */
  85967. if (s->last_lit != 0) do {
  85968. dist = s->d_buf[lx];
  85969. lc = s->l_buf[lx++];
  85970. if (dist == 0) {
  85971. send_code(s, lc, ltree); /* send a literal byte */
  85972. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85973. } else {
  85974. /* Here, lc is the match length - MIN_MATCH */
  85975. code = _length_code[lc];
  85976. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85977. extra = extra_lbits[code];
  85978. if (extra != 0) {
  85979. lc -= base_length[code];
  85980. send_bits(s, lc, extra); /* send the extra length bits */
  85981. }
  85982. dist--; /* dist is now the match distance - 1 */
  85983. code = d_code(dist);
  85984. Assert (code < D_CODES, "bad d_code");
  85985. send_code(s, code, dtree); /* send the distance code */
  85986. extra = extra_dbits[code];
  85987. if (extra != 0) {
  85988. dist -= base_dist[code];
  85989. send_bits(s, dist, extra); /* send the extra distance bits */
  85990. }
  85991. } /* literal or match pair ? */
  85992. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85993. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85994. "pendingBuf overflow");
  85995. } while (lx < s->last_lit);
  85996. send_code(s, END_BLOCK, ltree);
  85997. s->last_eob_len = ltree[END_BLOCK].Len;
  85998. }
  85999. /* ===========================================================================
  86000. * Set the data type to BINARY or TEXT, using a crude approximation:
  86001. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  86002. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  86003. * IN assertion: the fields Freq of dyn_ltree are set.
  86004. */
  86005. local void set_data_type (deflate_state *s)
  86006. {
  86007. int n;
  86008. for (n = 0; n < 9; n++)
  86009. if (s->dyn_ltree[n].Freq != 0)
  86010. break;
  86011. if (n == 9)
  86012. for (n = 14; n < 32; n++)
  86013. if (s->dyn_ltree[n].Freq != 0)
  86014. break;
  86015. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  86016. }
  86017. /* ===========================================================================
  86018. * Reverse the first len bits of a code, using straightforward code (a faster
  86019. * method would use a table)
  86020. * IN assertion: 1 <= len <= 15
  86021. */
  86022. local unsigned bi_reverse (unsigned code, int len)
  86023. {
  86024. register unsigned res = 0;
  86025. do {
  86026. res |= code & 1;
  86027. code >>= 1, res <<= 1;
  86028. } while (--len > 0);
  86029. return res >> 1;
  86030. }
  86031. /* ===========================================================================
  86032. * Flush the bit buffer, keeping at most 7 bits in it.
  86033. */
  86034. local void bi_flush (deflate_state *s)
  86035. {
  86036. if (s->bi_valid == 16) {
  86037. put_short(s, s->bi_buf);
  86038. s->bi_buf = 0;
  86039. s->bi_valid = 0;
  86040. } else if (s->bi_valid >= 8) {
  86041. put_byte(s, (Byte)s->bi_buf);
  86042. s->bi_buf >>= 8;
  86043. s->bi_valid -= 8;
  86044. }
  86045. }
  86046. /* ===========================================================================
  86047. * Flush the bit buffer and align the output on a byte boundary
  86048. */
  86049. local void bi_windup (deflate_state *s)
  86050. {
  86051. if (s->bi_valid > 8) {
  86052. put_short(s, s->bi_buf);
  86053. } else if (s->bi_valid > 0) {
  86054. put_byte(s, (Byte)s->bi_buf);
  86055. }
  86056. s->bi_buf = 0;
  86057. s->bi_valid = 0;
  86058. #ifdef DEBUG
  86059. s->bits_sent = (s->bits_sent+7) & ~7;
  86060. #endif
  86061. }
  86062. /* ===========================================================================
  86063. * Copy a stored block, storing first the length and its
  86064. * one's complement if requested.
  86065. */
  86066. local void copy_block(deflate_state *s,
  86067. charf *buf, /* the input data */
  86068. unsigned len, /* its length */
  86069. int header) /* true if block header must be written */
  86070. {
  86071. bi_windup(s); /* align on byte boundary */
  86072. s->last_eob_len = 8; /* enough lookahead for inflate */
  86073. if (header) {
  86074. put_short(s, (ush)len);
  86075. put_short(s, (ush)~len);
  86076. #ifdef DEBUG
  86077. s->bits_sent += 2*16;
  86078. #endif
  86079. }
  86080. #ifdef DEBUG
  86081. s->bits_sent += (ulg)len<<3;
  86082. #endif
  86083. while (len--) {
  86084. put_byte(s, *buf++);
  86085. }
  86086. }
  86087. /*** End of inlined file: trees.c ***/
  86088. /*** Start of inlined file: zutil.c ***/
  86089. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  86090. #ifndef NO_DUMMY_DECL
  86091. struct internal_state {int dummy;}; /* for buggy compilers */
  86092. #endif
  86093. const char * const z_errmsg[10] = {
  86094. "need dictionary", /* Z_NEED_DICT 2 */
  86095. "stream end", /* Z_STREAM_END 1 */
  86096. "", /* Z_OK 0 */
  86097. "file error", /* Z_ERRNO (-1) */
  86098. "stream error", /* Z_STREAM_ERROR (-2) */
  86099. "data error", /* Z_DATA_ERROR (-3) */
  86100. "insufficient memory", /* Z_MEM_ERROR (-4) */
  86101. "buffer error", /* Z_BUF_ERROR (-5) */
  86102. "incompatible version",/* Z_VERSION_ERROR (-6) */
  86103. ""};
  86104. /*const char * ZEXPORT zlibVersion()
  86105. {
  86106. return ZLIB_VERSION;
  86107. }
  86108. uLong ZEXPORT zlibCompileFlags()
  86109. {
  86110. uLong flags;
  86111. flags = 0;
  86112. switch (sizeof(uInt)) {
  86113. case 2: break;
  86114. case 4: flags += 1; break;
  86115. case 8: flags += 2; break;
  86116. default: flags += 3;
  86117. }
  86118. switch (sizeof(uLong)) {
  86119. case 2: break;
  86120. case 4: flags += 1 << 2; break;
  86121. case 8: flags += 2 << 2; break;
  86122. default: flags += 3 << 2;
  86123. }
  86124. switch (sizeof(voidpf)) {
  86125. case 2: break;
  86126. case 4: flags += 1 << 4; break;
  86127. case 8: flags += 2 << 4; break;
  86128. default: flags += 3 << 4;
  86129. }
  86130. switch (sizeof(z_off_t)) {
  86131. case 2: break;
  86132. case 4: flags += 1 << 6; break;
  86133. case 8: flags += 2 << 6; break;
  86134. default: flags += 3 << 6;
  86135. }
  86136. #ifdef DEBUG
  86137. flags += 1 << 8;
  86138. #endif
  86139. #if defined(ASMV) || defined(ASMINF)
  86140. flags += 1 << 9;
  86141. #endif
  86142. #ifdef ZLIB_WINAPI
  86143. flags += 1 << 10;
  86144. #endif
  86145. #ifdef BUILDFIXED
  86146. flags += 1 << 12;
  86147. #endif
  86148. #ifdef DYNAMIC_CRC_TABLE
  86149. flags += 1 << 13;
  86150. #endif
  86151. #ifdef NO_GZCOMPRESS
  86152. flags += 1L << 16;
  86153. #endif
  86154. #ifdef NO_GZIP
  86155. flags += 1L << 17;
  86156. #endif
  86157. #ifdef PKZIP_BUG_WORKAROUND
  86158. flags += 1L << 20;
  86159. #endif
  86160. #ifdef FASTEST
  86161. flags += 1L << 21;
  86162. #endif
  86163. #ifdef STDC
  86164. # ifdef NO_vsnprintf
  86165. flags += 1L << 25;
  86166. # ifdef HAS_vsprintf_void
  86167. flags += 1L << 26;
  86168. # endif
  86169. # else
  86170. # ifdef HAS_vsnprintf_void
  86171. flags += 1L << 26;
  86172. # endif
  86173. # endif
  86174. #else
  86175. flags += 1L << 24;
  86176. # ifdef NO_snprintf
  86177. flags += 1L << 25;
  86178. # ifdef HAS_sprintf_void
  86179. flags += 1L << 26;
  86180. # endif
  86181. # else
  86182. # ifdef HAS_snprintf_void
  86183. flags += 1L << 26;
  86184. # endif
  86185. # endif
  86186. #endif
  86187. return flags;
  86188. }*/
  86189. #ifdef DEBUG
  86190. # ifndef verbose
  86191. # define verbose 0
  86192. # endif
  86193. int z_verbose = verbose;
  86194. void z_error (const char *m)
  86195. {
  86196. fprintf(stderr, "%s\n", m);
  86197. exit(1);
  86198. }
  86199. #endif
  86200. /* exported to allow conversion of error code to string for compress() and
  86201. * uncompress()
  86202. */
  86203. const char * ZEXPORT zError(int err)
  86204. {
  86205. return ERR_MSG(err);
  86206. }
  86207. #if defined(_WIN32_WCE)
  86208. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86209. * errno. We define it as a global variable to simplify porting.
  86210. * Its value is always 0 and should not be used.
  86211. */
  86212. int errno = 0;
  86213. #endif
  86214. #ifndef HAVE_MEMCPY
  86215. void zmemcpy(dest, source, len)
  86216. Bytef* dest;
  86217. const Bytef* source;
  86218. uInt len;
  86219. {
  86220. if (len == 0) return;
  86221. do {
  86222. *dest++ = *source++; /* ??? to be unrolled */
  86223. } while (--len != 0);
  86224. }
  86225. int zmemcmp(s1, s2, len)
  86226. const Bytef* s1;
  86227. const Bytef* s2;
  86228. uInt len;
  86229. {
  86230. uInt j;
  86231. for (j = 0; j < len; j++) {
  86232. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86233. }
  86234. return 0;
  86235. }
  86236. void zmemzero(dest, len)
  86237. Bytef* dest;
  86238. uInt len;
  86239. {
  86240. if (len == 0) return;
  86241. do {
  86242. *dest++ = 0; /* ??? to be unrolled */
  86243. } while (--len != 0);
  86244. }
  86245. #endif
  86246. #ifdef SYS16BIT
  86247. #ifdef __TURBOC__
  86248. /* Turbo C in 16-bit mode */
  86249. # define MY_ZCALLOC
  86250. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86251. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86252. * must fix the pointer. Warning: the pointer must be put back to its
  86253. * original form in order to free it, use zcfree().
  86254. */
  86255. #define MAX_PTR 10
  86256. /* 10*64K = 640K */
  86257. local int next_ptr = 0;
  86258. typedef struct ptr_table_s {
  86259. voidpf org_ptr;
  86260. voidpf new_ptr;
  86261. } ptr_table;
  86262. local ptr_table table[MAX_PTR];
  86263. /* This table is used to remember the original form of pointers
  86264. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86265. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86266. * protected from concurrent access. This hack doesn't work anyway on
  86267. * a protected system like OS/2. Use Microsoft C instead.
  86268. */
  86269. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86270. {
  86271. voidpf buf = opaque; /* just to make some compilers happy */
  86272. ulg bsize = (ulg)items*size;
  86273. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86274. * will return a usable pointer which doesn't have to be normalized.
  86275. */
  86276. if (bsize < 65520L) {
  86277. buf = farmalloc(bsize);
  86278. if (*(ush*)&buf != 0) return buf;
  86279. } else {
  86280. buf = farmalloc(bsize + 16L);
  86281. }
  86282. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86283. table[next_ptr].org_ptr = buf;
  86284. /* Normalize the pointer to seg:0 */
  86285. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86286. *(ush*)&buf = 0;
  86287. table[next_ptr++].new_ptr = buf;
  86288. return buf;
  86289. }
  86290. void zcfree (voidpf opaque, voidpf ptr)
  86291. {
  86292. int n;
  86293. if (*(ush*)&ptr != 0) { /* object < 64K */
  86294. farfree(ptr);
  86295. return;
  86296. }
  86297. /* Find the original pointer */
  86298. for (n = 0; n < next_ptr; n++) {
  86299. if (ptr != table[n].new_ptr) continue;
  86300. farfree(table[n].org_ptr);
  86301. while (++n < next_ptr) {
  86302. table[n-1] = table[n];
  86303. }
  86304. next_ptr--;
  86305. return;
  86306. }
  86307. ptr = opaque; /* just to make some compilers happy */
  86308. Assert(0, "zcfree: ptr not found");
  86309. }
  86310. #endif /* __TURBOC__ */
  86311. #ifdef M_I86
  86312. /* Microsoft C in 16-bit mode */
  86313. # define MY_ZCALLOC
  86314. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86315. # define _halloc halloc
  86316. # define _hfree hfree
  86317. #endif
  86318. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86319. {
  86320. if (opaque) opaque = 0; /* to make compiler happy */
  86321. return _halloc((long)items, size);
  86322. }
  86323. void zcfree (voidpf opaque, voidpf ptr)
  86324. {
  86325. if (opaque) opaque = 0; /* to make compiler happy */
  86326. _hfree(ptr);
  86327. }
  86328. #endif /* M_I86 */
  86329. #endif /* SYS16BIT */
  86330. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86331. #ifndef STDC
  86332. extern voidp malloc OF((uInt size));
  86333. extern voidp calloc OF((uInt items, uInt size));
  86334. extern void free OF((voidpf ptr));
  86335. #endif
  86336. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86337. {
  86338. if (opaque) items += size - size; /* make compiler happy */
  86339. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86340. (voidpf)calloc(items, size);
  86341. }
  86342. void zcfree (voidpf opaque, voidpf ptr)
  86343. {
  86344. free(ptr);
  86345. if (opaque) return; /* make compiler happy */
  86346. }
  86347. #endif /* MY_ZCALLOC */
  86348. /*** End of inlined file: zutil.c ***/
  86349. #undef Byte
  86350. #else
  86351. #include <zlib.h>
  86352. #endif
  86353. }
  86354. #if JUCE_MSVC
  86355. #pragma warning (pop)
  86356. #endif
  86357. BEGIN_JUCE_NAMESPACE
  86358. // internal helper object that holds the zlib structures so they don't have to be
  86359. // included publicly.
  86360. class GZIPDecompressorInputStream::GZIPDecompressHelper
  86361. {
  86362. public:
  86363. GZIPDecompressHelper (const bool noWrap)
  86364. : finished (true),
  86365. needsDictionary (false),
  86366. error (true),
  86367. streamIsValid (false),
  86368. data (0),
  86369. dataSize (0)
  86370. {
  86371. using namespace zlibNamespace;
  86372. zerostruct (stream);
  86373. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86374. finished = error = ! streamIsValid;
  86375. }
  86376. ~GZIPDecompressHelper()
  86377. {
  86378. using namespace zlibNamespace;
  86379. if (streamIsValid)
  86380. inflateEnd (&stream);
  86381. }
  86382. bool needsInput() const throw() { return dataSize <= 0; }
  86383. void setInput (uint8* const data_, const int size) throw()
  86384. {
  86385. data = data_;
  86386. dataSize = size;
  86387. }
  86388. int doNextBlock (uint8* const dest, const int destSize)
  86389. {
  86390. using namespace zlibNamespace;
  86391. if (streamIsValid && data != 0 && ! finished)
  86392. {
  86393. stream.next_in = data;
  86394. stream.next_out = dest;
  86395. stream.avail_in = dataSize;
  86396. stream.avail_out = destSize;
  86397. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86398. {
  86399. case Z_STREAM_END:
  86400. finished = true;
  86401. // deliberate fall-through
  86402. case Z_OK:
  86403. data += dataSize - stream.avail_in;
  86404. dataSize = stream.avail_in;
  86405. return destSize - stream.avail_out;
  86406. case Z_NEED_DICT:
  86407. needsDictionary = true;
  86408. data += dataSize - stream.avail_in;
  86409. dataSize = stream.avail_in;
  86410. break;
  86411. case Z_DATA_ERROR:
  86412. case Z_MEM_ERROR:
  86413. error = true;
  86414. default:
  86415. break;
  86416. }
  86417. }
  86418. return 0;
  86419. }
  86420. bool finished, needsDictionary, error, streamIsValid;
  86421. enum { gzipDecompBufferSize = 32768 };
  86422. private:
  86423. zlibNamespace::z_stream stream;
  86424. uint8* data;
  86425. int dataSize;
  86426. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  86427. };
  86428. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86429. const bool deleteSourceWhenDestroyed,
  86430. const bool noWrap_,
  86431. const int64 uncompressedStreamLength_)
  86432. : sourceStream (sourceStream_, deleteSourceWhenDestroyed),
  86433. uncompressedStreamLength (uncompressedStreamLength_),
  86434. noWrap (noWrap_),
  86435. isEof (false),
  86436. activeBufferSize (0),
  86437. originalSourcePos (sourceStream_->getPosition()),
  86438. currentPos (0),
  86439. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86440. helper (new GZIPDecompressHelper (noWrap_))
  86441. {
  86442. }
  86443. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86444. : sourceStream (&sourceStream_, false),
  86445. uncompressedStreamLength (-1),
  86446. noWrap (false),
  86447. isEof (false),
  86448. activeBufferSize (0),
  86449. originalSourcePos (sourceStream_.getPosition()),
  86450. currentPos (0),
  86451. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86452. helper (new GZIPDecompressHelper (false))
  86453. {
  86454. }
  86455. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86456. {
  86457. }
  86458. int64 GZIPDecompressorInputStream::getTotalLength()
  86459. {
  86460. return uncompressedStreamLength;
  86461. }
  86462. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86463. {
  86464. if ((howMany > 0) && ! isEof)
  86465. {
  86466. jassert (destBuffer != 0);
  86467. if (destBuffer != 0)
  86468. {
  86469. int numRead = 0;
  86470. uint8* d = static_cast <uint8*> (destBuffer);
  86471. while (! helper->error)
  86472. {
  86473. const int n = helper->doNextBlock (d, howMany);
  86474. currentPos += n;
  86475. if (n == 0)
  86476. {
  86477. if (helper->finished || helper->needsDictionary)
  86478. {
  86479. isEof = true;
  86480. return numRead;
  86481. }
  86482. if (helper->needsInput())
  86483. {
  86484. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86485. if (activeBufferSize > 0)
  86486. {
  86487. helper->setInput (buffer, activeBufferSize);
  86488. }
  86489. else
  86490. {
  86491. isEof = true;
  86492. return numRead;
  86493. }
  86494. }
  86495. }
  86496. else
  86497. {
  86498. numRead += n;
  86499. howMany -= n;
  86500. d += n;
  86501. if (howMany <= 0)
  86502. return numRead;
  86503. }
  86504. }
  86505. }
  86506. }
  86507. return 0;
  86508. }
  86509. bool GZIPDecompressorInputStream::isExhausted()
  86510. {
  86511. return helper->error || isEof;
  86512. }
  86513. int64 GZIPDecompressorInputStream::getPosition()
  86514. {
  86515. return currentPos;
  86516. }
  86517. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86518. {
  86519. if (newPos < currentPos)
  86520. {
  86521. // to go backwards, reset the stream and start again..
  86522. isEof = false;
  86523. activeBufferSize = 0;
  86524. currentPos = 0;
  86525. helper = new GZIPDecompressHelper (noWrap);
  86526. sourceStream->setPosition (originalSourcePos);
  86527. }
  86528. skipNextBytes (newPos - currentPos);
  86529. return true;
  86530. }
  86531. END_JUCE_NAMESPACE
  86532. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86533. #endif
  86534. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86535. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86536. #if JUCE_USE_FLAC
  86537. #if JUCE_WINDOWS
  86538. #include <windows.h>
  86539. #endif
  86540. namespace FlacNamespace
  86541. {
  86542. #if JUCE_INCLUDE_FLAC_CODE
  86543. #if JUCE_MSVC
  86544. #pragma warning (disable: 4505 181 111)
  86545. #endif
  86546. #define FLAC__NO_DLL 1
  86547. #if ! defined (SIZE_MAX)
  86548. #define SIZE_MAX 0xffffffff
  86549. #endif
  86550. #define __STDC_LIMIT_MACROS 1
  86551. /*** Start of inlined file: all.h ***/
  86552. #ifndef FLAC__ALL_H
  86553. #define FLAC__ALL_H
  86554. /*** Start of inlined file: export.h ***/
  86555. #ifndef FLAC__EXPORT_H
  86556. #define FLAC__EXPORT_H
  86557. /** \file include/FLAC/export.h
  86558. *
  86559. * \brief
  86560. * This module contains #defines and symbols for exporting function
  86561. * calls, and providing version information and compiled-in features.
  86562. *
  86563. * See the \link flac_export export \endlink module.
  86564. */
  86565. /** \defgroup flac_export FLAC/export.h: export symbols
  86566. * \ingroup flac
  86567. *
  86568. * \brief
  86569. * This module contains #defines and symbols for exporting function
  86570. * calls, and providing version information and compiled-in features.
  86571. *
  86572. * If you are compiling with MSVC and will link to the static library
  86573. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86574. * make sure the symbols are exported properly.
  86575. *
  86576. * \{
  86577. */
  86578. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86579. #define FLAC_API
  86580. #else
  86581. #ifdef FLAC_API_EXPORTS
  86582. #define FLAC_API _declspec(dllexport)
  86583. #else
  86584. #define FLAC_API _declspec(dllimport)
  86585. #endif
  86586. #endif
  86587. /** These #defines will mirror the libtool-based library version number, see
  86588. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86589. */
  86590. #define FLAC_API_VERSION_CURRENT 10
  86591. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86592. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86593. #ifdef __cplusplus
  86594. extern "C" {
  86595. #endif
  86596. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86597. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86598. #ifdef __cplusplus
  86599. }
  86600. #endif
  86601. /* \} */
  86602. #endif
  86603. /*** End of inlined file: export.h ***/
  86604. /*** Start of inlined file: assert.h ***/
  86605. #ifndef FLAC__ASSERT_H
  86606. #define FLAC__ASSERT_H
  86607. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86608. #ifdef DEBUG
  86609. #include <assert.h>
  86610. #define FLAC__ASSERT(x) assert(x)
  86611. #define FLAC__ASSERT_DECLARATION(x) x
  86612. #else
  86613. #define FLAC__ASSERT(x)
  86614. #define FLAC__ASSERT_DECLARATION(x)
  86615. #endif
  86616. #endif
  86617. /*** End of inlined file: assert.h ***/
  86618. /*** Start of inlined file: callback.h ***/
  86619. #ifndef FLAC__CALLBACK_H
  86620. #define FLAC__CALLBACK_H
  86621. /*** Start of inlined file: ordinals.h ***/
  86622. #ifndef FLAC__ORDINALS_H
  86623. #define FLAC__ORDINALS_H
  86624. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86625. #include <inttypes.h>
  86626. #endif
  86627. typedef signed char FLAC__int8;
  86628. typedef unsigned char FLAC__uint8;
  86629. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86630. typedef __int16 FLAC__int16;
  86631. typedef __int32 FLAC__int32;
  86632. typedef __int64 FLAC__int64;
  86633. typedef unsigned __int16 FLAC__uint16;
  86634. typedef unsigned __int32 FLAC__uint32;
  86635. typedef unsigned __int64 FLAC__uint64;
  86636. #elif defined(__EMX__)
  86637. typedef short FLAC__int16;
  86638. typedef long FLAC__int32;
  86639. typedef long long FLAC__int64;
  86640. typedef unsigned short FLAC__uint16;
  86641. typedef unsigned long FLAC__uint32;
  86642. typedef unsigned long long FLAC__uint64;
  86643. #else
  86644. typedef int16_t FLAC__int16;
  86645. typedef int32_t FLAC__int32;
  86646. typedef int64_t FLAC__int64;
  86647. typedef uint16_t FLAC__uint16;
  86648. typedef uint32_t FLAC__uint32;
  86649. typedef uint64_t FLAC__uint64;
  86650. #endif
  86651. typedef int FLAC__bool;
  86652. typedef FLAC__uint8 FLAC__byte;
  86653. #ifdef true
  86654. #undef true
  86655. #endif
  86656. #ifdef false
  86657. #undef false
  86658. #endif
  86659. #ifndef __cplusplus
  86660. #define true 1
  86661. #define false 0
  86662. #endif
  86663. #endif
  86664. /*** End of inlined file: ordinals.h ***/
  86665. #include <stdlib.h> /* for size_t */
  86666. /** \file include/FLAC/callback.h
  86667. *
  86668. * \brief
  86669. * This module defines the structures for describing I/O callbacks
  86670. * to the other FLAC interfaces.
  86671. *
  86672. * See the detailed documentation for callbacks in the
  86673. * \link flac_callbacks callbacks \endlink module.
  86674. */
  86675. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86676. * \ingroup flac
  86677. *
  86678. * \brief
  86679. * This module defines the structures for describing I/O callbacks
  86680. * to the other FLAC interfaces.
  86681. *
  86682. * The purpose of the I/O callback functions is to create a common way
  86683. * for the metadata interfaces to handle I/O.
  86684. *
  86685. * Originally the metadata interfaces required filenames as the way of
  86686. * specifying FLAC files to operate on. This is problematic in some
  86687. * environments so there is an additional option to specify a set of
  86688. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86689. *
  86690. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86691. * opaque structure for a data source.
  86692. *
  86693. * The callback function prototypes are similar (but not identical) to the
  86694. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86695. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86696. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86697. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86698. * is required. \warning You generally CANNOT directly use fseek or ftell
  86699. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86700. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86701. * large files. You will have to find an equivalent function (e.g. ftello),
  86702. * or write a wrapper. The same is true for feof() since this is usually
  86703. * implemented as a macro, not as a function whose address can be taken.
  86704. *
  86705. * \{
  86706. */
  86707. #ifdef __cplusplus
  86708. extern "C" {
  86709. #endif
  86710. /** This is the opaque handle type used by the callbacks. Typically
  86711. * this is a \c FILE* or address of a file descriptor.
  86712. */
  86713. typedef void* FLAC__IOHandle;
  86714. /** Signature for the read callback.
  86715. * The signature and semantics match POSIX fread() implementations
  86716. * and can generally be used interchangeably.
  86717. *
  86718. * \param ptr The address of the read buffer.
  86719. * \param size The size of the records to be read.
  86720. * \param nmemb The number of records to be read.
  86721. * \param handle The handle to the data source.
  86722. * \retval size_t
  86723. * The number of records read.
  86724. */
  86725. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86726. /** Signature for the write callback.
  86727. * The signature and semantics match POSIX fwrite() implementations
  86728. * and can generally be used interchangeably.
  86729. *
  86730. * \param ptr The address of the write buffer.
  86731. * \param size The size of the records to be written.
  86732. * \param nmemb The number of records to be written.
  86733. * \param handle The handle to the data source.
  86734. * \retval size_t
  86735. * The number of records written.
  86736. */
  86737. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86738. /** Signature for the seek callback.
  86739. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86740. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86741. * and 32-bits wide.
  86742. *
  86743. * \param handle The handle to the data source.
  86744. * \param offset The new position, relative to \a whence
  86745. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86746. * \retval int
  86747. * \c 0 on success, \c -1 on error.
  86748. */
  86749. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86750. /** Signature for the tell callback.
  86751. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86752. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86753. * and 32-bits wide.
  86754. *
  86755. * \param handle The handle to the data source.
  86756. * \retval FLAC__int64
  86757. * The current position on success, \c -1 on error.
  86758. */
  86759. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86760. /** Signature for the EOF callback.
  86761. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86762. * on many systems, feof() is a macro, so in this case a wrapper function
  86763. * must be provided instead.
  86764. *
  86765. * \param handle The handle to the data source.
  86766. * \retval int
  86767. * \c 0 if not at end of file, nonzero if at end of file.
  86768. */
  86769. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86770. /** Signature for the close callback.
  86771. * The signature and semantics match POSIX fclose() implementations
  86772. * and can generally be used interchangeably.
  86773. *
  86774. * \param handle The handle to the data source.
  86775. * \retval int
  86776. * \c 0 on success, \c EOF on error.
  86777. */
  86778. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86779. /** A structure for holding a set of callbacks.
  86780. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86781. * describe which of the callbacks are required. The ones that are not
  86782. * required may be set to NULL.
  86783. *
  86784. * If the seek requirement for an interface is optional, you can signify that
  86785. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86786. */
  86787. typedef struct {
  86788. FLAC__IOCallback_Read read;
  86789. FLAC__IOCallback_Write write;
  86790. FLAC__IOCallback_Seek seek;
  86791. FLAC__IOCallback_Tell tell;
  86792. FLAC__IOCallback_Eof eof;
  86793. FLAC__IOCallback_Close close;
  86794. } FLAC__IOCallbacks;
  86795. /* \} */
  86796. #ifdef __cplusplus
  86797. }
  86798. #endif
  86799. #endif
  86800. /*** End of inlined file: callback.h ***/
  86801. /*** Start of inlined file: format.h ***/
  86802. #ifndef FLAC__FORMAT_H
  86803. #define FLAC__FORMAT_H
  86804. #ifdef __cplusplus
  86805. extern "C" {
  86806. #endif
  86807. /** \file include/FLAC/format.h
  86808. *
  86809. * \brief
  86810. * This module contains structure definitions for the representation
  86811. * of FLAC format components in memory. These are the basic
  86812. * structures used by the rest of the interfaces.
  86813. *
  86814. * See the detailed documentation in the
  86815. * \link flac_format format \endlink module.
  86816. */
  86817. /** \defgroup flac_format FLAC/format.h: format components
  86818. * \ingroup flac
  86819. *
  86820. * \brief
  86821. * This module contains structure definitions for the representation
  86822. * of FLAC format components in memory. These are the basic
  86823. * structures used by the rest of the interfaces.
  86824. *
  86825. * First, you should be familiar with the
  86826. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86827. * follow directly from the specification. As a user of libFLAC, the
  86828. * interesting parts really are the structures that describe the frame
  86829. * header and metadata blocks.
  86830. *
  86831. * The format structures here are very primitive, designed to store
  86832. * information in an efficient way. Reading information from the
  86833. * structures is easy but creating or modifying them directly is
  86834. * more complex. For the most part, as a user of a library, editing
  86835. * is not necessary; however, for metadata blocks it is, so there are
  86836. * convenience functions provided in the \link flac_metadata metadata
  86837. * module \endlink to simplify the manipulation of metadata blocks.
  86838. *
  86839. * \note
  86840. * It's not the best convention, but symbols ending in _LEN are in bits
  86841. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86842. * global variables because they are usually used when declaring byte
  86843. * arrays and some compilers require compile-time knowledge of array
  86844. * sizes when declared on the stack.
  86845. *
  86846. * \{
  86847. */
  86848. /*
  86849. Most of the values described in this file are defined by the FLAC
  86850. format specification. There is nothing to tune here.
  86851. */
  86852. /** The largest legal metadata type code. */
  86853. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86854. /** The minimum block size, in samples, permitted by the format. */
  86855. #define FLAC__MIN_BLOCK_SIZE (16u)
  86856. /** The maximum block size, in samples, permitted by the format. */
  86857. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86858. /** The maximum block size, in samples, permitted by the FLAC subset for
  86859. * sample rates up to 48kHz. */
  86860. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86861. /** The maximum number of channels permitted by the format. */
  86862. #define FLAC__MAX_CHANNELS (8u)
  86863. /** The minimum sample resolution permitted by the format. */
  86864. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86865. /** The maximum sample resolution permitted by the format. */
  86866. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86867. /** The maximum sample resolution permitted by libFLAC.
  86868. *
  86869. * \warning
  86870. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86871. * the reference encoder/decoder is currently limited to 24 bits because
  86872. * of prevalent 32-bit math, so make sure and use this value when
  86873. * appropriate.
  86874. */
  86875. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86876. /** The maximum sample rate permitted by the format. The value is
  86877. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86878. * as to why.
  86879. */
  86880. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86881. /** The maximum LPC order permitted by the format. */
  86882. #define FLAC__MAX_LPC_ORDER (32u)
  86883. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86884. * up to 48kHz. */
  86885. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86886. /** The minimum quantized linear predictor coefficient precision
  86887. * permitted by the format.
  86888. */
  86889. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86890. /** The maximum quantized linear predictor coefficient precision
  86891. * permitted by the format.
  86892. */
  86893. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86894. /** The maximum order of the fixed predictors permitted by the format. */
  86895. #define FLAC__MAX_FIXED_ORDER (4u)
  86896. /** The maximum Rice partition order permitted by the format. */
  86897. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86898. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86899. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86900. /** The version string of the release, stamped onto the libraries and binaries.
  86901. *
  86902. * \note
  86903. * This does not correspond to the shared library version number, which
  86904. * is used to determine binary compatibility.
  86905. */
  86906. extern FLAC_API const char *FLAC__VERSION_STRING;
  86907. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86908. * This is a NUL-terminated ASCII string; when inserted into the
  86909. * VORBIS_COMMENT the trailing null is stripped.
  86910. */
  86911. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86912. /** The byte string representation of the beginning of a FLAC stream. */
  86913. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86914. /** The 32-bit integer big-endian representation of the beginning of
  86915. * a FLAC stream.
  86916. */
  86917. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86918. /** The length of the FLAC signature in bits. */
  86919. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86920. /** The length of the FLAC signature in bytes. */
  86921. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86922. /*****************************************************************************
  86923. *
  86924. * Subframe structures
  86925. *
  86926. *****************************************************************************/
  86927. /*****************************************************************************/
  86928. /** An enumeration of the available entropy coding methods. */
  86929. typedef enum {
  86930. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86931. /**< Residual is coded by partitioning into contexts, each with it's own
  86932. * 4-bit Rice parameter. */
  86933. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86934. /**< Residual is coded by partitioning into contexts, each with it's own
  86935. * 5-bit Rice parameter. */
  86936. } FLAC__EntropyCodingMethodType;
  86937. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86938. *
  86939. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86940. * give the string equivalent. The contents should not be modified.
  86941. */
  86942. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86943. /** Contents of a Rice partitioned residual
  86944. */
  86945. typedef struct {
  86946. unsigned *parameters;
  86947. /**< The Rice parameters for each context. */
  86948. unsigned *raw_bits;
  86949. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86950. * partitions and zero for unescaped partitions.
  86951. */
  86952. unsigned capacity_by_order;
  86953. /**< The capacity of the \a parameters and \a raw_bits arrays
  86954. * specified as an order, i.e. the number of array elements
  86955. * allocated is 2 ^ \a capacity_by_order.
  86956. */
  86957. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86958. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86959. */
  86960. typedef struct {
  86961. unsigned order;
  86962. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86963. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86964. /**< The context's Rice parameters and/or raw bits. */
  86965. } FLAC__EntropyCodingMethod_PartitionedRice;
  86966. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86967. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86968. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86969. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86970. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86971. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86972. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86973. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86974. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86975. */
  86976. typedef struct {
  86977. FLAC__EntropyCodingMethodType type;
  86978. union {
  86979. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86980. } data;
  86981. } FLAC__EntropyCodingMethod;
  86982. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86983. /*****************************************************************************/
  86984. /** An enumeration of the available subframe types. */
  86985. typedef enum {
  86986. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86987. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86988. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86989. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86990. } FLAC__SubframeType;
  86991. /** Maps a FLAC__SubframeType to a C string.
  86992. *
  86993. * Using a FLAC__SubframeType as the index to this array will
  86994. * give the string equivalent. The contents should not be modified.
  86995. */
  86996. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86997. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86998. */
  86999. typedef struct {
  87000. FLAC__int32 value; /**< The constant signal value. */
  87001. } FLAC__Subframe_Constant;
  87002. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  87003. */
  87004. typedef struct {
  87005. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  87006. } FLAC__Subframe_Verbatim;
  87007. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  87008. */
  87009. typedef struct {
  87010. FLAC__EntropyCodingMethod entropy_coding_method;
  87011. /**< The residual coding method. */
  87012. unsigned order;
  87013. /**< The polynomial order. */
  87014. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  87015. /**< Warmup samples to prime the predictor, length == order. */
  87016. const FLAC__int32 *residual;
  87017. /**< The residual signal, length == (blocksize minus order) samples. */
  87018. } FLAC__Subframe_Fixed;
  87019. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  87020. */
  87021. typedef struct {
  87022. FLAC__EntropyCodingMethod entropy_coding_method;
  87023. /**< The residual coding method. */
  87024. unsigned order;
  87025. /**< The FIR order. */
  87026. unsigned qlp_coeff_precision;
  87027. /**< Quantized FIR filter coefficient precision in bits. */
  87028. int quantization_level;
  87029. /**< The qlp coeff shift needed. */
  87030. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  87031. /**< FIR filter coefficients. */
  87032. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  87033. /**< Warmup samples to prime the predictor, length == order. */
  87034. const FLAC__int32 *residual;
  87035. /**< The residual signal, length == (blocksize minus order) samples. */
  87036. } FLAC__Subframe_LPC;
  87037. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  87038. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  87039. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  87040. */
  87041. typedef struct {
  87042. FLAC__SubframeType type;
  87043. union {
  87044. FLAC__Subframe_Constant constant;
  87045. FLAC__Subframe_Fixed fixed;
  87046. FLAC__Subframe_LPC lpc;
  87047. FLAC__Subframe_Verbatim verbatim;
  87048. } data;
  87049. unsigned wasted_bits;
  87050. } FLAC__Subframe;
  87051. /** == 1 (bit)
  87052. *
  87053. * This used to be a zero-padding bit (hence the name
  87054. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  87055. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  87056. * to mean something else.
  87057. */
  87058. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  87059. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  87060. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  87061. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  87062. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  87063. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  87064. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  87065. /*****************************************************************************/
  87066. /*****************************************************************************
  87067. *
  87068. * Frame structures
  87069. *
  87070. *****************************************************************************/
  87071. /** An enumeration of the available channel assignments. */
  87072. typedef enum {
  87073. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  87074. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  87075. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  87076. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  87077. } FLAC__ChannelAssignment;
  87078. /** Maps a FLAC__ChannelAssignment to a C string.
  87079. *
  87080. * Using a FLAC__ChannelAssignment as the index to this array will
  87081. * give the string equivalent. The contents should not be modified.
  87082. */
  87083. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  87084. /** An enumeration of the possible frame numbering methods. */
  87085. typedef enum {
  87086. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  87087. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  87088. } FLAC__FrameNumberType;
  87089. /** Maps a FLAC__FrameNumberType to a C string.
  87090. *
  87091. * Using a FLAC__FrameNumberType as the index to this array will
  87092. * give the string equivalent. The contents should not be modified.
  87093. */
  87094. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  87095. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  87096. */
  87097. typedef struct {
  87098. unsigned blocksize;
  87099. /**< The number of samples per subframe. */
  87100. unsigned sample_rate;
  87101. /**< The sample rate in Hz. */
  87102. unsigned channels;
  87103. /**< The number of channels (== number of subframes). */
  87104. FLAC__ChannelAssignment channel_assignment;
  87105. /**< The channel assignment for the frame. */
  87106. unsigned bits_per_sample;
  87107. /**< The sample resolution. */
  87108. FLAC__FrameNumberType number_type;
  87109. /**< The numbering scheme used for the frame. As a convenience, the
  87110. * decoder will always convert a frame number to a sample number because
  87111. * the rules are complex. */
  87112. union {
  87113. FLAC__uint32 frame_number;
  87114. FLAC__uint64 sample_number;
  87115. } number;
  87116. /**< The frame number or sample number of first sample in frame;
  87117. * use the \a number_type value to determine which to use. */
  87118. FLAC__uint8 crc;
  87119. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  87120. * of the raw frame header bytes, meaning everything before the CRC byte
  87121. * including the sync code.
  87122. */
  87123. } FLAC__FrameHeader;
  87124. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  87125. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  87126. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  87127. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  87128. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  87129. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  87130. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  87131. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  87132. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  87133. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  87134. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  87135. */
  87136. typedef struct {
  87137. FLAC__uint16 crc;
  87138. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  87139. * 0) of the bytes before the crc, back to and including the frame header
  87140. * sync code.
  87141. */
  87142. } FLAC__FrameFooter;
  87143. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  87144. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  87145. */
  87146. typedef struct {
  87147. FLAC__FrameHeader header;
  87148. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  87149. FLAC__FrameFooter footer;
  87150. } FLAC__Frame;
  87151. /*****************************************************************************/
  87152. /*****************************************************************************
  87153. *
  87154. * Meta-data structures
  87155. *
  87156. *****************************************************************************/
  87157. /** An enumeration of the available metadata block types. */
  87158. typedef enum {
  87159. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87160. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87161. FLAC__METADATA_TYPE_PADDING = 1,
  87162. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87163. FLAC__METADATA_TYPE_APPLICATION = 2,
  87164. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87165. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87166. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87167. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87168. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87169. FLAC__METADATA_TYPE_CUESHEET = 5,
  87170. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87171. FLAC__METADATA_TYPE_PICTURE = 6,
  87172. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87173. FLAC__METADATA_TYPE_UNDEFINED = 7
  87174. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87175. } FLAC__MetadataType;
  87176. /** Maps a FLAC__MetadataType to a C string.
  87177. *
  87178. * Using a FLAC__MetadataType as the index to this array will
  87179. * give the string equivalent. The contents should not be modified.
  87180. */
  87181. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87182. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87183. */
  87184. typedef struct {
  87185. unsigned min_blocksize, max_blocksize;
  87186. unsigned min_framesize, max_framesize;
  87187. unsigned sample_rate;
  87188. unsigned channels;
  87189. unsigned bits_per_sample;
  87190. FLAC__uint64 total_samples;
  87191. FLAC__byte md5sum[16];
  87192. } FLAC__StreamMetadata_StreamInfo;
  87193. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87194. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87195. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87196. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87197. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87198. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87199. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87200. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87201. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87202. /** The total stream length of the STREAMINFO block in bytes. */
  87203. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87204. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87205. */
  87206. typedef struct {
  87207. int dummy;
  87208. /**< Conceptually this is an empty struct since we don't store the
  87209. * padding bytes. Empty structs are not allowed by some C compilers,
  87210. * hence the dummy.
  87211. */
  87212. } FLAC__StreamMetadata_Padding;
  87213. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87214. */
  87215. typedef struct {
  87216. FLAC__byte id[4];
  87217. FLAC__byte *data;
  87218. } FLAC__StreamMetadata_Application;
  87219. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87220. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87221. */
  87222. typedef struct {
  87223. FLAC__uint64 sample_number;
  87224. /**< The sample number of the target frame. */
  87225. FLAC__uint64 stream_offset;
  87226. /**< The offset, in bytes, of the target frame with respect to
  87227. * beginning of the first frame. */
  87228. unsigned frame_samples;
  87229. /**< The number of samples in the target frame. */
  87230. } FLAC__StreamMetadata_SeekPoint;
  87231. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87232. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87233. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87234. /** The total stream length of a seek point in bytes. */
  87235. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87236. /** The value used in the \a sample_number field of
  87237. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87238. * point (== 0xffffffffffffffff).
  87239. */
  87240. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87241. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87242. *
  87243. * \note From the format specification:
  87244. * - The seek points must be sorted by ascending sample number.
  87245. * - Each seek point's sample number must be the first sample of the
  87246. * target frame.
  87247. * - Each seek point's sample number must be unique within the table.
  87248. * - Existence of a SEEKTABLE block implies a correct setting of
  87249. * total_samples in the stream_info block.
  87250. * - Behavior is undefined when more than one SEEKTABLE block is
  87251. * present in a stream.
  87252. */
  87253. typedef struct {
  87254. unsigned num_points;
  87255. FLAC__StreamMetadata_SeekPoint *points;
  87256. } FLAC__StreamMetadata_SeekTable;
  87257. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87258. *
  87259. * For convenience, the APIs maintain a trailing NUL character at the end of
  87260. * \a entry which is not counted toward \a length, i.e.
  87261. * \code strlen(entry) == length \endcode
  87262. */
  87263. typedef struct {
  87264. FLAC__uint32 length;
  87265. FLAC__byte *entry;
  87266. } FLAC__StreamMetadata_VorbisComment_Entry;
  87267. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87268. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87269. */
  87270. typedef struct {
  87271. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87272. FLAC__uint32 num_comments;
  87273. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87274. } FLAC__StreamMetadata_VorbisComment;
  87275. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87276. /** FLAC CUESHEET track index structure. (See the
  87277. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87278. * the full description of each field.)
  87279. */
  87280. typedef struct {
  87281. FLAC__uint64 offset;
  87282. /**< Offset in samples, relative to the track offset, of the index
  87283. * point.
  87284. */
  87285. FLAC__byte number;
  87286. /**< The index point number. */
  87287. } FLAC__StreamMetadata_CueSheet_Index;
  87288. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87289. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87290. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87291. /** FLAC CUESHEET track structure. (See the
  87292. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87293. * the full description of each field.)
  87294. */
  87295. typedef struct {
  87296. FLAC__uint64 offset;
  87297. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87298. FLAC__byte number;
  87299. /**< The track number. */
  87300. char isrc[13];
  87301. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87302. unsigned type:1;
  87303. /**< The track type: 0 for audio, 1 for non-audio. */
  87304. unsigned pre_emphasis:1;
  87305. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87306. FLAC__byte num_indices;
  87307. /**< The number of track index points. */
  87308. FLAC__StreamMetadata_CueSheet_Index *indices;
  87309. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87310. } FLAC__StreamMetadata_CueSheet_Track;
  87311. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87312. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87313. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87314. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87315. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87316. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87317. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87318. /** FLAC CUESHEET structure. (See the
  87319. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87320. * for the full description of each field.)
  87321. */
  87322. typedef struct {
  87323. char media_catalog_number[129];
  87324. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87325. * general, the media catalog number may be 0 to 128 bytes long; any
  87326. * unused characters should be right-padded with NUL characters.
  87327. */
  87328. FLAC__uint64 lead_in;
  87329. /**< The number of lead-in samples. */
  87330. FLAC__bool is_cd;
  87331. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87332. unsigned num_tracks;
  87333. /**< The number of tracks. */
  87334. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87335. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87336. } FLAC__StreamMetadata_CueSheet;
  87337. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87338. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87339. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87340. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87341. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87342. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87343. typedef enum {
  87344. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87345. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87346. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87347. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87348. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87349. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87350. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87351. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87352. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87353. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87354. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87355. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87356. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87357. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87358. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87359. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87360. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87361. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87362. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87363. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87364. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87365. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87366. } FLAC__StreamMetadata_Picture_Type;
  87367. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87368. *
  87369. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87370. * will give the string equivalent. The contents should not be
  87371. * modified.
  87372. */
  87373. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87374. /** FLAC PICTURE structure. (See the
  87375. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87376. * for the full description of each field.)
  87377. */
  87378. typedef struct {
  87379. FLAC__StreamMetadata_Picture_Type type;
  87380. /**< The kind of picture stored. */
  87381. char *mime_type;
  87382. /**< Picture data's MIME type, in ASCII printable characters
  87383. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87384. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87385. * MIME type of '-->' is also allowed, in which case the picture
  87386. * data should be a complete URL. In file storage, the MIME type is
  87387. * stored as a 32-bit length followed by the ASCII string with no NUL
  87388. * terminator, but is converted to a plain C string in this structure
  87389. * for convenience.
  87390. */
  87391. FLAC__byte *description;
  87392. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87393. * the description is stored as a 32-bit length followed by the UTF-8
  87394. * string with no NUL terminator, but is converted to a plain C string
  87395. * in this structure for convenience.
  87396. */
  87397. FLAC__uint32 width;
  87398. /**< Picture's width in pixels. */
  87399. FLAC__uint32 height;
  87400. /**< Picture's height in pixels. */
  87401. FLAC__uint32 depth;
  87402. /**< Picture's color depth in bits-per-pixel. */
  87403. FLAC__uint32 colors;
  87404. /**< For indexed palettes (like GIF), picture's number of colors (the
  87405. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87406. */
  87407. FLAC__uint32 data_length;
  87408. /**< Length of binary picture data in bytes. */
  87409. FLAC__byte *data;
  87410. /**< Binary picture data. */
  87411. } FLAC__StreamMetadata_Picture;
  87412. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87413. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87414. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87415. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87416. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87417. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87418. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87419. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87420. /** Structure that is used when a metadata block of unknown type is loaded.
  87421. * The contents are opaque. The structure is used only internally to
  87422. * correctly handle unknown metadata.
  87423. */
  87424. typedef struct {
  87425. FLAC__byte *data;
  87426. } FLAC__StreamMetadata_Unknown;
  87427. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87428. */
  87429. typedef struct {
  87430. FLAC__MetadataType type;
  87431. /**< The type of the metadata block; used determine which member of the
  87432. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87433. * then \a data.unknown must be used. */
  87434. FLAC__bool is_last;
  87435. /**< \c true if this metadata block is the last, else \a false */
  87436. unsigned length;
  87437. /**< Length, in bytes, of the block data as it appears in the stream. */
  87438. union {
  87439. FLAC__StreamMetadata_StreamInfo stream_info;
  87440. FLAC__StreamMetadata_Padding padding;
  87441. FLAC__StreamMetadata_Application application;
  87442. FLAC__StreamMetadata_SeekTable seek_table;
  87443. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87444. FLAC__StreamMetadata_CueSheet cue_sheet;
  87445. FLAC__StreamMetadata_Picture picture;
  87446. FLAC__StreamMetadata_Unknown unknown;
  87447. } data;
  87448. /**< Polymorphic block data; use the \a type value to determine which
  87449. * to use. */
  87450. } FLAC__StreamMetadata;
  87451. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87452. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87453. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87454. /** The total stream length of a metadata block header in bytes. */
  87455. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87456. /*****************************************************************************/
  87457. /*****************************************************************************
  87458. *
  87459. * Utility functions
  87460. *
  87461. *****************************************************************************/
  87462. /** Tests that a sample rate is valid for FLAC.
  87463. *
  87464. * \param sample_rate The sample rate to test for compliance.
  87465. * \retval FLAC__bool
  87466. * \c true if the given sample rate conforms to the specification, else
  87467. * \c false.
  87468. */
  87469. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87470. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87471. * for valid sample rates are slightly more complex since the rate has to
  87472. * be expressible completely in the frame header.
  87473. *
  87474. * \param sample_rate The sample rate to test for compliance.
  87475. * \retval FLAC__bool
  87476. * \c true if the given sample rate conforms to the specification for the
  87477. * subset, else \c false.
  87478. */
  87479. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87480. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87481. * comment specification.
  87482. *
  87483. * Vorbis comment names must be composed only of characters from
  87484. * [0x20-0x3C,0x3E-0x7D].
  87485. *
  87486. * \param name A NUL-terminated string to be checked.
  87487. * \assert
  87488. * \code name != NULL \endcode
  87489. * \retval FLAC__bool
  87490. * \c false if entry name is illegal, else \c true.
  87491. */
  87492. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87493. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87494. * comment specification.
  87495. *
  87496. * Vorbis comment values must be valid UTF-8 sequences.
  87497. *
  87498. * \param value A string to be checked.
  87499. * \param length A the length of \a value in bytes. May be
  87500. * \c (unsigned)(-1) to indicate that \a value is a plain
  87501. * UTF-8 NUL-terminated string.
  87502. * \assert
  87503. * \code value != NULL \endcode
  87504. * \retval FLAC__bool
  87505. * \c false if entry name is illegal, else \c true.
  87506. */
  87507. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87508. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87509. * comment specification.
  87510. *
  87511. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87512. * 'value' must be legal according to
  87513. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87514. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87515. *
  87516. * \param entry An entry to be checked.
  87517. * \param length The length of \a entry in bytes.
  87518. * \assert
  87519. * \code value != NULL \endcode
  87520. * \retval FLAC__bool
  87521. * \c false if entry name is illegal, else \c true.
  87522. */
  87523. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87524. /** Check a seek table to see if it conforms to the FLAC specification.
  87525. * See the format specification for limits on the contents of the
  87526. * seek table.
  87527. *
  87528. * \param seek_table A pointer to a seek table to be checked.
  87529. * \assert
  87530. * \code seek_table != NULL \endcode
  87531. * \retval FLAC__bool
  87532. * \c false if seek table is illegal, else \c true.
  87533. */
  87534. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87535. /** Sort a seek table's seek points according to the format specification.
  87536. * This includes a "unique-ification" step to remove duplicates, i.e.
  87537. * seek points with identical \a sample_number values. Duplicate seek
  87538. * points are converted into placeholder points and sorted to the end of
  87539. * the table.
  87540. *
  87541. * \param seek_table A pointer to a seek table to be sorted.
  87542. * \assert
  87543. * \code seek_table != NULL \endcode
  87544. * \retval unsigned
  87545. * The number of duplicate seek points converted into placeholders.
  87546. */
  87547. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87548. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87549. * See the format specification for limits on the contents of the
  87550. * cue sheet.
  87551. *
  87552. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87553. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87554. * stringent requirements for a CD-DA (audio) disc.
  87555. * \param violation Address of a pointer to a string. If there is a
  87556. * violation, a pointer to a string explanation of the
  87557. * violation will be returned here. \a violation may be
  87558. * \c NULL if you don't need the returned string. Do not
  87559. * free the returned string; it will always point to static
  87560. * data.
  87561. * \assert
  87562. * \code cue_sheet != NULL \endcode
  87563. * \retval FLAC__bool
  87564. * \c false if cue sheet is illegal, else \c true.
  87565. */
  87566. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87567. /** Check picture data to see if it conforms to the FLAC specification.
  87568. * See the format specification for limits on the contents of the
  87569. * PICTURE block.
  87570. *
  87571. * \param picture A pointer to existing picture data to be checked.
  87572. * \param violation Address of a pointer to a string. If there is a
  87573. * violation, a pointer to a string explanation of the
  87574. * violation will be returned here. \a violation may be
  87575. * \c NULL if you don't need the returned string. Do not
  87576. * free the returned string; it will always point to static
  87577. * data.
  87578. * \assert
  87579. * \code picture != NULL \endcode
  87580. * \retval FLAC__bool
  87581. * \c false if picture data is illegal, else \c true.
  87582. */
  87583. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87584. /* \} */
  87585. #ifdef __cplusplus
  87586. }
  87587. #endif
  87588. #endif
  87589. /*** End of inlined file: format.h ***/
  87590. /*** Start of inlined file: metadata.h ***/
  87591. #ifndef FLAC__METADATA_H
  87592. #define FLAC__METADATA_H
  87593. #include <sys/types.h> /* for off_t */
  87594. /* --------------------------------------------------------------------
  87595. (For an example of how all these routines are used, see the source
  87596. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87597. metaflac in src/metaflac/)
  87598. ------------------------------------------------------------------*/
  87599. /** \file include/FLAC/metadata.h
  87600. *
  87601. * \brief
  87602. * This module provides functions for creating and manipulating FLAC
  87603. * metadata blocks in memory, and three progressively more powerful
  87604. * interfaces for traversing and editing metadata in FLAC files.
  87605. *
  87606. * See the detailed documentation for each interface in the
  87607. * \link flac_metadata metadata \endlink module.
  87608. */
  87609. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87610. * \ingroup flac
  87611. *
  87612. * \brief
  87613. * This module provides functions for creating and manipulating FLAC
  87614. * metadata blocks in memory, and three progressively more powerful
  87615. * interfaces for traversing and editing metadata in native FLAC files.
  87616. * Note that currently only the Chain interface (level 2) supports Ogg
  87617. * FLAC files, and it is read-only i.e. no writing back changed
  87618. * metadata to file.
  87619. *
  87620. * There are three metadata interfaces of increasing complexity:
  87621. *
  87622. * Level 0:
  87623. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87624. * PICTURE blocks.
  87625. *
  87626. * Level 1:
  87627. * Read-write access to all metadata blocks. This level is write-
  87628. * efficient in most cases (more on this below), and uses less memory
  87629. * than level 2.
  87630. *
  87631. * Level 2:
  87632. * Read-write access to all metadata blocks. This level is write-
  87633. * efficient in all cases, but uses more memory since all metadata for
  87634. * the whole file is read into memory and manipulated before writing
  87635. * out again.
  87636. *
  87637. * What do we mean by efficient? Since FLAC metadata appears at the
  87638. * beginning of the file, when writing metadata back to a FLAC file
  87639. * it is possible to grow or shrink the metadata such that the entire
  87640. * file must be rewritten. However, if the size remains the same during
  87641. * changes or PADDING blocks are utilized, only the metadata needs to be
  87642. * overwritten, which is much faster.
  87643. *
  87644. * Efficient means the whole file is rewritten at most one time, and only
  87645. * when necessary. Level 1 is not efficient only in the case that you
  87646. * cause more than one metadata block to grow or shrink beyond what can
  87647. * be accomodated by padding. In this case you should probably use level
  87648. * 2, which allows you to edit all the metadata for a file in memory and
  87649. * write it out all at once.
  87650. *
  87651. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87652. * front of the file.
  87653. *
  87654. * All levels access files via their filenames. In addition, level 2
  87655. * has additional alternative read and write functions that take an I/O
  87656. * handle and callbacks, for situations where access by filename is not
  87657. * possible.
  87658. *
  87659. * In addition to the three interfaces, this module defines functions for
  87660. * creating and manipulating various metadata objects in memory. As we see
  87661. * from the Format module, FLAC metadata blocks in memory are very primitive
  87662. * structures for storing information in an efficient way. Reading
  87663. * information from the structures is easy but creating or modifying them
  87664. * directly is more complex. The metadata object routines here facilitate
  87665. * this by taking care of the consistency and memory management drudgery.
  87666. *
  87667. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87668. * metadata however, you will not probably not need these.
  87669. *
  87670. * From a dependency standpoint, none of the encoders or decoders require
  87671. * the metadata module. This is so that embedded users can strip out the
  87672. * metadata module from libFLAC to reduce the size and complexity.
  87673. */
  87674. #ifdef __cplusplus
  87675. extern "C" {
  87676. #endif
  87677. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87678. * \ingroup flac_metadata
  87679. *
  87680. * \brief
  87681. * The level 0 interface consists of individual routines to read the
  87682. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87683. * only a filename.
  87684. *
  87685. * They try to skip any ID3v2 tag at the head of the file.
  87686. *
  87687. * \{
  87688. */
  87689. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87690. * will try to skip any ID3v2 tag at the head of the file.
  87691. *
  87692. * \param filename The path to the FLAC file to read.
  87693. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87694. * FLAC__StreamMetadata is a simple structure with no
  87695. * memory allocation involved, you pass the address of
  87696. * an existing structure. It need not be initialized.
  87697. * \assert
  87698. * \code filename != NULL \endcode
  87699. * \code streaminfo != NULL \endcode
  87700. * \retval FLAC__bool
  87701. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87702. * \c false if there was a memory allocation error, a file decoder error,
  87703. * or the file contained no STREAMINFO block. (A memory allocation error
  87704. * is possible because this function must set up a file decoder.)
  87705. */
  87706. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87707. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87708. * function will try to skip any ID3v2 tag at the head of the file.
  87709. *
  87710. * \param filename The path to the FLAC file to read.
  87711. * \param tags The address where the returned pointer will be
  87712. * stored. The \a tags object must be deleted by
  87713. * the caller using FLAC__metadata_object_delete().
  87714. * \assert
  87715. * \code filename != NULL \endcode
  87716. * \code tags != NULL \endcode
  87717. * \retval FLAC__bool
  87718. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87719. * and \a *tags will be set to the address of the metadata structure.
  87720. * Returns \c false if there was a memory allocation error, a file
  87721. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87722. * \a *tags will be set to \c NULL.
  87723. */
  87724. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87725. /** Read the CUESHEET metadata block of the given FLAC file. This
  87726. * function will try to skip any ID3v2 tag at the head of the file.
  87727. *
  87728. * \param filename The path to the FLAC file to read.
  87729. * \param cuesheet The address where the returned pointer will be
  87730. * stored. The \a cuesheet object must be deleted by
  87731. * the caller using FLAC__metadata_object_delete().
  87732. * \assert
  87733. * \code filename != NULL \endcode
  87734. * \code cuesheet != NULL \endcode
  87735. * \retval FLAC__bool
  87736. * \c true if a valid CUESHEET block was read from \a filename,
  87737. * and \a *cuesheet will be set to the address of the metadata
  87738. * structure. Returns \c false if there was a memory allocation
  87739. * error, a file decoder error, or the file contained no CUESHEET
  87740. * block, and \a *cuesheet will be set to \c NULL.
  87741. */
  87742. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87743. /** Read a PICTURE metadata block of the given FLAC file. This
  87744. * function will try to skip any ID3v2 tag at the head of the file.
  87745. * Since there can be more than one PICTURE block in a file, this
  87746. * function takes a number of parameters that act as constraints to
  87747. * the search. The PICTURE block with the largest area matching all
  87748. * the constraints will be returned, or \a *picture will be set to
  87749. * \c NULL if there was no such block.
  87750. *
  87751. * \param filename The path to the FLAC file to read.
  87752. * \param picture The address where the returned pointer will be
  87753. * stored. The \a picture object must be deleted by
  87754. * the caller using FLAC__metadata_object_delete().
  87755. * \param type The desired picture type. Use \c -1 to mean
  87756. * "any type".
  87757. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87758. * string will be matched exactly. Use \c NULL to
  87759. * mean "any MIME type".
  87760. * \param description The desired description. The string will be
  87761. * matched exactly. Use \c NULL to mean "any
  87762. * description".
  87763. * \param max_width The maximum width in pixels desired. Use
  87764. * \c (unsigned)(-1) to mean "any width".
  87765. * \param max_height The maximum height in pixels desired. Use
  87766. * \c (unsigned)(-1) to mean "any height".
  87767. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87768. * Use \c (unsigned)(-1) to mean "any depth".
  87769. * \param max_colors The maximum number of colors desired. Use
  87770. * \c (unsigned)(-1) to mean "any number of colors".
  87771. * \assert
  87772. * \code filename != NULL \endcode
  87773. * \code picture != NULL \endcode
  87774. * \retval FLAC__bool
  87775. * \c true if a valid PICTURE block was read from \a filename,
  87776. * and \a *picture will be set to the address of the metadata
  87777. * structure. Returns \c false if there was a memory allocation
  87778. * error, a file decoder error, or the file contained no PICTURE
  87779. * block, and \a *picture will be set to \c NULL.
  87780. */
  87781. 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);
  87782. /* \} */
  87783. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87784. * \ingroup flac_metadata
  87785. *
  87786. * \brief
  87787. * The level 1 interface provides read-write access to FLAC file metadata and
  87788. * operates directly on the FLAC file.
  87789. *
  87790. * The general usage of this interface is:
  87791. *
  87792. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87793. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87794. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87795. * see if the file is writable, or only read access is allowed.
  87796. * - Use FLAC__metadata_simple_iterator_next() and
  87797. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87798. * This is does not read the actual blocks themselves.
  87799. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87800. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87801. * forward from the front of the file.
  87802. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87803. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87804. * the current iterator position. The returned object is yours to modify
  87805. * and free.
  87806. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87807. * back. You must have write permission to the original file. Make sure to
  87808. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87809. * below.
  87810. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87811. * Use the object creation functions from
  87812. * \link flac_metadata_object here \endlink to generate new objects.
  87813. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87814. * currently referred to by the iterator, or replace it with padding.
  87815. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87816. * finished.
  87817. *
  87818. * \note
  87819. * The FLAC file remains open the whole time between
  87820. * FLAC__metadata_simple_iterator_init() and
  87821. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87822. * the file during this time.
  87823. *
  87824. * \note
  87825. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87826. * FLAC__StreamMetadata objects. These are managed automatically.
  87827. *
  87828. * \note
  87829. * If any of the modification functions
  87830. * (FLAC__metadata_simple_iterator_set_block(),
  87831. * FLAC__metadata_simple_iterator_delete_block(),
  87832. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87833. * you should delete the iterator as it may no longer be valid.
  87834. *
  87835. * \{
  87836. */
  87837. struct FLAC__Metadata_SimpleIterator;
  87838. /** The opaque structure definition for the level 1 iterator type.
  87839. * See the
  87840. * \link flac_metadata_level1 metadata level 1 module \endlink
  87841. * for a detailed description.
  87842. */
  87843. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87844. /** Status type for FLAC__Metadata_SimpleIterator.
  87845. *
  87846. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87847. */
  87848. typedef enum {
  87849. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87850. /**< The iterator is in the normal OK state */
  87851. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87852. /**< The data passed into a function violated the function's usage criteria */
  87853. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87854. /**< The iterator could not open the target file */
  87855. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87856. /**< The iterator could not find the FLAC signature at the start of the file */
  87857. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87858. /**< The iterator tried to write to a file that was not writable */
  87859. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87860. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87861. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87862. /**< The iterator encountered an error while reading the FLAC file */
  87863. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87864. /**< The iterator encountered an error while seeking in the FLAC file */
  87865. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87866. /**< The iterator encountered an error while writing the FLAC file */
  87867. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87868. /**< The iterator encountered an error renaming the FLAC file */
  87869. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87870. /**< The iterator encountered an error removing the temporary file */
  87871. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87872. /**< Memory allocation failed */
  87873. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87874. /**< The caller violated an assertion or an unexpected error occurred */
  87875. } FLAC__Metadata_SimpleIteratorStatus;
  87876. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87877. *
  87878. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87879. * will give the string equivalent. The contents should not be modified.
  87880. */
  87881. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87882. /** Create a new iterator instance.
  87883. *
  87884. * \retval FLAC__Metadata_SimpleIterator*
  87885. * \c NULL if there was an error allocating memory, else the new instance.
  87886. */
  87887. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87888. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87889. *
  87890. * \param iterator A pointer to an existing iterator.
  87891. * \assert
  87892. * \code iterator != NULL \endcode
  87893. */
  87894. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87895. /** Get the current status of the iterator. Call this after a function
  87896. * returns \c false to get the reason for the error. Also resets the status
  87897. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87898. *
  87899. * \param iterator A pointer to an existing iterator.
  87900. * \assert
  87901. * \code iterator != NULL \endcode
  87902. * \retval FLAC__Metadata_SimpleIteratorStatus
  87903. * The current status of the iterator.
  87904. */
  87905. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87906. /** Initialize the iterator to point to the first metadata block in the
  87907. * given FLAC file.
  87908. *
  87909. * \param iterator A pointer to an existing iterator.
  87910. * \param filename The path to the FLAC file.
  87911. * \param read_only If \c true, the FLAC file will be opened
  87912. * in read-only mode; if \c false, the FLAC
  87913. * file will be opened for edit even if no
  87914. * edits are performed.
  87915. * \param preserve_file_stats If \c true, the owner and modification
  87916. * time will be preserved even if the FLAC
  87917. * file is written to.
  87918. * \assert
  87919. * \code iterator != NULL \endcode
  87920. * \code filename != NULL \endcode
  87921. * \retval FLAC__bool
  87922. * \c false if a memory allocation error occurs, the file can't be
  87923. * opened, or another error occurs, else \c true.
  87924. */
  87925. 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);
  87926. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87927. * FLAC__metadata_simple_iterator_set_block() and
  87928. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87929. *
  87930. * \param iterator A pointer to an existing iterator.
  87931. * \assert
  87932. * \code iterator != NULL \endcode
  87933. * \retval FLAC__bool
  87934. * See above.
  87935. */
  87936. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87937. /** Moves the iterator forward one metadata block, returning \c false if
  87938. * already at the end.
  87939. *
  87940. * \param iterator A pointer to an existing initialized iterator.
  87941. * \assert
  87942. * \code iterator != NULL \endcode
  87943. * \a iterator has been successfully initialized with
  87944. * FLAC__metadata_simple_iterator_init()
  87945. * \retval FLAC__bool
  87946. * \c false if already at the last metadata block of the chain, else
  87947. * \c true.
  87948. */
  87949. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87950. /** Moves the iterator backward one metadata block, returning \c false if
  87951. * already at the beginning.
  87952. *
  87953. * \param iterator A pointer to an existing initialized iterator.
  87954. * \assert
  87955. * \code iterator != NULL \endcode
  87956. * \a iterator has been successfully initialized with
  87957. * FLAC__metadata_simple_iterator_init()
  87958. * \retval FLAC__bool
  87959. * \c false if already at the first metadata block of the chain, else
  87960. * \c true.
  87961. */
  87962. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87963. /** Returns a flag telling if the current metadata block is the last.
  87964. *
  87965. * \param iterator A pointer to an existing initialized iterator.
  87966. * \assert
  87967. * \code iterator != NULL \endcode
  87968. * \a iterator has been successfully initialized with
  87969. * FLAC__metadata_simple_iterator_init()
  87970. * \retval FLAC__bool
  87971. * \c true if the current metadata block is the last in the file,
  87972. * else \c false.
  87973. */
  87974. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87975. /** Get the offset of the metadata block at the current position. This
  87976. * avoids reading the actual block data which can save time for large
  87977. * blocks.
  87978. *
  87979. * \param iterator A pointer to an existing initialized iterator.
  87980. * \assert
  87981. * \code iterator != NULL \endcode
  87982. * \a iterator has been successfully initialized with
  87983. * FLAC__metadata_simple_iterator_init()
  87984. * \retval off_t
  87985. * The offset of the metadata block at the current iterator position.
  87986. * This is the byte offset relative to the beginning of the file of
  87987. * the current metadata block's header.
  87988. */
  87989. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87990. /** Get the type of the metadata block at the current position. This
  87991. * avoids reading the actual block data which can save time for large
  87992. * blocks.
  87993. *
  87994. * \param iterator A pointer to an existing initialized iterator.
  87995. * \assert
  87996. * \code iterator != NULL \endcode
  87997. * \a iterator has been successfully initialized with
  87998. * FLAC__metadata_simple_iterator_init()
  87999. * \retval FLAC__MetadataType
  88000. * The type of the metadata block at the current iterator position.
  88001. */
  88002. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  88003. /** Get the length of the metadata block at the current position. This
  88004. * avoids reading the actual block data which can save time for large
  88005. * blocks.
  88006. *
  88007. * \param iterator A pointer to an existing initialized iterator.
  88008. * \assert
  88009. * \code iterator != NULL \endcode
  88010. * \a iterator has been successfully initialized with
  88011. * FLAC__metadata_simple_iterator_init()
  88012. * \retval unsigned
  88013. * The length of the metadata block at the current iterator position.
  88014. * The is same length as that in the
  88015. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  88016. * i.e. the length of the metadata body that follows the header.
  88017. */
  88018. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  88019. /** Get the application ID of the \c APPLICATION block at the current
  88020. * position. This avoids reading the actual block data which can save
  88021. * time for large blocks.
  88022. *
  88023. * \param iterator A pointer to an existing initialized iterator.
  88024. * \param id A pointer to a buffer of at least \c 4 bytes where
  88025. * the ID will be stored.
  88026. * \assert
  88027. * \code iterator != NULL \endcode
  88028. * \code id != NULL \endcode
  88029. * \a iterator has been successfully initialized with
  88030. * FLAC__metadata_simple_iterator_init()
  88031. * \retval FLAC__bool
  88032. * \c true if the ID was successfully read, else \c false, in which
  88033. * case you should check FLAC__metadata_simple_iterator_status() to
  88034. * find out why. If the status is
  88035. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  88036. * current metadata block is not an \c APPLICATION block. Otherwise
  88037. * if the status is
  88038. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  88039. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  88040. * occurred and the iterator can no longer be used.
  88041. */
  88042. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  88043. /** Get the metadata block at the current position. You can modify the
  88044. * block but must use FLAC__metadata_simple_iterator_set_block() to
  88045. * write it back to the FLAC file.
  88046. *
  88047. * You must call FLAC__metadata_object_delete() on the returned object
  88048. * when you are finished with it.
  88049. *
  88050. * \param iterator A pointer to an existing initialized iterator.
  88051. * \assert
  88052. * \code iterator != NULL \endcode
  88053. * \a iterator has been successfully initialized with
  88054. * FLAC__metadata_simple_iterator_init()
  88055. * \retval FLAC__StreamMetadata*
  88056. * The current metadata block, or \c NULL if there was a memory
  88057. * allocation error.
  88058. */
  88059. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  88060. /** Write a block back to the FLAC file. This function tries to be
  88061. * as efficient as possible; how the block is actually written is
  88062. * shown by the following:
  88063. *
  88064. * Existing block is a STREAMINFO block and the new block is a
  88065. * STREAMINFO block: the new block is written in place. Make sure
  88066. * you know what you're doing when changing the values of a
  88067. * STREAMINFO block.
  88068. *
  88069. * Existing block is a STREAMINFO block and the new block is a
  88070. * not a STREAMINFO block: this is an error since the first block
  88071. * must be a STREAMINFO block. Returns \c false without altering the
  88072. * file.
  88073. *
  88074. * Existing block is not a STREAMINFO block and the new block is a
  88075. * STREAMINFO block: this is an error since there may be only one
  88076. * STREAMINFO block. Returns \c false without altering the file.
  88077. *
  88078. * Existing block and new block are the same length: the existing
  88079. * block will be replaced by the new block, written in place.
  88080. *
  88081. * Existing block is longer than new block: if use_padding is \c true,
  88082. * the existing block will be overwritten in place with the new
  88083. * block followed by a PADDING block, if possible, to make the total
  88084. * size the same as the existing block. Remember that a padding
  88085. * block requires at least four bytes so if the difference in size
  88086. * between the new block and existing block is less than that, the
  88087. * entire file will have to be rewritten, using the new block's
  88088. * exact size. If use_padding is \c false, the entire file will be
  88089. * rewritten, replacing the existing block by the new block.
  88090. *
  88091. * Existing block is shorter than new block: if use_padding is \c true,
  88092. * the function will try and expand the new block into the following
  88093. * PADDING block, if it exists and doing so won't shrink the PADDING
  88094. * block to less than 4 bytes. If there is no following PADDING
  88095. * block, or it will shrink to less than 4 bytes, or use_padding is
  88096. * \c false, the entire file is rewritten, replacing the existing block
  88097. * with the new block. Note that in this case any following PADDING
  88098. * block is preserved as is.
  88099. *
  88100. * After writing the block, the iterator will remain in the same
  88101. * place, i.e. pointing to the new block.
  88102. *
  88103. * \param iterator A pointer to an existing initialized iterator.
  88104. * \param block The block to set.
  88105. * \param use_padding See above.
  88106. * \assert
  88107. * \code iterator != NULL \endcode
  88108. * \a iterator has been successfully initialized with
  88109. * FLAC__metadata_simple_iterator_init()
  88110. * \code block != NULL \endcode
  88111. * \retval FLAC__bool
  88112. * \c true if successful, else \c false.
  88113. */
  88114. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88115. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  88116. * except that instead of writing over an existing block, it appends
  88117. * a block after the existing block. \a use_padding is again used to
  88118. * tell the function to try an expand into following padding in an
  88119. * attempt to avoid rewriting the entire file.
  88120. *
  88121. * This function will fail and return \c false if given a STREAMINFO
  88122. * block.
  88123. *
  88124. * After writing the block, the iterator will be pointing to the
  88125. * new block.
  88126. *
  88127. * \param iterator A pointer to an existing initialized iterator.
  88128. * \param block The block to set.
  88129. * \param use_padding See above.
  88130. * \assert
  88131. * \code iterator != NULL \endcode
  88132. * \a iterator has been successfully initialized with
  88133. * FLAC__metadata_simple_iterator_init()
  88134. * \code block != NULL \endcode
  88135. * \retval FLAC__bool
  88136. * \c true if successful, else \c false.
  88137. */
  88138. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88139. /** Deletes the block at the current position. This will cause the
  88140. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  88141. * in which case the block will be replaced by an equal-sized PADDING
  88142. * block. The iterator will be left pointing to the block before the
  88143. * one just deleted.
  88144. *
  88145. * You may not delete the STREAMINFO block.
  88146. *
  88147. * \param iterator A pointer to an existing initialized iterator.
  88148. * \param use_padding See above.
  88149. * \assert
  88150. * \code iterator != NULL \endcode
  88151. * \a iterator has been successfully initialized with
  88152. * FLAC__metadata_simple_iterator_init()
  88153. * \retval FLAC__bool
  88154. * \c true if successful, else \c false.
  88155. */
  88156. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  88157. /* \} */
  88158. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  88159. * \ingroup flac_metadata
  88160. *
  88161. * \brief
  88162. * The level 2 interface provides read-write access to FLAC file metadata;
  88163. * all metadata is read into memory, operated on in memory, and then written
  88164. * to file, which is more efficient than level 1 when editing multiple blocks.
  88165. *
  88166. * Currently Ogg FLAC is supported for read only, via
  88167. * FLAC__metadata_chain_read_ogg() but a subsequent
  88168. * FLAC__metadata_chain_write() will fail.
  88169. *
  88170. * The general usage of this interface is:
  88171. *
  88172. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88173. * linked list of FLAC metadata blocks.
  88174. * - Read all metadata into the the chain from a FLAC file using
  88175. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88176. * check the status.
  88177. * - Optionally, consolidate the padding using
  88178. * FLAC__metadata_chain_merge_padding() or
  88179. * FLAC__metadata_chain_sort_padding().
  88180. * - Create a new iterator using FLAC__metadata_iterator_new()
  88181. * - Initialize the iterator to point to the first element in the chain
  88182. * using FLAC__metadata_iterator_init()
  88183. * - Traverse the chain using FLAC__metadata_iterator_next and
  88184. * FLAC__metadata_iterator_prev().
  88185. * - Get a block for reading or modification using
  88186. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88187. * inside the chain is returned, so the block is yours to modify.
  88188. * Changes will be reflected in the FLAC file when you write the
  88189. * chain. You can also add and delete blocks (see functions below).
  88190. * - When done, write out the chain using FLAC__metadata_chain_write().
  88191. * Make sure to read the whole comment to the function below.
  88192. * - Delete the chain using FLAC__metadata_chain_delete().
  88193. *
  88194. * \note
  88195. * Even though the FLAC file is not open while the chain is being
  88196. * manipulated, you must not alter the file externally during
  88197. * this time. The chain assumes the FLAC file will not change
  88198. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88199. * and FLAC__metadata_chain_write().
  88200. *
  88201. * \note
  88202. * Do not modify the is_last, length, or type fields of returned
  88203. * FLAC__StreamMetadata objects. These are managed automatically.
  88204. *
  88205. * \note
  88206. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88207. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88208. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88209. * become owned by the chain and they will be deleted when the chain is
  88210. * deleted.
  88211. *
  88212. * \{
  88213. */
  88214. struct FLAC__Metadata_Chain;
  88215. /** The opaque structure definition for the level 2 chain type.
  88216. */
  88217. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88218. struct FLAC__Metadata_Iterator;
  88219. /** The opaque structure definition for the level 2 iterator type.
  88220. */
  88221. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88222. typedef enum {
  88223. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88224. /**< The chain is in the normal OK state */
  88225. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88226. /**< The data passed into a function violated the function's usage criteria */
  88227. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88228. /**< The chain could not open the target file */
  88229. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88230. /**< The chain could not find the FLAC signature at the start of the file */
  88231. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88232. /**< The chain tried to write to a file that was not writable */
  88233. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88234. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88235. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88236. /**< The chain encountered an error while reading the FLAC file */
  88237. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88238. /**< The chain encountered an error while seeking in the FLAC file */
  88239. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88240. /**< The chain encountered an error while writing the FLAC file */
  88241. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88242. /**< The chain encountered an error renaming the FLAC file */
  88243. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88244. /**< The chain encountered an error removing the temporary file */
  88245. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88246. /**< Memory allocation failed */
  88247. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88248. /**< The caller violated an assertion or an unexpected error occurred */
  88249. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88250. /**< One or more of the required callbacks was NULL */
  88251. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88252. /**< FLAC__metadata_chain_write() was called on a chain read by
  88253. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88254. * or
  88255. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88256. * was called on a chain read by
  88257. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88258. * Matching read/write methods must always be used. */
  88259. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88260. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88261. * chain write requires a tempfile; use
  88262. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88263. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88264. * called when the chain write does not require a tempfile; use
  88265. * FLAC__metadata_chain_write_with_callbacks() instead.
  88266. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88267. * before writing via callbacks. */
  88268. } FLAC__Metadata_ChainStatus;
  88269. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88270. *
  88271. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88272. * will give the string equivalent. The contents should not be modified.
  88273. */
  88274. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88275. /*********** FLAC__Metadata_Chain ***********/
  88276. /** Create a new chain instance.
  88277. *
  88278. * \retval FLAC__Metadata_Chain*
  88279. * \c NULL if there was an error allocating memory, else the new instance.
  88280. */
  88281. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88282. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88283. *
  88284. * \param chain A pointer to an existing chain.
  88285. * \assert
  88286. * \code chain != NULL \endcode
  88287. */
  88288. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88289. /** Get the current status of the chain. Call this after a function
  88290. * returns \c false to get the reason for the error. Also resets the
  88291. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88292. *
  88293. * \param chain A pointer to an existing chain.
  88294. * \assert
  88295. * \code chain != NULL \endcode
  88296. * \retval FLAC__Metadata_ChainStatus
  88297. * The current status of the chain.
  88298. */
  88299. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88300. /** Read all metadata from a FLAC file into the chain.
  88301. *
  88302. * \param chain A pointer to an existing chain.
  88303. * \param filename The path to the FLAC file to read.
  88304. * \assert
  88305. * \code chain != NULL \endcode
  88306. * \code filename != NULL \endcode
  88307. * \retval FLAC__bool
  88308. * \c true if a valid list of metadata blocks was read from
  88309. * \a filename, else \c false. On failure, check the status with
  88310. * FLAC__metadata_chain_status().
  88311. */
  88312. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88313. /** Read all metadata from an Ogg FLAC file into the chain.
  88314. *
  88315. * \note Ogg FLAC metadata data writing is not supported yet and
  88316. * FLAC__metadata_chain_write() will fail.
  88317. *
  88318. * \param chain A pointer to an existing chain.
  88319. * \param filename The path to the Ogg FLAC file to read.
  88320. * \assert
  88321. * \code chain != NULL \endcode
  88322. * \code filename != NULL \endcode
  88323. * \retval FLAC__bool
  88324. * \c true if a valid list of metadata blocks was read from
  88325. * \a filename, else \c false. On failure, check the status with
  88326. * FLAC__metadata_chain_status().
  88327. */
  88328. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88329. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88330. *
  88331. * The \a handle need only be open for reading, but must be seekable.
  88332. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88333. * for Windows).
  88334. *
  88335. * \param chain A pointer to an existing chain.
  88336. * \param handle The I/O handle of the FLAC stream to read. The
  88337. * handle will NOT be closed after the metadata is read;
  88338. * that is the duty of the caller.
  88339. * \param callbacks
  88340. * A set of callbacks to use for I/O. The mandatory
  88341. * callbacks are \a read, \a seek, and \a tell.
  88342. * \assert
  88343. * \code chain != NULL \endcode
  88344. * \retval FLAC__bool
  88345. * \c true if a valid list of metadata blocks was read from
  88346. * \a handle, else \c false. On failure, check the status with
  88347. * FLAC__metadata_chain_status().
  88348. */
  88349. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88350. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88351. *
  88352. * The \a handle need only be open for reading, but must be seekable.
  88353. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88354. * for Windows).
  88355. *
  88356. * \note Ogg FLAC metadata data writing is not supported yet and
  88357. * FLAC__metadata_chain_write() will fail.
  88358. *
  88359. * \param chain A pointer to an existing chain.
  88360. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88361. * handle will NOT be closed after the metadata is read;
  88362. * that is the duty of the caller.
  88363. * \param callbacks
  88364. * A set of callbacks to use for I/O. The mandatory
  88365. * callbacks are \a read, \a seek, and \a tell.
  88366. * \assert
  88367. * \code chain != NULL \endcode
  88368. * \retval FLAC__bool
  88369. * \c true if a valid list of metadata blocks was read from
  88370. * \a handle, else \c false. On failure, check the status with
  88371. * FLAC__metadata_chain_status().
  88372. */
  88373. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88374. /** Checks if writing the given chain would require the use of a
  88375. * temporary file, or if it could be written in place.
  88376. *
  88377. * Under certain conditions, padding can be utilized so that writing
  88378. * edited metadata back to the FLAC file does not require rewriting the
  88379. * entire file. If rewriting is required, then a temporary workfile is
  88380. * required. When writing metadata using callbacks, you must check
  88381. * this function to know whether to call
  88382. * FLAC__metadata_chain_write_with_callbacks() or
  88383. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88384. * writing with FLAC__metadata_chain_write(), the temporary file is
  88385. * handled internally.
  88386. *
  88387. * \param chain A pointer to an existing chain.
  88388. * \param use_padding
  88389. * Whether or not padding will be allowed to be used
  88390. * during the write. The value of \a use_padding given
  88391. * here must match the value later passed to
  88392. * FLAC__metadata_chain_write_with_callbacks() or
  88393. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88394. * \assert
  88395. * \code chain != NULL \endcode
  88396. * \retval FLAC__bool
  88397. * \c true if writing the current chain would require a tempfile, or
  88398. * \c false if metadata can be written in place.
  88399. */
  88400. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88401. /** Write all metadata out to the FLAC file. This function tries to be as
  88402. * efficient as possible; how the metadata is actually written is shown by
  88403. * the following:
  88404. *
  88405. * If the current chain is the same size as the existing metadata, the new
  88406. * data is written in place.
  88407. *
  88408. * If the current chain is longer than the existing metadata, and
  88409. * \a use_padding is \c true, and the last block is a PADDING block of
  88410. * sufficient length, the function will truncate the final padding block
  88411. * so that the overall size of the metadata is the same as the existing
  88412. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88413. * the above conditions are met, the entire FLAC file must be rewritten.
  88414. * If you want to use padding this way it is a good idea to call
  88415. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88416. * amount of padding to work with, unless you need to preserve ordering
  88417. * of the PADDING blocks for some reason.
  88418. *
  88419. * If the current chain is shorter than the existing metadata, and
  88420. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88421. * is extended to make the overall size the same as the existing data. If
  88422. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88423. * PADDING block is added to the end of the new data to make it the same
  88424. * size as the existing data (if possible, see the note to
  88425. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88426. * and the new data is written in place. If none of the above apply or
  88427. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88428. *
  88429. * If \a preserve_file_stats is \c true, the owner and modification time will
  88430. * be preserved even if the FLAC file is written.
  88431. *
  88432. * For this write function to be used, the chain must have been read with
  88433. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88434. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88435. *
  88436. * \param chain A pointer to an existing chain.
  88437. * \param use_padding See above.
  88438. * \param preserve_file_stats See above.
  88439. * \assert
  88440. * \code chain != NULL \endcode
  88441. * \retval FLAC__bool
  88442. * \c true if the write succeeded, else \c false. On failure,
  88443. * check the status with FLAC__metadata_chain_status().
  88444. */
  88445. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88446. /** Write all metadata out to a FLAC stream via callbacks.
  88447. *
  88448. * (See FLAC__metadata_chain_write() for the details on how padding is
  88449. * used to write metadata in place if possible.)
  88450. *
  88451. * The \a handle must be open for updating and be seekable. The
  88452. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88453. * for Windows).
  88454. *
  88455. * For this write function to be used, the chain must have been read with
  88456. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88457. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88458. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88459. * \c false.
  88460. *
  88461. * \param chain A pointer to an existing chain.
  88462. * \param use_padding See FLAC__metadata_chain_write()
  88463. * \param handle The I/O handle of the FLAC stream to write. The
  88464. * handle will NOT be closed after the metadata is
  88465. * written; that is the duty of the caller.
  88466. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88467. * callbacks are \a write and \a seek.
  88468. * \assert
  88469. * \code chain != NULL \endcode
  88470. * \retval FLAC__bool
  88471. * \c true if the write succeeded, else \c false. On failure,
  88472. * check the status with FLAC__metadata_chain_status().
  88473. */
  88474. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88475. /** Write all metadata out to a FLAC stream via callbacks.
  88476. *
  88477. * (See FLAC__metadata_chain_write() for the details on how padding is
  88478. * used to write metadata in place if possible.)
  88479. *
  88480. * This version of the write-with-callbacks function must be used when
  88481. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88482. * this function, you must supply an I/O handle corresponding to the
  88483. * FLAC file to edit, and a temporary handle to which the new FLAC
  88484. * file will be written. It is the caller's job to move this temporary
  88485. * FLAC file on top of the original FLAC file to complete the metadata
  88486. * edit.
  88487. *
  88488. * The \a handle must be open for reading and be seekable. The
  88489. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88490. * for Windows).
  88491. *
  88492. * The \a temp_handle must be open for writing. The
  88493. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88494. * for Windows). It should be an empty stream, or at least positioned
  88495. * at the start-of-file (in which case it is the caller's duty to
  88496. * truncate it on return).
  88497. *
  88498. * For this write function to be used, the chain must have been read with
  88499. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88500. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88501. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88502. * \c true.
  88503. *
  88504. * \param chain A pointer to an existing chain.
  88505. * \param use_padding See FLAC__metadata_chain_write()
  88506. * \param handle The I/O handle of the original FLAC stream to read.
  88507. * The handle will NOT be closed after the metadata is
  88508. * written; that is the duty of the caller.
  88509. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88510. * The mandatory callbacks are \a read, \a seek, and
  88511. * \a eof.
  88512. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88513. * handle will NOT be closed after the metadata is
  88514. * written; that is the duty of the caller.
  88515. * \param temp_callbacks
  88516. * A set of callbacks to use for I/O on temp_handle.
  88517. * The only mandatory callback is \a write.
  88518. * \assert
  88519. * \code chain != NULL \endcode
  88520. * \retval FLAC__bool
  88521. * \c true if the write succeeded, else \c false. On failure,
  88522. * check the status with FLAC__metadata_chain_status().
  88523. */
  88524. 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);
  88525. /** Merge adjacent PADDING blocks into a single block.
  88526. *
  88527. * \note This function does not write to the FLAC file, it only
  88528. * modifies the chain.
  88529. *
  88530. * \warning Any iterator on the current chain will become invalid after this
  88531. * call. You should delete the iterator and get a new one.
  88532. *
  88533. * \param chain A pointer to an existing chain.
  88534. * \assert
  88535. * \code chain != NULL \endcode
  88536. */
  88537. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88538. /** This function will move all PADDING blocks to the end on the metadata,
  88539. * then merge them into a single block.
  88540. *
  88541. * \note This function does not write to the FLAC file, it only
  88542. * modifies the chain.
  88543. *
  88544. * \warning Any iterator on the current chain will become invalid after this
  88545. * call. You should delete the iterator and get a new one.
  88546. *
  88547. * \param chain A pointer to an existing chain.
  88548. * \assert
  88549. * \code chain != NULL \endcode
  88550. */
  88551. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88552. /*********** FLAC__Metadata_Iterator ***********/
  88553. /** Create a new iterator instance.
  88554. *
  88555. * \retval FLAC__Metadata_Iterator*
  88556. * \c NULL if there was an error allocating memory, else the new instance.
  88557. */
  88558. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88559. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88560. *
  88561. * \param iterator A pointer to an existing iterator.
  88562. * \assert
  88563. * \code iterator != NULL \endcode
  88564. */
  88565. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88566. /** Initialize the iterator to point to the first metadata block in the
  88567. * given chain.
  88568. *
  88569. * \param iterator A pointer to an existing iterator.
  88570. * \param chain A pointer to an existing and initialized (read) chain.
  88571. * \assert
  88572. * \code iterator != NULL \endcode
  88573. * \code chain != NULL \endcode
  88574. */
  88575. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88576. /** Moves the iterator forward one metadata block, returning \c false if
  88577. * already at the end.
  88578. *
  88579. * \param iterator A pointer to an existing initialized iterator.
  88580. * \assert
  88581. * \code iterator != NULL \endcode
  88582. * \a iterator has been successfully initialized with
  88583. * FLAC__metadata_iterator_init()
  88584. * \retval FLAC__bool
  88585. * \c false if already at the last metadata block of the chain, else
  88586. * \c true.
  88587. */
  88588. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88589. /** Moves the iterator backward one metadata block, returning \c false if
  88590. * already at the beginning.
  88591. *
  88592. * \param iterator A pointer to an existing initialized iterator.
  88593. * \assert
  88594. * \code iterator != NULL \endcode
  88595. * \a iterator has been successfully initialized with
  88596. * FLAC__metadata_iterator_init()
  88597. * \retval FLAC__bool
  88598. * \c false if already at the first metadata block of the chain, else
  88599. * \c true.
  88600. */
  88601. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88602. /** Get the type of the metadata block at the current position.
  88603. *
  88604. * \param iterator A pointer to an existing initialized iterator.
  88605. * \assert
  88606. * \code iterator != NULL \endcode
  88607. * \a iterator has been successfully initialized with
  88608. * FLAC__metadata_iterator_init()
  88609. * \retval FLAC__MetadataType
  88610. * The type of the metadata block at the current iterator position.
  88611. */
  88612. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88613. /** Get the metadata block at the current position. You can modify
  88614. * the block in place but must write the chain before the changes
  88615. * are reflected to the FLAC file. You do not need to call
  88616. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88617. * the pointer returned by FLAC__metadata_iterator_get_block()
  88618. * points directly into the chain.
  88619. *
  88620. * \warning
  88621. * Do not call FLAC__metadata_object_delete() on the returned object;
  88622. * to delete a block use FLAC__metadata_iterator_delete_block().
  88623. *
  88624. * \param iterator A pointer to an existing initialized iterator.
  88625. * \assert
  88626. * \code iterator != NULL \endcode
  88627. * \a iterator has been successfully initialized with
  88628. * FLAC__metadata_iterator_init()
  88629. * \retval FLAC__StreamMetadata*
  88630. * The current metadata block.
  88631. */
  88632. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88633. /** Set the metadata block at the current position, replacing the existing
  88634. * block. The new block passed in becomes owned by the chain and it will be
  88635. * deleted when the chain is deleted.
  88636. *
  88637. * \param iterator A pointer to an existing initialized iterator.
  88638. * \param block A pointer to a metadata block.
  88639. * \assert
  88640. * \code iterator != NULL \endcode
  88641. * \a iterator has been successfully initialized with
  88642. * FLAC__metadata_iterator_init()
  88643. * \code block != NULL \endcode
  88644. * \retval FLAC__bool
  88645. * \c false if the conditions in the above description are not met, or
  88646. * a memory allocation error occurs, otherwise \c true.
  88647. */
  88648. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88649. /** Removes the current block from the chain. If \a replace_with_padding is
  88650. * \c true, the block will instead be replaced with a padding block of equal
  88651. * size. You can not delete the STREAMINFO block. The iterator will be
  88652. * left pointing to the block before the one just "deleted", even if
  88653. * \a replace_with_padding is \c true.
  88654. *
  88655. * \param iterator A pointer to an existing initialized iterator.
  88656. * \param replace_with_padding See above.
  88657. * \assert
  88658. * \code iterator != NULL \endcode
  88659. * \a iterator has been successfully initialized with
  88660. * FLAC__metadata_iterator_init()
  88661. * \retval FLAC__bool
  88662. * \c false if the conditions in the above description are not met,
  88663. * otherwise \c true.
  88664. */
  88665. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88666. /** Insert a new block before the current block. You cannot insert a block
  88667. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88668. * as there can be only one, the one that already exists at the head when you
  88669. * read in a chain. The chain takes ownership of the new block and it will be
  88670. * deleted when the chain is deleted. The iterator will be left pointing to
  88671. * the new block.
  88672. *
  88673. * \param iterator A pointer to an existing initialized iterator.
  88674. * \param block A pointer to a metadata block to insert.
  88675. * \assert
  88676. * \code iterator != NULL \endcode
  88677. * \a iterator has been successfully initialized with
  88678. * FLAC__metadata_iterator_init()
  88679. * \retval FLAC__bool
  88680. * \c false if the conditions in the above description are not met, or
  88681. * a memory allocation error occurs, otherwise \c true.
  88682. */
  88683. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88684. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88685. * block as there can be only one, the one that already exists at the head when
  88686. * you read in a chain. The chain takes ownership of the new block and it will
  88687. * be deleted when the chain is deleted. The iterator will be left pointing to
  88688. * the new block.
  88689. *
  88690. * \param iterator A pointer to an existing initialized iterator.
  88691. * \param block A pointer to a metadata block to insert.
  88692. * \assert
  88693. * \code iterator != NULL \endcode
  88694. * \a iterator has been successfully initialized with
  88695. * FLAC__metadata_iterator_init()
  88696. * \retval FLAC__bool
  88697. * \c false if the conditions in the above description are not met, or
  88698. * a memory allocation error occurs, otherwise \c true.
  88699. */
  88700. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88701. /* \} */
  88702. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88703. * \ingroup flac_metadata
  88704. *
  88705. * \brief
  88706. * This module contains methods for manipulating FLAC metadata objects.
  88707. *
  88708. * Since many are variable length we have to be careful about the memory
  88709. * management. We decree that all pointers to data in the object are
  88710. * owned by the object and memory-managed by the object.
  88711. *
  88712. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88713. * functions to create all instances. When using the
  88714. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88715. * \a copy to \c true to have the function make it's own copy of the data, or
  88716. * to \c false to give the object ownership of your data. In the latter case
  88717. * your pointer must be freeable by free() and will be free()d when the object
  88718. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88719. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88720. * the length argument is 0 and the \a copy argument is \c false.
  88721. *
  88722. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88723. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88724. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88725. * case of a memory allocation error.
  88726. *
  88727. * We don't have the convenience of C++ here, so note that the library relies
  88728. * on you to keep the types straight. In other words, if you pass, for
  88729. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88730. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88731. * failure.
  88732. *
  88733. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88734. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88735. * toward the length or stored in the stream, but it can make working with plain
  88736. * comments (those that don't contain embedded-NULs in the value) easier.
  88737. * Entries passed into these functions have trailing NULs added if missing, and
  88738. * returned entries are guaranteed to have a trailing NUL.
  88739. *
  88740. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88741. * comment entry/name/value will first validate that it complies with the Vorbis
  88742. * comment specification and return false if it does not.
  88743. *
  88744. * There is no need to recalculate the length field on metadata blocks you
  88745. * have modified. They will be calculated automatically before they are
  88746. * written back to a file.
  88747. *
  88748. * \{
  88749. */
  88750. /** Create a new metadata object instance of the given type.
  88751. *
  88752. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88753. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88754. * the vendor string set (but zero comments).
  88755. *
  88756. * Do not pass in a value greater than or equal to
  88757. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88758. * doing.
  88759. *
  88760. * \param type Type of object to create
  88761. * \retval FLAC__StreamMetadata*
  88762. * \c NULL if there was an error allocating memory or the type code is
  88763. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88764. */
  88765. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88766. /** Create a copy of an existing metadata object.
  88767. *
  88768. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88769. * object is also copied. The caller takes ownership of the new block and
  88770. * is responsible for freeing it with FLAC__metadata_object_delete().
  88771. *
  88772. * \param object Pointer to object to copy.
  88773. * \assert
  88774. * \code object != NULL \endcode
  88775. * \retval FLAC__StreamMetadata*
  88776. * \c NULL if there was an error allocating memory, else the new instance.
  88777. */
  88778. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88779. /** Free a metadata object. Deletes the object pointed to by \a object.
  88780. *
  88781. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88782. * object is also deleted.
  88783. *
  88784. * \param object A pointer to an existing object.
  88785. * \assert
  88786. * \code object != NULL \endcode
  88787. */
  88788. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88789. /** Compares two metadata objects.
  88790. *
  88791. * The compare is "deep", i.e. dynamically allocated data within the
  88792. * object is also compared.
  88793. *
  88794. * \param block1 A pointer to an existing object.
  88795. * \param block2 A pointer to an existing object.
  88796. * \assert
  88797. * \code block1 != NULL \endcode
  88798. * \code block2 != NULL \endcode
  88799. * \retval FLAC__bool
  88800. * \c true if objects are identical, else \c false.
  88801. */
  88802. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88803. /** Sets the application data of an APPLICATION block.
  88804. *
  88805. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88806. * takes ownership of the pointer. The existing data will be freed if this
  88807. * function is successful, otherwise the original data will remain if \a copy
  88808. * is \c true and malloc() fails.
  88809. *
  88810. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88811. *
  88812. * \param object A pointer to an existing APPLICATION object.
  88813. * \param data A pointer to the data to set.
  88814. * \param length The length of \a data in bytes.
  88815. * \param copy See above.
  88816. * \assert
  88817. * \code object != NULL \endcode
  88818. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88819. * \code (data != NULL && length > 0) ||
  88820. * (data == NULL && length == 0 && copy == false) \endcode
  88821. * \retval FLAC__bool
  88822. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88823. */
  88824. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88825. /** Resize the seekpoint array.
  88826. *
  88827. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88828. * points will be added to the end.
  88829. *
  88830. * \param object A pointer to an existing SEEKTABLE object.
  88831. * \param new_num_points The desired length of the array; may be \c 0.
  88832. * \assert
  88833. * \code object != NULL \endcode
  88834. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88835. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88836. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88837. * \retval FLAC__bool
  88838. * \c false if memory allocation error, else \c true.
  88839. */
  88840. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88841. /** Set a seekpoint in a seektable.
  88842. *
  88843. * \param object A pointer to an existing SEEKTABLE object.
  88844. * \param point_num Index into seekpoint array to set.
  88845. * \param point The point to set.
  88846. * \assert
  88847. * \code object != NULL \endcode
  88848. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88849. * \code object->data.seek_table.num_points > point_num \endcode
  88850. */
  88851. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88852. /** Insert a seekpoint into a seektable.
  88853. *
  88854. * \param object A pointer to an existing SEEKTABLE object.
  88855. * \param point_num Index into seekpoint array to set.
  88856. * \param point The point to set.
  88857. * \assert
  88858. * \code object != NULL \endcode
  88859. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88860. * \code object->data.seek_table.num_points >= point_num \endcode
  88861. * \retval FLAC__bool
  88862. * \c false if memory allocation error, else \c true.
  88863. */
  88864. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88865. /** Delete a seekpoint from a seektable.
  88866. *
  88867. * \param object A pointer to an existing SEEKTABLE object.
  88868. * \param point_num Index into seekpoint array to set.
  88869. * \assert
  88870. * \code object != NULL \endcode
  88871. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88872. * \code object->data.seek_table.num_points > point_num \endcode
  88873. * \retval FLAC__bool
  88874. * \c false if memory allocation error, else \c true.
  88875. */
  88876. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88877. /** Check a seektable to see if it conforms to the FLAC specification.
  88878. * See the format specification for limits on the contents of the
  88879. * seektable.
  88880. *
  88881. * \param object A pointer to an existing SEEKTABLE object.
  88882. * \assert
  88883. * \code object != NULL \endcode
  88884. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88885. * \retval FLAC__bool
  88886. * \c false if seek table is illegal, else \c true.
  88887. */
  88888. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88889. /** Append a number of placeholder points to the end of a seek table.
  88890. *
  88891. * \note
  88892. * As with the other ..._seektable_template_... functions, you should
  88893. * call FLAC__metadata_object_seektable_template_sort() when finished
  88894. * to make the seek table legal.
  88895. *
  88896. * \param object A pointer to an existing SEEKTABLE object.
  88897. * \param num The number of placeholder points to append.
  88898. * \assert
  88899. * \code object != NULL \endcode
  88900. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88901. * \retval FLAC__bool
  88902. * \c false if memory allocation fails, else \c true.
  88903. */
  88904. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88905. /** Append a specific seek point template to the end of a seek table.
  88906. *
  88907. * \note
  88908. * As with the other ..._seektable_template_... functions, you should
  88909. * call FLAC__metadata_object_seektable_template_sort() when finished
  88910. * to make the seek table legal.
  88911. *
  88912. * \param object A pointer to an existing SEEKTABLE object.
  88913. * \param sample_number The sample number of the seek point template.
  88914. * \assert
  88915. * \code object != NULL \endcode
  88916. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88917. * \retval FLAC__bool
  88918. * \c false if memory allocation fails, else \c true.
  88919. */
  88920. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88921. /** Append specific seek point templates to the end of a seek table.
  88922. *
  88923. * \note
  88924. * As with the other ..._seektable_template_... functions, you should
  88925. * call FLAC__metadata_object_seektable_template_sort() when finished
  88926. * to make the seek table legal.
  88927. *
  88928. * \param object A pointer to an existing SEEKTABLE object.
  88929. * \param sample_numbers An array of sample numbers for the seek points.
  88930. * \param num The number of seek point templates to append.
  88931. * \assert
  88932. * \code object != NULL \endcode
  88933. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88934. * \retval FLAC__bool
  88935. * \c false if memory allocation fails, else \c true.
  88936. */
  88937. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88938. /** Append a set of evenly-spaced seek point templates to the end of a
  88939. * seek table.
  88940. *
  88941. * \note
  88942. * As with the other ..._seektable_template_... functions, you should
  88943. * call FLAC__metadata_object_seektable_template_sort() when finished
  88944. * to make the seek table legal.
  88945. *
  88946. * \param object A pointer to an existing SEEKTABLE object.
  88947. * \param num The number of placeholder points to append.
  88948. * \param total_samples The total number of samples to be encoded;
  88949. * the seekpoints will be spaced approximately
  88950. * \a total_samples / \a num samples apart.
  88951. * \assert
  88952. * \code object != NULL \endcode
  88953. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88954. * \code total_samples > 0 \endcode
  88955. * \retval FLAC__bool
  88956. * \c false if memory allocation fails, else \c true.
  88957. */
  88958. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88959. /** Append a set of evenly-spaced seek point templates to the end of a
  88960. * seek table.
  88961. *
  88962. * \note
  88963. * As with the other ..._seektable_template_... functions, you should
  88964. * call FLAC__metadata_object_seektable_template_sort() when finished
  88965. * to make the seek table legal.
  88966. *
  88967. * \param object A pointer to an existing SEEKTABLE object.
  88968. * \param samples The number of samples apart to space the placeholder
  88969. * points. The first point will be at sample \c 0, the
  88970. * second at sample \a samples, then 2*\a samples, and
  88971. * so on. As long as \a samples and \a total_samples
  88972. * are greater than \c 0, there will always be at least
  88973. * one seekpoint at sample \c 0.
  88974. * \param total_samples The total number of samples to be encoded;
  88975. * the seekpoints will be spaced
  88976. * \a samples samples apart.
  88977. * \assert
  88978. * \code object != NULL \endcode
  88979. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88980. * \code samples > 0 \endcode
  88981. * \code total_samples > 0 \endcode
  88982. * \retval FLAC__bool
  88983. * \c false if memory allocation fails, else \c true.
  88984. */
  88985. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88986. /** Sort a seek table's seek points according to the format specification,
  88987. * removing duplicates.
  88988. *
  88989. * \param object A pointer to a seek table to be sorted.
  88990. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88991. * If \c true, duplicates are deleted and the seek table is
  88992. * shrunk appropriately; the number of placeholder points
  88993. * present in the seek table will be the same after the call
  88994. * as before.
  88995. * \assert
  88996. * \code object != NULL \endcode
  88997. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88998. * \retval FLAC__bool
  88999. * \c false if realloc() fails, else \c true.
  89000. */
  89001. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  89002. /** Sets the vendor string in a VORBIS_COMMENT block.
  89003. *
  89004. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89005. * one already.
  89006. *
  89007. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89008. * takes ownership of the \c entry.entry pointer.
  89009. *
  89010. * \note If this function returns \c false, the caller still owns the
  89011. * pointer.
  89012. *
  89013. * \param object A pointer to an existing VORBIS_COMMENT object.
  89014. * \param entry The entry to set the vendor string to.
  89015. * \param copy See above.
  89016. * \assert
  89017. * \code object != NULL \endcode
  89018. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89019. * \code (entry.entry != NULL && entry.length > 0) ||
  89020. * (entry.entry == NULL && entry.length == 0) \endcode
  89021. * \retval FLAC__bool
  89022. * \c false if memory allocation fails or \a entry does not comply with the
  89023. * Vorbis comment specification, else \c true.
  89024. */
  89025. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89026. /** Resize the comment array.
  89027. *
  89028. * If the size shrinks, elements will truncated; if it grows, new empty
  89029. * fields will be added to the end.
  89030. *
  89031. * \param object A pointer to an existing VORBIS_COMMENT object.
  89032. * \param new_num_comments The desired length of the array; may be \c 0.
  89033. * \assert
  89034. * \code object != NULL \endcode
  89035. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89036. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  89037. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  89038. * \retval FLAC__bool
  89039. * \c false if memory allocation fails, else \c true.
  89040. */
  89041. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  89042. /** Sets a comment in a VORBIS_COMMENT block.
  89043. *
  89044. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89045. * one already.
  89046. *
  89047. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89048. * takes ownership of the \c entry.entry pointer.
  89049. *
  89050. * \note If this function returns \c false, the caller still owns the
  89051. * pointer.
  89052. *
  89053. * \param object A pointer to an existing VORBIS_COMMENT object.
  89054. * \param comment_num Index into comment array to set.
  89055. * \param entry The entry to set the comment to.
  89056. * \param copy See above.
  89057. * \assert
  89058. * \code object != NULL \endcode
  89059. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89060. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  89061. * \code (entry.entry != NULL && entry.length > 0) ||
  89062. * (entry.entry == NULL && entry.length == 0) \endcode
  89063. * \retval FLAC__bool
  89064. * \c false if memory allocation fails or \a entry does not comply with the
  89065. * Vorbis comment specification, else \c true.
  89066. */
  89067. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89068. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  89069. *
  89070. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89071. * one already.
  89072. *
  89073. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89074. * takes ownership of the \c entry.entry pointer.
  89075. *
  89076. * \note If this function returns \c false, the caller still owns the
  89077. * pointer.
  89078. *
  89079. * \param object A pointer to an existing VORBIS_COMMENT object.
  89080. * \param comment_num The index at which to insert the comment. The comments
  89081. * at and after \a comment_num move right one position.
  89082. * To append a comment to the end, set \a comment_num to
  89083. * \c object->data.vorbis_comment.num_comments .
  89084. * \param entry The comment to insert.
  89085. * \param copy See above.
  89086. * \assert
  89087. * \code object != NULL \endcode
  89088. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89089. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  89090. * \code (entry.entry != NULL && entry.length > 0) ||
  89091. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89092. * \retval FLAC__bool
  89093. * \c false if memory allocation fails or \a entry does not comply with the
  89094. * Vorbis comment specification, else \c true.
  89095. */
  89096. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89097. /** Appends a comment to a VORBIS_COMMENT block.
  89098. *
  89099. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89100. * one already.
  89101. *
  89102. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89103. * takes ownership of the \c entry.entry pointer.
  89104. *
  89105. * \note If this function returns \c false, the caller still owns the
  89106. * pointer.
  89107. *
  89108. * \param object A pointer to an existing VORBIS_COMMENT object.
  89109. * \param entry The comment to insert.
  89110. * \param copy See above.
  89111. * \assert
  89112. * \code object != NULL \endcode
  89113. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89114. * \code (entry.entry != NULL && entry.length > 0) ||
  89115. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89116. * \retval FLAC__bool
  89117. * \c false if memory allocation fails or \a entry does not comply with the
  89118. * Vorbis comment specification, else \c true.
  89119. */
  89120. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89121. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  89122. *
  89123. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89124. * one already.
  89125. *
  89126. * Depending on the the value of \a all, either all or just the first comment
  89127. * whose field name(s) match the given entry's name will be replaced by the
  89128. * given entry. If no comments match, \a entry will simply be appended.
  89129. *
  89130. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89131. * takes ownership of the \c entry.entry pointer.
  89132. *
  89133. * \note If this function returns \c false, the caller still owns the
  89134. * pointer.
  89135. *
  89136. * \param object A pointer to an existing VORBIS_COMMENT object.
  89137. * \param entry The comment to insert.
  89138. * \param all If \c true, all comments whose field name matches
  89139. * \a entry's field name will be removed, and \a entry will
  89140. * be inserted at the position of the first matching
  89141. * comment. If \c false, only the first comment whose
  89142. * field name matches \a entry's field name will be
  89143. * replaced with \a entry.
  89144. * \param copy See above.
  89145. * \assert
  89146. * \code object != NULL \endcode
  89147. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89148. * \code (entry.entry != NULL && entry.length > 0) ||
  89149. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89150. * \retval FLAC__bool
  89151. * \c false if memory allocation fails or \a entry does not comply with the
  89152. * Vorbis comment specification, else \c true.
  89153. */
  89154. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  89155. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  89156. *
  89157. * \param object A pointer to an existing VORBIS_COMMENT object.
  89158. * \param comment_num The index of the comment to delete.
  89159. * \assert
  89160. * \code object != NULL \endcode
  89161. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89162. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89163. * \retval FLAC__bool
  89164. * \c false if realloc() fails, else \c true.
  89165. */
  89166. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89167. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89168. *
  89169. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89170. * memory and shall be owned by the caller. For convenience the entry will
  89171. * have a terminating NUL.
  89172. *
  89173. * \param entry A pointer to a Vorbis comment entry. The entry's
  89174. * \c entry pointer should not point to allocated
  89175. * memory as it will be overwritten.
  89176. * \param field_name The field name in ASCII, \c NUL terminated.
  89177. * \param field_value The field value in UTF-8, \c NUL terminated.
  89178. * \assert
  89179. * \code entry != NULL \endcode
  89180. * \code field_name != NULL \endcode
  89181. * \code field_value != NULL \endcode
  89182. * \retval FLAC__bool
  89183. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89184. * not comply with the Vorbis comment specification, else \c true.
  89185. */
  89186. 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);
  89187. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89188. *
  89189. * The returned pointers to name and value will be allocated by malloc()
  89190. * and shall be owned by the caller.
  89191. *
  89192. * \param entry An existing Vorbis comment entry.
  89193. * \param field_name The address of where the returned pointer to the
  89194. * field name will be stored.
  89195. * \param field_value The address of where the returned pointer to the
  89196. * field value will be stored.
  89197. * \assert
  89198. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89199. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89200. * \code field_name != NULL \endcode
  89201. * \code field_value != NULL \endcode
  89202. * \retval FLAC__bool
  89203. * \c false if memory allocation fails or \a entry does not comply with the
  89204. * Vorbis comment specification, else \c true.
  89205. */
  89206. 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);
  89207. /** Check if the given Vorbis comment entry's field name matches the given
  89208. * field name.
  89209. *
  89210. * \param entry An existing Vorbis comment entry.
  89211. * \param field_name The field name to check.
  89212. * \param field_name_length The length of \a field_name, not including the
  89213. * terminating \c NUL.
  89214. * \assert
  89215. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89216. * \retval FLAC__bool
  89217. * \c true if the field names match, else \c false
  89218. */
  89219. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89220. /** Find a Vorbis comment with the given field name.
  89221. *
  89222. * The search begins at entry number \a offset; use an offset of 0 to
  89223. * search from the beginning of the comment array.
  89224. *
  89225. * \param object A pointer to an existing VORBIS_COMMENT object.
  89226. * \param offset The offset into the comment array from where to start
  89227. * the search.
  89228. * \param field_name The field name of the comment to find.
  89229. * \assert
  89230. * \code object != NULL \endcode
  89231. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89232. * \code field_name != NULL \endcode
  89233. * \retval int
  89234. * The offset in the comment array of the first comment whose field
  89235. * name matches \a field_name, or \c -1 if no match was found.
  89236. */
  89237. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89238. /** Remove first Vorbis comment matching the given field name.
  89239. *
  89240. * \param object A pointer to an existing VORBIS_COMMENT object.
  89241. * \param field_name The field name of comment to delete.
  89242. * \assert
  89243. * \code object != NULL \endcode
  89244. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89245. * \retval int
  89246. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89247. * \c 1 for one matching entry deleted.
  89248. */
  89249. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89250. /** Remove all Vorbis comments matching the given field name.
  89251. *
  89252. * \param object A pointer to an existing VORBIS_COMMENT object.
  89253. * \param field_name The field name of comments to delete.
  89254. * \assert
  89255. * \code object != NULL \endcode
  89256. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89257. * \retval int
  89258. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89259. * else the number of matching entries deleted.
  89260. */
  89261. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89262. /** Create a new CUESHEET track instance.
  89263. *
  89264. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89265. *
  89266. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89267. * \c NULL if there was an error allocating memory, else the new instance.
  89268. */
  89269. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89270. /** Create a copy of an existing CUESHEET track object.
  89271. *
  89272. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89273. * object is also copied. The caller takes ownership of the new object and
  89274. * is responsible for freeing it with
  89275. * FLAC__metadata_object_cuesheet_track_delete().
  89276. *
  89277. * \param object Pointer to object to copy.
  89278. * \assert
  89279. * \code object != NULL \endcode
  89280. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89281. * \c NULL if there was an error allocating memory, else the new instance.
  89282. */
  89283. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89284. /** Delete a CUESHEET track object
  89285. *
  89286. * \param object A pointer to an existing CUESHEET track object.
  89287. * \assert
  89288. * \code object != NULL \endcode
  89289. */
  89290. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89291. /** Resize a track's index point array.
  89292. *
  89293. * If the size shrinks, elements will truncated; if it grows, new blank
  89294. * indices will be added to the end.
  89295. *
  89296. * \param object A pointer to an existing CUESHEET object.
  89297. * \param track_num The index of the track to modify. NOTE: this is not
  89298. * necessarily the same as the track's \a number field.
  89299. * \param new_num_indices The desired length of the array; may be \c 0.
  89300. * \assert
  89301. * \code object != NULL \endcode
  89302. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89303. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89304. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89305. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89306. * \retval FLAC__bool
  89307. * \c false if memory allocation error, else \c true.
  89308. */
  89309. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89310. /** Insert an index point in a CUESHEET track at the given index.
  89311. *
  89312. * \param object A pointer to an existing CUESHEET object.
  89313. * \param track_num The index of the track to modify. NOTE: this is not
  89314. * necessarily the same as the track's \a number field.
  89315. * \param index_num The index into the track's index array at which to
  89316. * insert the index point. NOTE: this is not necessarily
  89317. * the same as the index point's \a number field. The
  89318. * indices at and after \a index_num move right one
  89319. * position. To append an index point to the end, set
  89320. * \a index_num to
  89321. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89322. * \param index The index point to insert.
  89323. * \assert
  89324. * \code object != NULL \endcode
  89325. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89326. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89327. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89328. * \retval FLAC__bool
  89329. * \c false if realloc() fails, else \c true.
  89330. */
  89331. 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);
  89332. /** Insert a blank index point in a CUESHEET track at the given index.
  89333. *
  89334. * A blank index point is one in which all field values are zero.
  89335. *
  89336. * \param object A pointer to an existing CUESHEET object.
  89337. * \param track_num The index of the track to modify. NOTE: this is not
  89338. * necessarily the same as the track's \a number field.
  89339. * \param index_num The index into the track's index array at which to
  89340. * insert the index point. NOTE: this is not necessarily
  89341. * the same as the index point's \a number field. The
  89342. * indices at and after \a index_num move right one
  89343. * position. To append an index point to the end, set
  89344. * \a index_num to
  89345. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89346. * \assert
  89347. * \code object != NULL \endcode
  89348. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89349. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89350. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89351. * \retval FLAC__bool
  89352. * \c false if realloc() fails, else \c true.
  89353. */
  89354. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89355. /** Delete an index point in a CUESHEET track at the given index.
  89356. *
  89357. * \param object A pointer to an existing CUESHEET object.
  89358. * \param track_num The index into the track array of the track to
  89359. * modify. NOTE: this is not necessarily the same
  89360. * as the track's \a number field.
  89361. * \param index_num The index into the track's index array of the index
  89362. * to delete. NOTE: this is not necessarily the same
  89363. * as the index's \a number field.
  89364. * \assert
  89365. * \code object != NULL \endcode
  89366. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89367. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89368. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89369. * \retval FLAC__bool
  89370. * \c false if realloc() fails, else \c true.
  89371. */
  89372. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89373. /** Resize the track array.
  89374. *
  89375. * If the size shrinks, elements will truncated; if it grows, new blank
  89376. * tracks will be added to the end.
  89377. *
  89378. * \param object A pointer to an existing CUESHEET object.
  89379. * \param new_num_tracks The desired length of the array; may be \c 0.
  89380. * \assert
  89381. * \code object != NULL \endcode
  89382. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89383. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89384. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89385. * \retval FLAC__bool
  89386. * \c false if memory allocation error, else \c true.
  89387. */
  89388. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89389. /** Sets a track in a CUESHEET block.
  89390. *
  89391. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89392. * takes ownership of the \a track pointer.
  89393. *
  89394. * \param object A pointer to an existing CUESHEET object.
  89395. * \param track_num Index into track array to set. NOTE: this is not
  89396. * necessarily the same as the track's \a number field.
  89397. * \param track The track to set the track to. You may safely pass in
  89398. * a const pointer if \a copy is \c true.
  89399. * \param copy See above.
  89400. * \assert
  89401. * \code object != NULL \endcode
  89402. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89403. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89404. * \code (track->indices != NULL && track->num_indices > 0) ||
  89405. * (track->indices == NULL && track->num_indices == 0)
  89406. * \retval FLAC__bool
  89407. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89408. */
  89409. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89410. /** Insert a track in a CUESHEET block at the given index.
  89411. *
  89412. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89413. * takes ownership of the \a track pointer.
  89414. *
  89415. * \param object A pointer to an existing CUESHEET object.
  89416. * \param track_num The index at which to insert the track. NOTE: this
  89417. * is not necessarily the same as the track's \a number
  89418. * field. The tracks at and after \a track_num move right
  89419. * one position. To append a track to the end, set
  89420. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89421. * \param track The track to insert. You may safely pass in a const
  89422. * pointer if \a copy is \c true.
  89423. * \param copy See above.
  89424. * \assert
  89425. * \code object != NULL \endcode
  89426. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89427. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89428. * \retval FLAC__bool
  89429. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89430. */
  89431. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89432. /** Insert a blank track in a CUESHEET block at the given index.
  89433. *
  89434. * A blank track is one in which all field values are zero.
  89435. *
  89436. * \param object A pointer to an existing CUESHEET object.
  89437. * \param track_num The index at which to insert the track. NOTE: this
  89438. * is not necessarily the same as the track's \a number
  89439. * field. The tracks at and after \a track_num move right
  89440. * one position. To append a track to the end, set
  89441. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89442. * \assert
  89443. * \code object != NULL \endcode
  89444. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89445. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89446. * \retval FLAC__bool
  89447. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89448. */
  89449. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89450. /** Delete a track in a CUESHEET block at the given index.
  89451. *
  89452. * \param object A pointer to an existing CUESHEET object.
  89453. * \param track_num The index into the track array of the track to
  89454. * delete. NOTE: this is not necessarily the same
  89455. * as the track's \a number field.
  89456. * \assert
  89457. * \code object != NULL \endcode
  89458. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89459. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89460. * \retval FLAC__bool
  89461. * \c false if realloc() fails, else \c true.
  89462. */
  89463. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89464. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89465. * See the format specification for limits on the contents of the
  89466. * cue sheet.
  89467. *
  89468. * \param object A pointer to an existing CUESHEET object.
  89469. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89470. * stringent requirements for a CD-DA (audio) disc.
  89471. * \param violation Address of a pointer to a string. If there is a
  89472. * violation, a pointer to a string explanation of the
  89473. * violation will be returned here. \a violation may be
  89474. * \c NULL if you don't need the returned string. Do not
  89475. * free the returned string; it will always point to static
  89476. * data.
  89477. * \assert
  89478. * \code object != NULL \endcode
  89479. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89480. * \retval FLAC__bool
  89481. * \c false if cue sheet is illegal, else \c true.
  89482. */
  89483. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89484. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89485. * assumes the cue sheet corresponds to a CD; the result is undefined
  89486. * if the cuesheet's is_cd bit is not set.
  89487. *
  89488. * \param object A pointer to an existing CUESHEET object.
  89489. * \assert
  89490. * \code object != NULL \endcode
  89491. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89492. * \retval FLAC__uint32
  89493. * The unsigned integer representation of the CDDB/freedb ID
  89494. */
  89495. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89496. /** Sets the MIME type of a PICTURE block.
  89497. *
  89498. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89499. * takes ownership of the pointer. The existing string will be freed if this
  89500. * function is successful, otherwise the original string will remain if \a copy
  89501. * is \c true and malloc() fails.
  89502. *
  89503. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89504. *
  89505. * \param object A pointer to an existing PICTURE object.
  89506. * \param mime_type A pointer to the MIME type string. The string must be
  89507. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89508. * is done.
  89509. * \param copy See above.
  89510. * \assert
  89511. * \code object != NULL \endcode
  89512. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89513. * \code (mime_type != NULL) \endcode
  89514. * \retval FLAC__bool
  89515. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89516. */
  89517. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89518. /** Sets the description of a PICTURE block.
  89519. *
  89520. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89521. * takes ownership of the pointer. The existing string will be freed if this
  89522. * function is successful, otherwise the original string will remain if \a copy
  89523. * is \c true and malloc() fails.
  89524. *
  89525. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89526. *
  89527. * \param object A pointer to an existing PICTURE object.
  89528. * \param description A pointer to the description string. The string must be
  89529. * valid UTF-8, NUL-terminated. No validation is done.
  89530. * \param copy See above.
  89531. * \assert
  89532. * \code object != NULL \endcode
  89533. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89534. * \code (description != NULL) \endcode
  89535. * \retval FLAC__bool
  89536. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89537. */
  89538. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89539. /** Sets the picture data of a PICTURE block.
  89540. *
  89541. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89542. * takes ownership of the pointer. Also sets the \a data_length field of the
  89543. * metadata object to what is passed in as the \a length parameter. The
  89544. * existing data will be freed if this function is successful, otherwise the
  89545. * original data and data_length will remain if \a copy is \c true and
  89546. * malloc() fails.
  89547. *
  89548. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89549. *
  89550. * \param object A pointer to an existing PICTURE object.
  89551. * \param data A pointer to the data to set.
  89552. * \param length The length of \a data in bytes.
  89553. * \param copy See above.
  89554. * \assert
  89555. * \code object != NULL \endcode
  89556. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89557. * \code (data != NULL && length > 0) ||
  89558. * (data == NULL && length == 0 && copy == false) \endcode
  89559. * \retval FLAC__bool
  89560. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89561. */
  89562. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89563. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89564. * See the format specification for limits on the contents of the
  89565. * PICTURE block.
  89566. *
  89567. * \param object A pointer to existing PICTURE block to be checked.
  89568. * \param violation Address of a pointer to a string. If there is a
  89569. * violation, a pointer to a string explanation of the
  89570. * violation will be returned here. \a violation may be
  89571. * \c NULL if you don't need the returned string. Do not
  89572. * free the returned string; it will always point to static
  89573. * data.
  89574. * \assert
  89575. * \code object != NULL \endcode
  89576. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89577. * \retval FLAC__bool
  89578. * \c false if PICTURE block is illegal, else \c true.
  89579. */
  89580. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89581. /* \} */
  89582. #ifdef __cplusplus
  89583. }
  89584. #endif
  89585. #endif
  89586. /*** End of inlined file: metadata.h ***/
  89587. /*** Start of inlined file: stream_decoder.h ***/
  89588. #ifndef FLAC__STREAM_DECODER_H
  89589. #define FLAC__STREAM_DECODER_H
  89590. #include <stdio.h> /* for FILE */
  89591. #ifdef __cplusplus
  89592. extern "C" {
  89593. #endif
  89594. /** \file include/FLAC/stream_decoder.h
  89595. *
  89596. * \brief
  89597. * This module contains the functions which implement the stream
  89598. * decoder.
  89599. *
  89600. * See the detailed documentation in the
  89601. * \link flac_stream_decoder stream decoder \endlink module.
  89602. */
  89603. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89604. * \ingroup flac
  89605. *
  89606. * \brief
  89607. * This module describes the decoder layers provided by libFLAC.
  89608. *
  89609. * The stream decoder can be used to decode complete streams either from
  89610. * the client via callbacks, or directly from a file, depending on how
  89611. * it is initialized. When decoding via callbacks, the client provides
  89612. * callbacks for reading FLAC data and writing decoded samples, and
  89613. * handling metadata and errors. If the client also supplies seek-related
  89614. * callback, the decoder function for sample-accurate seeking within the
  89615. * FLAC input is also available. When decoding from a file, the client
  89616. * needs only supply a filename or open \c FILE* and write/metadata/error
  89617. * callbacks; the rest of the callbacks are supplied internally. For more
  89618. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89619. */
  89620. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89621. * \ingroup flac_decoder
  89622. *
  89623. * \brief
  89624. * This module contains the functions which implement the stream
  89625. * decoder.
  89626. *
  89627. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89628. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89629. *
  89630. * The basic usage of this decoder is as follows:
  89631. * - The program creates an instance of a decoder using
  89632. * FLAC__stream_decoder_new().
  89633. * - The program overrides the default settings using
  89634. * FLAC__stream_decoder_set_*() functions.
  89635. * - The program initializes the instance to validate the settings and
  89636. * prepare for decoding using
  89637. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89638. * or FLAC__stream_decoder_init_file() for native FLAC,
  89639. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89640. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89641. * - The program calls the FLAC__stream_decoder_process_*() functions
  89642. * to decode data, which subsequently calls the callbacks.
  89643. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89644. * which flushes the input and output and resets the decoder to the
  89645. * uninitialized state.
  89646. * - The instance may be used again or deleted with
  89647. * FLAC__stream_decoder_delete().
  89648. *
  89649. * In more detail, the program will create a new instance by calling
  89650. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89651. * functions to override the default decoder options, and call
  89652. * one of the FLAC__stream_decoder_init_*() functions.
  89653. *
  89654. * There are three initialization functions for native FLAC, one for
  89655. * setting up the decoder to decode FLAC data from the client via
  89656. * callbacks, and two for decoding directly from a FLAC file.
  89657. *
  89658. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89659. * You must also supply several callbacks for handling I/O. Some (like
  89660. * seeking) are optional, depending on the capabilities of the input.
  89661. *
  89662. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89663. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89664. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89665. * the other callbacks internally.
  89666. *
  89667. * There are three similarly-named init functions for decoding from Ogg
  89668. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89669. * library has been built with Ogg support.
  89670. *
  89671. * Once the decoder is initialized, your program will call one of several
  89672. * functions to start the decoding process:
  89673. *
  89674. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89675. * most one metadata block or audio frame and return, calling either the
  89676. * metadata callback or write callback, respectively, once. If the decoder
  89677. * loses sync it will return with only the error callback being called.
  89678. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89679. * to process the stream from the current location and stop upon reaching
  89680. * the first audio frame. The client will get one metadata, write, or error
  89681. * callback per metadata block, audio frame, or sync error, respectively.
  89682. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89683. * to process the stream from the current location until the read callback
  89684. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89685. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89686. * write, or error callback per metadata block, audio frame, or sync error,
  89687. * respectively.
  89688. *
  89689. * When the decoder has finished decoding (normally or through an abort),
  89690. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89691. * ensures the decoder is in the correct state and frees memory. Then the
  89692. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89693. * again to decode another stream.
  89694. *
  89695. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89696. * At any point after the stream decoder has been initialized, the client can
  89697. * call this function to seek to an exact sample within the stream.
  89698. * Subsequently, the first time the write callback is called it will be
  89699. * passed a (possibly partial) block starting at that sample.
  89700. *
  89701. * If the client cannot seek via the callback interface provided, but still
  89702. * has another way of seeking, it can flush the decoder using
  89703. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89704. * through the read callback.
  89705. *
  89706. * The stream decoder also provides MD5 signature checking. If this is
  89707. * turned on before initialization, FLAC__stream_decoder_finish() will
  89708. * report when the decoded MD5 signature does not match the one stored
  89709. * in the STREAMINFO block. MD5 checking is automatically turned off
  89710. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89711. * in the STREAMINFO block or when a seek is attempted.
  89712. *
  89713. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89714. * attention. By default, the decoder only calls the metadata_callback for
  89715. * the STREAMINFO block. These functions allow you to tell the decoder
  89716. * explicitly which blocks to parse and return via the metadata_callback
  89717. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89718. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89719. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89720. * which blocks to return. Remember that metadata blocks can potentially
  89721. * be big (for example, cover art) so filtering out the ones you don't
  89722. * use can reduce the memory requirements of the decoder. Also note the
  89723. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89724. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89725. * filtering APPLICATION blocks based on the application ID.
  89726. *
  89727. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89728. * they still can legally be filtered from the metadata_callback.
  89729. *
  89730. * \note
  89731. * The "set" functions may only be called when the decoder is in the
  89732. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89733. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89734. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89735. * return \c true, otherwise \c false.
  89736. *
  89737. * \note
  89738. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89739. * defaults, including the callbacks.
  89740. *
  89741. * \{
  89742. */
  89743. /** State values for a FLAC__StreamDecoder
  89744. *
  89745. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89746. */
  89747. typedef enum {
  89748. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89749. /**< The decoder is ready to search for metadata. */
  89750. FLAC__STREAM_DECODER_READ_METADATA,
  89751. /**< The decoder is ready to or is in the process of reading metadata. */
  89752. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89753. /**< The decoder is ready to or is in the process of searching for the
  89754. * frame sync code.
  89755. */
  89756. FLAC__STREAM_DECODER_READ_FRAME,
  89757. /**< The decoder is ready to or is in the process of reading a frame. */
  89758. FLAC__STREAM_DECODER_END_OF_STREAM,
  89759. /**< The decoder has reached the end of the stream. */
  89760. FLAC__STREAM_DECODER_OGG_ERROR,
  89761. /**< An error occurred in the underlying Ogg layer. */
  89762. FLAC__STREAM_DECODER_SEEK_ERROR,
  89763. /**< An error occurred while seeking. The decoder must be flushed
  89764. * with FLAC__stream_decoder_flush() or reset with
  89765. * FLAC__stream_decoder_reset() before decoding can continue.
  89766. */
  89767. FLAC__STREAM_DECODER_ABORTED,
  89768. /**< The decoder was aborted by the read callback. */
  89769. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89770. /**< An error occurred allocating memory. The decoder is in an invalid
  89771. * state and can no longer be used.
  89772. */
  89773. FLAC__STREAM_DECODER_UNINITIALIZED
  89774. /**< The decoder is in the uninitialized state; one of the
  89775. * FLAC__stream_decoder_init_*() functions must be called before samples
  89776. * can be processed.
  89777. */
  89778. } FLAC__StreamDecoderState;
  89779. /** Maps a FLAC__StreamDecoderState to a C string.
  89780. *
  89781. * Using a FLAC__StreamDecoderState as the index to this array
  89782. * will give the string equivalent. The contents should not be modified.
  89783. */
  89784. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89785. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89786. */
  89787. typedef enum {
  89788. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89789. /**< Initialization was successful. */
  89790. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89791. /**< The library was not compiled with support for the given container
  89792. * format.
  89793. */
  89794. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89795. /**< A required callback was not supplied. */
  89796. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89797. /**< An error occurred allocating memory. */
  89798. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89799. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89800. * FLAC__stream_decoder_init_ogg_file(). */
  89801. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89802. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89803. * already initialized, usually because
  89804. * FLAC__stream_decoder_finish() was not called.
  89805. */
  89806. } FLAC__StreamDecoderInitStatus;
  89807. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89808. *
  89809. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89810. * will give the string equivalent. The contents should not be modified.
  89811. */
  89812. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89813. /** Return values for the FLAC__StreamDecoder read callback.
  89814. */
  89815. typedef enum {
  89816. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89817. /**< The read was OK and decoding can continue. */
  89818. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89819. /**< The read was attempted while at the end of the stream. Note that
  89820. * the client must only return this value when the read callback was
  89821. * called when already at the end of the stream. Otherwise, if the read
  89822. * itself moves to the end of the stream, the client should still return
  89823. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89824. * the next read callback it should return
  89825. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89826. * of \c 0.
  89827. */
  89828. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89829. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89830. } FLAC__StreamDecoderReadStatus;
  89831. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89832. *
  89833. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89834. * will give the string equivalent. The contents should not be modified.
  89835. */
  89836. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89837. /** Return values for the FLAC__StreamDecoder seek callback.
  89838. */
  89839. typedef enum {
  89840. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89841. /**< The seek was OK and decoding can continue. */
  89842. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89843. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89844. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89845. /**< Client does not support seeking. */
  89846. } FLAC__StreamDecoderSeekStatus;
  89847. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89848. *
  89849. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89850. * will give the string equivalent. The contents should not be modified.
  89851. */
  89852. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89853. /** Return values for the FLAC__StreamDecoder tell callback.
  89854. */
  89855. typedef enum {
  89856. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89857. /**< The tell was OK and decoding can continue. */
  89858. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89859. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89860. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89861. /**< Client does not support telling the position. */
  89862. } FLAC__StreamDecoderTellStatus;
  89863. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89864. *
  89865. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89866. * will give the string equivalent. The contents should not be modified.
  89867. */
  89868. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89869. /** Return values for the FLAC__StreamDecoder length callback.
  89870. */
  89871. typedef enum {
  89872. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89873. /**< The length call was OK and decoding can continue. */
  89874. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89875. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89876. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89877. /**< Client does not support reporting the length. */
  89878. } FLAC__StreamDecoderLengthStatus;
  89879. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89880. *
  89881. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89882. * will give the string equivalent. The contents should not be modified.
  89883. */
  89884. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89885. /** Return values for the FLAC__StreamDecoder write callback.
  89886. */
  89887. typedef enum {
  89888. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89889. /**< The write was OK and decoding can continue. */
  89890. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89891. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89892. } FLAC__StreamDecoderWriteStatus;
  89893. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89894. *
  89895. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89896. * will give the string equivalent. The contents should not be modified.
  89897. */
  89898. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89899. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89900. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89901. * all. The rest could be caused by bad sync (false synchronization on
  89902. * data that is not the start of a frame) or corrupted data. The error
  89903. * itself is the decoder's best guess at what happened assuming a correct
  89904. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89905. * could be caused by a correct sync on the start of a frame, but some
  89906. * data in the frame header was corrupted. Or it could be the result of
  89907. * syncing on a point the stream that looked like the starting of a frame
  89908. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89909. * could be because the decoder encountered a valid frame made by a future
  89910. * version of the encoder which it cannot parse, or because of a false
  89911. * sync making it appear as though an encountered frame was generated by
  89912. * a future encoder.
  89913. */
  89914. typedef enum {
  89915. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89916. /**< An error in the stream caused the decoder to lose synchronization. */
  89917. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89918. /**< The decoder encountered a corrupted frame header. */
  89919. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89920. /**< The frame's data did not match the CRC in the footer. */
  89921. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89922. /**< The decoder encountered reserved fields in use in the stream. */
  89923. } FLAC__StreamDecoderErrorStatus;
  89924. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89925. *
  89926. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89927. * will give the string equivalent. The contents should not be modified.
  89928. */
  89929. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89930. /***********************************************************************
  89931. *
  89932. * class FLAC__StreamDecoder
  89933. *
  89934. ***********************************************************************/
  89935. struct FLAC__StreamDecoderProtected;
  89936. struct FLAC__StreamDecoderPrivate;
  89937. /** The opaque structure definition for the stream decoder type.
  89938. * See the \link flac_stream_decoder stream decoder module \endlink
  89939. * for a detailed description.
  89940. */
  89941. typedef struct {
  89942. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89943. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89944. } FLAC__StreamDecoder;
  89945. /** Signature for the read callback.
  89946. *
  89947. * A function pointer matching this signature must be passed to
  89948. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89949. * called when the decoder needs more input data. The address of the
  89950. * buffer to be filled is supplied, along with the number of bytes the
  89951. * buffer can hold. The callback may choose to supply less data and
  89952. * modify the byte count but must be careful not to overflow the buffer.
  89953. * The callback then returns a status code chosen from
  89954. * FLAC__StreamDecoderReadStatus.
  89955. *
  89956. * Here is an example of a read callback for stdio streams:
  89957. * \code
  89958. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89959. * {
  89960. * FILE *file = ((MyClientData*)client_data)->file;
  89961. * if(*bytes > 0) {
  89962. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89963. * if(ferror(file))
  89964. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89965. * else if(*bytes == 0)
  89966. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89967. * else
  89968. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89969. * }
  89970. * else
  89971. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89972. * }
  89973. * \endcode
  89974. *
  89975. * \note In general, FLAC__StreamDecoder functions which change the
  89976. * state should not be called on the \a decoder while in the callback.
  89977. *
  89978. * \param decoder The decoder instance calling the callback.
  89979. * \param buffer A pointer to a location for the callee to store
  89980. * data to be decoded.
  89981. * \param bytes A pointer to the size of the buffer. On entry
  89982. * to the callback, it contains the maximum number
  89983. * of bytes that may be stored in \a buffer. The
  89984. * callee must set it to the actual number of bytes
  89985. * stored (0 in case of error or end-of-stream) before
  89986. * returning.
  89987. * \param client_data The callee's client data set through
  89988. * FLAC__stream_decoder_init_*().
  89989. * \retval FLAC__StreamDecoderReadStatus
  89990. * The callee's return status. Note that the callback should return
  89991. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89992. * zero bytes were read and there is no more data to be read.
  89993. */
  89994. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89995. /** Signature for the seek callback.
  89996. *
  89997. * A function pointer matching this signature may be passed to
  89998. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89999. * called when the decoder needs to seek the input stream. The decoder
  90000. * will pass the absolute byte offset to seek to, 0 meaning the
  90001. * beginning of the stream.
  90002. *
  90003. * Here is an example of a seek callback for stdio streams:
  90004. * \code
  90005. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90006. * {
  90007. * FILE *file = ((MyClientData*)client_data)->file;
  90008. * if(file == stdin)
  90009. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  90010. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90011. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  90012. * else
  90013. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  90014. * }
  90015. * \endcode
  90016. *
  90017. * \note In general, FLAC__StreamDecoder functions which change the
  90018. * state should not be called on the \a decoder while in the callback.
  90019. *
  90020. * \param decoder The decoder instance calling the callback.
  90021. * \param absolute_byte_offset The offset from the beginning of the stream
  90022. * to seek to.
  90023. * \param client_data The callee's client data set through
  90024. * FLAC__stream_decoder_init_*().
  90025. * \retval FLAC__StreamDecoderSeekStatus
  90026. * The callee's return status.
  90027. */
  90028. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90029. /** Signature for the tell callback.
  90030. *
  90031. * A function pointer matching this signature may be passed to
  90032. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90033. * called when the decoder wants to know the current position of the
  90034. * stream. The callback should return the byte offset from the
  90035. * beginning of the stream.
  90036. *
  90037. * Here is an example of a tell callback for stdio streams:
  90038. * \code
  90039. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90040. * {
  90041. * FILE *file = ((MyClientData*)client_data)->file;
  90042. * off_t pos;
  90043. * if(file == stdin)
  90044. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  90045. * else if((pos = ftello(file)) < 0)
  90046. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  90047. * else {
  90048. * *absolute_byte_offset = (FLAC__uint64)pos;
  90049. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  90050. * }
  90051. * }
  90052. * \endcode
  90053. *
  90054. * \note In general, FLAC__StreamDecoder functions which change the
  90055. * state should not be called on the \a decoder while in the callback.
  90056. *
  90057. * \param decoder The decoder instance calling the callback.
  90058. * \param absolute_byte_offset A pointer to storage for the current offset
  90059. * from the beginning of the stream.
  90060. * \param client_data The callee's client data set through
  90061. * FLAC__stream_decoder_init_*().
  90062. * \retval FLAC__StreamDecoderTellStatus
  90063. * The callee's return status.
  90064. */
  90065. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90066. /** Signature for the length callback.
  90067. *
  90068. * A function pointer matching this signature may be passed to
  90069. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90070. * called when the decoder wants to know the total length of the stream
  90071. * in bytes.
  90072. *
  90073. * Here is an example of a length callback for stdio streams:
  90074. * \code
  90075. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  90076. * {
  90077. * FILE *file = ((MyClientData*)client_data)->file;
  90078. * struct stat filestats;
  90079. *
  90080. * if(file == stdin)
  90081. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  90082. * else if(fstat(fileno(file), &filestats) != 0)
  90083. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  90084. * else {
  90085. * *stream_length = (FLAC__uint64)filestats.st_size;
  90086. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  90087. * }
  90088. * }
  90089. * \endcode
  90090. *
  90091. * \note In general, FLAC__StreamDecoder functions which change the
  90092. * state should not be called on the \a decoder while in the callback.
  90093. *
  90094. * \param decoder The decoder instance calling the callback.
  90095. * \param stream_length A pointer to storage for the length of the stream
  90096. * in bytes.
  90097. * \param client_data The callee's client data set through
  90098. * FLAC__stream_decoder_init_*().
  90099. * \retval FLAC__StreamDecoderLengthStatus
  90100. * The callee's return status.
  90101. */
  90102. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  90103. /** Signature for the EOF callback.
  90104. *
  90105. * A function pointer matching this signature may be passed to
  90106. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90107. * called when the decoder needs to know if the end of the stream has
  90108. * been reached.
  90109. *
  90110. * Here is an example of a EOF callback for stdio streams:
  90111. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  90112. * \code
  90113. * {
  90114. * FILE *file = ((MyClientData*)client_data)->file;
  90115. * return feof(file)? true : false;
  90116. * }
  90117. * \endcode
  90118. *
  90119. * \note In general, FLAC__StreamDecoder functions which change the
  90120. * state should not be called on the \a decoder while in the callback.
  90121. *
  90122. * \param decoder The decoder instance calling the callback.
  90123. * \param client_data The callee's client data set through
  90124. * FLAC__stream_decoder_init_*().
  90125. * \retval FLAC__bool
  90126. * \c true if the currently at the end of the stream, else \c false.
  90127. */
  90128. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  90129. /** Signature for the write callback.
  90130. *
  90131. * A function pointer matching this signature must be passed to one of
  90132. * the FLAC__stream_decoder_init_*() functions.
  90133. * The supplied function will be called when the decoder has decoded a
  90134. * single audio frame. The decoder will pass the frame metadata as well
  90135. * as an array of pointers (one for each channel) pointing to the
  90136. * decoded audio.
  90137. *
  90138. * \note In general, FLAC__StreamDecoder functions which change the
  90139. * state should not be called on the \a decoder while in the callback.
  90140. *
  90141. * \param decoder The decoder instance calling the callback.
  90142. * \param frame The description of the decoded frame. See
  90143. * FLAC__Frame.
  90144. * \param buffer An array of pointers to decoded channels of data.
  90145. * Each pointer will point to an array of signed
  90146. * samples of length \a frame->header.blocksize.
  90147. * Channels will be ordered according to the FLAC
  90148. * specification; see the documentation for the
  90149. * <A HREF="../format.html#frame_header">frame header</A>.
  90150. * \param client_data The callee's client data set through
  90151. * FLAC__stream_decoder_init_*().
  90152. * \retval FLAC__StreamDecoderWriteStatus
  90153. * The callee's return status.
  90154. */
  90155. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  90156. /** Signature for the metadata callback.
  90157. *
  90158. * A function pointer matching this signature must be passed to one of
  90159. * the FLAC__stream_decoder_init_*() functions.
  90160. * The supplied function will be called when the decoder has decoded a
  90161. * metadata block. In a valid FLAC file there will always be one
  90162. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90163. * These will be supplied by the decoder in the same order as they
  90164. * appear in the stream and always before the first audio frame (i.e.
  90165. * write callback). The metadata block that is passed in must not be
  90166. * modified, and it doesn't live beyond the callback, so you should make
  90167. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90168. * elsewhere. Since metadata blocks can potentially be large, by
  90169. * default the decoder only calls the metadata callback for the
  90170. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90171. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90172. *
  90173. * \note In general, FLAC__StreamDecoder functions which change the
  90174. * state should not be called on the \a decoder while in the callback.
  90175. *
  90176. * \param decoder The decoder instance calling the callback.
  90177. * \param metadata The decoded metadata block.
  90178. * \param client_data The callee's client data set through
  90179. * FLAC__stream_decoder_init_*().
  90180. */
  90181. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90182. /** Signature for the error callback.
  90183. *
  90184. * A function pointer matching this signature must be passed to one of
  90185. * the FLAC__stream_decoder_init_*() functions.
  90186. * The supplied function will be called whenever an error occurs during
  90187. * decoding.
  90188. *
  90189. * \note In general, FLAC__StreamDecoder functions which change the
  90190. * state should not be called on the \a decoder while in the callback.
  90191. *
  90192. * \param decoder The decoder instance calling the callback.
  90193. * \param status The error encountered by the decoder.
  90194. * \param client_data The callee's client data set through
  90195. * FLAC__stream_decoder_init_*().
  90196. */
  90197. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90198. /***********************************************************************
  90199. *
  90200. * Class constructor/destructor
  90201. *
  90202. ***********************************************************************/
  90203. /** Create a new stream decoder instance. The instance is created with
  90204. * default settings; see the individual FLAC__stream_decoder_set_*()
  90205. * functions for each setting's default.
  90206. *
  90207. * \retval FLAC__StreamDecoder*
  90208. * \c NULL if there was an error allocating memory, else the new instance.
  90209. */
  90210. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90211. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90212. *
  90213. * \param decoder A pointer to an existing decoder.
  90214. * \assert
  90215. * \code decoder != NULL \endcode
  90216. */
  90217. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90218. /***********************************************************************
  90219. *
  90220. * Public class method prototypes
  90221. *
  90222. ***********************************************************************/
  90223. /** Set the serial number for the FLAC stream within the Ogg container.
  90224. * The default behavior is to use the serial number of the first Ogg
  90225. * page. Setting a serial number here will explicitly specify which
  90226. * stream is to be decoded.
  90227. *
  90228. * \note
  90229. * This does not need to be set for native FLAC decoding.
  90230. *
  90231. * \default \c use serial number of first page
  90232. * \param decoder A decoder instance to set.
  90233. * \param serial_number See above.
  90234. * \assert
  90235. * \code decoder != NULL \endcode
  90236. * \retval FLAC__bool
  90237. * \c false if the decoder is already initialized, else \c true.
  90238. */
  90239. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90240. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90241. * compute the MD5 signature of the unencoded audio data while decoding
  90242. * and compare it to the signature from the STREAMINFO block, if it
  90243. * exists, during FLAC__stream_decoder_finish().
  90244. *
  90245. * MD5 signature checking will be turned off (until the next
  90246. * FLAC__stream_decoder_reset()) if there is no signature in the
  90247. * STREAMINFO block or when a seek is attempted.
  90248. *
  90249. * Clients that do not use the MD5 check should leave this off to speed
  90250. * up decoding.
  90251. *
  90252. * \default \c false
  90253. * \param decoder A decoder instance to set.
  90254. * \param value Flag value (see above).
  90255. * \assert
  90256. * \code decoder != NULL \endcode
  90257. * \retval FLAC__bool
  90258. * \c false if the decoder is already initialized, else \c true.
  90259. */
  90260. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90261. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90262. *
  90263. * \default By default, only the \c STREAMINFO block is returned via the
  90264. * metadata callback.
  90265. * \param decoder A decoder instance to set.
  90266. * \param type See above.
  90267. * \assert
  90268. * \code decoder != NULL \endcode
  90269. * \a type is valid
  90270. * \retval FLAC__bool
  90271. * \c false if the decoder is already initialized, else \c true.
  90272. */
  90273. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90274. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90275. * given \a id.
  90276. *
  90277. * \default By default, only the \c STREAMINFO block is returned via the
  90278. * metadata callback.
  90279. * \param decoder A decoder instance to set.
  90280. * \param id See above.
  90281. * \assert
  90282. * \code decoder != NULL \endcode
  90283. * \code id != NULL \endcode
  90284. * \retval FLAC__bool
  90285. * \c false if the decoder is already initialized, else \c true.
  90286. */
  90287. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90288. /** Direct the decoder to pass on all metadata blocks of any type.
  90289. *
  90290. * \default By default, only the \c STREAMINFO block is returned via the
  90291. * metadata callback.
  90292. * \param decoder A decoder instance to set.
  90293. * \assert
  90294. * \code decoder != NULL \endcode
  90295. * \retval FLAC__bool
  90296. * \c false if the decoder is already initialized, else \c true.
  90297. */
  90298. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90299. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90300. *
  90301. * \default By default, only the \c STREAMINFO block is returned via the
  90302. * metadata callback.
  90303. * \param decoder A decoder instance to set.
  90304. * \param type See above.
  90305. * \assert
  90306. * \code decoder != NULL \endcode
  90307. * \a type is valid
  90308. * \retval FLAC__bool
  90309. * \c false if the decoder is already initialized, else \c true.
  90310. */
  90311. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90312. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90313. * the given \a id.
  90314. *
  90315. * \default By default, only the \c STREAMINFO block is returned via the
  90316. * metadata callback.
  90317. * \param decoder A decoder instance to set.
  90318. * \param id See above.
  90319. * \assert
  90320. * \code decoder != NULL \endcode
  90321. * \code id != NULL \endcode
  90322. * \retval FLAC__bool
  90323. * \c false if the decoder is already initialized, else \c true.
  90324. */
  90325. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90326. /** Direct the decoder to filter out all metadata blocks of any type.
  90327. *
  90328. * \default By default, only the \c STREAMINFO block is returned via the
  90329. * metadata callback.
  90330. * \param decoder A decoder instance to set.
  90331. * \assert
  90332. * \code decoder != NULL \endcode
  90333. * \retval FLAC__bool
  90334. * \c false if the decoder is already initialized, else \c true.
  90335. */
  90336. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90337. /** Get the current decoder state.
  90338. *
  90339. * \param decoder A decoder instance to query.
  90340. * \assert
  90341. * \code decoder != NULL \endcode
  90342. * \retval FLAC__StreamDecoderState
  90343. * The current decoder state.
  90344. */
  90345. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90346. /** Get the current decoder state as a C string.
  90347. *
  90348. * \param decoder A decoder instance to query.
  90349. * \assert
  90350. * \code decoder != NULL \endcode
  90351. * \retval const char *
  90352. * The decoder state as a C string. Do not modify the contents.
  90353. */
  90354. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90355. /** Get the "MD5 signature checking" flag.
  90356. * This is the value of the setting, not whether or not the decoder is
  90357. * currently checking the MD5 (remember, it can be turned off automatically
  90358. * by a seek). When the decoder is reset the flag will be restored to the
  90359. * value returned by this function.
  90360. *
  90361. * \param decoder A decoder instance to query.
  90362. * \assert
  90363. * \code decoder != NULL \endcode
  90364. * \retval FLAC__bool
  90365. * See above.
  90366. */
  90367. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90368. /** Get the total number of samples in the stream being decoded.
  90369. * Will only be valid after decoding has started and will contain the
  90370. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90371. *
  90372. * \param decoder A decoder instance to query.
  90373. * \assert
  90374. * \code decoder != NULL \endcode
  90375. * \retval unsigned
  90376. * See above.
  90377. */
  90378. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90379. /** Get the current number of channels in the stream being decoded.
  90380. * Will only be valid after decoding has started and will contain the
  90381. * value from the most recently decoded frame header.
  90382. *
  90383. * \param decoder A decoder instance to query.
  90384. * \assert
  90385. * \code decoder != NULL \endcode
  90386. * \retval unsigned
  90387. * See above.
  90388. */
  90389. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90390. /** Get the current channel assignment in the stream being decoded.
  90391. * Will only be valid after decoding has started and will contain the
  90392. * value from the most recently decoded frame header.
  90393. *
  90394. * \param decoder A decoder instance to query.
  90395. * \assert
  90396. * \code decoder != NULL \endcode
  90397. * \retval FLAC__ChannelAssignment
  90398. * See above.
  90399. */
  90400. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90401. /** Get the current sample resolution in the stream being decoded.
  90402. * Will only be valid after decoding has started and will contain the
  90403. * value from the most recently decoded frame header.
  90404. *
  90405. * \param decoder A decoder instance to query.
  90406. * \assert
  90407. * \code decoder != NULL \endcode
  90408. * \retval unsigned
  90409. * See above.
  90410. */
  90411. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90412. /** Get the current sample rate in Hz of the stream being decoded.
  90413. * Will only be valid after decoding has started and will contain the
  90414. * value from the most recently decoded frame header.
  90415. *
  90416. * \param decoder A decoder instance to query.
  90417. * \assert
  90418. * \code decoder != NULL \endcode
  90419. * \retval unsigned
  90420. * See above.
  90421. */
  90422. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90423. /** Get the current blocksize of the stream being decoded.
  90424. * Will only be valid after decoding has started and will contain the
  90425. * value from the most recently decoded frame header.
  90426. *
  90427. * \param decoder A decoder instance to query.
  90428. * \assert
  90429. * \code decoder != NULL \endcode
  90430. * \retval unsigned
  90431. * See above.
  90432. */
  90433. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90434. /** Returns the decoder's current read position within the stream.
  90435. * The position is the byte offset from the start of the stream.
  90436. * Bytes before this position have been fully decoded. Note that
  90437. * there may still be undecoded bytes in the decoder's read FIFO.
  90438. * The returned position is correct even after a seek.
  90439. *
  90440. * \warning This function currently only works for native FLAC,
  90441. * not Ogg FLAC streams.
  90442. *
  90443. * \param decoder A decoder instance to query.
  90444. * \param position Address at which to return the desired position.
  90445. * \assert
  90446. * \code decoder != NULL \endcode
  90447. * \code position != NULL \endcode
  90448. * \retval FLAC__bool
  90449. * \c true if successful, \c false if the stream is not native FLAC,
  90450. * or there was an error from the 'tell' callback or it returned
  90451. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90452. */
  90453. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90454. /** Initialize the decoder instance to decode native FLAC streams.
  90455. *
  90456. * This flavor of initialization sets up the decoder to decode from a
  90457. * native FLAC stream. I/O is performed via callbacks to the client.
  90458. * For decoding from a plain file via filename or open FILE*,
  90459. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90460. * provide a simpler interface.
  90461. *
  90462. * This function should be called after FLAC__stream_decoder_new() and
  90463. * FLAC__stream_decoder_set_*() but before any of the
  90464. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90465. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90466. * if initialization succeeded.
  90467. *
  90468. * \param decoder An uninitialized decoder instance.
  90469. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90470. * pointer must not be \c NULL.
  90471. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90472. * pointer may be \c NULL if seeking is not
  90473. * supported. If \a seek_callback is not \c NULL then a
  90474. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90475. * Alternatively, a dummy seek callback that just
  90476. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90477. * may also be supplied, all though this is slightly
  90478. * less efficient for the decoder.
  90479. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90480. * pointer may be \c NULL if not supported by the client. If
  90481. * \a seek_callback is not \c NULL then a
  90482. * \a tell_callback must also be supplied.
  90483. * Alternatively, a dummy tell callback that just
  90484. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90485. * may also be supplied, all though this is slightly
  90486. * less efficient for the decoder.
  90487. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90488. * pointer may be \c NULL if not supported by the client. If
  90489. * \a seek_callback is not \c NULL then a
  90490. * \a length_callback must also be supplied.
  90491. * Alternatively, a dummy length callback that just
  90492. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90493. * may also be supplied, all though this is slightly
  90494. * less efficient for the decoder.
  90495. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90496. * pointer may be \c NULL if not supported by the client. If
  90497. * \a seek_callback is not \c NULL then a
  90498. * \a eof_callback must also be supplied.
  90499. * Alternatively, a dummy length callback that just
  90500. * returns \c false
  90501. * may also be supplied, all though this is slightly
  90502. * less efficient for the decoder.
  90503. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90504. * pointer must not be \c NULL.
  90505. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90506. * pointer may be \c NULL if the callback is not
  90507. * desired.
  90508. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90509. * pointer must not be \c NULL.
  90510. * \param client_data This value will be supplied to callbacks in their
  90511. * \a client_data argument.
  90512. * \assert
  90513. * \code decoder != NULL \endcode
  90514. * \retval FLAC__StreamDecoderInitStatus
  90515. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90516. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90517. */
  90518. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90519. FLAC__StreamDecoder *decoder,
  90520. FLAC__StreamDecoderReadCallback read_callback,
  90521. FLAC__StreamDecoderSeekCallback seek_callback,
  90522. FLAC__StreamDecoderTellCallback tell_callback,
  90523. FLAC__StreamDecoderLengthCallback length_callback,
  90524. FLAC__StreamDecoderEofCallback eof_callback,
  90525. FLAC__StreamDecoderWriteCallback write_callback,
  90526. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90527. FLAC__StreamDecoderErrorCallback error_callback,
  90528. void *client_data
  90529. );
  90530. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90531. *
  90532. * This flavor of initialization sets up the decoder to decode from a
  90533. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90534. * client. For decoding from a plain file via filename or open FILE*,
  90535. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90536. * provide a simpler interface.
  90537. *
  90538. * This function should be called after FLAC__stream_decoder_new() and
  90539. * FLAC__stream_decoder_set_*() but before any of the
  90540. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90541. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90542. * if initialization succeeded.
  90543. *
  90544. * \note Support for Ogg FLAC in the library is optional. If this
  90545. * library has been built without support for Ogg FLAC, this function
  90546. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90547. *
  90548. * \param decoder An uninitialized decoder instance.
  90549. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90550. * pointer must not be \c NULL.
  90551. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90552. * pointer may be \c NULL if seeking is not
  90553. * supported. If \a seek_callback is not \c NULL then a
  90554. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90555. * Alternatively, a dummy seek callback that just
  90556. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90557. * may also be supplied, all though this is slightly
  90558. * less efficient for the decoder.
  90559. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90560. * pointer may be \c NULL if not supported by the client. If
  90561. * \a seek_callback is not \c NULL then a
  90562. * \a tell_callback must also be supplied.
  90563. * Alternatively, a dummy tell callback that just
  90564. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90565. * may also be supplied, all though this is slightly
  90566. * less efficient for the decoder.
  90567. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90568. * pointer may be \c NULL if not supported by the client. If
  90569. * \a seek_callback is not \c NULL then a
  90570. * \a length_callback must also be supplied.
  90571. * Alternatively, a dummy length callback that just
  90572. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90573. * may also be supplied, all though this is slightly
  90574. * less efficient for the decoder.
  90575. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90576. * pointer may be \c NULL if not supported by the client. If
  90577. * \a seek_callback is not \c NULL then a
  90578. * \a eof_callback must also be supplied.
  90579. * Alternatively, a dummy length callback that just
  90580. * returns \c false
  90581. * may also be supplied, all though this is slightly
  90582. * less efficient for the decoder.
  90583. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90584. * pointer must not be \c NULL.
  90585. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90586. * pointer may be \c NULL if the callback is not
  90587. * desired.
  90588. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90589. * pointer must not be \c NULL.
  90590. * \param client_data This value will be supplied to callbacks in their
  90591. * \a client_data argument.
  90592. * \assert
  90593. * \code decoder != NULL \endcode
  90594. * \retval FLAC__StreamDecoderInitStatus
  90595. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90596. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90597. */
  90598. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90599. FLAC__StreamDecoder *decoder,
  90600. FLAC__StreamDecoderReadCallback read_callback,
  90601. FLAC__StreamDecoderSeekCallback seek_callback,
  90602. FLAC__StreamDecoderTellCallback tell_callback,
  90603. FLAC__StreamDecoderLengthCallback length_callback,
  90604. FLAC__StreamDecoderEofCallback eof_callback,
  90605. FLAC__StreamDecoderWriteCallback write_callback,
  90606. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90607. FLAC__StreamDecoderErrorCallback error_callback,
  90608. void *client_data
  90609. );
  90610. /** Initialize the decoder instance to decode native FLAC files.
  90611. *
  90612. * This flavor of initialization sets up the decoder to decode from a
  90613. * plain native FLAC file. For non-stdio streams, you must use
  90614. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90615. *
  90616. * This function should be called after FLAC__stream_decoder_new() and
  90617. * FLAC__stream_decoder_set_*() but before any of the
  90618. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90619. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90620. * if initialization succeeded.
  90621. *
  90622. * \param decoder An uninitialized decoder instance.
  90623. * \param file An open FLAC file. The file should have been
  90624. * opened with mode \c "rb" and rewound. The file
  90625. * becomes owned by the decoder and should not be
  90626. * manipulated by the client while decoding.
  90627. * Unless \a file is \c stdin, it will be closed
  90628. * when FLAC__stream_decoder_finish() is called.
  90629. * Note however that seeking will not work when
  90630. * decoding from \c stdout since it is not seekable.
  90631. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90632. * pointer must not be \c NULL.
  90633. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90634. * pointer may be \c NULL if the callback is not
  90635. * desired.
  90636. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90637. * pointer must not be \c NULL.
  90638. * \param client_data This value will be supplied to callbacks in their
  90639. * \a client_data argument.
  90640. * \assert
  90641. * \code decoder != NULL \endcode
  90642. * \code file != NULL \endcode
  90643. * \retval FLAC__StreamDecoderInitStatus
  90644. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90645. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90646. */
  90647. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90648. FLAC__StreamDecoder *decoder,
  90649. FILE *file,
  90650. FLAC__StreamDecoderWriteCallback write_callback,
  90651. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90652. FLAC__StreamDecoderErrorCallback error_callback,
  90653. void *client_data
  90654. );
  90655. /** Initialize the decoder instance to decode Ogg FLAC files.
  90656. *
  90657. * This flavor of initialization sets up the decoder to decode from a
  90658. * plain Ogg FLAC file. For non-stdio streams, you must use
  90659. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90660. *
  90661. * This function should be called after FLAC__stream_decoder_new() and
  90662. * FLAC__stream_decoder_set_*() but before any of the
  90663. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90664. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90665. * if initialization succeeded.
  90666. *
  90667. * \note Support for Ogg FLAC in the library is optional. If this
  90668. * library has been built without support for Ogg FLAC, this function
  90669. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90670. *
  90671. * \param decoder An uninitialized decoder instance.
  90672. * \param file An open FLAC file. The file should have been
  90673. * opened with mode \c "rb" and rewound. The file
  90674. * becomes owned by the decoder and should not be
  90675. * manipulated by the client while decoding.
  90676. * Unless \a file is \c stdin, it will be closed
  90677. * when FLAC__stream_decoder_finish() is called.
  90678. * Note however that seeking will not work when
  90679. * decoding from \c stdout since it is not seekable.
  90680. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90681. * pointer must not be \c NULL.
  90682. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90683. * pointer may be \c NULL if the callback is not
  90684. * desired.
  90685. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90686. * pointer must not be \c NULL.
  90687. * \param client_data This value will be supplied to callbacks in their
  90688. * \a client_data argument.
  90689. * \assert
  90690. * \code decoder != NULL \endcode
  90691. * \code file != NULL \endcode
  90692. * \retval FLAC__StreamDecoderInitStatus
  90693. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90694. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90695. */
  90696. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90697. FLAC__StreamDecoder *decoder,
  90698. FILE *file,
  90699. FLAC__StreamDecoderWriteCallback write_callback,
  90700. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90701. FLAC__StreamDecoderErrorCallback error_callback,
  90702. void *client_data
  90703. );
  90704. /** Initialize the decoder instance to decode native FLAC files.
  90705. *
  90706. * This flavor of initialization sets up the decoder to decode from a plain
  90707. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90708. * example, with Unicode filenames on Windows), you must use
  90709. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90710. * and provide callbacks for the I/O.
  90711. *
  90712. * This function should be called after FLAC__stream_decoder_new() and
  90713. * FLAC__stream_decoder_set_*() but before any of the
  90714. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90715. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90716. * if initialization succeeded.
  90717. *
  90718. * \param decoder An uninitialized decoder instance.
  90719. * \param filename The name of the file to decode from. The file will
  90720. * be opened with fopen(). Use \c NULL to decode from
  90721. * \c stdin. Note that \c stdin is not seekable.
  90722. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90723. * pointer must not be \c NULL.
  90724. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90725. * pointer may be \c NULL if the callback is not
  90726. * desired.
  90727. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90728. * pointer must not be \c NULL.
  90729. * \param client_data This value will be supplied to callbacks in their
  90730. * \a client_data argument.
  90731. * \assert
  90732. * \code decoder != NULL \endcode
  90733. * \retval FLAC__StreamDecoderInitStatus
  90734. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90735. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90736. */
  90737. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90738. FLAC__StreamDecoder *decoder,
  90739. const char *filename,
  90740. FLAC__StreamDecoderWriteCallback write_callback,
  90741. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90742. FLAC__StreamDecoderErrorCallback error_callback,
  90743. void *client_data
  90744. );
  90745. /** Initialize the decoder instance to decode Ogg FLAC files.
  90746. *
  90747. * This flavor of initialization sets up the decoder to decode from a plain
  90748. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90749. * example, with Unicode filenames on Windows), you must use
  90750. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90751. * and provide callbacks for the I/O.
  90752. *
  90753. * This function should be called after FLAC__stream_decoder_new() and
  90754. * FLAC__stream_decoder_set_*() but before any of the
  90755. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90756. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90757. * if initialization succeeded.
  90758. *
  90759. * \note Support for Ogg FLAC in the library is optional. If this
  90760. * library has been built without support for Ogg FLAC, this function
  90761. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90762. *
  90763. * \param decoder An uninitialized decoder instance.
  90764. * \param filename The name of the file to decode from. The file will
  90765. * be opened with fopen(). Use \c NULL to decode from
  90766. * \c stdin. Note that \c stdin is not seekable.
  90767. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90768. * pointer must not be \c NULL.
  90769. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90770. * pointer may be \c NULL if the callback is not
  90771. * desired.
  90772. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90773. * pointer must not be \c NULL.
  90774. * \param client_data This value will be supplied to callbacks in their
  90775. * \a client_data argument.
  90776. * \assert
  90777. * \code decoder != NULL \endcode
  90778. * \retval FLAC__StreamDecoderInitStatus
  90779. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90780. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90781. */
  90782. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90783. FLAC__StreamDecoder *decoder,
  90784. const char *filename,
  90785. FLAC__StreamDecoderWriteCallback write_callback,
  90786. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90787. FLAC__StreamDecoderErrorCallback error_callback,
  90788. void *client_data
  90789. );
  90790. /** Finish the decoding process.
  90791. * Flushes the decoding buffer, releases resources, resets the decoder
  90792. * settings to their defaults, and returns the decoder state to
  90793. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90794. *
  90795. * In the event of a prematurely-terminated decode, it is not strictly
  90796. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90797. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90798. * with a FLAC__stream_decoder_finish().
  90799. *
  90800. * \param decoder An uninitialized decoder instance.
  90801. * \assert
  90802. * \code decoder != NULL \endcode
  90803. * \retval FLAC__bool
  90804. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90805. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90806. * signature does not match the one computed by the decoder; else
  90807. * \c true.
  90808. */
  90809. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90810. /** Flush the stream input.
  90811. * The decoder's input buffer will be cleared and the state set to
  90812. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90813. * off MD5 checking.
  90814. *
  90815. * \param decoder A decoder instance.
  90816. * \assert
  90817. * \code decoder != NULL \endcode
  90818. * \retval FLAC__bool
  90819. * \c true if successful, else \c false if a memory allocation
  90820. * error occurs (in which case the state will be set to
  90821. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90822. */
  90823. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90824. /** Reset the decoding process.
  90825. * The decoder's input buffer will be cleared and the state set to
  90826. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90827. * FLAC__stream_decoder_finish() except that the settings are
  90828. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90829. * before decoding again. MD5 checking will be restored to its original
  90830. * setting.
  90831. *
  90832. * If the decoder is seekable, or was initialized with
  90833. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90834. * the decoder will also attempt to seek to the beginning of the file.
  90835. * If this rewind fails, this function will return \c false. It follows
  90836. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90837. * \c stdin.
  90838. *
  90839. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90840. * and is not seekable (i.e. no seek callback was provided or the seek
  90841. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90842. * is the duty of the client to start feeding data from the beginning of
  90843. * the stream on the next FLAC__stream_decoder_process() or
  90844. * FLAC__stream_decoder_process_interleaved() call.
  90845. *
  90846. * \param decoder A decoder instance.
  90847. * \assert
  90848. * \code decoder != NULL \endcode
  90849. * \retval FLAC__bool
  90850. * \c true if successful, else \c false if a memory allocation occurs
  90851. * (in which case the state will be set to
  90852. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90853. * occurs (the state will be unchanged).
  90854. */
  90855. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90856. /** Decode one metadata block or audio frame.
  90857. * This version instructs the decoder to decode a either a single metadata
  90858. * block or a single frame and stop, unless the callbacks return a fatal
  90859. * error or the read callback returns
  90860. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90861. *
  90862. * As the decoder needs more input it will call the read callback.
  90863. * Depending on what was decoded, the metadata or write callback will be
  90864. * called with the decoded metadata block or audio frame.
  90865. *
  90866. * Unless there is a fatal read error or end of stream, this function
  90867. * will return once one whole frame is decoded. In other words, if the
  90868. * stream is not synchronized or points to a corrupt frame header, the
  90869. * decoder will continue to try and resync until it gets to a valid
  90870. * frame, then decode one frame, then return. If the decoder points to
  90871. * a frame whose frame CRC in the frame footer does not match the
  90872. * computed frame CRC, this function will issue a
  90873. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90874. * error callback, and return, having decoded one complete, although
  90875. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90876. * correct length to the write callback.)
  90877. *
  90878. * \param decoder An initialized decoder instance.
  90879. * \assert
  90880. * \code decoder != NULL \endcode
  90881. * \retval FLAC__bool
  90882. * \c false if any fatal read, write, or memory allocation error
  90883. * occurred (meaning decoding must stop), else \c true; for more
  90884. * information about the decoder, check the decoder state with
  90885. * FLAC__stream_decoder_get_state().
  90886. */
  90887. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90888. /** Decode until the end of the metadata.
  90889. * This version instructs the decoder to decode from the current position
  90890. * and continue until all the metadata has been read, or until the
  90891. * callbacks return a fatal error or the read callback returns
  90892. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90893. *
  90894. * As the decoder needs more input it will call the read callback.
  90895. * As each metadata block is decoded, the metadata callback will be called
  90896. * with the decoded metadata.
  90897. *
  90898. * \param decoder An initialized decoder instance.
  90899. * \assert
  90900. * \code decoder != NULL \endcode
  90901. * \retval FLAC__bool
  90902. * \c false if any fatal read, write, or memory allocation error
  90903. * occurred (meaning decoding must stop), else \c true; for more
  90904. * information about the decoder, check the decoder state with
  90905. * FLAC__stream_decoder_get_state().
  90906. */
  90907. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90908. /** Decode until the end of the stream.
  90909. * This version instructs the decoder to decode from the current position
  90910. * and continue until the end of stream (the read callback returns
  90911. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90912. * callbacks return a fatal error.
  90913. *
  90914. * As the decoder needs more input it will call the read callback.
  90915. * As each metadata block and frame is decoded, the metadata or write
  90916. * callback will be called with the decoded metadata or frame.
  90917. *
  90918. * \param decoder An initialized decoder instance.
  90919. * \assert
  90920. * \code decoder != NULL \endcode
  90921. * \retval FLAC__bool
  90922. * \c false if any fatal read, write, or memory allocation error
  90923. * occurred (meaning decoding must stop), else \c true; for more
  90924. * information about the decoder, check the decoder state with
  90925. * FLAC__stream_decoder_get_state().
  90926. */
  90927. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90928. /** Skip one audio frame.
  90929. * This version instructs the decoder to 'skip' a single frame and stop,
  90930. * unless the callbacks return a fatal error or the read callback returns
  90931. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90932. *
  90933. * The decoding flow is the same as what occurs when
  90934. * FLAC__stream_decoder_process_single() is called to process an audio
  90935. * frame, except that this function does not decode the parsed data into
  90936. * PCM or call the write callback. The integrity of the frame is still
  90937. * checked the same way as in the other process functions.
  90938. *
  90939. * This function will return once one whole frame is skipped, in the
  90940. * same way that FLAC__stream_decoder_process_single() will return once
  90941. * one whole frame is decoded.
  90942. *
  90943. * This function can be used in more quickly determining FLAC frame
  90944. * boundaries when decoding of the actual data is not needed, for
  90945. * example when an application is separating a FLAC stream into frames
  90946. * for editing or storing in a container. To do this, the application
  90947. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90948. * to the next frame, then use
  90949. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90950. * boundary.
  90951. *
  90952. * This function should only be called when the stream has advanced
  90953. * past all the metadata, otherwise it will return \c false.
  90954. *
  90955. * \param decoder An initialized decoder instance not in a metadata
  90956. * state.
  90957. * \assert
  90958. * \code decoder != NULL \endcode
  90959. * \retval FLAC__bool
  90960. * \c false if any fatal read, write, or memory allocation error
  90961. * occurred (meaning decoding must stop), or if the decoder
  90962. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90963. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90964. * information about the decoder, check the decoder state with
  90965. * FLAC__stream_decoder_get_state().
  90966. */
  90967. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90968. /** Flush the input and seek to an absolute sample.
  90969. * Decoding will resume at the given sample. Note that because of
  90970. * this, the next write callback may contain a partial block. The
  90971. * client must support seeking the input or this function will fail
  90972. * and return \c false. Furthermore, if the decoder state is
  90973. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90974. * with FLAC__stream_decoder_flush() or reset with
  90975. * FLAC__stream_decoder_reset() before decoding can continue.
  90976. *
  90977. * \param decoder A decoder instance.
  90978. * \param sample The target sample number to seek to.
  90979. * \assert
  90980. * \code decoder != NULL \endcode
  90981. * \retval FLAC__bool
  90982. * \c true if successful, else \c false.
  90983. */
  90984. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90985. /* \} */
  90986. #ifdef __cplusplus
  90987. }
  90988. #endif
  90989. #endif
  90990. /*** End of inlined file: stream_decoder.h ***/
  90991. /*** Start of inlined file: stream_encoder.h ***/
  90992. #ifndef FLAC__STREAM_ENCODER_H
  90993. #define FLAC__STREAM_ENCODER_H
  90994. #include <stdio.h> /* for FILE */
  90995. #ifdef __cplusplus
  90996. extern "C" {
  90997. #endif
  90998. /** \file include/FLAC/stream_encoder.h
  90999. *
  91000. * \brief
  91001. * This module contains the functions which implement the stream
  91002. * encoder.
  91003. *
  91004. * See the detailed documentation in the
  91005. * \link flac_stream_encoder stream encoder \endlink module.
  91006. */
  91007. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  91008. * \ingroup flac
  91009. *
  91010. * \brief
  91011. * This module describes the encoder layers provided by libFLAC.
  91012. *
  91013. * The stream encoder can be used to encode complete streams either to the
  91014. * client via callbacks, or directly to a file, depending on how it is
  91015. * initialized. When encoding via callbacks, the client provides a write
  91016. * callback which will be called whenever FLAC data is ready to be written.
  91017. * If the client also supplies a seek callback, the encoder will also
  91018. * automatically handle the writing back of metadata discovered while
  91019. * encoding, like stream info, seek points offsets, etc. When encoding to
  91020. * a file, the client needs only supply a filename or open \c FILE* and an
  91021. * optional progress callback for periodic notification of progress; the
  91022. * write and seek callbacks are supplied internally. For more info see the
  91023. * \link flac_stream_encoder stream encoder \endlink module.
  91024. */
  91025. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  91026. * \ingroup flac_encoder
  91027. *
  91028. * \brief
  91029. * This module contains the functions which implement the stream
  91030. * encoder.
  91031. *
  91032. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  91033. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  91034. *
  91035. * The basic usage of this encoder is as follows:
  91036. * - The program creates an instance of an encoder using
  91037. * FLAC__stream_encoder_new().
  91038. * - The program overrides the default settings using
  91039. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  91040. * functions should be called:
  91041. * - FLAC__stream_encoder_set_channels()
  91042. * - FLAC__stream_encoder_set_bits_per_sample()
  91043. * - FLAC__stream_encoder_set_sample_rate()
  91044. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  91045. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  91046. * - If the application wants to control the compression level or set its own
  91047. * metadata, then the following should also be called:
  91048. * - FLAC__stream_encoder_set_compression_level()
  91049. * - FLAC__stream_encoder_set_verify()
  91050. * - FLAC__stream_encoder_set_metadata()
  91051. * - The rest of the set functions should only be called if the client needs
  91052. * exact control over how the audio is compressed; thorough understanding
  91053. * of the FLAC format is necessary to achieve good results.
  91054. * - The program initializes the instance to validate the settings and
  91055. * prepare for encoding using
  91056. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  91057. * or FLAC__stream_encoder_init_file() for native FLAC
  91058. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  91059. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  91060. * - The program calls FLAC__stream_encoder_process() or
  91061. * FLAC__stream_encoder_process_interleaved() to encode data, which
  91062. * subsequently calls the callbacks when there is encoder data ready
  91063. * to be written.
  91064. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  91065. * which causes the encoder to encode any data still in its input pipe,
  91066. * update the metadata with the final encoding statistics if output
  91067. * seeking is possible, and finally reset the encoder to the
  91068. * uninitialized state.
  91069. * - The instance may be used again or deleted with
  91070. * FLAC__stream_encoder_delete().
  91071. *
  91072. * In more detail, the stream encoder functions similarly to the
  91073. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  91074. * callbacks and more options. Typically the client will create a new
  91075. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  91076. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  91077. * calling one of the FLAC__stream_encoder_init_*() functions.
  91078. *
  91079. * Unlike the decoders, the stream encoder has many options that can
  91080. * affect the speed and compression ratio. When setting these parameters
  91081. * you should have some basic knowledge of the format (see the
  91082. * <A HREF="../documentation.html#format">user-level documentation</A>
  91083. * or the <A HREF="../format.html">formal description</A>). The
  91084. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  91085. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  91086. * functions will do this, so make sure to pay attention to the state
  91087. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  91088. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  91089. * before FLAC__stream_encoder_init_*() will take on the defaults from
  91090. * the constructor.
  91091. *
  91092. * There are three initialization functions for native FLAC, one for
  91093. * setting up the encoder to encode FLAC data to the client via
  91094. * callbacks, and two for encoding directly to a file.
  91095. *
  91096. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  91097. * You must also supply a write callback which will be called anytime
  91098. * there is raw encoded data to write. If the client can seek the output
  91099. * it is best to also supply seek and tell callbacks, as this allows the
  91100. * encoder to go back after encoding is finished to write back
  91101. * information that was collected while encoding, like seek point offsets,
  91102. * frame sizes, etc.
  91103. *
  91104. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  91105. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  91106. * filename or open \c FILE*; the encoder will handle all the callbacks
  91107. * internally. You may also supply a progress callback for periodic
  91108. * notification of the encoding progress.
  91109. *
  91110. * There are three similarly-named init functions for encoding to Ogg
  91111. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  91112. * library has been built with Ogg support.
  91113. *
  91114. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  91115. * call the write callback several times, once with the \c fLaC signature,
  91116. * and once for each encoded metadata block. Note that for Ogg FLAC
  91117. * encoding you will usually get at least twice the number of callbacks than
  91118. * with native FLAC, one for the Ogg page header and one for the page body.
  91119. *
  91120. * After initializing the instance, the client may feed audio data to the
  91121. * encoder in one of two ways:
  91122. *
  91123. * - Channel separate, through FLAC__stream_encoder_process() - The client
  91124. * will pass an array of pointers to buffers, one for each channel, to
  91125. * the encoder, each of the same length. The samples need not be
  91126. * block-aligned, but each channel should have the same number of samples.
  91127. * - Channel interleaved, through
  91128. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  91129. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  91130. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91131. * Again, the samples need not be block-aligned but they must be
  91132. * sample-aligned, i.e. the first value should be channel0_sample0 and
  91133. * the last value channelN_sampleM.
  91134. *
  91135. * Note that for either process call, each sample in the buffers should be a
  91136. * signed integer, right-justified to the resolution set by
  91137. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  91138. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  91139. *
  91140. * When the client is finished encoding data, it calls
  91141. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  91142. * data still in its input pipe, and call the metadata callback with the
  91143. * final encoding statistics. Then the instance may be deleted with
  91144. * FLAC__stream_encoder_delete() or initialized again to encode another
  91145. * stream.
  91146. *
  91147. * For programs that write their own metadata, but that do not know the
  91148. * actual metadata until after encoding, it is advantageous to instruct
  91149. * the encoder to write a PADDING block of the correct size, so that
  91150. * instead of rewriting the whole stream after encoding, the program can
  91151. * just overwrite the PADDING block. If only the maximum size of the
  91152. * metadata is known, the program can write a slightly larger padding
  91153. * block, then split it after encoding.
  91154. *
  91155. * Make sure you understand how lengths are calculated. All FLAC metadata
  91156. * blocks have a 4 byte header which contains the type and length. This
  91157. * length does not include the 4 bytes of the header. See the format page
  91158. * for the specification of metadata blocks and their lengths.
  91159. *
  91160. * \note
  91161. * If you are writing the FLAC data to a file via callbacks, make sure it
  91162. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91163. * after the first encoding pass, the encoder will try to seek back to the
  91164. * beginning of the stream, to the STREAMINFO block, to write some data
  91165. * there. (If using FLAC__stream_encoder_init*_file() or
  91166. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91167. *
  91168. * \note
  91169. * The "set" functions may only be called when the encoder is in the
  91170. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91171. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91172. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91173. * return \c true, otherwise \c false.
  91174. *
  91175. * \note
  91176. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91177. * defaults.
  91178. *
  91179. * \{
  91180. */
  91181. /** State values for a FLAC__StreamEncoder.
  91182. *
  91183. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91184. *
  91185. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91186. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91187. * must be deleted with FLAC__stream_encoder_delete().
  91188. */
  91189. typedef enum {
  91190. FLAC__STREAM_ENCODER_OK = 0,
  91191. /**< The encoder is in the normal OK state and samples can be processed. */
  91192. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91193. /**< The encoder is in the uninitialized state; one of the
  91194. * FLAC__stream_encoder_init_*() functions must be called before samples
  91195. * can be processed.
  91196. */
  91197. FLAC__STREAM_ENCODER_OGG_ERROR,
  91198. /**< An error occurred in the underlying Ogg layer. */
  91199. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91200. /**< An error occurred in the underlying verify stream decoder;
  91201. * check FLAC__stream_encoder_get_verify_decoder_state().
  91202. */
  91203. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91204. /**< The verify decoder detected a mismatch between the original
  91205. * audio signal and the decoded audio signal.
  91206. */
  91207. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91208. /**< One of the callbacks returned a fatal error. */
  91209. FLAC__STREAM_ENCODER_IO_ERROR,
  91210. /**< An I/O error occurred while opening/reading/writing a file.
  91211. * Check \c errno.
  91212. */
  91213. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91214. /**< An error occurred while writing the stream; usually, the
  91215. * write_callback returned an error.
  91216. */
  91217. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91218. /**< Memory allocation failed. */
  91219. } FLAC__StreamEncoderState;
  91220. /** Maps a FLAC__StreamEncoderState to a C string.
  91221. *
  91222. * Using a FLAC__StreamEncoderState as the index to this array
  91223. * will give the string equivalent. The contents should not be modified.
  91224. */
  91225. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91226. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91227. */
  91228. typedef enum {
  91229. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91230. /**< Initialization was successful. */
  91231. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91232. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91233. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91234. /**< The library was not compiled with support for the given container
  91235. * format.
  91236. */
  91237. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91238. /**< A required callback was not supplied. */
  91239. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91240. /**< The encoder has an invalid setting for number of channels. */
  91241. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91242. /**< The encoder has an invalid setting for bits-per-sample.
  91243. * FLAC supports 4-32 bps but the reference encoder currently supports
  91244. * only up to 24 bps.
  91245. */
  91246. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91247. /**< The encoder has an invalid setting for the input sample rate. */
  91248. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91249. /**< The encoder has an invalid setting for the block size. */
  91250. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91251. /**< The encoder has an invalid setting for the maximum LPC order. */
  91252. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91253. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91254. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91255. /**< The specified block size is less than the maximum LPC order. */
  91256. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91257. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91258. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91259. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91260. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91261. * - One of the metadata blocks contains an undefined type
  91262. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91263. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91264. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91265. */
  91266. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91267. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91268. * already initialized, usually because
  91269. * FLAC__stream_encoder_finish() was not called.
  91270. */
  91271. } FLAC__StreamEncoderInitStatus;
  91272. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91273. *
  91274. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91275. * will give the string equivalent. The contents should not be modified.
  91276. */
  91277. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91278. /** Return values for the FLAC__StreamEncoder read callback.
  91279. */
  91280. typedef enum {
  91281. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91282. /**< The read was OK and decoding can continue. */
  91283. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91284. /**< The read was attempted at the end of the stream. */
  91285. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91286. /**< An unrecoverable error occurred. */
  91287. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91288. /**< Client does not support reading back from the output. */
  91289. } FLAC__StreamEncoderReadStatus;
  91290. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91291. *
  91292. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91293. * will give the string equivalent. The contents should not be modified.
  91294. */
  91295. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91296. /** Return values for the FLAC__StreamEncoder write callback.
  91297. */
  91298. typedef enum {
  91299. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91300. /**< The write was OK and encoding can continue. */
  91301. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91302. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91303. } FLAC__StreamEncoderWriteStatus;
  91304. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91305. *
  91306. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91307. * will give the string equivalent. The contents should not be modified.
  91308. */
  91309. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91310. /** Return values for the FLAC__StreamEncoder seek callback.
  91311. */
  91312. typedef enum {
  91313. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91314. /**< The seek was OK and encoding can continue. */
  91315. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91316. /**< An unrecoverable error occurred. */
  91317. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91318. /**< Client does not support seeking. */
  91319. } FLAC__StreamEncoderSeekStatus;
  91320. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91321. *
  91322. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91323. * will give the string equivalent. The contents should not be modified.
  91324. */
  91325. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91326. /** Return values for the FLAC__StreamEncoder tell callback.
  91327. */
  91328. typedef enum {
  91329. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91330. /**< The tell was OK and encoding can continue. */
  91331. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91332. /**< An unrecoverable error occurred. */
  91333. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91334. /**< Client does not support seeking. */
  91335. } FLAC__StreamEncoderTellStatus;
  91336. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91337. *
  91338. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91339. * will give the string equivalent. The contents should not be modified.
  91340. */
  91341. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91342. /***********************************************************************
  91343. *
  91344. * class FLAC__StreamEncoder
  91345. *
  91346. ***********************************************************************/
  91347. struct FLAC__StreamEncoderProtected;
  91348. struct FLAC__StreamEncoderPrivate;
  91349. /** The opaque structure definition for the stream encoder type.
  91350. * See the \link flac_stream_encoder stream encoder module \endlink
  91351. * for a detailed description.
  91352. */
  91353. typedef struct {
  91354. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91355. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91356. } FLAC__StreamEncoder;
  91357. /** Signature for the read callback.
  91358. *
  91359. * A function pointer matching this signature must be passed to
  91360. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91361. * The supplied function will be called when the encoder needs to read back
  91362. * encoded data. This happens during the metadata callback, when the encoder
  91363. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91364. * while encoding. The address of the buffer to be filled is supplied, along
  91365. * with the number of bytes the buffer can hold. The callback may choose to
  91366. * supply less data and modify the byte count but must be careful not to
  91367. * overflow the buffer. The callback then returns a status code chosen from
  91368. * FLAC__StreamEncoderReadStatus.
  91369. *
  91370. * Here is an example of a read callback for stdio streams:
  91371. * \code
  91372. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91373. * {
  91374. * FILE *file = ((MyClientData*)client_data)->file;
  91375. * if(*bytes > 0) {
  91376. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91377. * if(ferror(file))
  91378. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91379. * else if(*bytes == 0)
  91380. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91381. * else
  91382. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91383. * }
  91384. * else
  91385. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91386. * }
  91387. * \endcode
  91388. *
  91389. * \note In general, FLAC__StreamEncoder functions which change the
  91390. * state should not be called on the \a encoder while in the callback.
  91391. *
  91392. * \param encoder The encoder instance calling the callback.
  91393. * \param buffer A pointer to a location for the callee to store
  91394. * data to be encoded.
  91395. * \param bytes A pointer to the size of the buffer. On entry
  91396. * to the callback, it contains the maximum number
  91397. * of bytes that may be stored in \a buffer. The
  91398. * callee must set it to the actual number of bytes
  91399. * stored (0 in case of error or end-of-stream) before
  91400. * returning.
  91401. * \param client_data The callee's client data set through
  91402. * FLAC__stream_encoder_set_client_data().
  91403. * \retval FLAC__StreamEncoderReadStatus
  91404. * The callee's return status.
  91405. */
  91406. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91407. /** Signature for the write callback.
  91408. *
  91409. * A function pointer matching this signature must be passed to
  91410. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91411. * by the encoder anytime there is raw encoded data ready to write. It may
  91412. * include metadata mixed with encoded audio frames and the data is not
  91413. * guaranteed to be aligned on frame or metadata block boundaries.
  91414. *
  91415. * The only duty of the callback is to write out the \a bytes worth of data
  91416. * in \a buffer to the current position in the output stream. The arguments
  91417. * \a samples and \a current_frame are purely informational. If \a samples
  91418. * is greater than \c 0, then \a current_frame will hold the current frame
  91419. * number that is being written; otherwise it indicates that the write
  91420. * callback is being called to write metadata.
  91421. *
  91422. * \note
  91423. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91424. * write callback will be called twice when writing each audio
  91425. * frame; once for the page header, and once for the page body.
  91426. * When writing the page header, the \a samples argument to the
  91427. * write callback will be \c 0.
  91428. *
  91429. * \note In general, FLAC__StreamEncoder functions which change the
  91430. * state should not be called on the \a encoder while in the callback.
  91431. *
  91432. * \param encoder The encoder instance calling the callback.
  91433. * \param buffer An array of encoded data of length \a bytes.
  91434. * \param bytes The byte length of \a buffer.
  91435. * \param samples The number of samples encoded by \a buffer.
  91436. * \c 0 has a special meaning; see above.
  91437. * \param current_frame The number of the current frame being encoded.
  91438. * \param client_data The callee's client data set through
  91439. * FLAC__stream_encoder_init_*().
  91440. * \retval FLAC__StreamEncoderWriteStatus
  91441. * The callee's return status.
  91442. */
  91443. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91444. /** Signature for the seek callback.
  91445. *
  91446. * A function pointer matching this signature may be passed to
  91447. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91448. * when the encoder needs to seek the output stream. The encoder will pass
  91449. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91450. *
  91451. * Here is an example of a seek callback for stdio streams:
  91452. * \code
  91453. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91454. * {
  91455. * FILE *file = ((MyClientData*)client_data)->file;
  91456. * if(file == stdin)
  91457. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91458. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91459. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91460. * else
  91461. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91462. * }
  91463. * \endcode
  91464. *
  91465. * \note In general, FLAC__StreamEncoder functions which change the
  91466. * state should not be called on the \a encoder while in the callback.
  91467. *
  91468. * \param encoder The encoder instance calling the callback.
  91469. * \param absolute_byte_offset The offset from the beginning of the stream
  91470. * to seek to.
  91471. * \param client_data The callee's client data set through
  91472. * FLAC__stream_encoder_init_*().
  91473. * \retval FLAC__StreamEncoderSeekStatus
  91474. * The callee's return status.
  91475. */
  91476. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91477. /** Signature for the tell callback.
  91478. *
  91479. * A function pointer matching this signature may be passed to
  91480. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91481. * when the encoder needs to know the current position of the output stream.
  91482. *
  91483. * \warning
  91484. * The callback must return the true current byte offset of the output to
  91485. * which the encoder is writing. If you are buffering the output, make
  91486. * sure and take this into account. If you are writing directly to a
  91487. * FILE* from your write callback, ftell() is sufficient. If you are
  91488. * writing directly to a file descriptor from your write callback, you
  91489. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91490. * these points to rewrite metadata after encoding.
  91491. *
  91492. * Here is an example of a tell callback for stdio streams:
  91493. * \code
  91494. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91495. * {
  91496. * FILE *file = ((MyClientData*)client_data)->file;
  91497. * off_t pos;
  91498. * if(file == stdin)
  91499. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91500. * else if((pos = ftello(file)) < 0)
  91501. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91502. * else {
  91503. * *absolute_byte_offset = (FLAC__uint64)pos;
  91504. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91505. * }
  91506. * }
  91507. * \endcode
  91508. *
  91509. * \note In general, FLAC__StreamEncoder functions which change the
  91510. * state should not be called on the \a encoder while in the callback.
  91511. *
  91512. * \param encoder The encoder instance calling the callback.
  91513. * \param absolute_byte_offset The address at which to store the current
  91514. * position of the output.
  91515. * \param client_data The callee's client data set through
  91516. * FLAC__stream_encoder_init_*().
  91517. * \retval FLAC__StreamEncoderTellStatus
  91518. * The callee's return status.
  91519. */
  91520. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91521. /** Signature for the metadata callback.
  91522. *
  91523. * A function pointer matching this signature may be passed to
  91524. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91525. * once at the end of encoding with the populated STREAMINFO structure. This
  91526. * is so the client can seek back to the beginning of the file and write the
  91527. * STREAMINFO block with the correct statistics after encoding (like
  91528. * minimum/maximum frame size and total samples).
  91529. *
  91530. * \note In general, FLAC__StreamEncoder functions which change the
  91531. * state should not be called on the \a encoder while in the callback.
  91532. *
  91533. * \param encoder The encoder instance calling the callback.
  91534. * \param metadata The final populated STREAMINFO block.
  91535. * \param client_data The callee's client data set through
  91536. * FLAC__stream_encoder_init_*().
  91537. */
  91538. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91539. /** Signature for the progress callback.
  91540. *
  91541. * A function pointer matching this signature may be passed to
  91542. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91543. * The supplied function will be called when the encoder has finished
  91544. * writing a frame. The \c total_frames_estimate argument to the
  91545. * callback will be based on the value from
  91546. * FLAC__stream_encoder_set_total_samples_estimate().
  91547. *
  91548. * \note In general, FLAC__StreamEncoder functions which change the
  91549. * state should not be called on the \a encoder while in the callback.
  91550. *
  91551. * \param encoder The encoder instance calling the callback.
  91552. * \param bytes_written Bytes written so far.
  91553. * \param samples_written Samples written so far.
  91554. * \param frames_written Frames written so far.
  91555. * \param total_frames_estimate The estimate of the total number of
  91556. * frames to be written.
  91557. * \param client_data The callee's client data set through
  91558. * FLAC__stream_encoder_init_*().
  91559. */
  91560. 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);
  91561. /***********************************************************************
  91562. *
  91563. * Class constructor/destructor
  91564. *
  91565. ***********************************************************************/
  91566. /** Create a new stream encoder instance. The instance is created with
  91567. * default settings; see the individual FLAC__stream_encoder_set_*()
  91568. * functions for each setting's default.
  91569. *
  91570. * \retval FLAC__StreamEncoder*
  91571. * \c NULL if there was an error allocating memory, else the new instance.
  91572. */
  91573. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91574. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91575. *
  91576. * \param encoder A pointer to an existing encoder.
  91577. * \assert
  91578. * \code encoder != NULL \endcode
  91579. */
  91580. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91581. /***********************************************************************
  91582. *
  91583. * Public class method prototypes
  91584. *
  91585. ***********************************************************************/
  91586. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91587. *
  91588. * \note
  91589. * This does not need to be set for native FLAC encoding.
  91590. *
  91591. * \note
  91592. * It is recommended to set a serial number explicitly as the default of '0'
  91593. * may collide with other streams.
  91594. *
  91595. * \default \c 0
  91596. * \param encoder An encoder instance to set.
  91597. * \param serial_number See above.
  91598. * \assert
  91599. * \code encoder != NULL \endcode
  91600. * \retval FLAC__bool
  91601. * \c false if the encoder is already initialized, else \c true.
  91602. */
  91603. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91604. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91605. * encoded output by feeding it through an internal decoder and comparing
  91606. * the original signal against the decoded signal. If a mismatch occurs,
  91607. * the process call will return \c false. Note that this will slow the
  91608. * encoding process by the extra time required for decoding and comparison.
  91609. *
  91610. * \default \c false
  91611. * \param encoder An encoder instance to set.
  91612. * \param value Flag value (see above).
  91613. * \assert
  91614. * \code encoder != NULL \endcode
  91615. * \retval FLAC__bool
  91616. * \c false if the encoder is already initialized, else \c true.
  91617. */
  91618. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91619. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91620. * the encoder will comply with the Subset and will check the
  91621. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91622. * comply. If \c false, the settings may take advantage of the full
  91623. * range that the format allows.
  91624. *
  91625. * Make sure you know what it entails before setting this to \c false.
  91626. *
  91627. * \default \c true
  91628. * \param encoder An encoder instance to set.
  91629. * \param value Flag value (see above).
  91630. * \assert
  91631. * \code encoder != NULL \endcode
  91632. * \retval FLAC__bool
  91633. * \c false if the encoder is already initialized, else \c true.
  91634. */
  91635. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91636. /** Set the number of channels to be encoded.
  91637. *
  91638. * \default \c 2
  91639. * \param encoder An encoder instance to set.
  91640. * \param value See above.
  91641. * \assert
  91642. * \code encoder != NULL \endcode
  91643. * \retval FLAC__bool
  91644. * \c false if the encoder is already initialized, else \c true.
  91645. */
  91646. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91647. /** Set the sample resolution of the input to be encoded.
  91648. *
  91649. * \warning
  91650. * Do not feed the encoder data that is wider than the value you
  91651. * set here or you will generate an invalid stream.
  91652. *
  91653. * \default \c 16
  91654. * \param encoder An encoder instance to set.
  91655. * \param value See above.
  91656. * \assert
  91657. * \code encoder != NULL \endcode
  91658. * \retval FLAC__bool
  91659. * \c false if the encoder is already initialized, else \c true.
  91660. */
  91661. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91662. /** Set the sample rate (in Hz) of the input to be encoded.
  91663. *
  91664. * \default \c 44100
  91665. * \param encoder An encoder instance to set.
  91666. * \param value See above.
  91667. * \assert
  91668. * \code encoder != NULL \endcode
  91669. * \retval FLAC__bool
  91670. * \c false if the encoder is already initialized, else \c true.
  91671. */
  91672. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91673. /** Set the compression level
  91674. *
  91675. * The compression level is roughly proportional to the amount of effort
  91676. * the encoder expends to compress the file. A higher level usually
  91677. * means more computation but higher compression. The default level is
  91678. * suitable for most applications.
  91679. *
  91680. * Currently the levels range from \c 0 (fastest, least compression) to
  91681. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91682. * treated as \c 8.
  91683. *
  91684. * This function automatically calls the following other \c _set_
  91685. * functions with appropriate values, so the client does not need to
  91686. * unless it specifically wants to override them:
  91687. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91688. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91689. * - FLAC__stream_encoder_set_apodization()
  91690. * - FLAC__stream_encoder_set_max_lpc_order()
  91691. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91692. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91693. * - FLAC__stream_encoder_set_do_escape_coding()
  91694. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91695. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91696. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91697. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91698. *
  91699. * The actual values set for each level are:
  91700. * <table>
  91701. * <tr>
  91702. * <td><b>level</b><td>
  91703. * <td>do mid-side stereo<td>
  91704. * <td>loose mid-side stereo<td>
  91705. * <td>apodization<td>
  91706. * <td>max lpc order<td>
  91707. * <td>qlp coeff precision<td>
  91708. * <td>qlp coeff prec search<td>
  91709. * <td>escape coding<td>
  91710. * <td>exhaustive model search<td>
  91711. * <td>min residual partition order<td>
  91712. * <td>max residual partition order<td>
  91713. * <td>rice parameter search dist<td>
  91714. * </tr>
  91715. * <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>
  91716. * <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>
  91717. * <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>
  91718. * <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>
  91719. * <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>
  91720. * <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>
  91721. * <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>
  91722. * <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>
  91723. * <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>
  91724. * </table>
  91725. *
  91726. * \default \c 5
  91727. * \param encoder An encoder instance to set.
  91728. * \param value See above.
  91729. * \assert
  91730. * \code encoder != NULL \endcode
  91731. * \retval FLAC__bool
  91732. * \c false if the encoder is already initialized, else \c true.
  91733. */
  91734. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91735. /** Set the blocksize to use while encoding.
  91736. *
  91737. * The number of samples to use per frame. Use \c 0 to let the encoder
  91738. * estimate a blocksize; this is usually best.
  91739. *
  91740. * \default \c 0
  91741. * \param encoder An encoder instance to set.
  91742. * \param value See above.
  91743. * \assert
  91744. * \code encoder != NULL \endcode
  91745. * \retval FLAC__bool
  91746. * \c false if the encoder is already initialized, else \c true.
  91747. */
  91748. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91749. /** Set to \c true to enable mid-side encoding on stereo input. The
  91750. * number of channels must be 2 for this to have any effect. Set to
  91751. * \c false to use only independent channel coding.
  91752. *
  91753. * \default \c false
  91754. * \param encoder An encoder instance to set.
  91755. * \param value Flag value (see above).
  91756. * \assert
  91757. * \code encoder != NULL \endcode
  91758. * \retval FLAC__bool
  91759. * \c false if the encoder is already initialized, else \c true.
  91760. */
  91761. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91762. /** Set to \c true to enable adaptive switching between mid-side and
  91763. * left-right encoding on stereo input. Set to \c false to use
  91764. * exhaustive searching. Setting this to \c true requires
  91765. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91766. * \c true in order to have any effect.
  91767. *
  91768. * \default \c false
  91769. * \param encoder An encoder instance to set.
  91770. * \param value Flag value (see above).
  91771. * \assert
  91772. * \code encoder != NULL \endcode
  91773. * \retval FLAC__bool
  91774. * \c false if the encoder is already initialized, else \c true.
  91775. */
  91776. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91777. /** Sets the apodization function(s) the encoder will use when windowing
  91778. * audio data for LPC analysis.
  91779. *
  91780. * The \a specification is a plain ASCII string which specifies exactly
  91781. * which functions to use. There may be more than one (up to 32),
  91782. * separated by \c ';' characters. Some functions take one or more
  91783. * comma-separated arguments in parentheses.
  91784. *
  91785. * The available functions are \c bartlett, \c bartlett_hann,
  91786. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91787. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91788. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91789. *
  91790. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91791. * (0<STDDEV<=0.5).
  91792. *
  91793. * For \c tukey(P), P specifies the fraction of the window that is
  91794. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91795. * corresponds to \c hann.
  91796. *
  91797. * Example specifications are \c "blackman" or
  91798. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91799. *
  91800. * Any function that is specified erroneously is silently dropped. Up
  91801. * to 32 functions are kept, the rest are dropped. If the specification
  91802. * is empty the encoder defaults to \c "tukey(0.5)".
  91803. *
  91804. * When more than one function is specified, then for every subframe the
  91805. * encoder will try each of them separately and choose the window that
  91806. * results in the smallest compressed subframe.
  91807. *
  91808. * Note that each function specified causes the encoder to occupy a
  91809. * floating point array in which to store the window.
  91810. *
  91811. * \default \c "tukey(0.5)"
  91812. * \param encoder An encoder instance to set.
  91813. * \param specification See above.
  91814. * \assert
  91815. * \code encoder != NULL \endcode
  91816. * \code specification != NULL \endcode
  91817. * \retval FLAC__bool
  91818. * \c false if the encoder is already initialized, else \c true.
  91819. */
  91820. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91821. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91822. *
  91823. * \default \c 0
  91824. * \param encoder An encoder instance to set.
  91825. * \param value See above.
  91826. * \assert
  91827. * \code encoder != NULL \endcode
  91828. * \retval FLAC__bool
  91829. * \c false if the encoder is already initialized, else \c true.
  91830. */
  91831. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91832. /** Set the precision, in bits, of the quantized linear predictor
  91833. * coefficients, or \c 0 to let the encoder select it based on the
  91834. * blocksize.
  91835. *
  91836. * \note
  91837. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91838. * be less than 32.
  91839. *
  91840. * \default \c 0
  91841. * \param encoder An encoder instance to set.
  91842. * \param value See above.
  91843. * \assert
  91844. * \code encoder != NULL \endcode
  91845. * \retval FLAC__bool
  91846. * \c false if the encoder is already initialized, else \c true.
  91847. */
  91848. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91849. /** Set to \c false to use only the specified quantized linear predictor
  91850. * coefficient precision, or \c true to search neighboring precision
  91851. * values and use the best one.
  91852. *
  91853. * \default \c false
  91854. * \param encoder An encoder instance to set.
  91855. * \param value See above.
  91856. * \assert
  91857. * \code encoder != NULL \endcode
  91858. * \retval FLAC__bool
  91859. * \c false if the encoder is already initialized, else \c true.
  91860. */
  91861. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91862. /** Deprecated. Setting this value has no effect.
  91863. *
  91864. * \default \c false
  91865. * \param encoder An encoder instance to set.
  91866. * \param value See above.
  91867. * \assert
  91868. * \code encoder != NULL \endcode
  91869. * \retval FLAC__bool
  91870. * \c false if the encoder is already initialized, else \c true.
  91871. */
  91872. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91873. /** Set to \c false to let the encoder estimate the best model order
  91874. * based on the residual signal energy, or \c true to force the
  91875. * encoder to evaluate all order models and select the best.
  91876. *
  91877. * \default \c false
  91878. * \param encoder An encoder instance to set.
  91879. * \param value See above.
  91880. * \assert
  91881. * \code encoder != NULL \endcode
  91882. * \retval FLAC__bool
  91883. * \c false if the encoder is already initialized, else \c true.
  91884. */
  91885. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91886. /** Set the minimum partition order to search when coding the residual.
  91887. * This is used in tandem with
  91888. * FLAC__stream_encoder_set_max_residual_partition_order().
  91889. *
  91890. * The partition order determines the context size in the residual.
  91891. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91892. *
  91893. * Set both min and max values to \c 0 to force a single context,
  91894. * whose Rice parameter is based on the residual signal variance.
  91895. * Otherwise, set a min and max order, and the encoder will search
  91896. * all orders, using the mean of each context for its Rice parameter,
  91897. * and use the best.
  91898. *
  91899. * \default \c 0
  91900. * \param encoder An encoder instance to set.
  91901. * \param value See above.
  91902. * \assert
  91903. * \code encoder != NULL \endcode
  91904. * \retval FLAC__bool
  91905. * \c false if the encoder is already initialized, else \c true.
  91906. */
  91907. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91908. /** Set the maximum partition order to search when coding the residual.
  91909. * This is used in tandem with
  91910. * FLAC__stream_encoder_set_min_residual_partition_order().
  91911. *
  91912. * The partition order determines the context size in the residual.
  91913. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91914. *
  91915. * Set both min and max values to \c 0 to force a single context,
  91916. * whose Rice parameter is based on the residual signal variance.
  91917. * Otherwise, set a min and max order, and the encoder will search
  91918. * all orders, using the mean of each context for its Rice parameter,
  91919. * and use the best.
  91920. *
  91921. * \default \c 0
  91922. * \param encoder An encoder instance to set.
  91923. * \param value See above.
  91924. * \assert
  91925. * \code encoder != NULL \endcode
  91926. * \retval FLAC__bool
  91927. * \c false if the encoder is already initialized, else \c true.
  91928. */
  91929. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91930. /** Deprecated. Setting this value has no effect.
  91931. *
  91932. * \default \c 0
  91933. * \param encoder An encoder instance to set.
  91934. * \param value See above.
  91935. * \assert
  91936. * \code encoder != NULL \endcode
  91937. * \retval FLAC__bool
  91938. * \c false if the encoder is already initialized, else \c true.
  91939. */
  91940. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91941. /** Set an estimate of the total samples that will be encoded.
  91942. * This is merely an estimate and may be set to \c 0 if unknown.
  91943. * This value will be written to the STREAMINFO block before encoding,
  91944. * and can remove the need for the caller to rewrite the value later
  91945. * if the value is known before encoding.
  91946. *
  91947. * \default \c 0
  91948. * \param encoder An encoder instance to set.
  91949. * \param value See above.
  91950. * \assert
  91951. * \code encoder != NULL \endcode
  91952. * \retval FLAC__bool
  91953. * \c false if the encoder is already initialized, else \c true.
  91954. */
  91955. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91956. /** Set the metadata blocks to be emitted to the stream before encoding.
  91957. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91958. * array of pointers to metadata blocks. The array is non-const since
  91959. * the encoder may need to change the \a is_last flag inside them, and
  91960. * in some cases update seek point offsets. Otherwise, the encoder will
  91961. * not modify or free the blocks. It is up to the caller to free the
  91962. * metadata blocks after encoding finishes.
  91963. *
  91964. * \note
  91965. * The encoder stores only copies of the pointers in the \a metadata array;
  91966. * the metadata blocks themselves must survive at least until after
  91967. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91968. *
  91969. * \note
  91970. * The STREAMINFO block is always written and no STREAMINFO block may
  91971. * occur in the supplied array.
  91972. *
  91973. * \note
  91974. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91975. * in the \a metadata array, but the client has specified that it does not
  91976. * support seeking, then the SEEKTABLE will be written verbatim. However
  91977. * by itself this is not very useful as the client will not know the stream
  91978. * offsets for the seekpoints ahead of time. In order to get a proper
  91979. * seektable the client must support seeking. See next note.
  91980. *
  91981. * \note
  91982. * SEEKTABLE blocks are handled specially. Since you will not know
  91983. * the values for the seek point stream offsets, you should pass in
  91984. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91985. * required sample numbers (or placeholder points), with \c 0 for the
  91986. * \a frame_samples and \a stream_offset fields for each point. If the
  91987. * client has specified that it supports seeking by providing a seek
  91988. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91989. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91990. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91991. * then while it is encoding the encoder will fill the stream offsets in
  91992. * for you and when encoding is finished, it will seek back and write the
  91993. * real values into the SEEKTABLE block in the stream. There are helper
  91994. * routines for manipulating seektable template blocks; see metadata.h:
  91995. * FLAC__metadata_object_seektable_template_*(). If the client does
  91996. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91997. * will slow down or remove the ability to seek in the FLAC stream.
  91998. *
  91999. * \note
  92000. * The encoder instance \b will modify the first \c SEEKTABLE block
  92001. * as it transforms the template to a valid seektable while encoding,
  92002. * but it is still up to the caller to free all metadata blocks after
  92003. * encoding.
  92004. *
  92005. * \note
  92006. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  92007. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  92008. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  92009. * will simply write it's own into the stream. If no VORBIS_COMMENT
  92010. * block is present in the \a metadata array, libFLAC will write an
  92011. * empty one, containing only the vendor string.
  92012. *
  92013. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  92014. * the second metadata block of the stream. The encoder already supplies
  92015. * the STREAMINFO block automatically. If \a metadata does not contain a
  92016. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  92017. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  92018. * first, the init function will reorder \a metadata by moving the
  92019. * VORBIS_COMMENT block to the front; the relative ordering of the other
  92020. * blocks will remain as they were.
  92021. *
  92022. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  92023. * stream to \c 65535. If \a num_blocks exceeds this the function will
  92024. * return \c false.
  92025. *
  92026. * \default \c NULL, 0
  92027. * \param encoder An encoder instance to set.
  92028. * \param metadata See above.
  92029. * \param num_blocks See above.
  92030. * \assert
  92031. * \code encoder != NULL \endcode
  92032. * \retval FLAC__bool
  92033. * \c false if the encoder is already initialized, else \c true.
  92034. * \c false if the encoder is already initialized, or if
  92035. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  92036. */
  92037. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  92038. /** Get the current encoder state.
  92039. *
  92040. * \param encoder An encoder instance to query.
  92041. * \assert
  92042. * \code encoder != NULL \endcode
  92043. * \retval FLAC__StreamEncoderState
  92044. * The current encoder state.
  92045. */
  92046. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  92047. /** Get the state of the verify stream decoder.
  92048. * Useful when the stream encoder state is
  92049. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  92050. *
  92051. * \param encoder An encoder instance to query.
  92052. * \assert
  92053. * \code encoder != NULL \endcode
  92054. * \retval FLAC__StreamDecoderState
  92055. * The verify stream decoder state.
  92056. */
  92057. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  92058. /** Get the current encoder state as a C string.
  92059. * This version automatically resolves
  92060. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  92061. * verify decoder's state.
  92062. *
  92063. * \param encoder A encoder instance to query.
  92064. * \assert
  92065. * \code encoder != NULL \endcode
  92066. * \retval const char *
  92067. * The encoder state as a C string. Do not modify the contents.
  92068. */
  92069. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  92070. /** Get relevant values about the nature of a verify decoder error.
  92071. * Useful when the stream encoder state is
  92072. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  92073. * be addresses in which the stats will be returned, or NULL if value
  92074. * is not desired.
  92075. *
  92076. * \param encoder An encoder instance to query.
  92077. * \param absolute_sample The absolute sample number of the mismatch.
  92078. * \param frame_number The number of the frame in which the mismatch occurred.
  92079. * \param channel The channel in which the mismatch occurred.
  92080. * \param sample The number of the sample (relative to the frame) in
  92081. * which the mismatch occurred.
  92082. * \param expected The expected value for the sample in question.
  92083. * \param got The actual value returned by the decoder.
  92084. * \assert
  92085. * \code encoder != NULL \endcode
  92086. */
  92087. 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);
  92088. /** Get the "verify" flag.
  92089. *
  92090. * \param encoder An encoder instance to query.
  92091. * \assert
  92092. * \code encoder != NULL \endcode
  92093. * \retval FLAC__bool
  92094. * See FLAC__stream_encoder_set_verify().
  92095. */
  92096. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  92097. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  92098. *
  92099. * \param encoder An encoder instance to query.
  92100. * \assert
  92101. * \code encoder != NULL \endcode
  92102. * \retval FLAC__bool
  92103. * See FLAC__stream_encoder_set_streamable_subset().
  92104. */
  92105. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  92106. /** Get the number of input channels being processed.
  92107. *
  92108. * \param encoder An encoder instance to query.
  92109. * \assert
  92110. * \code encoder != NULL \endcode
  92111. * \retval unsigned
  92112. * See FLAC__stream_encoder_set_channels().
  92113. */
  92114. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  92115. /** Get the input sample resolution setting.
  92116. *
  92117. * \param encoder An encoder instance to query.
  92118. * \assert
  92119. * \code encoder != NULL \endcode
  92120. * \retval unsigned
  92121. * See FLAC__stream_encoder_set_bits_per_sample().
  92122. */
  92123. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  92124. /** Get the input sample rate setting.
  92125. *
  92126. * \param encoder An encoder instance to query.
  92127. * \assert
  92128. * \code encoder != NULL \endcode
  92129. * \retval unsigned
  92130. * See FLAC__stream_encoder_set_sample_rate().
  92131. */
  92132. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  92133. /** Get the blocksize setting.
  92134. *
  92135. * \param encoder An encoder instance to query.
  92136. * \assert
  92137. * \code encoder != NULL \endcode
  92138. * \retval unsigned
  92139. * See FLAC__stream_encoder_set_blocksize().
  92140. */
  92141. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  92142. /** Get the "mid/side stereo coding" flag.
  92143. *
  92144. * \param encoder An encoder instance to query.
  92145. * \assert
  92146. * \code encoder != NULL \endcode
  92147. * \retval FLAC__bool
  92148. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  92149. */
  92150. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92151. /** Get the "adaptive mid/side switching" flag.
  92152. *
  92153. * \param encoder An encoder instance to query.
  92154. * \assert
  92155. * \code encoder != NULL \endcode
  92156. * \retval FLAC__bool
  92157. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  92158. */
  92159. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92160. /** Get the maximum LPC order setting.
  92161. *
  92162. * \param encoder An encoder instance to query.
  92163. * \assert
  92164. * \code encoder != NULL \endcode
  92165. * \retval unsigned
  92166. * See FLAC__stream_encoder_set_max_lpc_order().
  92167. */
  92168. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92169. /** Get the quantized linear predictor coefficient precision setting.
  92170. *
  92171. * \param encoder An encoder instance to query.
  92172. * \assert
  92173. * \code encoder != NULL \endcode
  92174. * \retval unsigned
  92175. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92176. */
  92177. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92178. /** Get the qlp coefficient precision search flag.
  92179. *
  92180. * \param encoder An encoder instance to query.
  92181. * \assert
  92182. * \code encoder != NULL \endcode
  92183. * \retval FLAC__bool
  92184. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92185. */
  92186. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92187. /** Get the "escape coding" flag.
  92188. *
  92189. * \param encoder An encoder instance to query.
  92190. * \assert
  92191. * \code encoder != NULL \endcode
  92192. * \retval FLAC__bool
  92193. * See FLAC__stream_encoder_set_do_escape_coding().
  92194. */
  92195. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92196. /** Get the exhaustive model search flag.
  92197. *
  92198. * \param encoder An encoder instance to query.
  92199. * \assert
  92200. * \code encoder != NULL \endcode
  92201. * \retval FLAC__bool
  92202. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92203. */
  92204. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92205. /** Get the minimum residual partition order setting.
  92206. *
  92207. * \param encoder An encoder instance to query.
  92208. * \assert
  92209. * \code encoder != NULL \endcode
  92210. * \retval unsigned
  92211. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92212. */
  92213. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92214. /** Get maximum residual partition order setting.
  92215. *
  92216. * \param encoder An encoder instance to query.
  92217. * \assert
  92218. * \code encoder != NULL \endcode
  92219. * \retval unsigned
  92220. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92221. */
  92222. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92223. /** Get the Rice parameter search distance setting.
  92224. *
  92225. * \param encoder An encoder instance to query.
  92226. * \assert
  92227. * \code encoder != NULL \endcode
  92228. * \retval unsigned
  92229. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92230. */
  92231. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92232. /** Get the previously set estimate of the total samples to be encoded.
  92233. * The encoder merely mimics back the value given to
  92234. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92235. * other way of knowing how many samples the client will encode.
  92236. *
  92237. * \param encoder An encoder instance to set.
  92238. * \assert
  92239. * \code encoder != NULL \endcode
  92240. * \retval FLAC__uint64
  92241. * See FLAC__stream_encoder_get_total_samples_estimate().
  92242. */
  92243. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92244. /** Initialize the encoder instance to encode native FLAC streams.
  92245. *
  92246. * This flavor of initialization sets up the encoder to encode to a
  92247. * native FLAC stream. I/O is performed via callbacks to the client.
  92248. * For encoding to a plain file via filename or open \c FILE*,
  92249. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92250. * provide a simpler interface.
  92251. *
  92252. * This function should be called after FLAC__stream_encoder_new() and
  92253. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92254. * or FLAC__stream_encoder_process_interleaved().
  92255. * initialization succeeded.
  92256. *
  92257. * The call to FLAC__stream_encoder_init_stream() currently will also
  92258. * immediately call the write callback several times, once with the \c fLaC
  92259. * signature, and once for each encoded metadata block.
  92260. *
  92261. * \param encoder An uninitialized encoder instance.
  92262. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92263. * pointer must not be \c NULL.
  92264. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92265. * pointer may be \c NULL if seeking is not
  92266. * supported. The encoder uses seeking to go back
  92267. * and write some some stream statistics to the
  92268. * STREAMINFO block; this is recommended but not
  92269. * necessary to create a valid FLAC stream. If
  92270. * \a seek_callback is not \c NULL then a
  92271. * \a tell_callback must also be supplied.
  92272. * Alternatively, a dummy seek callback that just
  92273. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92274. * may also be supplied, all though this is slightly
  92275. * less efficient for the encoder.
  92276. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92277. * pointer may be \c NULL if seeking is not
  92278. * supported. If \a seek_callback is \c NULL then
  92279. * this argument will be ignored. If
  92280. * \a seek_callback is not \c NULL then a
  92281. * \a tell_callback must also be supplied.
  92282. * Alternatively, a dummy tell callback that just
  92283. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92284. * may also be supplied, all though this is slightly
  92285. * less efficient for the encoder.
  92286. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92287. * pointer may be \c NULL if the callback is not
  92288. * desired. If the client provides a seek callback,
  92289. * this function is not necessary as the encoder
  92290. * will automatically seek back and update the
  92291. * STREAMINFO block. It may also be \c NULL if the
  92292. * client does not support seeking, since it will
  92293. * have no way of going back to update the
  92294. * STREAMINFO. However the client can still supply
  92295. * a callback if it would like to know the details
  92296. * from the STREAMINFO.
  92297. * \param client_data This value will be supplied to callbacks in their
  92298. * \a client_data argument.
  92299. * \assert
  92300. * \code encoder != NULL \endcode
  92301. * \retval FLAC__StreamEncoderInitStatus
  92302. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92303. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92304. */
  92305. 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);
  92306. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92307. *
  92308. * This flavor of initialization sets up the encoder to encode to a FLAC
  92309. * stream in an Ogg container. I/O is performed via callbacks to the
  92310. * client. For encoding to a plain file via filename or open \c FILE*,
  92311. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92312. * provide a simpler interface.
  92313. *
  92314. * This function should be called after FLAC__stream_encoder_new() and
  92315. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92316. * or FLAC__stream_encoder_process_interleaved().
  92317. * initialization succeeded.
  92318. *
  92319. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92320. * immediately call the write callback several times to write the metadata
  92321. * packets.
  92322. *
  92323. * \param encoder An uninitialized encoder instance.
  92324. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92325. * pointer must not be \c NULL if \a seek_callback
  92326. * is non-NULL since they are both needed to be
  92327. * able to write data back to the Ogg FLAC stream
  92328. * in the post-encode phase.
  92329. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92330. * pointer must not be \c NULL.
  92331. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92332. * pointer may be \c NULL if seeking is not
  92333. * supported. The encoder uses seeking to go back
  92334. * and write some some stream statistics to the
  92335. * STREAMINFO block; this is recommended but not
  92336. * necessary to create a valid FLAC stream. If
  92337. * \a seek_callback is not \c NULL then a
  92338. * \a tell_callback must also be supplied.
  92339. * Alternatively, a dummy seek callback that just
  92340. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92341. * may also be supplied, all though this is slightly
  92342. * less efficient for the encoder.
  92343. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92344. * pointer may be \c NULL if seeking is not
  92345. * supported. If \a seek_callback is \c NULL then
  92346. * this argument will be ignored. If
  92347. * \a seek_callback is not \c NULL then a
  92348. * \a tell_callback must also be supplied.
  92349. * Alternatively, a dummy tell callback that just
  92350. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92351. * may also be supplied, all though this is slightly
  92352. * less efficient for the encoder.
  92353. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92354. * pointer may be \c NULL if the callback is not
  92355. * desired. If the client provides a seek callback,
  92356. * this function is not necessary as the encoder
  92357. * will automatically seek back and update the
  92358. * STREAMINFO block. It may also be \c NULL if the
  92359. * client does not support seeking, since it will
  92360. * have no way of going back to update the
  92361. * STREAMINFO. However the client can still supply
  92362. * a callback if it would like to know the details
  92363. * from the STREAMINFO.
  92364. * \param client_data This value will be supplied to callbacks in their
  92365. * \a client_data argument.
  92366. * \assert
  92367. * \code encoder != NULL \endcode
  92368. * \retval FLAC__StreamEncoderInitStatus
  92369. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92370. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92371. */
  92372. 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);
  92373. /** Initialize the encoder instance to encode native FLAC files.
  92374. *
  92375. * This flavor of initialization sets up the encoder to encode to a
  92376. * plain native FLAC file. For non-stdio streams, you must use
  92377. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92378. *
  92379. * This function should be called after FLAC__stream_encoder_new() and
  92380. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92381. * or FLAC__stream_encoder_process_interleaved().
  92382. * initialization succeeded.
  92383. *
  92384. * \param encoder An uninitialized encoder instance.
  92385. * \param file An open file. The file should have been opened
  92386. * with mode \c "w+b" and rewound. The file
  92387. * becomes owned by the encoder and should not be
  92388. * manipulated by the client while encoding.
  92389. * Unless \a file is \c stdout, it will be closed
  92390. * when FLAC__stream_encoder_finish() is called.
  92391. * Note however that a proper SEEKTABLE cannot be
  92392. * created when encoding to \c stdout since it is
  92393. * not seekable.
  92394. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92395. * pointer may be \c NULL if the callback is not
  92396. * desired.
  92397. * \param client_data This value will be supplied to callbacks in their
  92398. * \a client_data argument.
  92399. * \assert
  92400. * \code encoder != NULL \endcode
  92401. * \code file != NULL \endcode
  92402. * \retval FLAC__StreamEncoderInitStatus
  92403. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92404. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92405. */
  92406. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92407. /** Initialize the encoder instance to encode Ogg FLAC files.
  92408. *
  92409. * This flavor of initialization sets up the encoder to encode to a
  92410. * plain Ogg FLAC file. For non-stdio streams, you must use
  92411. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92412. *
  92413. * This function should be called after FLAC__stream_encoder_new() and
  92414. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92415. * or FLAC__stream_encoder_process_interleaved().
  92416. * initialization succeeded.
  92417. *
  92418. * \param encoder An uninitialized encoder instance.
  92419. * \param file An open file. The file should have been opened
  92420. * with mode \c "w+b" and rewound. The file
  92421. * becomes owned by the encoder and should not be
  92422. * manipulated by the client while encoding.
  92423. * Unless \a file is \c stdout, it will be closed
  92424. * when FLAC__stream_encoder_finish() is called.
  92425. * Note however that a proper SEEKTABLE cannot be
  92426. * created when encoding to \c stdout since it is
  92427. * not seekable.
  92428. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92429. * pointer may be \c NULL if the callback is not
  92430. * desired.
  92431. * \param client_data This value will be supplied to callbacks in their
  92432. * \a client_data argument.
  92433. * \assert
  92434. * \code encoder != NULL \endcode
  92435. * \code file != NULL \endcode
  92436. * \retval FLAC__StreamEncoderInitStatus
  92437. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92438. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92439. */
  92440. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92441. /** Initialize the encoder instance to encode native FLAC files.
  92442. *
  92443. * This flavor of initialization sets up the encoder to encode to a plain
  92444. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92445. * with Unicode filenames on Windows), you must use
  92446. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92447. * and provide callbacks for the I/O.
  92448. *
  92449. * This function should be called after FLAC__stream_encoder_new() and
  92450. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92451. * or FLAC__stream_encoder_process_interleaved().
  92452. * initialization succeeded.
  92453. *
  92454. * \param encoder An uninitialized encoder instance.
  92455. * \param filename The name of the file to encode to. The file will
  92456. * be opened with fopen(). Use \c NULL to encode to
  92457. * \c stdout. Note however that a proper SEEKTABLE
  92458. * cannot be created when encoding to \c stdout since
  92459. * it is not seekable.
  92460. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92461. * pointer may be \c NULL if the callback is not
  92462. * desired.
  92463. * \param client_data This value will be supplied to callbacks in their
  92464. * \a client_data argument.
  92465. * \assert
  92466. * \code encoder != NULL \endcode
  92467. * \retval FLAC__StreamEncoderInitStatus
  92468. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92469. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92470. */
  92471. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92472. /** Initialize the encoder instance to encode Ogg FLAC files.
  92473. *
  92474. * This flavor of initialization sets up the encoder to encode to a plain
  92475. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92476. * with Unicode filenames on Windows), you must use
  92477. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92478. * and provide callbacks for the I/O.
  92479. *
  92480. * This function should be called after FLAC__stream_encoder_new() and
  92481. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92482. * or FLAC__stream_encoder_process_interleaved().
  92483. * initialization succeeded.
  92484. *
  92485. * \param encoder An uninitialized encoder instance.
  92486. * \param filename The name of the file to encode to. The file will
  92487. * be opened with fopen(). Use \c NULL to encode to
  92488. * \c stdout. Note however that a proper SEEKTABLE
  92489. * cannot be created when encoding to \c stdout since
  92490. * it is not seekable.
  92491. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92492. * pointer may be \c NULL if the callback is not
  92493. * desired.
  92494. * \param client_data This value will be supplied to callbacks in their
  92495. * \a client_data argument.
  92496. * \assert
  92497. * \code encoder != NULL \endcode
  92498. * \retval FLAC__StreamEncoderInitStatus
  92499. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92500. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92501. */
  92502. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92503. /** Finish the encoding process.
  92504. * Flushes the encoding buffer, releases resources, resets the encoder
  92505. * settings to their defaults, and returns the encoder state to
  92506. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92507. * one or more write callbacks before returning, and will generate
  92508. * a metadata callback.
  92509. *
  92510. * Note that in the course of processing the last frame, errors can
  92511. * occur, so the caller should be sure to check the return value to
  92512. * ensure the file was encoded properly.
  92513. *
  92514. * In the event of a prematurely-terminated encode, it is not strictly
  92515. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92516. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92517. * with a FLAC__stream_encoder_finish().
  92518. *
  92519. * \param encoder An uninitialized encoder instance.
  92520. * \assert
  92521. * \code encoder != NULL \endcode
  92522. * \retval FLAC__bool
  92523. * \c false if an error occurred processing the last frame; or if verify
  92524. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92525. * verify mismatch; else \c true. If \c false, caller should check the
  92526. * state with FLAC__stream_encoder_get_state() for more information
  92527. * about the error.
  92528. */
  92529. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92530. /** Submit data for encoding.
  92531. * This version allows you to supply the input data via an array of
  92532. * pointers, each pointer pointing to an array of \a samples samples
  92533. * representing one channel. The samples need not be block-aligned,
  92534. * but each channel should have the same number of samples. Each sample
  92535. * should be a signed integer, right-justified to the resolution set by
  92536. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92537. * resolution is 16 bits per sample, the samples should all be in the
  92538. * range [-32768,32767].
  92539. *
  92540. * For applications where channel order is important, channels must
  92541. * follow the order as described in the
  92542. * <A HREF="../format.html#frame_header">frame header</A>.
  92543. *
  92544. * \param encoder An initialized encoder instance in the OK state.
  92545. * \param buffer An array of pointers to each channel's signal.
  92546. * \param samples The number of samples in one channel.
  92547. * \assert
  92548. * \code encoder != NULL \endcode
  92549. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92550. * \retval FLAC__bool
  92551. * \c true if successful, else \c false; in this case, check the
  92552. * encoder state with FLAC__stream_encoder_get_state() to see what
  92553. * went wrong.
  92554. */
  92555. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92556. /** Submit data for encoding.
  92557. * This version allows you to supply the input data where the channels
  92558. * are interleaved into a single array (i.e. channel0_sample0,
  92559. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92560. * The samples need not be block-aligned but they must be
  92561. * sample-aligned, i.e. the first value should be channel0_sample0
  92562. * and the last value channelN_sampleM. Each sample should be a signed
  92563. * integer, right-justified to the resolution set by
  92564. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92565. * resolution is 16 bits per sample, the samples should all be in the
  92566. * range [-32768,32767].
  92567. *
  92568. * For applications where channel order is important, channels must
  92569. * follow the order as described in the
  92570. * <A HREF="../format.html#frame_header">frame header</A>.
  92571. *
  92572. * \param encoder An initialized encoder instance in the OK state.
  92573. * \param buffer An array of channel-interleaved data (see above).
  92574. * \param samples The number of samples in one channel, the same as for
  92575. * FLAC__stream_encoder_process(). For example, if
  92576. * encoding two channels, \c 1000 \a samples corresponds
  92577. * to a \a buffer of 2000 values.
  92578. * \assert
  92579. * \code encoder != NULL \endcode
  92580. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92581. * \retval FLAC__bool
  92582. * \c true if successful, else \c false; in this case, check the
  92583. * encoder state with FLAC__stream_encoder_get_state() to see what
  92584. * went wrong.
  92585. */
  92586. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92587. /* \} */
  92588. #ifdef __cplusplus
  92589. }
  92590. #endif
  92591. #endif
  92592. /*** End of inlined file: stream_encoder.h ***/
  92593. #ifdef _MSC_VER
  92594. /* OPT: an MSVC built-in would be better */
  92595. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92596. {
  92597. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92598. return (x>>16) | (x<<16);
  92599. }
  92600. #endif
  92601. #if defined(_MSC_VER) && defined(_X86_)
  92602. /* OPT: an MSVC built-in would be better */
  92603. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92604. {
  92605. __asm {
  92606. mov edx, start
  92607. mov ecx, len
  92608. test ecx, ecx
  92609. loop1:
  92610. jz done1
  92611. mov eax, [edx]
  92612. bswap eax
  92613. mov [edx], eax
  92614. add edx, 4
  92615. dec ecx
  92616. jmp short loop1
  92617. done1:
  92618. }
  92619. }
  92620. #endif
  92621. /** \mainpage
  92622. *
  92623. * \section intro Introduction
  92624. *
  92625. * This is the documentation for the FLAC C and C++ APIs. It is
  92626. * highly interconnected; this introduction should give you a top
  92627. * level idea of the structure and how to find the information you
  92628. * need. As a prerequisite you should have at least a basic
  92629. * knowledge of the FLAC format, documented
  92630. * <A HREF="../format.html">here</A>.
  92631. *
  92632. * \section c_api FLAC C API
  92633. *
  92634. * The FLAC C API is the interface to libFLAC, a set of structures
  92635. * describing the components of FLAC streams, and functions for
  92636. * encoding and decoding streams, as well as manipulating FLAC
  92637. * metadata in files. The public include files will be installed
  92638. * in your include area (for example /usr/include/FLAC/...).
  92639. *
  92640. * By writing a little code and linking against libFLAC, it is
  92641. * relatively easy to add FLAC support to another program. The
  92642. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92643. * Complete source code of libFLAC as well as the command-line
  92644. * encoder and plugins is available and is a useful source of
  92645. * examples.
  92646. *
  92647. * Aside from encoders and decoders, libFLAC provides a powerful
  92648. * metadata interface for manipulating metadata in FLAC files. It
  92649. * allows the user to add, delete, and modify FLAC metadata blocks
  92650. * and it can automatically take advantage of PADDING blocks to avoid
  92651. * rewriting the entire FLAC file when changing the size of the
  92652. * metadata.
  92653. *
  92654. * libFLAC usually only requires the standard C library and C math
  92655. * library. In particular, threading is not used so there is no
  92656. * dependency on a thread library. However, libFLAC does not use
  92657. * global variables and should be thread-safe.
  92658. *
  92659. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92660. * However the metadata editing interfaces currently have limited
  92661. * read-only support for Ogg FLAC files.
  92662. *
  92663. * \section cpp_api FLAC C++ API
  92664. *
  92665. * The FLAC C++ API is a set of classes that encapsulate the
  92666. * structures and functions in libFLAC. They provide slightly more
  92667. * functionality with respect to metadata but are otherwise
  92668. * equivalent. For the most part, they share the same usage as
  92669. * their counterparts in libFLAC, and the FLAC C API documentation
  92670. * can be used as a supplement. The public include files
  92671. * for the C++ API will be installed in your include area (for
  92672. * example /usr/include/FLAC++/...).
  92673. *
  92674. * libFLAC++ is also licensed under
  92675. * <A HREF="../license.html">Xiph's BSD license</A>.
  92676. *
  92677. * \section getting_started Getting Started
  92678. *
  92679. * A good starting point for learning the API is to browse through
  92680. * the <A HREF="modules.html">modules</A>. Modules are logical
  92681. * groupings of related functions or classes, which correspond roughly
  92682. * to header files or sections of header files. Each module includes a
  92683. * detailed description of the general usage of its functions or
  92684. * classes.
  92685. *
  92686. * From there you can go on to look at the documentation of
  92687. * individual functions. You can see different views of the individual
  92688. * functions through the links in top bar across this page.
  92689. *
  92690. * If you prefer a more hands-on approach, you can jump right to some
  92691. * <A HREF="../documentation_example_code.html">example code</A>.
  92692. *
  92693. * \section porting_guide Porting Guide
  92694. *
  92695. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92696. * has been introduced which gives detailed instructions on how to
  92697. * port your code to newer versions of FLAC.
  92698. *
  92699. * \section embedded_developers Embedded Developers
  92700. *
  92701. * libFLAC has grown larger over time as more functionality has been
  92702. * included, but much of it may be unnecessary for a particular embedded
  92703. * implementation. Unused parts may be pruned by some simple editing of
  92704. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92705. * metadata interface are all independent from each other.
  92706. *
  92707. * It is easiest to just describe the dependencies:
  92708. *
  92709. * - All modules depend on the \link flac_format Format \endlink module.
  92710. * - The decoders and encoders depend on the bitbuffer.
  92711. * - The decoder is independent of the encoder. The encoder uses the
  92712. * decoder because of the verify feature, but this can be removed if
  92713. * not needed.
  92714. * - Parts of the metadata interface require the stream decoder (but not
  92715. * the encoder).
  92716. * - Ogg support is selectable through the compile time macro
  92717. * \c FLAC__HAS_OGG.
  92718. *
  92719. * For example, if your application only requires the stream decoder, no
  92720. * encoder, and no metadata interface, you can remove the stream encoder
  92721. * and the metadata interface, which will greatly reduce the size of the
  92722. * library.
  92723. *
  92724. * Also, there are several places in the libFLAC code with comments marked
  92725. * with "OPT:" where a #define can be changed to enable code that might be
  92726. * faster on a specific platform. Experimenting with these can yield faster
  92727. * binaries.
  92728. */
  92729. /** \defgroup porting Porting Guide for New Versions
  92730. *
  92731. * This module describes differences in the library interfaces from
  92732. * version to version. It assists in the porting of code that uses
  92733. * the libraries to newer versions of FLAC.
  92734. *
  92735. * One simple facility for making porting easier that has been added
  92736. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92737. * library's includes (e.g. \c include/FLAC/export.h). The
  92738. * \c #defines mirror the libraries'
  92739. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92740. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92741. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92742. * These can be used to support multiple versions of an API during the
  92743. * transition phase, e.g.
  92744. *
  92745. * \code
  92746. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92747. * legacy code
  92748. * #else
  92749. * new code
  92750. * #endif
  92751. * \endcode
  92752. *
  92753. * The the source will work for multiple versions and the legacy code can
  92754. * easily be removed when the transition is complete.
  92755. *
  92756. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92757. * include/FLAC/export.h), which can be used to determine whether or not
  92758. * the library has been compiled with support for Ogg FLAC. This is
  92759. * simpler than trying to call an Ogg init function and catching the
  92760. * error.
  92761. */
  92762. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92763. * \ingroup porting
  92764. *
  92765. * \brief
  92766. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92767. *
  92768. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92769. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92770. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92771. * decoding layers and three encoding layers have been merged into a
  92772. * single stream decoder and stream encoder. That is, the functionality
  92773. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92774. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92775. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92776. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92777. * is there is now a single API that can be used to encode or decode
  92778. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92779. * on both seekable and non-seekable streams.
  92780. *
  92781. * Instead of creating an encoder or decoder of a certain layer, now the
  92782. * client will always create a FLAC__StreamEncoder or
  92783. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92784. * initialization function. For example, for the decoder,
  92785. * FLAC__stream_decoder_init() has been replaced by
  92786. * FLAC__stream_decoder_init_stream(). This init function takes
  92787. * callbacks for the I/O, and the seeking callbacks are optional. This
  92788. * allows the client to use the same object for seekable and
  92789. * non-seekable streams. For decoding a FLAC file directly, the client
  92790. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92791. * and fewer callbacks; most of the other callbacks are supplied
  92792. * internally. For situations where fopen()ing by filename is not
  92793. * possible (e.g. Unicode filenames on Windows) the client can instead
  92794. * open the file itself and supply the FILE* to
  92795. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92796. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92797. * Since the callbacks and client data are now passed to the init
  92798. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92799. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92800. * rest of the calls to the decoder are the same as before.
  92801. *
  92802. * There are counterpart init functions for Ogg FLAC, e.g.
  92803. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92804. * and callbacks are the same as for native FLAC.
  92805. *
  92806. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92807. * been set up like so:
  92808. *
  92809. * \code
  92810. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92811. * if(decoder == NULL) do_something;
  92812. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92813. * [... other settings ...]
  92814. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92815. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92816. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92817. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92818. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92819. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92820. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92821. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92822. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92823. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92824. * \endcode
  92825. *
  92826. * In FLAC 1.1.3 it is like this:
  92827. *
  92828. * \code
  92829. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92830. * if(decoder == NULL) do_something;
  92831. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92832. * [... other settings ...]
  92833. * if(FLAC__stream_decoder_init_stream(
  92834. * decoder,
  92835. * my_read_callback,
  92836. * my_seek_callback, // or NULL
  92837. * my_tell_callback, // or NULL
  92838. * my_length_callback, // or NULL
  92839. * my_eof_callback, // or NULL
  92840. * my_write_callback,
  92841. * my_metadata_callback, // or NULL
  92842. * my_error_callback,
  92843. * my_client_data
  92844. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92845. * \endcode
  92846. *
  92847. * or you could do;
  92848. *
  92849. * \code
  92850. * [...]
  92851. * FILE *file = fopen("somefile.flac","rb");
  92852. * if(file == NULL) do_somthing;
  92853. * if(FLAC__stream_decoder_init_FILE(
  92854. * decoder,
  92855. * file,
  92856. * my_write_callback,
  92857. * my_metadata_callback, // or NULL
  92858. * my_error_callback,
  92859. * my_client_data
  92860. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92861. * \endcode
  92862. *
  92863. * or just:
  92864. *
  92865. * \code
  92866. * [...]
  92867. * if(FLAC__stream_decoder_init_file(
  92868. * decoder,
  92869. * "somefile.flac",
  92870. * my_write_callback,
  92871. * my_metadata_callback, // or NULL
  92872. * my_error_callback,
  92873. * my_client_data
  92874. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92875. * \endcode
  92876. *
  92877. * Another small change to the decoder is in how it handles unparseable
  92878. * streams. Before, when the decoder found an unparseable stream
  92879. * (reserved for when the decoder encounters a stream from a future
  92880. * encoder that it can't parse), it changed the state to
  92881. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92882. * drops sync and calls the error callback with a new error code
  92883. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92884. * more robust. If your error callback does not discriminate on the the
  92885. * error state, your code does not need to be changed.
  92886. *
  92887. * The encoder now has a new setting:
  92888. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92889. * method used to window the data before LPC analysis. You only need to
  92890. * add a call to this function if the default is not suitable. There
  92891. * are also two new convenience functions that may be useful:
  92892. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92893. * FLAC__metadata_get_cuesheet().
  92894. *
  92895. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92896. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92897. * is now \c size_t instead of \c unsigned.
  92898. */
  92899. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92900. * \ingroup porting
  92901. *
  92902. * \brief
  92903. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92904. *
  92905. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92906. * There was a slight change in the implementation of
  92907. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92908. * of the \a metadata array of pointers so the client no longer needs
  92909. * to maintain it after the call. The objects themselves that are
  92910. * pointed to by the array are still not copied though and must be
  92911. * maintained until the call to FLAC__stream_encoder_finish().
  92912. */
  92913. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92914. * \ingroup porting
  92915. *
  92916. * \brief
  92917. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92918. *
  92919. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92920. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92921. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92922. *
  92923. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92924. * has changed to reflect the conversion of one of the reserved bits
  92925. * into active use. It used to be \c 2 and now is \c 1. However the
  92926. * FLAC frame header length has not changed, so to skip the proper
  92927. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92928. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92929. */
  92930. /** \defgroup flac FLAC C API
  92931. *
  92932. * The FLAC C API is the interface to libFLAC, a set of structures
  92933. * describing the components of FLAC streams, and functions for
  92934. * encoding and decoding streams, as well as manipulating FLAC
  92935. * metadata in files.
  92936. *
  92937. * You should start with the format components as all other modules
  92938. * are dependent on it.
  92939. */
  92940. #endif
  92941. /*** End of inlined file: all.h ***/
  92942. /*** Start of inlined file: bitmath.c ***/
  92943. /*** Start of inlined file: juce_FlacHeader.h ***/
  92944. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92945. // tasks..
  92946. #define VERSION "1.2.1"
  92947. #define FLAC__NO_DLL 1
  92948. #if JUCE_MSVC
  92949. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92950. #endif
  92951. #if JUCE_MAC
  92952. #define FLAC__SYS_DARWIN 1
  92953. #endif
  92954. /*** End of inlined file: juce_FlacHeader.h ***/
  92955. #if JUCE_USE_FLAC
  92956. #if HAVE_CONFIG_H
  92957. # include <config.h>
  92958. #endif
  92959. /*** Start of inlined file: bitmath.h ***/
  92960. #ifndef FLAC__PRIVATE__BITMATH_H
  92961. #define FLAC__PRIVATE__BITMATH_H
  92962. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92963. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92964. unsigned FLAC__bitmath_silog2(int v);
  92965. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92966. #endif
  92967. /*** End of inlined file: bitmath.h ***/
  92968. /* An example of what FLAC__bitmath_ilog2() computes:
  92969. *
  92970. * ilog2( 0) = assertion failure
  92971. * ilog2( 1) = 0
  92972. * ilog2( 2) = 1
  92973. * ilog2( 3) = 1
  92974. * ilog2( 4) = 2
  92975. * ilog2( 5) = 2
  92976. * ilog2( 6) = 2
  92977. * ilog2( 7) = 2
  92978. * ilog2( 8) = 3
  92979. * ilog2( 9) = 3
  92980. * ilog2(10) = 3
  92981. * ilog2(11) = 3
  92982. * ilog2(12) = 3
  92983. * ilog2(13) = 3
  92984. * ilog2(14) = 3
  92985. * ilog2(15) = 3
  92986. * ilog2(16) = 4
  92987. * ilog2(17) = 4
  92988. * ilog2(18) = 4
  92989. */
  92990. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92991. {
  92992. unsigned l = 0;
  92993. FLAC__ASSERT(v > 0);
  92994. while(v >>= 1)
  92995. l++;
  92996. return l;
  92997. }
  92998. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92999. {
  93000. unsigned l = 0;
  93001. FLAC__ASSERT(v > 0);
  93002. while(v >>= 1)
  93003. l++;
  93004. return l;
  93005. }
  93006. /* An example of what FLAC__bitmath_silog2() computes:
  93007. *
  93008. * silog2(-10) = 5
  93009. * silog2(- 9) = 5
  93010. * silog2(- 8) = 4
  93011. * silog2(- 7) = 4
  93012. * silog2(- 6) = 4
  93013. * silog2(- 5) = 4
  93014. * silog2(- 4) = 3
  93015. * silog2(- 3) = 3
  93016. * silog2(- 2) = 2
  93017. * silog2(- 1) = 2
  93018. * silog2( 0) = 0
  93019. * silog2( 1) = 2
  93020. * silog2( 2) = 3
  93021. * silog2( 3) = 3
  93022. * silog2( 4) = 4
  93023. * silog2( 5) = 4
  93024. * silog2( 6) = 4
  93025. * silog2( 7) = 4
  93026. * silog2( 8) = 5
  93027. * silog2( 9) = 5
  93028. * silog2( 10) = 5
  93029. */
  93030. unsigned FLAC__bitmath_silog2(int v)
  93031. {
  93032. while(1) {
  93033. if(v == 0) {
  93034. return 0;
  93035. }
  93036. else if(v > 0) {
  93037. unsigned l = 0;
  93038. while(v) {
  93039. l++;
  93040. v >>= 1;
  93041. }
  93042. return l+1;
  93043. }
  93044. else if(v == -1) {
  93045. return 2;
  93046. }
  93047. else {
  93048. v++;
  93049. v = -v;
  93050. }
  93051. }
  93052. }
  93053. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  93054. {
  93055. while(1) {
  93056. if(v == 0) {
  93057. return 0;
  93058. }
  93059. else if(v > 0) {
  93060. unsigned l = 0;
  93061. while(v) {
  93062. l++;
  93063. v >>= 1;
  93064. }
  93065. return l+1;
  93066. }
  93067. else if(v == -1) {
  93068. return 2;
  93069. }
  93070. else {
  93071. v++;
  93072. v = -v;
  93073. }
  93074. }
  93075. }
  93076. #endif
  93077. /*** End of inlined file: bitmath.c ***/
  93078. /*** Start of inlined file: bitreader.c ***/
  93079. /*** Start of inlined file: juce_FlacHeader.h ***/
  93080. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93081. // tasks..
  93082. #define VERSION "1.2.1"
  93083. #define FLAC__NO_DLL 1
  93084. #if JUCE_MSVC
  93085. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93086. #endif
  93087. #if JUCE_MAC
  93088. #define FLAC__SYS_DARWIN 1
  93089. #endif
  93090. /*** End of inlined file: juce_FlacHeader.h ***/
  93091. #if JUCE_USE_FLAC
  93092. #if HAVE_CONFIG_H
  93093. # include <config.h>
  93094. #endif
  93095. #include <stdlib.h> /* for malloc() */
  93096. #include <string.h> /* for memcpy(), memset() */
  93097. #ifdef _MSC_VER
  93098. #include <winsock.h> /* for ntohl() */
  93099. #elif defined FLAC__SYS_DARWIN
  93100. #include <machine/endian.h> /* for ntohl() */
  93101. #elif defined __MINGW32__
  93102. #include <winsock.h> /* for ntohl() */
  93103. #else
  93104. #include <netinet/in.h> /* for ntohl() */
  93105. #endif
  93106. /*** Start of inlined file: bitreader.h ***/
  93107. #ifndef FLAC__PRIVATE__BITREADER_H
  93108. #define FLAC__PRIVATE__BITREADER_H
  93109. #include <stdio.h> /* for FILE */
  93110. /*** Start of inlined file: cpu.h ***/
  93111. #ifndef FLAC__PRIVATE__CPU_H
  93112. #define FLAC__PRIVATE__CPU_H
  93113. #ifdef HAVE_CONFIG_H
  93114. #include <config.h>
  93115. #endif
  93116. typedef enum {
  93117. FLAC__CPUINFO_TYPE_IA32,
  93118. FLAC__CPUINFO_TYPE_PPC,
  93119. FLAC__CPUINFO_TYPE_UNKNOWN
  93120. } FLAC__CPUInfo_Type;
  93121. typedef struct {
  93122. FLAC__bool cpuid;
  93123. FLAC__bool bswap;
  93124. FLAC__bool cmov;
  93125. FLAC__bool mmx;
  93126. FLAC__bool fxsr;
  93127. FLAC__bool sse;
  93128. FLAC__bool sse2;
  93129. FLAC__bool sse3;
  93130. FLAC__bool ssse3;
  93131. FLAC__bool _3dnow;
  93132. FLAC__bool ext3dnow;
  93133. FLAC__bool extmmx;
  93134. } FLAC__CPUInfo_IA32;
  93135. typedef struct {
  93136. FLAC__bool altivec;
  93137. FLAC__bool ppc64;
  93138. } FLAC__CPUInfo_PPC;
  93139. typedef struct {
  93140. FLAC__bool use_asm;
  93141. FLAC__CPUInfo_Type type;
  93142. union {
  93143. FLAC__CPUInfo_IA32 ia32;
  93144. FLAC__CPUInfo_PPC ppc;
  93145. } data;
  93146. } FLAC__CPUInfo;
  93147. void FLAC__cpu_info(FLAC__CPUInfo *info);
  93148. #ifndef FLAC__NO_ASM
  93149. #ifdef FLAC__CPU_IA32
  93150. #ifdef FLAC__HAS_NASM
  93151. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  93152. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  93153. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  93154. #endif
  93155. #endif
  93156. #endif
  93157. #endif
  93158. /*** End of inlined file: cpu.h ***/
  93159. /*
  93160. * opaque structure definition
  93161. */
  93162. struct FLAC__BitReader;
  93163. typedef struct FLAC__BitReader FLAC__BitReader;
  93164. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93165. /*
  93166. * construction, deletion, initialization, etc functions
  93167. */
  93168. FLAC__BitReader *FLAC__bitreader_new(void);
  93169. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93170. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93171. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93172. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93173. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93174. /*
  93175. * CRC functions
  93176. */
  93177. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93178. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93179. /*
  93180. * info functions
  93181. */
  93182. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93183. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93184. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93185. /*
  93186. * read functions
  93187. */
  93188. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93189. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93190. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93191. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93192. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93193. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93194. 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! */
  93195. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93196. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93197. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93198. #ifndef FLAC__NO_ASM
  93199. # ifdef FLAC__CPU_IA32
  93200. # ifdef FLAC__HAS_NASM
  93201. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93202. # endif
  93203. # endif
  93204. #endif
  93205. #if 0 /* UNUSED */
  93206. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93207. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93208. #endif
  93209. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93210. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93211. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93212. #endif
  93213. /*** End of inlined file: bitreader.h ***/
  93214. /*** Start of inlined file: crc.h ***/
  93215. #ifndef FLAC__PRIVATE__CRC_H
  93216. #define FLAC__PRIVATE__CRC_H
  93217. /* 8 bit CRC generator, MSB shifted first
  93218. ** polynomial = x^8 + x^2 + x^1 + x^0
  93219. ** init = 0
  93220. */
  93221. extern FLAC__byte const FLAC__crc8_table[256];
  93222. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93223. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93224. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93225. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93226. /* 16 bit CRC generator, MSB shifted first
  93227. ** polynomial = x^16 + x^15 + x^2 + x^0
  93228. ** init = 0
  93229. */
  93230. extern unsigned FLAC__crc16_table[256];
  93231. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93232. /* this alternate may be faster on some systems/compilers */
  93233. #if 0
  93234. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93235. #endif
  93236. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93237. #endif
  93238. /*** End of inlined file: crc.h ***/
  93239. /* Things should be fastest when this matches the machine word size */
  93240. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93241. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93242. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93243. typedef FLAC__uint32 brword;
  93244. #define FLAC__BYTES_PER_WORD 4
  93245. #define FLAC__BITS_PER_WORD 32
  93246. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93247. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93248. #if WORDS_BIGENDIAN
  93249. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93250. #else
  93251. #if defined (_MSC_VER) && defined (_X86_)
  93252. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93253. #else
  93254. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93255. #endif
  93256. #endif
  93257. /* counts the # of zero MSBs in a word */
  93258. #define COUNT_ZERO_MSBS(word) ( \
  93259. (word) <= 0xffff ? \
  93260. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93261. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93262. )
  93263. /* this alternate might be slightly faster on some systems/compilers: */
  93264. #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])) )
  93265. /*
  93266. * This should be at least twice as large as the largest number of words
  93267. * required to represent any 'number' (in any encoding) you are going to
  93268. * read. With FLAC this is on the order of maybe a few hundred bits.
  93269. * If the buffer is smaller than that, the decoder won't be able to read
  93270. * in a whole number that is in a variable length encoding (e.g. Rice).
  93271. * But to be practical it should be at least 1K bytes.
  93272. *
  93273. * Increase this number to decrease the number of read callbacks, at the
  93274. * expense of using more memory. Or decrease for the reverse effect,
  93275. * keeping in mind the limit from the first paragraph. The optimal size
  93276. * also depends on the CPU cache size and other factors; some twiddling
  93277. * may be necessary to squeeze out the best performance.
  93278. */
  93279. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93280. static const unsigned char byte_to_unary_table[] = {
  93281. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93282. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93283. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93284. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93285. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93286. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93287. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93288. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93297. };
  93298. #ifdef min
  93299. #undef min
  93300. #endif
  93301. #define min(x,y) ((x)<(y)?(x):(y))
  93302. #ifdef max
  93303. #undef max
  93304. #endif
  93305. #define max(x,y) ((x)>(y)?(x):(y))
  93306. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93307. #ifdef _MSC_VER
  93308. #define FLAC__U64L(x) x
  93309. #else
  93310. #define FLAC__U64L(x) x##LLU
  93311. #endif
  93312. #ifndef FLaC__INLINE
  93313. #define FLaC__INLINE
  93314. #endif
  93315. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93316. struct FLAC__BitReader {
  93317. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93318. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93319. brword *buffer;
  93320. unsigned capacity; /* in words */
  93321. unsigned words; /* # of completed words in buffer */
  93322. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93323. unsigned consumed_words; /* #words ... */
  93324. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93325. unsigned read_crc16; /* the running frame CRC */
  93326. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93327. FLAC__BitReaderReadCallback read_callback;
  93328. void *client_data;
  93329. FLAC__CPUInfo cpu_info;
  93330. };
  93331. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93332. {
  93333. register unsigned crc = br->read_crc16;
  93334. #if FLAC__BYTES_PER_WORD == 4
  93335. switch(br->crc16_align) {
  93336. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93337. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93338. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93339. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93340. }
  93341. #elif FLAC__BYTES_PER_WORD == 8
  93342. switch(br->crc16_align) {
  93343. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93344. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93345. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93346. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93347. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93348. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93349. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93350. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93351. }
  93352. #else
  93353. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93354. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93355. br->read_crc16 = crc;
  93356. #endif
  93357. br->crc16_align = 0;
  93358. }
  93359. /* would be static except it needs to be called by asm routines */
  93360. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93361. {
  93362. unsigned start, end;
  93363. size_t bytes;
  93364. FLAC__byte *target;
  93365. /* first shift the unconsumed buffer data toward the front as much as possible */
  93366. if(br->consumed_words > 0) {
  93367. start = br->consumed_words;
  93368. end = br->words + (br->bytes? 1:0);
  93369. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93370. br->words -= start;
  93371. br->consumed_words = 0;
  93372. }
  93373. /*
  93374. * set the target for reading, taking into account word alignment and endianness
  93375. */
  93376. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93377. if(bytes == 0)
  93378. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93379. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93380. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93381. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93382. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93383. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93384. * ^^-------target, bytes=3
  93385. * on LE machines, have to byteswap the odd tail word so nothing is
  93386. * overwritten:
  93387. */
  93388. #if WORDS_BIGENDIAN
  93389. #else
  93390. if(br->bytes)
  93391. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93392. #endif
  93393. /* now it looks like:
  93394. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93395. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93396. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93397. * ^^-------target, bytes=3
  93398. */
  93399. /* read in the data; note that the callback may return a smaller number of bytes */
  93400. if(!br->read_callback(target, &bytes, br->client_data))
  93401. return false;
  93402. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93403. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93404. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93405. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93406. * now have to byteswap on LE machines:
  93407. */
  93408. #if WORDS_BIGENDIAN
  93409. #else
  93410. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93411. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93412. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93413. start = br->words;
  93414. local_swap32_block_(br->buffer + start, end - start);
  93415. }
  93416. else
  93417. # endif
  93418. for(start = br->words; start < end; start++)
  93419. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93420. #endif
  93421. /* now it looks like:
  93422. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93423. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93424. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93425. * finally we'll update the reader values:
  93426. */
  93427. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93428. br->words = end / FLAC__BYTES_PER_WORD;
  93429. br->bytes = end % FLAC__BYTES_PER_WORD;
  93430. return true;
  93431. }
  93432. /***********************************************************************
  93433. *
  93434. * Class constructor/destructor
  93435. *
  93436. ***********************************************************************/
  93437. FLAC__BitReader *FLAC__bitreader_new(void)
  93438. {
  93439. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93440. /* calloc() implies:
  93441. memset(br, 0, sizeof(FLAC__BitReader));
  93442. br->buffer = 0;
  93443. br->capacity = 0;
  93444. br->words = br->bytes = 0;
  93445. br->consumed_words = br->consumed_bits = 0;
  93446. br->read_callback = 0;
  93447. br->client_data = 0;
  93448. */
  93449. return br;
  93450. }
  93451. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93452. {
  93453. FLAC__ASSERT(0 != br);
  93454. FLAC__bitreader_free(br);
  93455. free(br);
  93456. }
  93457. /***********************************************************************
  93458. *
  93459. * Public class methods
  93460. *
  93461. ***********************************************************************/
  93462. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93463. {
  93464. FLAC__ASSERT(0 != br);
  93465. br->words = br->bytes = 0;
  93466. br->consumed_words = br->consumed_bits = 0;
  93467. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93468. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93469. if(br->buffer == 0)
  93470. return false;
  93471. br->read_callback = rcb;
  93472. br->client_data = cd;
  93473. br->cpu_info = cpu;
  93474. return true;
  93475. }
  93476. void FLAC__bitreader_free(FLAC__BitReader *br)
  93477. {
  93478. FLAC__ASSERT(0 != br);
  93479. if(0 != br->buffer)
  93480. free(br->buffer);
  93481. br->buffer = 0;
  93482. br->capacity = 0;
  93483. br->words = br->bytes = 0;
  93484. br->consumed_words = br->consumed_bits = 0;
  93485. br->read_callback = 0;
  93486. br->client_data = 0;
  93487. }
  93488. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93489. {
  93490. br->words = br->bytes = 0;
  93491. br->consumed_words = br->consumed_bits = 0;
  93492. return true;
  93493. }
  93494. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93495. {
  93496. unsigned i, j;
  93497. if(br == 0) {
  93498. fprintf(out, "bitreader is NULL\n");
  93499. }
  93500. else {
  93501. 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);
  93502. for(i = 0; i < br->words; i++) {
  93503. fprintf(out, "%08X: ", i);
  93504. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93505. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93506. fprintf(out, ".");
  93507. else
  93508. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93509. fprintf(out, "\n");
  93510. }
  93511. if(br->bytes > 0) {
  93512. fprintf(out, "%08X: ", i);
  93513. for(j = 0; j < br->bytes*8; j++)
  93514. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93515. fprintf(out, ".");
  93516. else
  93517. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93518. fprintf(out, "\n");
  93519. }
  93520. }
  93521. }
  93522. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93523. {
  93524. FLAC__ASSERT(0 != br);
  93525. FLAC__ASSERT(0 != br->buffer);
  93526. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93527. br->read_crc16 = (unsigned)seed;
  93528. br->crc16_align = br->consumed_bits;
  93529. }
  93530. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93531. {
  93532. FLAC__ASSERT(0 != br);
  93533. FLAC__ASSERT(0 != br->buffer);
  93534. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93535. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93536. /* CRC any tail bytes in a partially-consumed word */
  93537. if(br->consumed_bits) {
  93538. const brword tail = br->buffer[br->consumed_words];
  93539. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93540. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93541. }
  93542. return br->read_crc16;
  93543. }
  93544. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93545. {
  93546. return ((br->consumed_bits & 7) == 0);
  93547. }
  93548. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93549. {
  93550. return 8 - (br->consumed_bits & 7);
  93551. }
  93552. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93553. {
  93554. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93555. }
  93556. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93557. {
  93558. FLAC__ASSERT(0 != br);
  93559. FLAC__ASSERT(0 != br->buffer);
  93560. FLAC__ASSERT(bits <= 32);
  93561. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93562. FLAC__ASSERT(br->consumed_words <= br->words);
  93563. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93564. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93565. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93566. *val = 0;
  93567. return true;
  93568. }
  93569. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93570. if(!bitreader_read_from_client_(br))
  93571. return false;
  93572. }
  93573. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93574. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93575. if(br->consumed_bits) {
  93576. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93577. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93578. const brword word = br->buffer[br->consumed_words];
  93579. if(bits < n) {
  93580. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93581. br->consumed_bits += bits;
  93582. return true;
  93583. }
  93584. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93585. bits -= n;
  93586. crc16_update_word_(br, word);
  93587. br->consumed_words++;
  93588. br->consumed_bits = 0;
  93589. 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 */
  93590. *val <<= bits;
  93591. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93592. br->consumed_bits = bits;
  93593. }
  93594. return true;
  93595. }
  93596. else {
  93597. const brword word = br->buffer[br->consumed_words];
  93598. if(bits < FLAC__BITS_PER_WORD) {
  93599. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93600. br->consumed_bits = bits;
  93601. return true;
  93602. }
  93603. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93604. *val = word;
  93605. crc16_update_word_(br, word);
  93606. br->consumed_words++;
  93607. return true;
  93608. }
  93609. }
  93610. else {
  93611. /* in this case we're starting our read at a partial tail word;
  93612. * the reader has guaranteed that we have at least 'bits' bits
  93613. * available to read, which makes this case simpler.
  93614. */
  93615. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93616. if(br->consumed_bits) {
  93617. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93618. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93619. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93620. br->consumed_bits += bits;
  93621. return true;
  93622. }
  93623. else {
  93624. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93625. br->consumed_bits += bits;
  93626. return true;
  93627. }
  93628. }
  93629. }
  93630. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93631. {
  93632. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93633. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93634. return false;
  93635. /* sign-extend: */
  93636. *val <<= (32-bits);
  93637. *val >>= (32-bits);
  93638. return true;
  93639. }
  93640. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93641. {
  93642. FLAC__uint32 hi, lo;
  93643. if(bits > 32) {
  93644. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93645. return false;
  93646. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93647. return false;
  93648. *val = hi;
  93649. *val <<= 32;
  93650. *val |= lo;
  93651. }
  93652. else {
  93653. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93654. return false;
  93655. *val = lo;
  93656. }
  93657. return true;
  93658. }
  93659. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93660. {
  93661. FLAC__uint32 x8, x32 = 0;
  93662. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93663. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93664. return false;
  93665. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93666. return false;
  93667. x32 |= (x8 << 8);
  93668. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93669. return false;
  93670. x32 |= (x8 << 16);
  93671. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93672. return false;
  93673. x32 |= (x8 << 24);
  93674. *val = x32;
  93675. return true;
  93676. }
  93677. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93678. {
  93679. /*
  93680. * OPT: a faster implementation is possible but probably not that useful
  93681. * since this is only called a couple of times in the metadata readers.
  93682. */
  93683. FLAC__ASSERT(0 != br);
  93684. FLAC__ASSERT(0 != br->buffer);
  93685. if(bits > 0) {
  93686. const unsigned n = br->consumed_bits & 7;
  93687. unsigned m;
  93688. FLAC__uint32 x;
  93689. if(n != 0) {
  93690. m = min(8-n, bits);
  93691. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93692. return false;
  93693. bits -= m;
  93694. }
  93695. m = bits / 8;
  93696. if(m > 0) {
  93697. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93698. return false;
  93699. bits %= 8;
  93700. }
  93701. if(bits > 0) {
  93702. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93703. return false;
  93704. }
  93705. }
  93706. return true;
  93707. }
  93708. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93709. {
  93710. FLAC__uint32 x;
  93711. FLAC__ASSERT(0 != br);
  93712. FLAC__ASSERT(0 != br->buffer);
  93713. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93714. /* step 1: skip over partial head word to get word aligned */
  93715. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93716. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93717. return false;
  93718. nvals--;
  93719. }
  93720. if(0 == nvals)
  93721. return true;
  93722. /* step 2: skip whole words in chunks */
  93723. while(nvals >= FLAC__BYTES_PER_WORD) {
  93724. if(br->consumed_words < br->words) {
  93725. br->consumed_words++;
  93726. nvals -= FLAC__BYTES_PER_WORD;
  93727. }
  93728. else if(!bitreader_read_from_client_(br))
  93729. return false;
  93730. }
  93731. /* step 3: skip any remainder from partial tail bytes */
  93732. while(nvals) {
  93733. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93734. return false;
  93735. nvals--;
  93736. }
  93737. return true;
  93738. }
  93739. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93740. {
  93741. FLAC__uint32 x;
  93742. FLAC__ASSERT(0 != br);
  93743. FLAC__ASSERT(0 != br->buffer);
  93744. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93745. /* step 1: read from partial head word to get word aligned */
  93746. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93747. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93748. return false;
  93749. *val++ = (FLAC__byte)x;
  93750. nvals--;
  93751. }
  93752. if(0 == nvals)
  93753. return true;
  93754. /* step 2: read whole words in chunks */
  93755. while(nvals >= FLAC__BYTES_PER_WORD) {
  93756. if(br->consumed_words < br->words) {
  93757. const brword word = br->buffer[br->consumed_words++];
  93758. #if FLAC__BYTES_PER_WORD == 4
  93759. val[0] = (FLAC__byte)(word >> 24);
  93760. val[1] = (FLAC__byte)(word >> 16);
  93761. val[2] = (FLAC__byte)(word >> 8);
  93762. val[3] = (FLAC__byte)word;
  93763. #elif FLAC__BYTES_PER_WORD == 8
  93764. val[0] = (FLAC__byte)(word >> 56);
  93765. val[1] = (FLAC__byte)(word >> 48);
  93766. val[2] = (FLAC__byte)(word >> 40);
  93767. val[3] = (FLAC__byte)(word >> 32);
  93768. val[4] = (FLAC__byte)(word >> 24);
  93769. val[5] = (FLAC__byte)(word >> 16);
  93770. val[6] = (FLAC__byte)(word >> 8);
  93771. val[7] = (FLAC__byte)word;
  93772. #else
  93773. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93774. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93775. #endif
  93776. val += FLAC__BYTES_PER_WORD;
  93777. nvals -= FLAC__BYTES_PER_WORD;
  93778. }
  93779. else if(!bitreader_read_from_client_(br))
  93780. return false;
  93781. }
  93782. /* step 3: read any remainder from partial tail bytes */
  93783. while(nvals) {
  93784. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93785. return false;
  93786. *val++ = (FLAC__byte)x;
  93787. nvals--;
  93788. }
  93789. return true;
  93790. }
  93791. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93792. #if 0 /* slow but readable version */
  93793. {
  93794. unsigned bit;
  93795. FLAC__ASSERT(0 != br);
  93796. FLAC__ASSERT(0 != br->buffer);
  93797. *val = 0;
  93798. while(1) {
  93799. if(!FLAC__bitreader_read_bit(br, &bit))
  93800. return false;
  93801. if(bit)
  93802. break;
  93803. else
  93804. *val++;
  93805. }
  93806. return true;
  93807. }
  93808. #else
  93809. {
  93810. unsigned i;
  93811. FLAC__ASSERT(0 != br);
  93812. FLAC__ASSERT(0 != br->buffer);
  93813. *val = 0;
  93814. while(1) {
  93815. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93816. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93817. if(b) {
  93818. i = COUNT_ZERO_MSBS(b);
  93819. *val += i;
  93820. i++;
  93821. br->consumed_bits += i;
  93822. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93823. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93824. br->consumed_words++;
  93825. br->consumed_bits = 0;
  93826. }
  93827. return true;
  93828. }
  93829. else {
  93830. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93831. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93832. br->consumed_words++;
  93833. br->consumed_bits = 0;
  93834. /* didn't find stop bit yet, have to keep going... */
  93835. }
  93836. }
  93837. /* at this point we've eaten up all the whole words; have to try
  93838. * reading through any tail bytes before calling the read callback.
  93839. * this is a repeat of the above logic adjusted for the fact we
  93840. * don't have a whole word. note though if the client is feeding
  93841. * us data a byte at a time (unlikely), br->consumed_bits may not
  93842. * be zero.
  93843. */
  93844. if(br->bytes) {
  93845. const unsigned end = br->bytes * 8;
  93846. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93847. if(b) {
  93848. i = COUNT_ZERO_MSBS(b);
  93849. *val += i;
  93850. i++;
  93851. br->consumed_bits += i;
  93852. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93853. return true;
  93854. }
  93855. else {
  93856. *val += end - br->consumed_bits;
  93857. br->consumed_bits += end;
  93858. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93859. /* didn't find stop bit yet, have to keep going... */
  93860. }
  93861. }
  93862. if(!bitreader_read_from_client_(br))
  93863. return false;
  93864. }
  93865. }
  93866. #endif
  93867. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93868. {
  93869. FLAC__uint32 lsbs = 0, msbs = 0;
  93870. unsigned uval;
  93871. FLAC__ASSERT(0 != br);
  93872. FLAC__ASSERT(0 != br->buffer);
  93873. FLAC__ASSERT(parameter <= 31);
  93874. /* read the unary MSBs and end bit */
  93875. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93876. return false;
  93877. /* read the binary LSBs */
  93878. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93879. return false;
  93880. /* compose the value */
  93881. uval = (msbs << parameter) | lsbs;
  93882. if(uval & 1)
  93883. *val = -((int)(uval >> 1)) - 1;
  93884. else
  93885. *val = (int)(uval >> 1);
  93886. return true;
  93887. }
  93888. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93889. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93890. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93891. /* OPT: possibly faster version for use with MSVC */
  93892. #ifdef _MSC_VER
  93893. {
  93894. unsigned i;
  93895. unsigned uval = 0;
  93896. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93897. /* try and get br->consumed_words and br->consumed_bits into register;
  93898. * must remember to flush them back to *br before calling other
  93899. * bitwriter functions that use them, and before returning */
  93900. register unsigned cwords;
  93901. register unsigned cbits;
  93902. FLAC__ASSERT(0 != br);
  93903. FLAC__ASSERT(0 != br->buffer);
  93904. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93905. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93906. FLAC__ASSERT(parameter < 32);
  93907. /* 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 */
  93908. if(nvals == 0)
  93909. return true;
  93910. cbits = br->consumed_bits;
  93911. cwords = br->consumed_words;
  93912. while(1) {
  93913. /* read unary part */
  93914. while(1) {
  93915. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93916. brword b = br->buffer[cwords] << cbits;
  93917. if(b) {
  93918. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93919. __asm {
  93920. bsr eax, b
  93921. not eax
  93922. and eax, 31
  93923. mov i, eax
  93924. }
  93925. #else
  93926. i = COUNT_ZERO_MSBS(b);
  93927. #endif
  93928. uval += i;
  93929. bits = parameter;
  93930. i++;
  93931. cbits += i;
  93932. if(cbits == FLAC__BITS_PER_WORD) {
  93933. crc16_update_word_(br, br->buffer[cwords]);
  93934. cwords++;
  93935. cbits = 0;
  93936. }
  93937. goto break1;
  93938. }
  93939. else {
  93940. uval += FLAC__BITS_PER_WORD - cbits;
  93941. crc16_update_word_(br, br->buffer[cwords]);
  93942. cwords++;
  93943. cbits = 0;
  93944. /* didn't find stop bit yet, have to keep going... */
  93945. }
  93946. }
  93947. /* at this point we've eaten up all the whole words; have to try
  93948. * reading through any tail bytes before calling the read callback.
  93949. * this is a repeat of the above logic adjusted for the fact we
  93950. * don't have a whole word. note though if the client is feeding
  93951. * us data a byte at a time (unlikely), br->consumed_bits may not
  93952. * be zero.
  93953. */
  93954. if(br->bytes) {
  93955. const unsigned end = br->bytes * 8;
  93956. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93957. if(b) {
  93958. i = COUNT_ZERO_MSBS(b);
  93959. uval += i;
  93960. bits = parameter;
  93961. i++;
  93962. cbits += i;
  93963. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93964. goto break1;
  93965. }
  93966. else {
  93967. uval += end - cbits;
  93968. cbits += end;
  93969. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93970. /* didn't find stop bit yet, have to keep going... */
  93971. }
  93972. }
  93973. /* flush registers and read; bitreader_read_from_client_() does
  93974. * not touch br->consumed_bits at all but we still need to set
  93975. * it in case it fails and we have to return false.
  93976. */
  93977. br->consumed_bits = cbits;
  93978. br->consumed_words = cwords;
  93979. if(!bitreader_read_from_client_(br))
  93980. return false;
  93981. cwords = br->consumed_words;
  93982. }
  93983. break1:
  93984. /* read binary part */
  93985. FLAC__ASSERT(cwords <= br->words);
  93986. if(bits) {
  93987. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93988. /* flush registers and read; bitreader_read_from_client_() does
  93989. * not touch br->consumed_bits at all but we still need to set
  93990. * it in case it fails and we have to return false.
  93991. */
  93992. br->consumed_bits = cbits;
  93993. br->consumed_words = cwords;
  93994. if(!bitreader_read_from_client_(br))
  93995. return false;
  93996. cwords = br->consumed_words;
  93997. }
  93998. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93999. if(cbits) {
  94000. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94001. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94002. const brword word = br->buffer[cwords];
  94003. if(bits < n) {
  94004. uval <<= bits;
  94005. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  94006. cbits += bits;
  94007. goto break2;
  94008. }
  94009. uval <<= n;
  94010. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94011. bits -= n;
  94012. crc16_update_word_(br, word);
  94013. cwords++;
  94014. cbits = 0;
  94015. 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 */
  94016. uval <<= bits;
  94017. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  94018. cbits = bits;
  94019. }
  94020. goto break2;
  94021. }
  94022. else {
  94023. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  94024. uval <<= bits;
  94025. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94026. cbits = bits;
  94027. goto break2;
  94028. }
  94029. }
  94030. else {
  94031. /* in this case we're starting our read at a partial tail word;
  94032. * the reader has guaranteed that we have at least 'bits' bits
  94033. * available to read, which makes this case simpler.
  94034. */
  94035. uval <<= bits;
  94036. if(cbits) {
  94037. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94038. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  94039. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  94040. cbits += bits;
  94041. goto break2;
  94042. }
  94043. else {
  94044. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94045. cbits += bits;
  94046. goto break2;
  94047. }
  94048. }
  94049. }
  94050. break2:
  94051. /* compose the value */
  94052. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94053. /* are we done? */
  94054. --nvals;
  94055. if(nvals == 0) {
  94056. br->consumed_bits = cbits;
  94057. br->consumed_words = cwords;
  94058. return true;
  94059. }
  94060. uval = 0;
  94061. ++vals;
  94062. }
  94063. }
  94064. #else
  94065. {
  94066. unsigned i;
  94067. unsigned uval = 0;
  94068. /* try and get br->consumed_words and br->consumed_bits into register;
  94069. * must remember to flush them back to *br before calling other
  94070. * bitwriter functions that use them, and before returning */
  94071. register unsigned cwords;
  94072. register unsigned cbits;
  94073. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  94074. FLAC__ASSERT(0 != br);
  94075. FLAC__ASSERT(0 != br->buffer);
  94076. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94077. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94078. FLAC__ASSERT(parameter < 32);
  94079. /* 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 */
  94080. if(nvals == 0)
  94081. return true;
  94082. cbits = br->consumed_bits;
  94083. cwords = br->consumed_words;
  94084. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94085. while(1) {
  94086. /* read unary part */
  94087. while(1) {
  94088. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94089. brword b = br->buffer[cwords] << cbits;
  94090. if(b) {
  94091. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  94092. asm volatile (
  94093. "bsrl %1, %0;"
  94094. "notl %0;"
  94095. "andl $31, %0;"
  94096. : "=r"(i)
  94097. : "r"(b)
  94098. );
  94099. #else
  94100. i = COUNT_ZERO_MSBS(b);
  94101. #endif
  94102. uval += i;
  94103. cbits += i;
  94104. cbits++; /* skip over stop bit */
  94105. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  94106. crc16_update_word_(br, br->buffer[cwords]);
  94107. cwords++;
  94108. cbits = 0;
  94109. }
  94110. goto break1;
  94111. }
  94112. else {
  94113. uval += FLAC__BITS_PER_WORD - cbits;
  94114. crc16_update_word_(br, br->buffer[cwords]);
  94115. cwords++;
  94116. cbits = 0;
  94117. /* didn't find stop bit yet, have to keep going... */
  94118. }
  94119. }
  94120. /* at this point we've eaten up all the whole words; have to try
  94121. * reading through any tail bytes before calling the read callback.
  94122. * this is a repeat of the above logic adjusted for the fact we
  94123. * don't have a whole word. note though if the client is feeding
  94124. * us data a byte at a time (unlikely), br->consumed_bits may not
  94125. * be zero.
  94126. */
  94127. if(br->bytes) {
  94128. const unsigned end = br->bytes * 8;
  94129. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  94130. if(b) {
  94131. i = COUNT_ZERO_MSBS(b);
  94132. uval += i;
  94133. cbits += i;
  94134. cbits++; /* skip over stop bit */
  94135. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94136. goto break1;
  94137. }
  94138. else {
  94139. uval += end - cbits;
  94140. cbits += end;
  94141. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94142. /* didn't find stop bit yet, have to keep going... */
  94143. }
  94144. }
  94145. /* flush registers and read; bitreader_read_from_client_() does
  94146. * not touch br->consumed_bits at all but we still need to set
  94147. * it in case it fails and we have to return false.
  94148. */
  94149. br->consumed_bits = cbits;
  94150. br->consumed_words = cwords;
  94151. if(!bitreader_read_from_client_(br))
  94152. return false;
  94153. cwords = br->consumed_words;
  94154. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  94155. /* + uval to offset our count by the # of unary bits already
  94156. * consumed before the read, because we will add these back
  94157. * in all at once at break1
  94158. */
  94159. }
  94160. break1:
  94161. ucbits -= uval;
  94162. ucbits--; /* account for stop bit */
  94163. /* read binary part */
  94164. FLAC__ASSERT(cwords <= br->words);
  94165. if(parameter) {
  94166. while(ucbits < parameter) {
  94167. /* flush registers and read; bitreader_read_from_client_() does
  94168. * not touch br->consumed_bits at all but we still need to set
  94169. * it in case it fails and we have to return false.
  94170. */
  94171. br->consumed_bits = cbits;
  94172. br->consumed_words = cwords;
  94173. if(!bitreader_read_from_client_(br))
  94174. return false;
  94175. cwords = br->consumed_words;
  94176. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94177. }
  94178. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94179. if(cbits) {
  94180. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94181. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94182. const brword word = br->buffer[cwords];
  94183. if(parameter < n) {
  94184. uval <<= parameter;
  94185. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94186. cbits += parameter;
  94187. }
  94188. else {
  94189. uval <<= n;
  94190. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94191. crc16_update_word_(br, word);
  94192. cwords++;
  94193. cbits = parameter - n;
  94194. 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 */
  94195. uval <<= cbits;
  94196. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94197. }
  94198. }
  94199. }
  94200. else {
  94201. cbits = parameter;
  94202. uval <<= parameter;
  94203. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94204. }
  94205. }
  94206. else {
  94207. /* in this case we're starting our read at a partial tail word;
  94208. * the reader has guaranteed that we have at least 'parameter'
  94209. * bits available to read, which makes this case simpler.
  94210. */
  94211. uval <<= parameter;
  94212. if(cbits) {
  94213. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94214. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94215. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94216. cbits += parameter;
  94217. }
  94218. else {
  94219. cbits = parameter;
  94220. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94221. }
  94222. }
  94223. }
  94224. ucbits -= parameter;
  94225. /* compose the value */
  94226. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94227. /* are we done? */
  94228. --nvals;
  94229. if(nvals == 0) {
  94230. br->consumed_bits = cbits;
  94231. br->consumed_words = cwords;
  94232. return true;
  94233. }
  94234. uval = 0;
  94235. ++vals;
  94236. }
  94237. }
  94238. #endif
  94239. #if 0 /* UNUSED */
  94240. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94241. {
  94242. FLAC__uint32 lsbs = 0, msbs = 0;
  94243. unsigned bit, uval, k;
  94244. FLAC__ASSERT(0 != br);
  94245. FLAC__ASSERT(0 != br->buffer);
  94246. k = FLAC__bitmath_ilog2(parameter);
  94247. /* read the unary MSBs and end bit */
  94248. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94249. return false;
  94250. /* read the binary LSBs */
  94251. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94252. return false;
  94253. if(parameter == 1u<<k) {
  94254. /* compose the value */
  94255. uval = (msbs << k) | lsbs;
  94256. }
  94257. else {
  94258. unsigned d = (1 << (k+1)) - parameter;
  94259. if(lsbs >= d) {
  94260. if(!FLAC__bitreader_read_bit(br, &bit))
  94261. return false;
  94262. lsbs <<= 1;
  94263. lsbs |= bit;
  94264. lsbs -= d;
  94265. }
  94266. /* compose the value */
  94267. uval = msbs * parameter + lsbs;
  94268. }
  94269. /* unfold unsigned to signed */
  94270. if(uval & 1)
  94271. *val = -((int)(uval >> 1)) - 1;
  94272. else
  94273. *val = (int)(uval >> 1);
  94274. return true;
  94275. }
  94276. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94277. {
  94278. FLAC__uint32 lsbs, msbs = 0;
  94279. unsigned bit, k;
  94280. FLAC__ASSERT(0 != br);
  94281. FLAC__ASSERT(0 != br->buffer);
  94282. k = FLAC__bitmath_ilog2(parameter);
  94283. /* read the unary MSBs and end bit */
  94284. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94285. return false;
  94286. /* read the binary LSBs */
  94287. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94288. return false;
  94289. if(parameter == 1u<<k) {
  94290. /* compose the value */
  94291. *val = (msbs << k) | lsbs;
  94292. }
  94293. else {
  94294. unsigned d = (1 << (k+1)) - parameter;
  94295. if(lsbs >= d) {
  94296. if(!FLAC__bitreader_read_bit(br, &bit))
  94297. return false;
  94298. lsbs <<= 1;
  94299. lsbs |= bit;
  94300. lsbs -= d;
  94301. }
  94302. /* compose the value */
  94303. *val = msbs * parameter + lsbs;
  94304. }
  94305. return true;
  94306. }
  94307. #endif /* UNUSED */
  94308. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94309. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94310. {
  94311. FLAC__uint32 v = 0;
  94312. FLAC__uint32 x;
  94313. unsigned i;
  94314. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94315. return false;
  94316. if(raw)
  94317. raw[(*rawlen)++] = (FLAC__byte)x;
  94318. if(!(x & 0x80)) { /* 0xxxxxxx */
  94319. v = x;
  94320. i = 0;
  94321. }
  94322. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94323. v = x & 0x1F;
  94324. i = 1;
  94325. }
  94326. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94327. v = x & 0x0F;
  94328. i = 2;
  94329. }
  94330. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94331. v = x & 0x07;
  94332. i = 3;
  94333. }
  94334. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94335. v = x & 0x03;
  94336. i = 4;
  94337. }
  94338. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94339. v = x & 0x01;
  94340. i = 5;
  94341. }
  94342. else {
  94343. *val = 0xffffffff;
  94344. return true;
  94345. }
  94346. for( ; i; i--) {
  94347. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94348. return false;
  94349. if(raw)
  94350. raw[(*rawlen)++] = (FLAC__byte)x;
  94351. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94352. *val = 0xffffffff;
  94353. return true;
  94354. }
  94355. v <<= 6;
  94356. v |= (x & 0x3F);
  94357. }
  94358. *val = v;
  94359. return true;
  94360. }
  94361. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94362. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94363. {
  94364. FLAC__uint64 v = 0;
  94365. FLAC__uint32 x;
  94366. unsigned i;
  94367. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94368. return false;
  94369. if(raw)
  94370. raw[(*rawlen)++] = (FLAC__byte)x;
  94371. if(!(x & 0x80)) { /* 0xxxxxxx */
  94372. v = x;
  94373. i = 0;
  94374. }
  94375. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94376. v = x & 0x1F;
  94377. i = 1;
  94378. }
  94379. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94380. v = x & 0x0F;
  94381. i = 2;
  94382. }
  94383. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94384. v = x & 0x07;
  94385. i = 3;
  94386. }
  94387. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94388. v = x & 0x03;
  94389. i = 4;
  94390. }
  94391. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94392. v = x & 0x01;
  94393. i = 5;
  94394. }
  94395. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94396. v = 0;
  94397. i = 6;
  94398. }
  94399. else {
  94400. *val = FLAC__U64L(0xffffffffffffffff);
  94401. return true;
  94402. }
  94403. for( ; i; i--) {
  94404. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94405. return false;
  94406. if(raw)
  94407. raw[(*rawlen)++] = (FLAC__byte)x;
  94408. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94409. *val = FLAC__U64L(0xffffffffffffffff);
  94410. return true;
  94411. }
  94412. v <<= 6;
  94413. v |= (x & 0x3F);
  94414. }
  94415. *val = v;
  94416. return true;
  94417. }
  94418. #endif
  94419. /*** End of inlined file: bitreader.c ***/
  94420. /*** Start of inlined file: bitwriter.c ***/
  94421. /*** Start of inlined file: juce_FlacHeader.h ***/
  94422. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94423. // tasks..
  94424. #define VERSION "1.2.1"
  94425. #define FLAC__NO_DLL 1
  94426. #if JUCE_MSVC
  94427. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94428. #endif
  94429. #if JUCE_MAC
  94430. #define FLAC__SYS_DARWIN 1
  94431. #endif
  94432. /*** End of inlined file: juce_FlacHeader.h ***/
  94433. #if JUCE_USE_FLAC
  94434. #if HAVE_CONFIG_H
  94435. # include <config.h>
  94436. #endif
  94437. #include <stdlib.h> /* for malloc() */
  94438. #include <string.h> /* for memcpy(), memset() */
  94439. #ifdef _MSC_VER
  94440. #include <winsock.h> /* for ntohl() */
  94441. #elif defined FLAC__SYS_DARWIN
  94442. #include <machine/endian.h> /* for ntohl() */
  94443. #elif defined __MINGW32__
  94444. #include <winsock.h> /* for ntohl() */
  94445. #else
  94446. #include <netinet/in.h> /* for ntohl() */
  94447. #endif
  94448. #if 0 /* UNUSED */
  94449. #endif
  94450. /*** Start of inlined file: bitwriter.h ***/
  94451. #ifndef FLAC__PRIVATE__BITWRITER_H
  94452. #define FLAC__PRIVATE__BITWRITER_H
  94453. #include <stdio.h> /* for FILE */
  94454. /*
  94455. * opaque structure definition
  94456. */
  94457. struct FLAC__BitWriter;
  94458. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94459. /*
  94460. * construction, deletion, initialization, etc functions
  94461. */
  94462. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94463. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94464. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94465. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94466. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94467. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94468. /*
  94469. * CRC functions
  94470. *
  94471. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94472. */
  94473. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94474. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94475. /*
  94476. * info functions
  94477. */
  94478. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94479. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94480. /*
  94481. * direct buffer access
  94482. *
  94483. * there may be no calls on the bitwriter between get and release.
  94484. * the bitwriter continues to own the returned buffer.
  94485. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94486. */
  94487. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94488. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94489. /*
  94490. * write functions
  94491. */
  94492. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94493. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94494. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94495. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94496. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94497. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94498. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94499. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94500. #if 0 /* UNUSED */
  94501. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94502. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94503. #endif
  94504. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94505. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94506. #if 0 /* UNUSED */
  94507. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94508. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94509. #endif
  94510. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94511. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94512. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94513. #endif
  94514. /*** End of inlined file: bitwriter.h ***/
  94515. /*** Start of inlined file: alloc.h ***/
  94516. #ifndef FLAC__SHARE__ALLOC_H
  94517. #define FLAC__SHARE__ALLOC_H
  94518. #if HAVE_CONFIG_H
  94519. # include <config.h>
  94520. #endif
  94521. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94522. * before #including this file, otherwise SIZE_MAX might not be defined
  94523. */
  94524. #include <limits.h> /* for SIZE_MAX */
  94525. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94526. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94527. #endif
  94528. #include <stdlib.h> /* for size_t, malloc(), etc */
  94529. #ifndef SIZE_MAX
  94530. # ifndef SIZE_T_MAX
  94531. # ifdef _MSC_VER
  94532. # define SIZE_T_MAX UINT_MAX
  94533. # else
  94534. # error
  94535. # endif
  94536. # endif
  94537. # define SIZE_MAX SIZE_T_MAX
  94538. #endif
  94539. #ifndef FLaC__INLINE
  94540. #define FLaC__INLINE
  94541. #endif
  94542. /* avoid malloc()ing 0 bytes, see:
  94543. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94544. */
  94545. static FLaC__INLINE void *safe_malloc_(size_t size)
  94546. {
  94547. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94548. if(!size)
  94549. size++;
  94550. return malloc(size);
  94551. }
  94552. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94553. {
  94554. if(!nmemb || !size)
  94555. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94556. return calloc(nmemb, size);
  94557. }
  94558. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94559. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94560. {
  94561. size2 += size1;
  94562. if(size2 < size1)
  94563. return 0;
  94564. return safe_malloc_(size2);
  94565. }
  94566. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94567. {
  94568. size2 += size1;
  94569. if(size2 < size1)
  94570. return 0;
  94571. size3 += size2;
  94572. if(size3 < size2)
  94573. return 0;
  94574. return safe_malloc_(size3);
  94575. }
  94576. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94577. {
  94578. size2 += size1;
  94579. if(size2 < size1)
  94580. return 0;
  94581. size3 += size2;
  94582. if(size3 < size2)
  94583. return 0;
  94584. size4 += size3;
  94585. if(size4 < size3)
  94586. return 0;
  94587. return safe_malloc_(size4);
  94588. }
  94589. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94590. #if 0
  94591. needs support for cases where sizeof(size_t) != 4
  94592. {
  94593. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94594. if(sizeof(size_t) == 4) {
  94595. if ((double)size1 * (double)size2 < 4294967296.0)
  94596. return malloc(size1*size2);
  94597. }
  94598. return 0;
  94599. }
  94600. #else
  94601. /* better? */
  94602. {
  94603. if(!size1 || !size2)
  94604. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94605. if(size1 > SIZE_MAX / size2)
  94606. return 0;
  94607. return malloc(size1*size2);
  94608. }
  94609. #endif
  94610. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94611. {
  94612. if(!size1 || !size2 || !size3)
  94613. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94614. if(size1 > SIZE_MAX / size2)
  94615. return 0;
  94616. size1 *= size2;
  94617. if(size1 > SIZE_MAX / size3)
  94618. return 0;
  94619. return malloc(size1*size3);
  94620. }
  94621. /* size1*size2 + size3 */
  94622. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94623. {
  94624. if(!size1 || !size2)
  94625. return safe_malloc_(size3);
  94626. if(size1 > SIZE_MAX / size2)
  94627. return 0;
  94628. return safe_malloc_add_2op_(size1*size2, size3);
  94629. }
  94630. /* size1 * (size2 + size3) */
  94631. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94632. {
  94633. if(!size1 || (!size2 && !size3))
  94634. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94635. size2 += size3;
  94636. if(size2 < size3)
  94637. return 0;
  94638. return safe_malloc_mul_2op_(size1, size2);
  94639. }
  94640. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94641. {
  94642. size2 += size1;
  94643. if(size2 < size1)
  94644. return 0;
  94645. return realloc(ptr, size2);
  94646. }
  94647. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94648. {
  94649. size2 += size1;
  94650. if(size2 < size1)
  94651. return 0;
  94652. size3 += size2;
  94653. if(size3 < size2)
  94654. return 0;
  94655. return realloc(ptr, size3);
  94656. }
  94657. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94658. {
  94659. size2 += size1;
  94660. if(size2 < size1)
  94661. return 0;
  94662. size3 += size2;
  94663. if(size3 < size2)
  94664. return 0;
  94665. size4 += size3;
  94666. if(size4 < size3)
  94667. return 0;
  94668. return realloc(ptr, size4);
  94669. }
  94670. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94671. {
  94672. if(!size1 || !size2)
  94673. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94674. if(size1 > SIZE_MAX / size2)
  94675. return 0;
  94676. return realloc(ptr, size1*size2);
  94677. }
  94678. /* size1 * (size2 + size3) */
  94679. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94680. {
  94681. if(!size1 || (!size2 && !size3))
  94682. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94683. size2 += size3;
  94684. if(size2 < size3)
  94685. return 0;
  94686. return safe_realloc_mul_2op_(ptr, size1, size2);
  94687. }
  94688. #endif
  94689. /*** End of inlined file: alloc.h ***/
  94690. /* Things should be fastest when this matches the machine word size */
  94691. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94692. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94693. typedef FLAC__uint32 bwword;
  94694. #define FLAC__BYTES_PER_WORD 4
  94695. #define FLAC__BITS_PER_WORD 32
  94696. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94697. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94698. #if WORDS_BIGENDIAN
  94699. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94700. #else
  94701. #ifdef _MSC_VER
  94702. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94703. #else
  94704. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94705. #endif
  94706. #endif
  94707. /*
  94708. * The default capacity here doesn't matter too much. The buffer always grows
  94709. * to hold whatever is written to it. Usually the encoder will stop adding at
  94710. * a frame or metadata block, then write that out and clear the buffer for the
  94711. * next one.
  94712. */
  94713. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94714. /* When growing, increment 4K at a time */
  94715. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94716. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94717. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94718. #ifdef min
  94719. #undef min
  94720. #endif
  94721. #define min(x,y) ((x)<(y)?(x):(y))
  94722. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94723. #ifdef _MSC_VER
  94724. #define FLAC__U64L(x) x
  94725. #else
  94726. #define FLAC__U64L(x) x##LLU
  94727. #endif
  94728. #ifndef FLaC__INLINE
  94729. #define FLaC__INLINE
  94730. #endif
  94731. struct FLAC__BitWriter {
  94732. bwword *buffer;
  94733. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94734. unsigned capacity; /* capacity of buffer in words */
  94735. unsigned words; /* # of complete words in buffer */
  94736. unsigned bits; /* # of used bits in accum */
  94737. };
  94738. /* * WATCHOUT: The current implementation only grows the buffer. */
  94739. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94740. {
  94741. unsigned new_capacity;
  94742. bwword *new_buffer;
  94743. FLAC__ASSERT(0 != bw);
  94744. FLAC__ASSERT(0 != bw->buffer);
  94745. /* calculate total words needed to store 'bits_to_add' additional bits */
  94746. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94747. /* it's possible (due to pessimism in the growth estimation that
  94748. * leads to this call) that we don't actually need to grow
  94749. */
  94750. if(bw->capacity >= new_capacity)
  94751. return true;
  94752. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94753. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94754. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94755. /* make sure we got everything right */
  94756. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94757. FLAC__ASSERT(new_capacity > bw->capacity);
  94758. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94759. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94760. if(new_buffer == 0)
  94761. return false;
  94762. bw->buffer = new_buffer;
  94763. bw->capacity = new_capacity;
  94764. return true;
  94765. }
  94766. /***********************************************************************
  94767. *
  94768. * Class constructor/destructor
  94769. *
  94770. ***********************************************************************/
  94771. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94772. {
  94773. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94774. /* note that calloc() sets all members to 0 for us */
  94775. return bw;
  94776. }
  94777. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94778. {
  94779. FLAC__ASSERT(0 != bw);
  94780. FLAC__bitwriter_free(bw);
  94781. free(bw);
  94782. }
  94783. /***********************************************************************
  94784. *
  94785. * Public class methods
  94786. *
  94787. ***********************************************************************/
  94788. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94789. {
  94790. FLAC__ASSERT(0 != bw);
  94791. bw->words = bw->bits = 0;
  94792. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94793. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94794. if(bw->buffer == 0)
  94795. return false;
  94796. return true;
  94797. }
  94798. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94799. {
  94800. FLAC__ASSERT(0 != bw);
  94801. if(0 != bw->buffer)
  94802. free(bw->buffer);
  94803. bw->buffer = 0;
  94804. bw->capacity = 0;
  94805. bw->words = bw->bits = 0;
  94806. }
  94807. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94808. {
  94809. bw->words = bw->bits = 0;
  94810. }
  94811. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94812. {
  94813. unsigned i, j;
  94814. if(bw == 0) {
  94815. fprintf(out, "bitwriter is NULL\n");
  94816. }
  94817. else {
  94818. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94819. for(i = 0; i < bw->words; i++) {
  94820. fprintf(out, "%08X: ", i);
  94821. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94822. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94823. fprintf(out, "\n");
  94824. }
  94825. if(bw->bits > 0) {
  94826. fprintf(out, "%08X: ", i);
  94827. for(j = 0; j < bw->bits; j++)
  94828. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94829. fprintf(out, "\n");
  94830. }
  94831. }
  94832. }
  94833. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94834. {
  94835. const FLAC__byte *buffer;
  94836. size_t bytes;
  94837. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94838. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94839. return false;
  94840. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94841. FLAC__bitwriter_release_buffer(bw);
  94842. return true;
  94843. }
  94844. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94845. {
  94846. const FLAC__byte *buffer;
  94847. size_t bytes;
  94848. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94849. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94850. return false;
  94851. *crc = FLAC__crc8(buffer, bytes);
  94852. FLAC__bitwriter_release_buffer(bw);
  94853. return true;
  94854. }
  94855. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94856. {
  94857. return ((bw->bits & 7) == 0);
  94858. }
  94859. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94860. {
  94861. return FLAC__TOTAL_BITS(bw);
  94862. }
  94863. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94864. {
  94865. FLAC__ASSERT((bw->bits & 7) == 0);
  94866. /* double protection */
  94867. if(bw->bits & 7)
  94868. return false;
  94869. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94870. if(bw->bits) {
  94871. FLAC__ASSERT(bw->words <= bw->capacity);
  94872. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94873. return false;
  94874. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94875. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94876. }
  94877. /* now we can just return what we have */
  94878. *buffer = (FLAC__byte*)bw->buffer;
  94879. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94880. return true;
  94881. }
  94882. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94883. {
  94884. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94885. * get-mode' flag could be added everywhere and then cleared here
  94886. */
  94887. (void)bw;
  94888. }
  94889. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94890. {
  94891. unsigned n;
  94892. FLAC__ASSERT(0 != bw);
  94893. FLAC__ASSERT(0 != bw->buffer);
  94894. if(bits == 0)
  94895. return true;
  94896. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94897. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94898. return false;
  94899. /* first part gets to word alignment */
  94900. if(bw->bits) {
  94901. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94902. bw->accum <<= n;
  94903. bits -= n;
  94904. bw->bits += n;
  94905. if(bw->bits == FLAC__BITS_PER_WORD) {
  94906. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94907. bw->bits = 0;
  94908. }
  94909. else
  94910. return true;
  94911. }
  94912. /* do whole words */
  94913. while(bits >= FLAC__BITS_PER_WORD) {
  94914. bw->buffer[bw->words++] = 0;
  94915. bits -= FLAC__BITS_PER_WORD;
  94916. }
  94917. /* do any leftovers */
  94918. if(bits > 0) {
  94919. bw->accum = 0;
  94920. bw->bits = bits;
  94921. }
  94922. return true;
  94923. }
  94924. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94925. {
  94926. register unsigned left;
  94927. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94928. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94929. FLAC__ASSERT(0 != bw);
  94930. FLAC__ASSERT(0 != bw->buffer);
  94931. FLAC__ASSERT(bits <= 32);
  94932. if(bits == 0)
  94933. return true;
  94934. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94935. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94936. return false;
  94937. left = FLAC__BITS_PER_WORD - bw->bits;
  94938. if(bits < left) {
  94939. bw->accum <<= bits;
  94940. bw->accum |= val;
  94941. bw->bits += bits;
  94942. }
  94943. 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 */
  94944. bw->accum <<= left;
  94945. bw->accum |= val >> (bw->bits = bits - left);
  94946. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94947. bw->accum = val;
  94948. }
  94949. else {
  94950. bw->accum = val;
  94951. bw->bits = 0;
  94952. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94953. }
  94954. return true;
  94955. }
  94956. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94957. {
  94958. /* zero-out unused bits */
  94959. if(bits < 32)
  94960. val &= (~(0xffffffff << bits));
  94961. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94962. }
  94963. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94964. {
  94965. /* this could be a little faster but it's not used for much */
  94966. if(bits > 32) {
  94967. return
  94968. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94969. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94970. }
  94971. else
  94972. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94973. }
  94974. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94975. {
  94976. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94977. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94978. return false;
  94979. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94980. return false;
  94981. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94982. return false;
  94983. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94984. return false;
  94985. return true;
  94986. }
  94987. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94988. {
  94989. unsigned i;
  94990. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94991. for(i = 0; i < nvals; i++) {
  94992. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94993. return false;
  94994. }
  94995. return true;
  94996. }
  94997. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94998. {
  94999. if(val < 32)
  95000. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  95001. else
  95002. return
  95003. FLAC__bitwriter_write_zeroes(bw, val) &&
  95004. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  95005. }
  95006. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  95007. {
  95008. FLAC__uint32 uval;
  95009. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  95010. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95011. uval = (val<<1) ^ (val>>31);
  95012. return 1 + parameter + (uval >> parameter);
  95013. }
  95014. #if 0 /* UNUSED */
  95015. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  95016. {
  95017. unsigned bits, msbs, uval;
  95018. unsigned k;
  95019. FLAC__ASSERT(parameter > 0);
  95020. /* fold signed to unsigned */
  95021. if(val < 0)
  95022. uval = (unsigned)(((-(++val)) << 1) + 1);
  95023. else
  95024. uval = (unsigned)(val << 1);
  95025. k = FLAC__bitmath_ilog2(parameter);
  95026. if(parameter == 1u<<k) {
  95027. FLAC__ASSERT(k <= 30);
  95028. msbs = uval >> k;
  95029. bits = 1 + k + msbs;
  95030. }
  95031. else {
  95032. unsigned q, r, d;
  95033. d = (1 << (k+1)) - parameter;
  95034. q = uval / parameter;
  95035. r = uval - (q * parameter);
  95036. bits = 1 + q + k;
  95037. if(r >= d)
  95038. bits++;
  95039. }
  95040. return bits;
  95041. }
  95042. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  95043. {
  95044. unsigned bits, msbs;
  95045. unsigned k;
  95046. FLAC__ASSERT(parameter > 0);
  95047. k = FLAC__bitmath_ilog2(parameter);
  95048. if(parameter == 1u<<k) {
  95049. FLAC__ASSERT(k <= 30);
  95050. msbs = uval >> k;
  95051. bits = 1 + k + msbs;
  95052. }
  95053. else {
  95054. unsigned q, r, d;
  95055. d = (1 << (k+1)) - parameter;
  95056. q = uval / parameter;
  95057. r = uval - (q * parameter);
  95058. bits = 1 + q + k;
  95059. if(r >= d)
  95060. bits++;
  95061. }
  95062. return bits;
  95063. }
  95064. #endif /* UNUSED */
  95065. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  95066. {
  95067. unsigned total_bits, interesting_bits, msbs;
  95068. FLAC__uint32 uval, pattern;
  95069. FLAC__ASSERT(0 != bw);
  95070. FLAC__ASSERT(0 != bw->buffer);
  95071. FLAC__ASSERT(parameter < 8*sizeof(uval));
  95072. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95073. uval = (val<<1) ^ (val>>31);
  95074. msbs = uval >> parameter;
  95075. interesting_bits = 1 + parameter;
  95076. total_bits = interesting_bits + msbs;
  95077. pattern = 1 << parameter; /* the unary end bit */
  95078. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  95079. if(total_bits <= 32)
  95080. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  95081. else
  95082. return
  95083. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  95084. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  95085. }
  95086. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  95087. {
  95088. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  95089. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  95090. FLAC__uint32 uval;
  95091. unsigned left;
  95092. const unsigned lsbits = 1 + parameter;
  95093. unsigned msbits;
  95094. FLAC__ASSERT(0 != bw);
  95095. FLAC__ASSERT(0 != bw->buffer);
  95096. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  95097. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  95098. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  95099. while(nvals) {
  95100. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95101. uval = (*vals<<1) ^ (*vals>>31);
  95102. msbits = uval >> parameter;
  95103. #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) */
  95104. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95105. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95106. bw->bits = bw->bits + msbits + lsbits;
  95107. uval |= mask1; /* set stop bit */
  95108. uval &= mask2; /* mask off unused top bits */
  95109. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  95110. bw->accum <<= msbits;
  95111. bw->accum <<= lsbits;
  95112. bw->accum |= uval;
  95113. if(bw->bits == FLAC__BITS_PER_WORD) {
  95114. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95115. bw->bits = 0;
  95116. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  95117. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  95118. FLAC__ASSERT(bw->capacity == bw->words);
  95119. return false;
  95120. }
  95121. }
  95122. }
  95123. else {
  95124. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  95125. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95126. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95127. bw->bits = bw->bits + msbits + lsbits;
  95128. uval |= mask1; /* set stop bit */
  95129. uval &= mask2; /* mask off unused top bits */
  95130. bw->accum <<= msbits + lsbits;
  95131. bw->accum |= uval;
  95132. }
  95133. else {
  95134. #endif
  95135. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  95136. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  95137. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  95138. return false;
  95139. if(msbits) {
  95140. /* first part gets to word alignment */
  95141. if(bw->bits) {
  95142. left = FLAC__BITS_PER_WORD - bw->bits;
  95143. if(msbits < left) {
  95144. bw->accum <<= msbits;
  95145. bw->bits += msbits;
  95146. goto break1;
  95147. }
  95148. else {
  95149. bw->accum <<= left;
  95150. msbits -= left;
  95151. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95152. bw->bits = 0;
  95153. }
  95154. }
  95155. /* do whole words */
  95156. while(msbits >= FLAC__BITS_PER_WORD) {
  95157. bw->buffer[bw->words++] = 0;
  95158. msbits -= FLAC__BITS_PER_WORD;
  95159. }
  95160. /* do any leftovers */
  95161. if(msbits > 0) {
  95162. bw->accum = 0;
  95163. bw->bits = msbits;
  95164. }
  95165. }
  95166. break1:
  95167. uval |= mask1; /* set stop bit */
  95168. uval &= mask2; /* mask off unused top bits */
  95169. left = FLAC__BITS_PER_WORD - bw->bits;
  95170. if(lsbits < left) {
  95171. bw->accum <<= lsbits;
  95172. bw->accum |= uval;
  95173. bw->bits += lsbits;
  95174. }
  95175. else {
  95176. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95177. * be > lsbits (because of previous assertions) so it would have
  95178. * triggered the (lsbits<left) case above.
  95179. */
  95180. FLAC__ASSERT(bw->bits);
  95181. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95182. bw->accum <<= left;
  95183. bw->accum |= uval >> (bw->bits = lsbits - left);
  95184. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95185. bw->accum = uval;
  95186. }
  95187. #if 1
  95188. }
  95189. #endif
  95190. vals++;
  95191. nvals--;
  95192. }
  95193. return true;
  95194. }
  95195. #if 0 /* UNUSED */
  95196. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95197. {
  95198. unsigned total_bits, msbs, uval;
  95199. unsigned k;
  95200. FLAC__ASSERT(0 != bw);
  95201. FLAC__ASSERT(0 != bw->buffer);
  95202. FLAC__ASSERT(parameter > 0);
  95203. /* fold signed to unsigned */
  95204. if(val < 0)
  95205. uval = (unsigned)(((-(++val)) << 1) + 1);
  95206. else
  95207. uval = (unsigned)(val << 1);
  95208. k = FLAC__bitmath_ilog2(parameter);
  95209. if(parameter == 1u<<k) {
  95210. unsigned pattern;
  95211. FLAC__ASSERT(k <= 30);
  95212. msbs = uval >> k;
  95213. total_bits = 1 + k + msbs;
  95214. pattern = 1 << k; /* the unary end bit */
  95215. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95216. if(total_bits <= 32) {
  95217. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95218. return false;
  95219. }
  95220. else {
  95221. /* write the unary MSBs */
  95222. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95223. return false;
  95224. /* write the unary end bit and binary LSBs */
  95225. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95226. return false;
  95227. }
  95228. }
  95229. else {
  95230. unsigned q, r, d;
  95231. d = (1 << (k+1)) - parameter;
  95232. q = uval / parameter;
  95233. r = uval - (q * parameter);
  95234. /* write the unary MSBs */
  95235. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95236. return false;
  95237. /* write the unary end bit */
  95238. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95239. return false;
  95240. /* write the binary LSBs */
  95241. if(r >= d) {
  95242. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95243. return false;
  95244. }
  95245. else {
  95246. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95247. return false;
  95248. }
  95249. }
  95250. return true;
  95251. }
  95252. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95253. {
  95254. unsigned total_bits, msbs;
  95255. unsigned k;
  95256. FLAC__ASSERT(0 != bw);
  95257. FLAC__ASSERT(0 != bw->buffer);
  95258. FLAC__ASSERT(parameter > 0);
  95259. k = FLAC__bitmath_ilog2(parameter);
  95260. if(parameter == 1u<<k) {
  95261. unsigned pattern;
  95262. FLAC__ASSERT(k <= 30);
  95263. msbs = uval >> k;
  95264. total_bits = 1 + k + msbs;
  95265. pattern = 1 << k; /* the unary end bit */
  95266. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95267. if(total_bits <= 32) {
  95268. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95269. return false;
  95270. }
  95271. else {
  95272. /* write the unary MSBs */
  95273. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95274. return false;
  95275. /* write the unary end bit and binary LSBs */
  95276. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95277. return false;
  95278. }
  95279. }
  95280. else {
  95281. unsigned q, r, d;
  95282. d = (1 << (k+1)) - parameter;
  95283. q = uval / parameter;
  95284. r = uval - (q * parameter);
  95285. /* write the unary MSBs */
  95286. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95287. return false;
  95288. /* write the unary end bit */
  95289. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95290. return false;
  95291. /* write the binary LSBs */
  95292. if(r >= d) {
  95293. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95294. return false;
  95295. }
  95296. else {
  95297. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95298. return false;
  95299. }
  95300. }
  95301. return true;
  95302. }
  95303. #endif /* UNUSED */
  95304. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95305. {
  95306. FLAC__bool ok = 1;
  95307. FLAC__ASSERT(0 != bw);
  95308. FLAC__ASSERT(0 != bw->buffer);
  95309. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95310. if(val < 0x80) {
  95311. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95312. }
  95313. else if(val < 0x800) {
  95314. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95315. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95316. }
  95317. else if(val < 0x10000) {
  95318. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95319. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95320. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95321. }
  95322. else if(val < 0x200000) {
  95323. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95324. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95325. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95326. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95327. }
  95328. else if(val < 0x4000000) {
  95329. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95330. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95331. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95332. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95333. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95334. }
  95335. else {
  95336. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95337. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95338. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95339. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95340. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95341. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95342. }
  95343. return ok;
  95344. }
  95345. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95346. {
  95347. FLAC__bool ok = 1;
  95348. FLAC__ASSERT(0 != bw);
  95349. FLAC__ASSERT(0 != bw->buffer);
  95350. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95351. if(val < 0x80) {
  95352. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95353. }
  95354. else if(val < 0x800) {
  95355. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95356. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95357. }
  95358. else if(val < 0x10000) {
  95359. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95360. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95361. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95362. }
  95363. else if(val < 0x200000) {
  95364. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95365. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95366. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95367. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95368. }
  95369. else if(val < 0x4000000) {
  95370. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95371. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95372. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95373. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95374. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95375. }
  95376. else if(val < 0x80000000) {
  95377. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95378. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95379. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95380. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95381. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95382. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95383. }
  95384. else {
  95385. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95386. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95387. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95388. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95389. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95390. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95391. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95392. }
  95393. return ok;
  95394. }
  95395. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95396. {
  95397. /* 0-pad to byte boundary */
  95398. if(bw->bits & 7u)
  95399. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95400. else
  95401. return true;
  95402. }
  95403. #endif
  95404. /*** End of inlined file: bitwriter.c ***/
  95405. /*** Start of inlined file: cpu.c ***/
  95406. /*** Start of inlined file: juce_FlacHeader.h ***/
  95407. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95408. // tasks..
  95409. #define VERSION "1.2.1"
  95410. #define FLAC__NO_DLL 1
  95411. #if JUCE_MSVC
  95412. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95413. #endif
  95414. #if JUCE_MAC
  95415. #define FLAC__SYS_DARWIN 1
  95416. #endif
  95417. /*** End of inlined file: juce_FlacHeader.h ***/
  95418. #if JUCE_USE_FLAC
  95419. #if HAVE_CONFIG_H
  95420. # include <config.h>
  95421. #endif
  95422. #include <stdlib.h>
  95423. #include <stdio.h>
  95424. #if defined FLAC__CPU_IA32
  95425. # include <signal.h>
  95426. #elif defined FLAC__CPU_PPC
  95427. # if !defined FLAC__NO_ASM
  95428. # if defined FLAC__SYS_DARWIN
  95429. # include <sys/sysctl.h>
  95430. # include <mach/mach.h>
  95431. # include <mach/mach_host.h>
  95432. # include <mach/host_info.h>
  95433. # include <mach/machine.h>
  95434. # ifndef CPU_SUBTYPE_POWERPC_970
  95435. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95436. # endif
  95437. # else /* FLAC__SYS_DARWIN */
  95438. # include <signal.h>
  95439. # include <setjmp.h>
  95440. static sigjmp_buf jmpbuf;
  95441. static volatile sig_atomic_t canjump = 0;
  95442. static void sigill_handler (int sig)
  95443. {
  95444. if (!canjump) {
  95445. signal (sig, SIG_DFL);
  95446. raise (sig);
  95447. }
  95448. canjump = 0;
  95449. siglongjmp (jmpbuf, 1);
  95450. }
  95451. # endif /* FLAC__SYS_DARWIN */
  95452. # endif /* FLAC__NO_ASM */
  95453. #endif /* FLAC__CPU_PPC */
  95454. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95455. #include <sys/param.h>
  95456. #include <sys/sysctl.h>
  95457. #include <machine/cpu.h>
  95458. #endif
  95459. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95460. #include <sys/types.h>
  95461. #include <sys/sysctl.h>
  95462. #endif
  95463. #if defined(__APPLE__)
  95464. /* how to get sysctlbyname()? */
  95465. #endif
  95466. /* these are flags in EDX of CPUID AX=00000001 */
  95467. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95468. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95469. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95470. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95471. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95472. /* these are flags in ECX of CPUID AX=00000001 */
  95473. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95474. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95475. /* these are flags in EDX of CPUID AX=80000001 */
  95476. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95477. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95478. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95479. /*
  95480. * Extra stuff needed for detection of OS support for SSE on IA-32
  95481. */
  95482. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95483. # if defined(__linux__)
  95484. /*
  95485. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95486. * modify the return address to jump over the offending SSE instruction
  95487. * and also the operation following it that indicates the instruction
  95488. * executed successfully. In this way we use no global variables and
  95489. * stay thread-safe.
  95490. *
  95491. * 3 + 3 + 6:
  95492. * 3 bytes for "xorps xmm0,xmm0"
  95493. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95494. * 6 bytes extra in case our estimate is wrong
  95495. * 12 bytes puts us in the NOP "landing zone"
  95496. */
  95497. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95498. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95499. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95500. {
  95501. (void)signal;
  95502. sc.eip += 3 + 3 + 6;
  95503. }
  95504. # else
  95505. # include <sys/ucontext.h>
  95506. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95507. {
  95508. (void)signal, (void)si;
  95509. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95510. }
  95511. # endif
  95512. # elif defined(_MSC_VER)
  95513. # include <windows.h>
  95514. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95515. # ifdef USE_TRY_CATCH_FLAVOR
  95516. # else
  95517. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95518. {
  95519. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95520. ep->ContextRecord->Eip += 3 + 3 + 6;
  95521. return EXCEPTION_CONTINUE_EXECUTION;
  95522. }
  95523. return EXCEPTION_CONTINUE_SEARCH;
  95524. }
  95525. # endif
  95526. # endif
  95527. #endif
  95528. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95529. {
  95530. /*
  95531. * IA32-specific
  95532. */
  95533. #ifdef FLAC__CPU_IA32
  95534. info->type = FLAC__CPUINFO_TYPE_IA32;
  95535. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95536. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95537. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95538. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95539. info->data.ia32.cmov = false;
  95540. info->data.ia32.mmx = false;
  95541. info->data.ia32.fxsr = false;
  95542. info->data.ia32.sse = false;
  95543. info->data.ia32.sse2 = false;
  95544. info->data.ia32.sse3 = false;
  95545. info->data.ia32.ssse3 = false;
  95546. info->data.ia32._3dnow = false;
  95547. info->data.ia32.ext3dnow = false;
  95548. info->data.ia32.extmmx = false;
  95549. if(info->data.ia32.cpuid) {
  95550. /* http://www.sandpile.org/ia32/cpuid.htm */
  95551. FLAC__uint32 flags_edx, flags_ecx;
  95552. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95553. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95554. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95555. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95556. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95557. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95558. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95559. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95560. #ifdef FLAC__USE_3DNOW
  95561. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95562. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95563. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95564. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95565. #else
  95566. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95567. #endif
  95568. #ifdef DEBUG
  95569. fprintf(stderr, "CPU info (IA-32):\n");
  95570. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95571. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95572. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95573. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95574. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95575. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95576. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95577. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95578. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95579. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95580. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95581. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95582. #endif
  95583. /*
  95584. * now have to check for OS support of SSE/SSE2
  95585. */
  95586. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95587. #if defined FLAC__NO_SSE_OS
  95588. /* assume user knows better than us; turn it off */
  95589. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95590. #elif defined FLAC__SSE_OS
  95591. /* assume user knows better than us; leave as detected above */
  95592. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95593. int sse = 0;
  95594. size_t len;
  95595. /* at least one of these must work: */
  95596. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95597. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95598. if(!sse)
  95599. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95600. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95601. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95602. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95603. size_t len = sizeof(val);
  95604. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95605. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95606. else { /* double-check SSE2 */
  95607. mib[1] = CPU_SSE2;
  95608. len = sizeof(val);
  95609. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95610. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95611. }
  95612. # else
  95613. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95614. # endif
  95615. #elif defined(__linux__)
  95616. int sse = 0;
  95617. struct sigaction sigill_save;
  95618. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95619. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95620. #else
  95621. struct sigaction sigill_sse;
  95622. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95623. __sigemptyset(&sigill_sse.sa_mask);
  95624. 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 */
  95625. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95626. #endif
  95627. {
  95628. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95629. /* see sigill_handler_sse_os() for an explanation of the following: */
  95630. asm volatile (
  95631. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95632. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95633. "incl %0\n\t" /* SIGILL handler will jump over this */
  95634. /* landing zone */
  95635. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95636. "nop\n\t"
  95637. "nop\n\t"
  95638. "nop\n\t"
  95639. "nop\n\t"
  95640. "nop\n\t"
  95641. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95642. "nop\n\t"
  95643. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95644. : "=r"(sse)
  95645. : "r"(sse)
  95646. );
  95647. sigaction(SIGILL, &sigill_save, NULL);
  95648. }
  95649. if(!sse)
  95650. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95651. #elif defined(_MSC_VER)
  95652. # ifdef USE_TRY_CATCH_FLAVOR
  95653. _try {
  95654. __asm {
  95655. # if _MSC_VER <= 1200
  95656. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95657. _emit 0x0F
  95658. _emit 0x57
  95659. _emit 0xC0
  95660. # else
  95661. xorps xmm0,xmm0
  95662. # endif
  95663. }
  95664. }
  95665. _except(EXCEPTION_EXECUTE_HANDLER) {
  95666. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95667. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95668. }
  95669. # else
  95670. int sse = 0;
  95671. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95672. /* see GCC version above for explanation */
  95673. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95674. /* http://www.codeproject.com/cpp/gccasm.asp */
  95675. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95676. __asm {
  95677. # if _MSC_VER <= 1200
  95678. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95679. _emit 0x0F
  95680. _emit 0x57
  95681. _emit 0xC0
  95682. # else
  95683. xorps xmm0,xmm0
  95684. # endif
  95685. inc sse
  95686. nop
  95687. nop
  95688. nop
  95689. nop
  95690. nop
  95691. nop
  95692. nop
  95693. nop
  95694. nop
  95695. }
  95696. SetUnhandledExceptionFilter(save);
  95697. if(!sse)
  95698. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95699. # endif
  95700. #else
  95701. /* no way to test, disable to be safe */
  95702. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95703. #endif
  95704. #ifdef DEBUG
  95705. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95706. #endif
  95707. }
  95708. }
  95709. #else
  95710. info->use_asm = false;
  95711. #endif
  95712. /*
  95713. * PPC-specific
  95714. */
  95715. #elif defined FLAC__CPU_PPC
  95716. info->type = FLAC__CPUINFO_TYPE_PPC;
  95717. # if !defined FLAC__NO_ASM
  95718. info->use_asm = true;
  95719. # ifdef FLAC__USE_ALTIVEC
  95720. # if defined FLAC__SYS_DARWIN
  95721. {
  95722. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95723. size_t len = sizeof(val);
  95724. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95725. }
  95726. {
  95727. host_basic_info_data_t hostInfo;
  95728. mach_msg_type_number_t infoCount;
  95729. infoCount = HOST_BASIC_INFO_COUNT;
  95730. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95731. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95732. }
  95733. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95734. {
  95735. /* no Darwin, do it the brute-force way */
  95736. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95737. info->data.ppc.altivec = 0;
  95738. info->data.ppc.ppc64 = 0;
  95739. signal (SIGILL, sigill_handler);
  95740. canjump = 0;
  95741. if (!sigsetjmp (jmpbuf, 1)) {
  95742. canjump = 1;
  95743. asm volatile (
  95744. "mtspr 256, %0\n\t"
  95745. "vand %%v0, %%v0, %%v0"
  95746. :
  95747. : "r" (-1)
  95748. );
  95749. info->data.ppc.altivec = 1;
  95750. }
  95751. canjump = 0;
  95752. if (!sigsetjmp (jmpbuf, 1)) {
  95753. int x = 0;
  95754. canjump = 1;
  95755. /* PPC64 hardware implements the cntlzd instruction */
  95756. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95757. info->data.ppc.ppc64 = 1;
  95758. }
  95759. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95760. }
  95761. # endif
  95762. # else /* !FLAC__USE_ALTIVEC */
  95763. info->data.ppc.altivec = 0;
  95764. info->data.ppc.ppc64 = 0;
  95765. # endif
  95766. # else
  95767. info->use_asm = false;
  95768. # endif
  95769. /*
  95770. * unknown CPI
  95771. */
  95772. #else
  95773. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95774. info->use_asm = false;
  95775. #endif
  95776. }
  95777. #endif
  95778. /*** End of inlined file: cpu.c ***/
  95779. /*** Start of inlined file: crc.c ***/
  95780. /*** Start of inlined file: juce_FlacHeader.h ***/
  95781. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95782. // tasks..
  95783. #define VERSION "1.2.1"
  95784. #define FLAC__NO_DLL 1
  95785. #if JUCE_MSVC
  95786. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95787. #endif
  95788. #if JUCE_MAC
  95789. #define FLAC__SYS_DARWIN 1
  95790. #endif
  95791. /*** End of inlined file: juce_FlacHeader.h ***/
  95792. #if JUCE_USE_FLAC
  95793. #if HAVE_CONFIG_H
  95794. # include <config.h>
  95795. #endif
  95796. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95797. FLAC__byte const FLAC__crc8_table[256] = {
  95798. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95799. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95800. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95801. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95802. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95803. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95804. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95805. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95806. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95807. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95808. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95809. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95810. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95811. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95812. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95813. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95814. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95815. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95816. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95817. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95818. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95819. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95820. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95821. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95822. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95823. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95824. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95825. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95826. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95827. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95828. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95829. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95830. };
  95831. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95832. unsigned FLAC__crc16_table[256] = {
  95833. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95834. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95835. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95836. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95837. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95838. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95839. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95840. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95841. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95842. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95843. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95844. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95845. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95846. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95847. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95848. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95849. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95850. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95851. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95852. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95853. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95854. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95855. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95856. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95857. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95858. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95859. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95860. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95861. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95862. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95863. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95864. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95865. };
  95866. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95867. {
  95868. *crc = FLAC__crc8_table[*crc ^ data];
  95869. }
  95870. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95871. {
  95872. while(len--)
  95873. *crc = FLAC__crc8_table[*crc ^ *data++];
  95874. }
  95875. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95876. {
  95877. FLAC__uint8 crc = 0;
  95878. while(len--)
  95879. crc = FLAC__crc8_table[crc ^ *data++];
  95880. return crc;
  95881. }
  95882. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95883. {
  95884. unsigned crc = 0;
  95885. while(len--)
  95886. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95887. return crc;
  95888. }
  95889. #endif
  95890. /*** End of inlined file: crc.c ***/
  95891. /*** Start of inlined file: fixed.c ***/
  95892. /*** Start of inlined file: juce_FlacHeader.h ***/
  95893. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95894. // tasks..
  95895. #define VERSION "1.2.1"
  95896. #define FLAC__NO_DLL 1
  95897. #if JUCE_MSVC
  95898. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95899. #endif
  95900. #if JUCE_MAC
  95901. #define FLAC__SYS_DARWIN 1
  95902. #endif
  95903. /*** End of inlined file: juce_FlacHeader.h ***/
  95904. #if JUCE_USE_FLAC
  95905. #if HAVE_CONFIG_H
  95906. # include <config.h>
  95907. #endif
  95908. #include <math.h>
  95909. #include <string.h>
  95910. /*** Start of inlined file: fixed.h ***/
  95911. #ifndef FLAC__PRIVATE__FIXED_H
  95912. #define FLAC__PRIVATE__FIXED_H
  95913. #ifdef HAVE_CONFIG_H
  95914. #include <config.h>
  95915. #endif
  95916. /*** Start of inlined file: float.h ***/
  95917. #ifndef FLAC__PRIVATE__FLOAT_H
  95918. #define FLAC__PRIVATE__FLOAT_H
  95919. #ifdef HAVE_CONFIG_H
  95920. #include <config.h>
  95921. #endif
  95922. /*
  95923. * These typedefs make it easier to ensure that integer versions of
  95924. * the library really only contain integer operations. All the code
  95925. * in libFLAC should use FLAC__float and FLAC__double in place of
  95926. * float and double, and be protected by checks of the macro
  95927. * FLAC__INTEGER_ONLY_LIBRARY.
  95928. *
  95929. * FLAC__real is the basic floating point type used in LPC analysis.
  95930. */
  95931. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95932. typedef double FLAC__double;
  95933. typedef float FLAC__float;
  95934. /*
  95935. * WATCHOUT: changing FLAC__real will change the signatures of many
  95936. * functions that have assembly language equivalents and break them.
  95937. */
  95938. typedef float FLAC__real;
  95939. #else
  95940. /*
  95941. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95942. * for the integer part and lower 16 bits for the fractional part.
  95943. */
  95944. typedef FLAC__int32 FLAC__fixedpoint;
  95945. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95946. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95947. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95948. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95949. extern const FLAC__fixedpoint FLAC__FP_E;
  95950. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95951. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95952. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95953. /*
  95954. * FLAC__fixedpoint_log2()
  95955. * --------------------------------------------------------------------
  95956. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95957. * algorithm by Knuth for x >= 1.0
  95958. *
  95959. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95960. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95961. *
  95962. * 'precision' roughly limits the number of iterations that are done;
  95963. * use (unsigned)(-1) for maximum precision.
  95964. *
  95965. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95966. * function will punt and return 0.
  95967. *
  95968. * The return value will also have 'fracbits' fractional bits.
  95969. */
  95970. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95971. #endif
  95972. #endif
  95973. /*** End of inlined file: float.h ***/
  95974. /*** Start of inlined file: format.h ***/
  95975. #ifndef FLAC__PRIVATE__FORMAT_H
  95976. #define FLAC__PRIVATE__FORMAT_H
  95977. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95978. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95979. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95980. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95981. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95982. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95983. #endif
  95984. /*** End of inlined file: format.h ***/
  95985. /*
  95986. * FLAC__fixed_compute_best_predictor()
  95987. * --------------------------------------------------------------------
  95988. * Compute the best fixed predictor and the expected bits-per-sample
  95989. * of the residual signal for each order. The _wide() version uses
  95990. * 64-bit integers which is statistically necessary when bits-per-
  95991. * sample + log2(blocksize) > 30
  95992. *
  95993. * IN data[0,data_len-1]
  95994. * IN data_len
  95995. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95996. */
  95997. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95998. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95999. # ifndef FLAC__NO_ASM
  96000. # ifdef FLAC__CPU_IA32
  96001. # ifdef FLAC__HAS_NASM
  96002. 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]);
  96003. # endif
  96004. # endif
  96005. # endif
  96006. 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]);
  96007. #else
  96008. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96009. 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]);
  96010. #endif
  96011. /*
  96012. * FLAC__fixed_compute_residual()
  96013. * --------------------------------------------------------------------
  96014. * Compute the residual signal obtained from sutracting the predicted
  96015. * signal from the original.
  96016. *
  96017. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96018. * IN data_len length of original signal
  96019. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96020. * OUT residual[0,data_len-1] residual signal
  96021. */
  96022. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  96023. /*
  96024. * FLAC__fixed_restore_signal()
  96025. * --------------------------------------------------------------------
  96026. * Restore the original signal by summing the residual and the
  96027. * predictor.
  96028. *
  96029. * IN residual[0,data_len-1] residual signal
  96030. * IN data_len length of original signal
  96031. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96032. * *** IMPORTANT: the caller must pass in the historical samples:
  96033. * IN data[-order,-1] previously-reconstructed historical samples
  96034. * OUT data[0,data_len-1] original signal
  96035. */
  96036. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  96037. #endif
  96038. /*** End of inlined file: fixed.h ***/
  96039. #ifndef M_LN2
  96040. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96041. #define M_LN2 0.69314718055994530942
  96042. #endif
  96043. #ifdef min
  96044. #undef min
  96045. #endif
  96046. #define min(x,y) ((x) < (y)? (x) : (y))
  96047. #ifdef local_abs
  96048. #undef local_abs
  96049. #endif
  96050. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  96051. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96052. /* rbps stands for residual bits per sample
  96053. *
  96054. * (ln(2) * err)
  96055. * rbps = log (-----------)
  96056. * 2 ( n )
  96057. */
  96058. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  96059. {
  96060. FLAC__uint32 rbps;
  96061. unsigned bits; /* the number of bits required to represent a number */
  96062. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96063. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96064. FLAC__ASSERT(err > 0);
  96065. FLAC__ASSERT(n > 0);
  96066. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96067. if(err <= n)
  96068. return 0;
  96069. /*
  96070. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96071. * These allow us later to know we won't lose too much precision in the
  96072. * fixed-point division (err<<fracbits)/n.
  96073. */
  96074. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  96075. err <<= fracbits;
  96076. err /= n;
  96077. /* err now holds err/n with fracbits fractional bits */
  96078. /*
  96079. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96080. * our purposes.
  96081. */
  96082. FLAC__ASSERT(err > 0);
  96083. bits = FLAC__bitmath_ilog2(err)+1;
  96084. if(bits > 16) {
  96085. err >>= (bits-16);
  96086. fracbits -= (bits-16);
  96087. }
  96088. rbps = (FLAC__uint32)err;
  96089. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96090. rbps *= FLAC__FP_LN2;
  96091. fracbits += 16;
  96092. FLAC__ASSERT(fracbits >= 0);
  96093. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96094. {
  96095. const int f = fracbits & 3;
  96096. if(f) {
  96097. rbps >>= f;
  96098. fracbits -= f;
  96099. }
  96100. }
  96101. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96102. if(rbps == 0)
  96103. return 0;
  96104. /*
  96105. * The return value must have 16 fractional bits. Since the whole part
  96106. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96107. * must be >= -3, these assertion allows us to be able to shift rbps
  96108. * left if necessary to get 16 fracbits without losing any bits of the
  96109. * whole part of rbps.
  96110. *
  96111. * There is a slight chance due to accumulated error that the whole part
  96112. * will require 6 bits, so we use 6 in the assertion. Really though as
  96113. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96114. */
  96115. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96116. FLAC__ASSERT(fracbits >= -3);
  96117. /* now shift the decimal point into place */
  96118. if(fracbits < 16)
  96119. return rbps << (16-fracbits);
  96120. else if(fracbits > 16)
  96121. return rbps >> (fracbits-16);
  96122. else
  96123. return rbps;
  96124. }
  96125. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  96126. {
  96127. FLAC__uint32 rbps;
  96128. unsigned bits; /* the number of bits required to represent a number */
  96129. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96130. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96131. FLAC__ASSERT(err > 0);
  96132. FLAC__ASSERT(n > 0);
  96133. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96134. if(err <= n)
  96135. return 0;
  96136. /*
  96137. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96138. * These allow us later to know we won't lose too much precision in the
  96139. * fixed-point division (err<<fracbits)/n.
  96140. */
  96141. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  96142. err <<= fracbits;
  96143. err /= n;
  96144. /* err now holds err/n with fracbits fractional bits */
  96145. /*
  96146. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96147. * our purposes.
  96148. */
  96149. FLAC__ASSERT(err > 0);
  96150. bits = FLAC__bitmath_ilog2_wide(err)+1;
  96151. if(bits > 16) {
  96152. err >>= (bits-16);
  96153. fracbits -= (bits-16);
  96154. }
  96155. rbps = (FLAC__uint32)err;
  96156. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96157. rbps *= FLAC__FP_LN2;
  96158. fracbits += 16;
  96159. FLAC__ASSERT(fracbits >= 0);
  96160. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96161. {
  96162. const int f = fracbits & 3;
  96163. if(f) {
  96164. rbps >>= f;
  96165. fracbits -= f;
  96166. }
  96167. }
  96168. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96169. if(rbps == 0)
  96170. return 0;
  96171. /*
  96172. * The return value must have 16 fractional bits. Since the whole part
  96173. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96174. * must be >= -3, these assertion allows us to be able to shift rbps
  96175. * left if necessary to get 16 fracbits without losing any bits of the
  96176. * whole part of rbps.
  96177. *
  96178. * There is a slight chance due to accumulated error that the whole part
  96179. * will require 6 bits, so we use 6 in the assertion. Really though as
  96180. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96181. */
  96182. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96183. FLAC__ASSERT(fracbits >= -3);
  96184. /* now shift the decimal point into place */
  96185. if(fracbits < 16)
  96186. return rbps << (16-fracbits);
  96187. else if(fracbits > 16)
  96188. return rbps >> (fracbits-16);
  96189. else
  96190. return rbps;
  96191. }
  96192. #endif
  96193. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96194. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96195. #else
  96196. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96197. #endif
  96198. {
  96199. FLAC__int32 last_error_0 = data[-1];
  96200. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96201. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96202. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96203. FLAC__int32 error, save;
  96204. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96205. unsigned i, order;
  96206. for(i = 0; i < data_len; i++) {
  96207. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96208. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96209. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96210. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96211. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96212. }
  96213. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96214. order = 0;
  96215. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96216. order = 1;
  96217. else if(total_error_2 < min(total_error_3, total_error_4))
  96218. order = 2;
  96219. else if(total_error_3 < total_error_4)
  96220. order = 3;
  96221. else
  96222. order = 4;
  96223. /* Estimate the expected number of bits per residual signal sample. */
  96224. /* 'total_error*' is linearly related to the variance of the residual */
  96225. /* signal, so we use it directly to compute E(|x|) */
  96226. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96227. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96228. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96229. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96230. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96231. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96232. 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);
  96233. 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);
  96234. 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);
  96235. 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);
  96236. 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);
  96237. #else
  96238. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96239. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96240. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96241. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96242. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96243. #endif
  96244. return order;
  96245. }
  96246. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96247. 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])
  96248. #else
  96249. 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])
  96250. #endif
  96251. {
  96252. FLAC__int32 last_error_0 = data[-1];
  96253. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96254. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96255. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96256. FLAC__int32 error, save;
  96257. /* total_error_* are 64-bits to avoid overflow when encoding
  96258. * erratic signals when the bits-per-sample and blocksize are
  96259. * large.
  96260. */
  96261. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96262. unsigned i, order;
  96263. for(i = 0; i < data_len; i++) {
  96264. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96265. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96266. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96267. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96268. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96269. }
  96270. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96271. order = 0;
  96272. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96273. order = 1;
  96274. else if(total_error_2 < min(total_error_3, total_error_4))
  96275. order = 2;
  96276. else if(total_error_3 < total_error_4)
  96277. order = 3;
  96278. else
  96279. order = 4;
  96280. /* Estimate the expected number of bits per residual signal sample. */
  96281. /* 'total_error*' is linearly related to the variance of the residual */
  96282. /* signal, so we use it directly to compute E(|x|) */
  96283. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96284. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96285. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96286. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96287. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96288. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96289. #if defined _MSC_VER || defined __MINGW32__
  96290. /* with MSVC you have to spoon feed it the casting */
  96291. 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);
  96292. 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);
  96293. 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);
  96294. 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);
  96295. 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);
  96296. #else
  96297. 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);
  96298. 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);
  96299. 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);
  96300. 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);
  96301. 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);
  96302. #endif
  96303. #else
  96304. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96305. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96306. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96307. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96308. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96309. #endif
  96310. return order;
  96311. }
  96312. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96313. {
  96314. const int idata_len = (int)data_len;
  96315. int i;
  96316. switch(order) {
  96317. case 0:
  96318. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96319. memcpy(residual, data, sizeof(residual[0])*data_len);
  96320. break;
  96321. case 1:
  96322. for(i = 0; i < idata_len; i++)
  96323. residual[i] = data[i] - data[i-1];
  96324. break;
  96325. case 2:
  96326. for(i = 0; i < idata_len; i++)
  96327. #if 1 /* OPT: may be faster with some compilers on some systems */
  96328. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96329. #else
  96330. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96331. #endif
  96332. break;
  96333. case 3:
  96334. for(i = 0; i < idata_len; i++)
  96335. #if 1 /* OPT: may be faster with some compilers on some systems */
  96336. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96337. #else
  96338. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96339. #endif
  96340. break;
  96341. case 4:
  96342. for(i = 0; i < idata_len; i++)
  96343. #if 1 /* OPT: may be faster with some compilers on some systems */
  96344. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96345. #else
  96346. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96347. #endif
  96348. break;
  96349. default:
  96350. FLAC__ASSERT(0);
  96351. }
  96352. }
  96353. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96354. {
  96355. int i, idata_len = (int)data_len;
  96356. switch(order) {
  96357. case 0:
  96358. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96359. memcpy(data, residual, sizeof(residual[0])*data_len);
  96360. break;
  96361. case 1:
  96362. for(i = 0; i < idata_len; i++)
  96363. data[i] = residual[i] + data[i-1];
  96364. break;
  96365. case 2:
  96366. for(i = 0; i < idata_len; i++)
  96367. #if 1 /* OPT: may be faster with some compilers on some systems */
  96368. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96369. #else
  96370. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96371. #endif
  96372. break;
  96373. case 3:
  96374. for(i = 0; i < idata_len; i++)
  96375. #if 1 /* OPT: may be faster with some compilers on some systems */
  96376. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96377. #else
  96378. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96379. #endif
  96380. break;
  96381. case 4:
  96382. for(i = 0; i < idata_len; i++)
  96383. #if 1 /* OPT: may be faster with some compilers on some systems */
  96384. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96385. #else
  96386. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96387. #endif
  96388. break;
  96389. default:
  96390. FLAC__ASSERT(0);
  96391. }
  96392. }
  96393. #endif
  96394. /*** End of inlined file: fixed.c ***/
  96395. /*** Start of inlined file: float.c ***/
  96396. /*** Start of inlined file: juce_FlacHeader.h ***/
  96397. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96398. // tasks..
  96399. #define VERSION "1.2.1"
  96400. #define FLAC__NO_DLL 1
  96401. #if JUCE_MSVC
  96402. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96403. #endif
  96404. #if JUCE_MAC
  96405. #define FLAC__SYS_DARWIN 1
  96406. #endif
  96407. /*** End of inlined file: juce_FlacHeader.h ***/
  96408. #if JUCE_USE_FLAC
  96409. #if HAVE_CONFIG_H
  96410. # include <config.h>
  96411. #endif
  96412. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96413. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96414. #ifdef _MSC_VER
  96415. #define FLAC__U64L(x) x
  96416. #else
  96417. #define FLAC__U64L(x) x##LLU
  96418. #endif
  96419. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96420. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96421. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96422. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96423. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96424. /* Lookup tables for Knuth's logarithm algorithm */
  96425. #define LOG2_LOOKUP_PRECISION 16
  96426. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96427. {
  96428. /*
  96429. * 0 fraction bits
  96430. */
  96431. /* undefined */ 0x00000000,
  96432. /* lg(2/1) = */ 0x00000001,
  96433. /* lg(4/3) = */ 0x00000000,
  96434. /* lg(8/7) = */ 0x00000000,
  96435. /* lg(16/15) = */ 0x00000000,
  96436. /* lg(32/31) = */ 0x00000000,
  96437. /* lg(64/63) = */ 0x00000000,
  96438. /* lg(128/127) = */ 0x00000000,
  96439. /* lg(256/255) = */ 0x00000000,
  96440. /* lg(512/511) = */ 0x00000000,
  96441. /* lg(1024/1023) = */ 0x00000000,
  96442. /* lg(2048/2047) = */ 0x00000000,
  96443. /* lg(4096/4095) = */ 0x00000000,
  96444. /* lg(8192/8191) = */ 0x00000000,
  96445. /* lg(16384/16383) = */ 0x00000000,
  96446. /* lg(32768/32767) = */ 0x00000000
  96447. },
  96448. {
  96449. /*
  96450. * 4 fraction bits
  96451. */
  96452. /* undefined */ 0x00000000,
  96453. /* lg(2/1) = */ 0x00000010,
  96454. /* lg(4/3) = */ 0x00000007,
  96455. /* lg(8/7) = */ 0x00000003,
  96456. /* lg(16/15) = */ 0x00000001,
  96457. /* lg(32/31) = */ 0x00000001,
  96458. /* lg(64/63) = */ 0x00000000,
  96459. /* lg(128/127) = */ 0x00000000,
  96460. /* lg(256/255) = */ 0x00000000,
  96461. /* lg(512/511) = */ 0x00000000,
  96462. /* lg(1024/1023) = */ 0x00000000,
  96463. /* lg(2048/2047) = */ 0x00000000,
  96464. /* lg(4096/4095) = */ 0x00000000,
  96465. /* lg(8192/8191) = */ 0x00000000,
  96466. /* lg(16384/16383) = */ 0x00000000,
  96467. /* lg(32768/32767) = */ 0x00000000
  96468. },
  96469. {
  96470. /*
  96471. * 8 fraction bits
  96472. */
  96473. /* undefined */ 0x00000000,
  96474. /* lg(2/1) = */ 0x00000100,
  96475. /* lg(4/3) = */ 0x0000006a,
  96476. /* lg(8/7) = */ 0x00000031,
  96477. /* lg(16/15) = */ 0x00000018,
  96478. /* lg(32/31) = */ 0x0000000c,
  96479. /* lg(64/63) = */ 0x00000006,
  96480. /* lg(128/127) = */ 0x00000003,
  96481. /* lg(256/255) = */ 0x00000001,
  96482. /* lg(512/511) = */ 0x00000001,
  96483. /* lg(1024/1023) = */ 0x00000000,
  96484. /* lg(2048/2047) = */ 0x00000000,
  96485. /* lg(4096/4095) = */ 0x00000000,
  96486. /* lg(8192/8191) = */ 0x00000000,
  96487. /* lg(16384/16383) = */ 0x00000000,
  96488. /* lg(32768/32767) = */ 0x00000000
  96489. },
  96490. {
  96491. /*
  96492. * 12 fraction bits
  96493. */
  96494. /* undefined */ 0x00000000,
  96495. /* lg(2/1) = */ 0x00001000,
  96496. /* lg(4/3) = */ 0x000006a4,
  96497. /* lg(8/7) = */ 0x00000315,
  96498. /* lg(16/15) = */ 0x0000017d,
  96499. /* lg(32/31) = */ 0x000000bc,
  96500. /* lg(64/63) = */ 0x0000005d,
  96501. /* lg(128/127) = */ 0x0000002e,
  96502. /* lg(256/255) = */ 0x00000017,
  96503. /* lg(512/511) = */ 0x0000000c,
  96504. /* lg(1024/1023) = */ 0x00000006,
  96505. /* lg(2048/2047) = */ 0x00000003,
  96506. /* lg(4096/4095) = */ 0x00000001,
  96507. /* lg(8192/8191) = */ 0x00000001,
  96508. /* lg(16384/16383) = */ 0x00000000,
  96509. /* lg(32768/32767) = */ 0x00000000
  96510. },
  96511. {
  96512. /*
  96513. * 16 fraction bits
  96514. */
  96515. /* undefined */ 0x00000000,
  96516. /* lg(2/1) = */ 0x00010000,
  96517. /* lg(4/3) = */ 0x00006a40,
  96518. /* lg(8/7) = */ 0x00003151,
  96519. /* lg(16/15) = */ 0x000017d6,
  96520. /* lg(32/31) = */ 0x00000bba,
  96521. /* lg(64/63) = */ 0x000005d1,
  96522. /* lg(128/127) = */ 0x000002e6,
  96523. /* lg(256/255) = */ 0x00000172,
  96524. /* lg(512/511) = */ 0x000000b9,
  96525. /* lg(1024/1023) = */ 0x0000005c,
  96526. /* lg(2048/2047) = */ 0x0000002e,
  96527. /* lg(4096/4095) = */ 0x00000017,
  96528. /* lg(8192/8191) = */ 0x0000000c,
  96529. /* lg(16384/16383) = */ 0x00000006,
  96530. /* lg(32768/32767) = */ 0x00000003
  96531. },
  96532. {
  96533. /*
  96534. * 20 fraction bits
  96535. */
  96536. /* undefined */ 0x00000000,
  96537. /* lg(2/1) = */ 0x00100000,
  96538. /* lg(4/3) = */ 0x0006a3fe,
  96539. /* lg(8/7) = */ 0x00031513,
  96540. /* lg(16/15) = */ 0x00017d60,
  96541. /* lg(32/31) = */ 0x0000bb9d,
  96542. /* lg(64/63) = */ 0x00005d10,
  96543. /* lg(128/127) = */ 0x00002e59,
  96544. /* lg(256/255) = */ 0x00001721,
  96545. /* lg(512/511) = */ 0x00000b8e,
  96546. /* lg(1024/1023) = */ 0x000005c6,
  96547. /* lg(2048/2047) = */ 0x000002e3,
  96548. /* lg(4096/4095) = */ 0x00000171,
  96549. /* lg(8192/8191) = */ 0x000000b9,
  96550. /* lg(16384/16383) = */ 0x0000005c,
  96551. /* lg(32768/32767) = */ 0x0000002e
  96552. },
  96553. {
  96554. /*
  96555. * 24 fraction bits
  96556. */
  96557. /* undefined */ 0x00000000,
  96558. /* lg(2/1) = */ 0x01000000,
  96559. /* lg(4/3) = */ 0x006a3fe6,
  96560. /* lg(8/7) = */ 0x00315130,
  96561. /* lg(16/15) = */ 0x0017d605,
  96562. /* lg(32/31) = */ 0x000bb9ca,
  96563. /* lg(64/63) = */ 0x0005d0fc,
  96564. /* lg(128/127) = */ 0x0002e58f,
  96565. /* lg(256/255) = */ 0x0001720e,
  96566. /* lg(512/511) = */ 0x0000b8d8,
  96567. /* lg(1024/1023) = */ 0x00005c61,
  96568. /* lg(2048/2047) = */ 0x00002e2d,
  96569. /* lg(4096/4095) = */ 0x00001716,
  96570. /* lg(8192/8191) = */ 0x00000b8b,
  96571. /* lg(16384/16383) = */ 0x000005c5,
  96572. /* lg(32768/32767) = */ 0x000002e3
  96573. },
  96574. {
  96575. /*
  96576. * 28 fraction bits
  96577. */
  96578. /* undefined */ 0x00000000,
  96579. /* lg(2/1) = */ 0x10000000,
  96580. /* lg(4/3) = */ 0x06a3fe5c,
  96581. /* lg(8/7) = */ 0x03151301,
  96582. /* lg(16/15) = */ 0x017d6049,
  96583. /* lg(32/31) = */ 0x00bb9ca6,
  96584. /* lg(64/63) = */ 0x005d0fba,
  96585. /* lg(128/127) = */ 0x002e58f7,
  96586. /* lg(256/255) = */ 0x001720da,
  96587. /* lg(512/511) = */ 0x000b8d87,
  96588. /* lg(1024/1023) = */ 0x0005c60b,
  96589. /* lg(2048/2047) = */ 0x0002e2d7,
  96590. /* lg(4096/4095) = */ 0x00017160,
  96591. /* lg(8192/8191) = */ 0x0000b8ad,
  96592. /* lg(16384/16383) = */ 0x00005c56,
  96593. /* lg(32768/32767) = */ 0x00002e2b
  96594. }
  96595. };
  96596. #if 0
  96597. static const FLAC__uint64 log2_lookup_wide[] = {
  96598. {
  96599. /*
  96600. * 32 fraction bits
  96601. */
  96602. /* undefined */ 0x00000000,
  96603. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96604. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96605. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96606. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96607. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96608. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96609. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96610. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96611. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96612. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96613. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96614. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96615. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96616. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96617. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96618. },
  96619. {
  96620. /*
  96621. * 48 fraction bits
  96622. */
  96623. /* undefined */ 0x00000000,
  96624. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96625. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96626. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96627. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96628. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96629. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96630. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96631. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96632. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96633. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96634. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96635. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96636. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96637. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96638. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96639. }
  96640. };
  96641. #endif
  96642. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96643. {
  96644. const FLAC__uint32 ONE = (1u << fracbits);
  96645. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96646. FLAC__ASSERT(fracbits < 32);
  96647. FLAC__ASSERT((fracbits & 0x3) == 0);
  96648. if(x < ONE)
  96649. return 0;
  96650. if(precision > LOG2_LOOKUP_PRECISION)
  96651. precision = LOG2_LOOKUP_PRECISION;
  96652. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96653. {
  96654. FLAC__uint32 y = 0;
  96655. FLAC__uint32 z = x >> 1, k = 1;
  96656. while (x > ONE && k < precision) {
  96657. if (x - z >= ONE) {
  96658. x -= z;
  96659. z = x >> k;
  96660. y += table[k];
  96661. }
  96662. else {
  96663. z >>= 1;
  96664. k++;
  96665. }
  96666. }
  96667. return y;
  96668. }
  96669. }
  96670. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96671. #endif
  96672. /*** End of inlined file: float.c ***/
  96673. /*** Start of inlined file: format.c ***/
  96674. /*** Start of inlined file: juce_FlacHeader.h ***/
  96675. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96676. // tasks..
  96677. #define VERSION "1.2.1"
  96678. #define FLAC__NO_DLL 1
  96679. #if JUCE_MSVC
  96680. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96681. #endif
  96682. #if JUCE_MAC
  96683. #define FLAC__SYS_DARWIN 1
  96684. #endif
  96685. /*** End of inlined file: juce_FlacHeader.h ***/
  96686. #if JUCE_USE_FLAC
  96687. #if HAVE_CONFIG_H
  96688. # include <config.h>
  96689. #endif
  96690. #include <stdio.h>
  96691. #include <stdlib.h> /* for qsort() */
  96692. #include <string.h> /* for memset() */
  96693. #ifndef FLaC__INLINE
  96694. #define FLaC__INLINE
  96695. #endif
  96696. #ifdef min
  96697. #undef min
  96698. #endif
  96699. #define min(a,b) ((a)<(b)?(a):(b))
  96700. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96701. #ifdef _MSC_VER
  96702. #define FLAC__U64L(x) x
  96703. #else
  96704. #define FLAC__U64L(x) x##LLU
  96705. #endif
  96706. /* VERSION should come from configure */
  96707. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96708. ;
  96709. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96710. /* yet one more hack because of MSVC6: */
  96711. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96712. #else
  96713. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96714. #endif
  96715. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96716. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96717. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96718. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96719. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96720. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96721. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96722. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96723. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96724. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96725. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96726. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96727. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96728. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96729. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96730. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96731. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96732. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96733. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96734. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96735. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96736. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96737. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96738. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96739. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96740. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96741. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96742. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96743. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96744. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96745. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96746. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96747. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96748. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96749. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96750. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96751. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96752. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96753. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96754. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96755. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96756. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96757. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96758. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96759. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96760. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96761. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96762. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96763. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96764. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96765. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96766. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96767. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96768. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96769. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96770. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96771. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96772. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96773. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96774. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96775. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96776. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96777. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96778. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96779. "PARTITIONED_RICE",
  96780. "PARTITIONED_RICE2"
  96781. };
  96782. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96783. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96784. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96785. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96786. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96787. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96788. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96789. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96790. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96791. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96792. "CONSTANT",
  96793. "VERBATIM",
  96794. "FIXED",
  96795. "LPC"
  96796. };
  96797. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96798. "INDEPENDENT",
  96799. "LEFT_SIDE",
  96800. "RIGHT_SIDE",
  96801. "MID_SIDE"
  96802. };
  96803. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96804. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96805. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96806. };
  96807. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96808. "STREAMINFO",
  96809. "PADDING",
  96810. "APPLICATION",
  96811. "SEEKTABLE",
  96812. "VORBIS_COMMENT",
  96813. "CUESHEET",
  96814. "PICTURE"
  96815. };
  96816. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96817. "Other",
  96818. "32x32 pixels 'file icon' (PNG only)",
  96819. "Other file icon",
  96820. "Cover (front)",
  96821. "Cover (back)",
  96822. "Leaflet page",
  96823. "Media (e.g. label side of CD)",
  96824. "Lead artist/lead performer/soloist",
  96825. "Artist/performer",
  96826. "Conductor",
  96827. "Band/Orchestra",
  96828. "Composer",
  96829. "Lyricist/text writer",
  96830. "Recording Location",
  96831. "During recording",
  96832. "During performance",
  96833. "Movie/video screen capture",
  96834. "A bright coloured fish",
  96835. "Illustration",
  96836. "Band/artist logotype",
  96837. "Publisher/Studio logotype"
  96838. };
  96839. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96840. {
  96841. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96842. return false;
  96843. }
  96844. else
  96845. return true;
  96846. }
  96847. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96848. {
  96849. if(
  96850. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96851. (
  96852. sample_rate >= (1u << 16) &&
  96853. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96854. )
  96855. ) {
  96856. return false;
  96857. }
  96858. else
  96859. return true;
  96860. }
  96861. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96862. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96863. {
  96864. unsigned i;
  96865. FLAC__uint64 prev_sample_number = 0;
  96866. FLAC__bool got_prev = false;
  96867. FLAC__ASSERT(0 != seek_table);
  96868. for(i = 0; i < seek_table->num_points; i++) {
  96869. if(got_prev) {
  96870. if(
  96871. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96872. seek_table->points[i].sample_number <= prev_sample_number
  96873. )
  96874. return false;
  96875. }
  96876. prev_sample_number = seek_table->points[i].sample_number;
  96877. got_prev = true;
  96878. }
  96879. return true;
  96880. }
  96881. /* used as the sort predicate for qsort() */
  96882. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96883. {
  96884. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96885. if(l->sample_number == r->sample_number)
  96886. return 0;
  96887. else if(l->sample_number < r->sample_number)
  96888. return -1;
  96889. else
  96890. return 1;
  96891. }
  96892. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96893. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96894. {
  96895. unsigned i, j;
  96896. FLAC__bool first;
  96897. FLAC__ASSERT(0 != seek_table);
  96898. /* sort the seekpoints */
  96899. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96900. /* uniquify the seekpoints */
  96901. first = true;
  96902. for(i = j = 0; i < seek_table->num_points; i++) {
  96903. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96904. if(!first) {
  96905. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96906. continue;
  96907. }
  96908. }
  96909. first = false;
  96910. seek_table->points[j++] = seek_table->points[i];
  96911. }
  96912. for(i = j; i < seek_table->num_points; i++) {
  96913. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96914. seek_table->points[i].stream_offset = 0;
  96915. seek_table->points[i].frame_samples = 0;
  96916. }
  96917. return j;
  96918. }
  96919. /*
  96920. * also disallows non-shortest-form encodings, c.f.
  96921. * http://www.unicode.org/versions/corrigendum1.html
  96922. * and a more clear explanation at the end of this section:
  96923. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96924. */
  96925. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96926. {
  96927. FLAC__ASSERT(0 != utf8);
  96928. if ((utf8[0] & 0x80) == 0) {
  96929. return 1;
  96930. }
  96931. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96932. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96933. return 0;
  96934. return 2;
  96935. }
  96936. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96937. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96938. return 0;
  96939. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96940. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96941. return 0;
  96942. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96943. return 0;
  96944. return 3;
  96945. }
  96946. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96947. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96948. return 0;
  96949. return 4;
  96950. }
  96951. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96952. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96953. return 0;
  96954. return 5;
  96955. }
  96956. 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) {
  96957. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96958. return 0;
  96959. return 6;
  96960. }
  96961. else {
  96962. return 0;
  96963. }
  96964. }
  96965. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96966. {
  96967. char c;
  96968. for(c = *name; c; c = *(++name))
  96969. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96970. return false;
  96971. return true;
  96972. }
  96973. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96974. {
  96975. if(length == (unsigned)(-1)) {
  96976. while(*value) {
  96977. unsigned n = utf8len_(value);
  96978. if(n == 0)
  96979. return false;
  96980. value += n;
  96981. }
  96982. }
  96983. else {
  96984. const FLAC__byte *end = value + length;
  96985. while(value < end) {
  96986. unsigned n = utf8len_(value);
  96987. if(n == 0)
  96988. return false;
  96989. value += n;
  96990. }
  96991. if(value != end)
  96992. return false;
  96993. }
  96994. return true;
  96995. }
  96996. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96997. {
  96998. const FLAC__byte *s, *end;
  96999. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  97000. if(*s < 0x20 || *s > 0x7D)
  97001. return false;
  97002. }
  97003. if(s == end)
  97004. return false;
  97005. s++; /* skip '=' */
  97006. while(s < end) {
  97007. unsigned n = utf8len_(s);
  97008. if(n == 0)
  97009. return false;
  97010. s += n;
  97011. }
  97012. if(s != end)
  97013. return false;
  97014. return true;
  97015. }
  97016. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97017. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  97018. {
  97019. unsigned i, j;
  97020. if(check_cd_da_subset) {
  97021. if(cue_sheet->lead_in < 2 * 44100) {
  97022. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  97023. return false;
  97024. }
  97025. if(cue_sheet->lead_in % 588 != 0) {
  97026. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  97027. return false;
  97028. }
  97029. }
  97030. if(cue_sheet->num_tracks == 0) {
  97031. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  97032. return false;
  97033. }
  97034. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  97035. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  97036. return false;
  97037. }
  97038. for(i = 0; i < cue_sheet->num_tracks; i++) {
  97039. if(cue_sheet->tracks[i].number == 0) {
  97040. if(violation) *violation = "cue sheet may not have a track number 0";
  97041. return false;
  97042. }
  97043. if(check_cd_da_subset) {
  97044. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  97045. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  97046. return false;
  97047. }
  97048. }
  97049. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  97050. if(violation) {
  97051. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  97052. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  97053. else
  97054. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  97055. }
  97056. return false;
  97057. }
  97058. if(i < cue_sheet->num_tracks - 1) {
  97059. if(cue_sheet->tracks[i].num_indices == 0) {
  97060. if(violation) *violation = "cue sheet track must have at least one index point";
  97061. return false;
  97062. }
  97063. if(cue_sheet->tracks[i].indices[0].number > 1) {
  97064. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  97065. return false;
  97066. }
  97067. }
  97068. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  97069. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  97070. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  97071. return false;
  97072. }
  97073. if(j > 0) {
  97074. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  97075. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  97076. return false;
  97077. }
  97078. }
  97079. }
  97080. }
  97081. return true;
  97082. }
  97083. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97084. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  97085. {
  97086. char *p;
  97087. FLAC__byte *b;
  97088. for(p = picture->mime_type; *p; p++) {
  97089. if(*p < 0x20 || *p > 0x7e) {
  97090. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  97091. return false;
  97092. }
  97093. }
  97094. for(b = picture->description; *b; ) {
  97095. unsigned n = utf8len_(b);
  97096. if(n == 0) {
  97097. if(violation) *violation = "description string must be valid UTF-8";
  97098. return false;
  97099. }
  97100. b += n;
  97101. }
  97102. return true;
  97103. }
  97104. /*
  97105. * These routines are private to libFLAC
  97106. */
  97107. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  97108. {
  97109. return
  97110. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  97111. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  97112. blocksize,
  97113. predictor_order
  97114. );
  97115. }
  97116. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  97117. {
  97118. unsigned max_rice_partition_order = 0;
  97119. while(!(blocksize & 1)) {
  97120. max_rice_partition_order++;
  97121. blocksize >>= 1;
  97122. }
  97123. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  97124. }
  97125. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  97126. {
  97127. unsigned max_rice_partition_order = limit;
  97128. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  97129. max_rice_partition_order--;
  97130. FLAC__ASSERT(
  97131. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  97132. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  97133. );
  97134. return max_rice_partition_order;
  97135. }
  97136. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97137. {
  97138. FLAC__ASSERT(0 != object);
  97139. object->parameters = 0;
  97140. object->raw_bits = 0;
  97141. object->capacity_by_order = 0;
  97142. }
  97143. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97144. {
  97145. FLAC__ASSERT(0 != object);
  97146. if(0 != object->parameters)
  97147. free(object->parameters);
  97148. if(0 != object->raw_bits)
  97149. free(object->raw_bits);
  97150. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  97151. }
  97152. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  97153. {
  97154. FLAC__ASSERT(0 != object);
  97155. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  97156. if(object->capacity_by_order < max_partition_order) {
  97157. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  97158. return false;
  97159. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97160. return false;
  97161. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97162. object->capacity_by_order = max_partition_order;
  97163. }
  97164. return true;
  97165. }
  97166. #endif
  97167. /*** End of inlined file: format.c ***/
  97168. /*** Start of inlined file: lpc_flac.c ***/
  97169. /*** Start of inlined file: juce_FlacHeader.h ***/
  97170. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97171. // tasks..
  97172. #define VERSION "1.2.1"
  97173. #define FLAC__NO_DLL 1
  97174. #if JUCE_MSVC
  97175. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97176. #endif
  97177. #if JUCE_MAC
  97178. #define FLAC__SYS_DARWIN 1
  97179. #endif
  97180. /*** End of inlined file: juce_FlacHeader.h ***/
  97181. #if JUCE_USE_FLAC
  97182. #if HAVE_CONFIG_H
  97183. # include <config.h>
  97184. #endif
  97185. #include <math.h>
  97186. /*** Start of inlined file: lpc.h ***/
  97187. #ifndef FLAC__PRIVATE__LPC_H
  97188. #define FLAC__PRIVATE__LPC_H
  97189. #ifdef HAVE_CONFIG_H
  97190. #include <config.h>
  97191. #endif
  97192. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97193. /*
  97194. * FLAC__lpc_window_data()
  97195. * --------------------------------------------------------------------
  97196. * Applies the given window to the data.
  97197. * OPT: asm implementation
  97198. *
  97199. * IN in[0,data_len-1]
  97200. * IN window[0,data_len-1]
  97201. * OUT out[0,lag-1]
  97202. * IN data_len
  97203. */
  97204. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97205. /*
  97206. * FLAC__lpc_compute_autocorrelation()
  97207. * --------------------------------------------------------------------
  97208. * Compute the autocorrelation for lags between 0 and lag-1.
  97209. * Assumes data[] outside of [0,data_len-1] == 0.
  97210. * Asserts that lag > 0.
  97211. *
  97212. * IN data[0,data_len-1]
  97213. * IN data_len
  97214. * IN 0 < lag <= data_len
  97215. * OUT autoc[0,lag-1]
  97216. */
  97217. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97218. #ifndef FLAC__NO_ASM
  97219. # ifdef FLAC__CPU_IA32
  97220. # ifdef FLAC__HAS_NASM
  97221. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97222. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97223. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97224. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97225. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97226. # endif
  97227. # endif
  97228. #endif
  97229. /*
  97230. * FLAC__lpc_compute_lp_coefficients()
  97231. * --------------------------------------------------------------------
  97232. * Computes LP coefficients for orders 1..max_order.
  97233. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97234. * and there is no point in calculating a predictor.
  97235. *
  97236. * IN autoc[0,max_order] autocorrelation values
  97237. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97238. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97239. * *** IMPORTANT:
  97240. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97241. * OUT error[0,max_order-1] error for each order (more
  97242. * specifically, the variance of
  97243. * the error signal times # of
  97244. * samples in the signal)
  97245. *
  97246. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97247. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97248. * in lp_coeff[7][0,7], etc.
  97249. */
  97250. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97251. /*
  97252. * FLAC__lpc_quantize_coefficients()
  97253. * --------------------------------------------------------------------
  97254. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97255. * must be less than 32 (sizeof(FLAC__int32)*8).
  97256. *
  97257. * IN lp_coeff[0,order-1] LP coefficients
  97258. * IN order LP order
  97259. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97260. * desired precision (in bits, including sign
  97261. * bit) of largest coefficient
  97262. * OUT qlp_coeff[0,order-1] quantized coefficients
  97263. * OUT shift # of bits to shift right to get approximated
  97264. * LP coefficients. NOTE: could be negative.
  97265. * RETURN 0 => quantization OK
  97266. * 1 => coefficients require too much shifting for *shift to
  97267. * fit in the LPC subframe header. 'shift' is unset.
  97268. * 2 => coefficients are all zero, which is bad. 'shift' is
  97269. * unset.
  97270. */
  97271. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97272. /*
  97273. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97274. * --------------------------------------------------------------------
  97275. * Compute the residual signal obtained from sutracting the predicted
  97276. * signal from the original.
  97277. *
  97278. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97279. * IN data_len length of original signal
  97280. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97281. * IN order > 0 LP order
  97282. * IN lp_quantization quantization of LP coefficients in bits
  97283. * OUT residual[0,data_len-1] residual signal
  97284. */
  97285. 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[]);
  97286. 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[]);
  97287. #ifndef FLAC__NO_ASM
  97288. # ifdef FLAC__CPU_IA32
  97289. # ifdef FLAC__HAS_NASM
  97290. 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[]);
  97291. 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[]);
  97292. # endif
  97293. # endif
  97294. #endif
  97295. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97296. /*
  97297. * FLAC__lpc_restore_signal()
  97298. * --------------------------------------------------------------------
  97299. * Restore the original signal by summing the residual and the
  97300. * predictor.
  97301. *
  97302. * IN residual[0,data_len-1] residual signal
  97303. * IN data_len length of original signal
  97304. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97305. * IN order > 0 LP order
  97306. * IN lp_quantization quantization of LP coefficients in bits
  97307. * *** IMPORTANT: the caller must pass in the historical samples:
  97308. * IN data[-order,-1] previously-reconstructed historical samples
  97309. * OUT data[0,data_len-1] original signal
  97310. */
  97311. 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[]);
  97312. 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[]);
  97313. #ifndef FLAC__NO_ASM
  97314. # ifdef FLAC__CPU_IA32
  97315. # ifdef FLAC__HAS_NASM
  97316. 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[]);
  97317. 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[]);
  97318. # endif /* FLAC__HAS_NASM */
  97319. # elif defined FLAC__CPU_PPC
  97320. 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[]);
  97321. 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[]);
  97322. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97323. #endif /* FLAC__NO_ASM */
  97324. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97325. /*
  97326. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97327. * --------------------------------------------------------------------
  97328. * Compute the expected number of bits per residual signal sample
  97329. * based on the LP error (which is related to the residual variance).
  97330. *
  97331. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97332. * IN total_samples > 0 # of samples in residual signal
  97333. * RETURN expected bits per sample
  97334. */
  97335. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97336. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97337. /*
  97338. * FLAC__lpc_compute_best_order()
  97339. * --------------------------------------------------------------------
  97340. * Compute the best order from the array of signal errors returned
  97341. * during coefficient computation.
  97342. *
  97343. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97344. * IN max_order > 0 max LP order
  97345. * IN total_samples > 0 # of samples in residual signal
  97346. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97347. * (includes warmup sample size and quantized LP coefficient)
  97348. * RETURN [1,max_order] best order
  97349. */
  97350. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97351. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97352. #endif
  97353. /*** End of inlined file: lpc.h ***/
  97354. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97355. #include <stdio.h>
  97356. #endif
  97357. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97358. #ifndef M_LN2
  97359. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97360. #define M_LN2 0.69314718055994530942
  97361. #endif
  97362. /* OPT: #undef'ing this may improve the speed on some architectures */
  97363. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97364. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97365. {
  97366. unsigned i;
  97367. for(i = 0; i < data_len; i++)
  97368. out[i] = in[i] * window[i];
  97369. }
  97370. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97371. {
  97372. /* a readable, but slower, version */
  97373. #if 0
  97374. FLAC__real d;
  97375. unsigned i;
  97376. FLAC__ASSERT(lag > 0);
  97377. FLAC__ASSERT(lag <= data_len);
  97378. /*
  97379. * Technically we should subtract the mean first like so:
  97380. * for(i = 0; i < data_len; i++)
  97381. * data[i] -= mean;
  97382. * but it appears not to make enough of a difference to matter, and
  97383. * most signals are already closely centered around zero
  97384. */
  97385. while(lag--) {
  97386. for(i = lag, d = 0.0; i < data_len; i++)
  97387. d += data[i] * data[i - lag];
  97388. autoc[lag] = d;
  97389. }
  97390. #endif
  97391. /*
  97392. * this version tends to run faster because of better data locality
  97393. * ('data_len' is usually much larger than 'lag')
  97394. */
  97395. FLAC__real d;
  97396. unsigned sample, coeff;
  97397. const unsigned limit = data_len - lag;
  97398. FLAC__ASSERT(lag > 0);
  97399. FLAC__ASSERT(lag <= data_len);
  97400. for(coeff = 0; coeff < lag; coeff++)
  97401. autoc[coeff] = 0.0;
  97402. for(sample = 0; sample <= limit; sample++) {
  97403. d = data[sample];
  97404. for(coeff = 0; coeff < lag; coeff++)
  97405. autoc[coeff] += d * data[sample+coeff];
  97406. }
  97407. for(; sample < data_len; sample++) {
  97408. d = data[sample];
  97409. for(coeff = 0; coeff < data_len - sample; coeff++)
  97410. autoc[coeff] += d * data[sample+coeff];
  97411. }
  97412. }
  97413. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97414. {
  97415. unsigned i, j;
  97416. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97417. FLAC__ASSERT(0 != max_order);
  97418. FLAC__ASSERT(0 < *max_order);
  97419. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97420. FLAC__ASSERT(autoc[0] != 0.0);
  97421. err = autoc[0];
  97422. for(i = 0; i < *max_order; i++) {
  97423. /* Sum up this iteration's reflection coefficient. */
  97424. r = -autoc[i+1];
  97425. for(j = 0; j < i; j++)
  97426. r -= lpc[j] * autoc[i-j];
  97427. ref[i] = (r/=err);
  97428. /* Update LPC coefficients and total error. */
  97429. lpc[i]=r;
  97430. for(j = 0; j < (i>>1); j++) {
  97431. FLAC__double tmp = lpc[j];
  97432. lpc[j] += r * lpc[i-1-j];
  97433. lpc[i-1-j] += r * tmp;
  97434. }
  97435. if(i & 1)
  97436. lpc[j] += lpc[j] * r;
  97437. err *= (1.0 - r * r);
  97438. /* save this order */
  97439. for(j = 0; j <= i; j++)
  97440. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97441. error[i] = err;
  97442. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97443. if(err == 0.0) {
  97444. *max_order = i+1;
  97445. return;
  97446. }
  97447. }
  97448. }
  97449. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97450. {
  97451. unsigned i;
  97452. FLAC__double cmax;
  97453. FLAC__int32 qmax, qmin;
  97454. FLAC__ASSERT(precision > 0);
  97455. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97456. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97457. precision--;
  97458. qmax = 1 << precision;
  97459. qmin = -qmax;
  97460. qmax--;
  97461. /* calc cmax = max( |lp_coeff[i]| ) */
  97462. cmax = 0.0;
  97463. for(i = 0; i < order; i++) {
  97464. const FLAC__double d = fabs(lp_coeff[i]);
  97465. if(d > cmax)
  97466. cmax = d;
  97467. }
  97468. if(cmax <= 0.0) {
  97469. /* => coefficients are all 0, which means our constant-detect didn't work */
  97470. return 2;
  97471. }
  97472. else {
  97473. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97474. const int min_shiftlimit = -max_shiftlimit - 1;
  97475. int log2cmax;
  97476. (void)frexp(cmax, &log2cmax);
  97477. log2cmax--;
  97478. *shift = (int)precision - log2cmax - 1;
  97479. if(*shift > max_shiftlimit)
  97480. *shift = max_shiftlimit;
  97481. else if(*shift < min_shiftlimit)
  97482. return 1;
  97483. }
  97484. if(*shift >= 0) {
  97485. FLAC__double error = 0.0;
  97486. FLAC__int32 q;
  97487. for(i = 0; i < order; i++) {
  97488. error += lp_coeff[i] * (1 << *shift);
  97489. #if 1 /* unfortunately lround() is C99 */
  97490. if(error >= 0.0)
  97491. q = (FLAC__int32)(error + 0.5);
  97492. else
  97493. q = (FLAC__int32)(error - 0.5);
  97494. #else
  97495. q = lround(error);
  97496. #endif
  97497. #ifdef FLAC__OVERFLOW_DETECT
  97498. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97499. 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]);
  97500. else if(q < qmin)
  97501. 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]);
  97502. #endif
  97503. if(q > qmax)
  97504. q = qmax;
  97505. else if(q < qmin)
  97506. q = qmin;
  97507. error -= q;
  97508. qlp_coeff[i] = q;
  97509. }
  97510. }
  97511. /* negative shift is very rare but due to design flaw, negative shift is
  97512. * a NOP in the decoder, so it must be handled specially by scaling down
  97513. * coeffs
  97514. */
  97515. else {
  97516. const int nshift = -(*shift);
  97517. FLAC__double error = 0.0;
  97518. FLAC__int32 q;
  97519. #ifdef DEBUG
  97520. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97521. #endif
  97522. for(i = 0; i < order; i++) {
  97523. error += lp_coeff[i] / (1 << nshift);
  97524. #if 1 /* unfortunately lround() is C99 */
  97525. if(error >= 0.0)
  97526. q = (FLAC__int32)(error + 0.5);
  97527. else
  97528. q = (FLAC__int32)(error - 0.5);
  97529. #else
  97530. q = lround(error);
  97531. #endif
  97532. #ifdef FLAC__OVERFLOW_DETECT
  97533. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97534. 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]);
  97535. else if(q < qmin)
  97536. 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]);
  97537. #endif
  97538. if(q > qmax)
  97539. q = qmax;
  97540. else if(q < qmin)
  97541. q = qmin;
  97542. error -= q;
  97543. qlp_coeff[i] = q;
  97544. }
  97545. *shift = 0;
  97546. }
  97547. return 0;
  97548. }
  97549. 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[])
  97550. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97551. {
  97552. FLAC__int64 sumo;
  97553. unsigned i, j;
  97554. FLAC__int32 sum;
  97555. const FLAC__int32 *history;
  97556. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97557. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97558. for(i=0;i<order;i++)
  97559. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97560. fprintf(stderr,"\n");
  97561. #endif
  97562. FLAC__ASSERT(order > 0);
  97563. for(i = 0; i < data_len; i++) {
  97564. sumo = 0;
  97565. sum = 0;
  97566. history = data;
  97567. for(j = 0; j < order; j++) {
  97568. sum += qlp_coeff[j] * (*(--history));
  97569. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97570. #if defined _MSC_VER
  97571. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97572. 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);
  97573. #else
  97574. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97575. 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);
  97576. #endif
  97577. }
  97578. *(residual++) = *(data++) - (sum >> lp_quantization);
  97579. }
  97580. /* Here's a slower but clearer version:
  97581. for(i = 0; i < data_len; i++) {
  97582. sum = 0;
  97583. for(j = 0; j < order; j++)
  97584. sum += qlp_coeff[j] * data[i-j-1];
  97585. residual[i] = data[i] - (sum >> lp_quantization);
  97586. }
  97587. */
  97588. }
  97589. #else /* fully unrolled version for normal use */
  97590. {
  97591. int i;
  97592. FLAC__int32 sum;
  97593. FLAC__ASSERT(order > 0);
  97594. FLAC__ASSERT(order <= 32);
  97595. /*
  97596. * We do unique versions up to 12th order since that's the subset limit.
  97597. * Also they are roughly ordered to match frequency of occurrence to
  97598. * minimize branching.
  97599. */
  97600. if(order <= 12) {
  97601. if(order > 8) {
  97602. if(order > 10) {
  97603. if(order == 12) {
  97604. for(i = 0; i < (int)data_len; i++) {
  97605. sum = 0;
  97606. sum += qlp_coeff[11] * data[i-12];
  97607. sum += qlp_coeff[10] * data[i-11];
  97608. sum += qlp_coeff[9] * data[i-10];
  97609. sum += qlp_coeff[8] * data[i-9];
  97610. sum += qlp_coeff[7] * data[i-8];
  97611. sum += qlp_coeff[6] * data[i-7];
  97612. sum += qlp_coeff[5] * data[i-6];
  97613. sum += qlp_coeff[4] * data[i-5];
  97614. sum += qlp_coeff[3] * data[i-4];
  97615. sum += qlp_coeff[2] * data[i-3];
  97616. sum += qlp_coeff[1] * data[i-2];
  97617. sum += qlp_coeff[0] * data[i-1];
  97618. residual[i] = data[i] - (sum >> lp_quantization);
  97619. }
  97620. }
  97621. else { /* order == 11 */
  97622. for(i = 0; i < (int)data_len; i++) {
  97623. sum = 0;
  97624. sum += qlp_coeff[10] * data[i-11];
  97625. sum += qlp_coeff[9] * data[i-10];
  97626. sum += qlp_coeff[8] * data[i-9];
  97627. sum += qlp_coeff[7] * data[i-8];
  97628. sum += qlp_coeff[6] * data[i-7];
  97629. sum += qlp_coeff[5] * data[i-6];
  97630. sum += qlp_coeff[4] * data[i-5];
  97631. sum += qlp_coeff[3] * data[i-4];
  97632. sum += qlp_coeff[2] * data[i-3];
  97633. sum += qlp_coeff[1] * data[i-2];
  97634. sum += qlp_coeff[0] * data[i-1];
  97635. residual[i] = data[i] - (sum >> lp_quantization);
  97636. }
  97637. }
  97638. }
  97639. else {
  97640. if(order == 10) {
  97641. for(i = 0; i < (int)data_len; i++) {
  97642. sum = 0;
  97643. sum += qlp_coeff[9] * data[i-10];
  97644. sum += qlp_coeff[8] * data[i-9];
  97645. sum += qlp_coeff[7] * data[i-8];
  97646. sum += qlp_coeff[6] * data[i-7];
  97647. sum += qlp_coeff[5] * data[i-6];
  97648. sum += qlp_coeff[4] * data[i-5];
  97649. sum += qlp_coeff[3] * data[i-4];
  97650. sum += qlp_coeff[2] * data[i-3];
  97651. sum += qlp_coeff[1] * data[i-2];
  97652. sum += qlp_coeff[0] * data[i-1];
  97653. residual[i] = data[i] - (sum >> lp_quantization);
  97654. }
  97655. }
  97656. else { /* order == 9 */
  97657. for(i = 0; i < (int)data_len; i++) {
  97658. sum = 0;
  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. residual[i] = data[i] - (sum >> lp_quantization);
  97669. }
  97670. }
  97671. }
  97672. }
  97673. else if(order > 4) {
  97674. if(order > 6) {
  97675. if(order == 8) {
  97676. for(i = 0; i < (int)data_len; i++) {
  97677. sum = 0;
  97678. sum += qlp_coeff[7] * data[i-8];
  97679. sum += qlp_coeff[6] * data[i-7];
  97680. sum += qlp_coeff[5] * data[i-6];
  97681. sum += qlp_coeff[4] * data[i-5];
  97682. sum += qlp_coeff[3] * data[i-4];
  97683. sum += qlp_coeff[2] * data[i-3];
  97684. sum += qlp_coeff[1] * data[i-2];
  97685. sum += qlp_coeff[0] * data[i-1];
  97686. residual[i] = data[i] - (sum >> lp_quantization);
  97687. }
  97688. }
  97689. else { /* order == 7 */
  97690. for(i = 0; i < (int)data_len; i++) {
  97691. sum = 0;
  97692. sum += qlp_coeff[6] * data[i-7];
  97693. sum += qlp_coeff[5] * data[i-6];
  97694. sum += qlp_coeff[4] * data[i-5];
  97695. sum += qlp_coeff[3] * data[i-4];
  97696. sum += qlp_coeff[2] * data[i-3];
  97697. sum += qlp_coeff[1] * data[i-2];
  97698. sum += qlp_coeff[0] * data[i-1];
  97699. residual[i] = data[i] - (sum >> lp_quantization);
  97700. }
  97701. }
  97702. }
  97703. else {
  97704. if(order == 6) {
  97705. for(i = 0; i < (int)data_len; i++) {
  97706. sum = 0;
  97707. sum += qlp_coeff[5] * data[i-6];
  97708. sum += qlp_coeff[4] * data[i-5];
  97709. sum += qlp_coeff[3] * data[i-4];
  97710. sum += qlp_coeff[2] * data[i-3];
  97711. sum += qlp_coeff[1] * data[i-2];
  97712. sum += qlp_coeff[0] * data[i-1];
  97713. residual[i] = data[i] - (sum >> lp_quantization);
  97714. }
  97715. }
  97716. else { /* order == 5 */
  97717. for(i = 0; i < (int)data_len; i++) {
  97718. sum = 0;
  97719. sum += qlp_coeff[4] * data[i-5];
  97720. sum += qlp_coeff[3] * data[i-4];
  97721. sum += qlp_coeff[2] * data[i-3];
  97722. sum += qlp_coeff[1] * data[i-2];
  97723. sum += qlp_coeff[0] * data[i-1];
  97724. residual[i] = data[i] - (sum >> lp_quantization);
  97725. }
  97726. }
  97727. }
  97728. }
  97729. else {
  97730. if(order > 2) {
  97731. if(order == 4) {
  97732. for(i = 0; i < (int)data_len; i++) {
  97733. sum = 0;
  97734. sum += qlp_coeff[3] * data[i-4];
  97735. sum += qlp_coeff[2] * data[i-3];
  97736. sum += qlp_coeff[1] * data[i-2];
  97737. sum += qlp_coeff[0] * data[i-1];
  97738. residual[i] = data[i] - (sum >> lp_quantization);
  97739. }
  97740. }
  97741. else { /* order == 3 */
  97742. for(i = 0; i < (int)data_len; i++) {
  97743. sum = 0;
  97744. sum += qlp_coeff[2] * data[i-3];
  97745. sum += qlp_coeff[1] * data[i-2];
  97746. sum += qlp_coeff[0] * data[i-1];
  97747. residual[i] = data[i] - (sum >> lp_quantization);
  97748. }
  97749. }
  97750. }
  97751. else {
  97752. if(order == 2) {
  97753. for(i = 0; i < (int)data_len; i++) {
  97754. sum = 0;
  97755. sum += qlp_coeff[1] * data[i-2];
  97756. sum += qlp_coeff[0] * data[i-1];
  97757. residual[i] = data[i] - (sum >> lp_quantization);
  97758. }
  97759. }
  97760. else { /* order == 1 */
  97761. for(i = 0; i < (int)data_len; i++)
  97762. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97763. }
  97764. }
  97765. }
  97766. }
  97767. else { /* order > 12 */
  97768. for(i = 0; i < (int)data_len; i++) {
  97769. sum = 0;
  97770. switch(order) {
  97771. case 32: sum += qlp_coeff[31] * data[i-32];
  97772. case 31: sum += qlp_coeff[30] * data[i-31];
  97773. case 30: sum += qlp_coeff[29] * data[i-30];
  97774. case 29: sum += qlp_coeff[28] * data[i-29];
  97775. case 28: sum += qlp_coeff[27] * data[i-28];
  97776. case 27: sum += qlp_coeff[26] * data[i-27];
  97777. case 26: sum += qlp_coeff[25] * data[i-26];
  97778. case 25: sum += qlp_coeff[24] * data[i-25];
  97779. case 24: sum += qlp_coeff[23] * data[i-24];
  97780. case 23: sum += qlp_coeff[22] * data[i-23];
  97781. case 22: sum += qlp_coeff[21] * data[i-22];
  97782. case 21: sum += qlp_coeff[20] * data[i-21];
  97783. case 20: sum += qlp_coeff[19] * data[i-20];
  97784. case 19: sum += qlp_coeff[18] * data[i-19];
  97785. case 18: sum += qlp_coeff[17] * data[i-18];
  97786. case 17: sum += qlp_coeff[16] * data[i-17];
  97787. case 16: sum += qlp_coeff[15] * data[i-16];
  97788. case 15: sum += qlp_coeff[14] * data[i-15];
  97789. case 14: sum += qlp_coeff[13] * data[i-14];
  97790. case 13: sum += qlp_coeff[12] * data[i-13];
  97791. sum += qlp_coeff[11] * data[i-12];
  97792. sum += qlp_coeff[10] * data[i-11];
  97793. sum += qlp_coeff[ 9] * data[i-10];
  97794. sum += qlp_coeff[ 8] * data[i- 9];
  97795. sum += qlp_coeff[ 7] * data[i- 8];
  97796. sum += qlp_coeff[ 6] * data[i- 7];
  97797. sum += qlp_coeff[ 5] * data[i- 6];
  97798. sum += qlp_coeff[ 4] * data[i- 5];
  97799. sum += qlp_coeff[ 3] * data[i- 4];
  97800. sum += qlp_coeff[ 2] * data[i- 3];
  97801. sum += qlp_coeff[ 1] * data[i- 2];
  97802. sum += qlp_coeff[ 0] * data[i- 1];
  97803. }
  97804. residual[i] = data[i] - (sum >> lp_quantization);
  97805. }
  97806. }
  97807. }
  97808. #endif
  97809. 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[])
  97810. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97811. {
  97812. unsigned i, j;
  97813. FLAC__int64 sum;
  97814. const FLAC__int32 *history;
  97815. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97816. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97817. for(i=0;i<order;i++)
  97818. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97819. fprintf(stderr,"\n");
  97820. #endif
  97821. FLAC__ASSERT(order > 0);
  97822. for(i = 0; i < data_len; i++) {
  97823. sum = 0;
  97824. history = data;
  97825. for(j = 0; j < order; j++)
  97826. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97827. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97828. #if defined _MSC_VER
  97829. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97830. #else
  97831. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97832. #endif
  97833. break;
  97834. }
  97835. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97836. #if defined _MSC_VER
  97837. 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));
  97838. #else
  97839. 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)));
  97840. #endif
  97841. break;
  97842. }
  97843. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97844. }
  97845. }
  97846. #else /* fully unrolled version for normal use */
  97847. {
  97848. int i;
  97849. FLAC__int64 sum;
  97850. FLAC__ASSERT(order > 0);
  97851. FLAC__ASSERT(order <= 32);
  97852. /*
  97853. * We do unique versions up to 12th order since that's the subset limit.
  97854. * Also they are roughly ordered to match frequency of occurrence to
  97855. * minimize branching.
  97856. */
  97857. if(order <= 12) {
  97858. if(order > 8) {
  97859. if(order > 10) {
  97860. if(order == 12) {
  97861. for(i = 0; i < (int)data_len; i++) {
  97862. sum = 0;
  97863. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97864. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97865. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97866. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97867. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97868. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97869. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97870. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97871. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97872. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97873. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97874. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97875. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97876. }
  97877. }
  97878. else { /* order == 11 */
  97879. for(i = 0; i < (int)data_len; i++) {
  97880. sum = 0;
  97881. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97882. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97883. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97884. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97885. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97886. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97887. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97888. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97889. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97890. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97891. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97892. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97893. }
  97894. }
  97895. }
  97896. else {
  97897. if(order == 10) {
  97898. for(i = 0; i < (int)data_len; i++) {
  97899. sum = 0;
  97900. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97901. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97902. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97903. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97904. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97905. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97906. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97907. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97908. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97909. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97910. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97911. }
  97912. }
  97913. else { /* order == 9 */
  97914. for(i = 0; i < (int)data_len; i++) {
  97915. sum = 0;
  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. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97926. }
  97927. }
  97928. }
  97929. }
  97930. else if(order > 4) {
  97931. if(order > 6) {
  97932. if(order == 8) {
  97933. for(i = 0; i < (int)data_len; i++) {
  97934. sum = 0;
  97935. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97936. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97937. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97938. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97939. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97940. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97941. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97942. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97943. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97944. }
  97945. }
  97946. else { /* order == 7 */
  97947. for(i = 0; i < (int)data_len; i++) {
  97948. sum = 0;
  97949. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97950. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97951. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97952. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97953. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97954. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97955. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97956. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97957. }
  97958. }
  97959. }
  97960. else {
  97961. if(order == 6) {
  97962. for(i = 0; i < (int)data_len; i++) {
  97963. sum = 0;
  97964. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97965. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97966. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97967. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97968. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97969. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97970. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97971. }
  97972. }
  97973. else { /* order == 5 */
  97974. for(i = 0; i < (int)data_len; i++) {
  97975. sum = 0;
  97976. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97977. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97978. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97979. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97980. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97981. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97982. }
  97983. }
  97984. }
  97985. }
  97986. else {
  97987. if(order > 2) {
  97988. if(order == 4) {
  97989. for(i = 0; i < (int)data_len; i++) {
  97990. sum = 0;
  97991. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97992. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97993. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97994. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97995. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97996. }
  97997. }
  97998. else { /* order == 3 */
  97999. for(i = 0; i < (int)data_len; i++) {
  98000. sum = 0;
  98001. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98002. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98003. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98004. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98005. }
  98006. }
  98007. }
  98008. else {
  98009. if(order == 2) {
  98010. for(i = 0; i < (int)data_len; i++) {
  98011. sum = 0;
  98012. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98013. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98014. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98015. }
  98016. }
  98017. else { /* order == 1 */
  98018. for(i = 0; i < (int)data_len; i++)
  98019. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98020. }
  98021. }
  98022. }
  98023. }
  98024. else { /* order > 12 */
  98025. for(i = 0; i < (int)data_len; i++) {
  98026. sum = 0;
  98027. switch(order) {
  98028. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98029. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98030. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98031. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98032. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98033. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98034. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98035. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98036. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98037. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98038. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98039. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98040. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98041. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98042. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98043. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98044. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98045. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98046. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98047. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98048. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98049. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98050. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98051. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98052. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98053. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98054. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98055. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98056. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98057. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98058. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98059. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98060. }
  98061. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98062. }
  98063. }
  98064. }
  98065. #endif
  98066. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98067. 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[])
  98068. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98069. {
  98070. FLAC__int64 sumo;
  98071. unsigned i, j;
  98072. FLAC__int32 sum;
  98073. const FLAC__int32 *r = residual, *history;
  98074. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98075. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98076. for(i=0;i<order;i++)
  98077. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98078. fprintf(stderr,"\n");
  98079. #endif
  98080. FLAC__ASSERT(order > 0);
  98081. for(i = 0; i < data_len; i++) {
  98082. sumo = 0;
  98083. sum = 0;
  98084. history = data;
  98085. for(j = 0; j < order; j++) {
  98086. sum += qlp_coeff[j] * (*(--history));
  98087. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  98088. #if defined _MSC_VER
  98089. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  98090. 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);
  98091. #else
  98092. if(sumo > 2147483647ll || sumo < -2147483648ll)
  98093. 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);
  98094. #endif
  98095. }
  98096. *(data++) = *(r++) + (sum >> lp_quantization);
  98097. }
  98098. /* Here's a slower but clearer version:
  98099. for(i = 0; i < data_len; i++) {
  98100. sum = 0;
  98101. for(j = 0; j < order; j++)
  98102. sum += qlp_coeff[j] * data[i-j-1];
  98103. data[i] = residual[i] + (sum >> lp_quantization);
  98104. }
  98105. */
  98106. }
  98107. #else /* fully unrolled version for normal use */
  98108. {
  98109. int i;
  98110. FLAC__int32 sum;
  98111. FLAC__ASSERT(order > 0);
  98112. FLAC__ASSERT(order <= 32);
  98113. /*
  98114. * We do unique versions up to 12th order since that's the subset limit.
  98115. * Also they are roughly ordered to match frequency of occurrence to
  98116. * minimize branching.
  98117. */
  98118. if(order <= 12) {
  98119. if(order > 8) {
  98120. if(order > 10) {
  98121. if(order == 12) {
  98122. for(i = 0; i < (int)data_len; i++) {
  98123. sum = 0;
  98124. sum += qlp_coeff[11] * data[i-12];
  98125. sum += qlp_coeff[10] * data[i-11];
  98126. sum += qlp_coeff[9] * data[i-10];
  98127. sum += qlp_coeff[8] * data[i-9];
  98128. sum += qlp_coeff[7] * data[i-8];
  98129. sum += qlp_coeff[6] * data[i-7];
  98130. sum += qlp_coeff[5] * data[i-6];
  98131. sum += qlp_coeff[4] * data[i-5];
  98132. sum += qlp_coeff[3] * data[i-4];
  98133. sum += qlp_coeff[2] * data[i-3];
  98134. sum += qlp_coeff[1] * data[i-2];
  98135. sum += qlp_coeff[0] * data[i-1];
  98136. data[i] = residual[i] + (sum >> lp_quantization);
  98137. }
  98138. }
  98139. else { /* order == 11 */
  98140. for(i = 0; i < (int)data_len; i++) {
  98141. sum = 0;
  98142. sum += qlp_coeff[10] * data[i-11];
  98143. sum += qlp_coeff[9] * data[i-10];
  98144. sum += qlp_coeff[8] * data[i-9];
  98145. sum += qlp_coeff[7] * data[i-8];
  98146. sum += qlp_coeff[6] * data[i-7];
  98147. sum += qlp_coeff[5] * data[i-6];
  98148. sum += qlp_coeff[4] * data[i-5];
  98149. sum += qlp_coeff[3] * data[i-4];
  98150. sum += qlp_coeff[2] * data[i-3];
  98151. sum += qlp_coeff[1] * data[i-2];
  98152. sum += qlp_coeff[0] * data[i-1];
  98153. data[i] = residual[i] + (sum >> lp_quantization);
  98154. }
  98155. }
  98156. }
  98157. else {
  98158. if(order == 10) {
  98159. for(i = 0; i < (int)data_len; i++) {
  98160. sum = 0;
  98161. sum += qlp_coeff[9] * data[i-10];
  98162. sum += qlp_coeff[8] * data[i-9];
  98163. sum += qlp_coeff[7] * data[i-8];
  98164. sum += qlp_coeff[6] * data[i-7];
  98165. sum += qlp_coeff[5] * data[i-6];
  98166. sum += qlp_coeff[4] * data[i-5];
  98167. sum += qlp_coeff[3] * data[i-4];
  98168. sum += qlp_coeff[2] * data[i-3];
  98169. sum += qlp_coeff[1] * data[i-2];
  98170. sum += qlp_coeff[0] * data[i-1];
  98171. data[i] = residual[i] + (sum >> lp_quantization);
  98172. }
  98173. }
  98174. else { /* order == 9 */
  98175. for(i = 0; i < (int)data_len; i++) {
  98176. sum = 0;
  98177. sum += qlp_coeff[8] * data[i-9];
  98178. sum += qlp_coeff[7] * data[i-8];
  98179. sum += qlp_coeff[6] * data[i-7];
  98180. sum += qlp_coeff[5] * data[i-6];
  98181. sum += qlp_coeff[4] * data[i-5];
  98182. sum += qlp_coeff[3] * data[i-4];
  98183. sum += qlp_coeff[2] * data[i-3];
  98184. sum += qlp_coeff[1] * data[i-2];
  98185. sum += qlp_coeff[0] * data[i-1];
  98186. data[i] = residual[i] + (sum >> lp_quantization);
  98187. }
  98188. }
  98189. }
  98190. }
  98191. else if(order > 4) {
  98192. if(order > 6) {
  98193. if(order == 8) {
  98194. for(i = 0; i < (int)data_len; i++) {
  98195. sum = 0;
  98196. sum += qlp_coeff[7] * data[i-8];
  98197. sum += qlp_coeff[6] * data[i-7];
  98198. sum += qlp_coeff[5] * data[i-6];
  98199. sum += qlp_coeff[4] * data[i-5];
  98200. sum += qlp_coeff[3] * data[i-4];
  98201. sum += qlp_coeff[2] * data[i-3];
  98202. sum += qlp_coeff[1] * data[i-2];
  98203. sum += qlp_coeff[0] * data[i-1];
  98204. data[i] = residual[i] + (sum >> lp_quantization);
  98205. }
  98206. }
  98207. else { /* order == 7 */
  98208. for(i = 0; i < (int)data_len; i++) {
  98209. sum = 0;
  98210. sum += qlp_coeff[6] * data[i-7];
  98211. sum += qlp_coeff[5] * data[i-6];
  98212. sum += qlp_coeff[4] * data[i-5];
  98213. sum += qlp_coeff[3] * data[i-4];
  98214. sum += qlp_coeff[2] * data[i-3];
  98215. sum += qlp_coeff[1] * data[i-2];
  98216. sum += qlp_coeff[0] * data[i-1];
  98217. data[i] = residual[i] + (sum >> lp_quantization);
  98218. }
  98219. }
  98220. }
  98221. else {
  98222. if(order == 6) {
  98223. for(i = 0; i < (int)data_len; i++) {
  98224. sum = 0;
  98225. sum += qlp_coeff[5] * data[i-6];
  98226. sum += qlp_coeff[4] * data[i-5];
  98227. sum += qlp_coeff[3] * data[i-4];
  98228. sum += qlp_coeff[2] * data[i-3];
  98229. sum += qlp_coeff[1] * data[i-2];
  98230. sum += qlp_coeff[0] * data[i-1];
  98231. data[i] = residual[i] + (sum >> lp_quantization);
  98232. }
  98233. }
  98234. else { /* order == 5 */
  98235. for(i = 0; i < (int)data_len; i++) {
  98236. sum = 0;
  98237. sum += qlp_coeff[4] * data[i-5];
  98238. sum += qlp_coeff[3] * data[i-4];
  98239. sum += qlp_coeff[2] * data[i-3];
  98240. sum += qlp_coeff[1] * data[i-2];
  98241. sum += qlp_coeff[0] * data[i-1];
  98242. data[i] = residual[i] + (sum >> lp_quantization);
  98243. }
  98244. }
  98245. }
  98246. }
  98247. else {
  98248. if(order > 2) {
  98249. if(order == 4) {
  98250. for(i = 0; i < (int)data_len; i++) {
  98251. sum = 0;
  98252. sum += qlp_coeff[3] * data[i-4];
  98253. sum += qlp_coeff[2] * data[i-3];
  98254. sum += qlp_coeff[1] * data[i-2];
  98255. sum += qlp_coeff[0] * data[i-1];
  98256. data[i] = residual[i] + (sum >> lp_quantization);
  98257. }
  98258. }
  98259. else { /* order == 3 */
  98260. for(i = 0; i < (int)data_len; i++) {
  98261. sum = 0;
  98262. sum += qlp_coeff[2] * data[i-3];
  98263. sum += qlp_coeff[1] * data[i-2];
  98264. sum += qlp_coeff[0] * data[i-1];
  98265. data[i] = residual[i] + (sum >> lp_quantization);
  98266. }
  98267. }
  98268. }
  98269. else {
  98270. if(order == 2) {
  98271. for(i = 0; i < (int)data_len; i++) {
  98272. sum = 0;
  98273. sum += qlp_coeff[1] * data[i-2];
  98274. sum += qlp_coeff[0] * data[i-1];
  98275. data[i] = residual[i] + (sum >> lp_quantization);
  98276. }
  98277. }
  98278. else { /* order == 1 */
  98279. for(i = 0; i < (int)data_len; i++)
  98280. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98281. }
  98282. }
  98283. }
  98284. }
  98285. else { /* order > 12 */
  98286. for(i = 0; i < (int)data_len; i++) {
  98287. sum = 0;
  98288. switch(order) {
  98289. case 32: sum += qlp_coeff[31] * data[i-32];
  98290. case 31: sum += qlp_coeff[30] * data[i-31];
  98291. case 30: sum += qlp_coeff[29] * data[i-30];
  98292. case 29: sum += qlp_coeff[28] * data[i-29];
  98293. case 28: sum += qlp_coeff[27] * data[i-28];
  98294. case 27: sum += qlp_coeff[26] * data[i-27];
  98295. case 26: sum += qlp_coeff[25] * data[i-26];
  98296. case 25: sum += qlp_coeff[24] * data[i-25];
  98297. case 24: sum += qlp_coeff[23] * data[i-24];
  98298. case 23: sum += qlp_coeff[22] * data[i-23];
  98299. case 22: sum += qlp_coeff[21] * data[i-22];
  98300. case 21: sum += qlp_coeff[20] * data[i-21];
  98301. case 20: sum += qlp_coeff[19] * data[i-20];
  98302. case 19: sum += qlp_coeff[18] * data[i-19];
  98303. case 18: sum += qlp_coeff[17] * data[i-18];
  98304. case 17: sum += qlp_coeff[16] * data[i-17];
  98305. case 16: sum += qlp_coeff[15] * data[i-16];
  98306. case 15: sum += qlp_coeff[14] * data[i-15];
  98307. case 14: sum += qlp_coeff[13] * data[i-14];
  98308. case 13: sum += qlp_coeff[12] * data[i-13];
  98309. sum += qlp_coeff[11] * data[i-12];
  98310. sum += qlp_coeff[10] * data[i-11];
  98311. sum += qlp_coeff[ 9] * data[i-10];
  98312. sum += qlp_coeff[ 8] * data[i- 9];
  98313. sum += qlp_coeff[ 7] * data[i- 8];
  98314. sum += qlp_coeff[ 6] * data[i- 7];
  98315. sum += qlp_coeff[ 5] * data[i- 6];
  98316. sum += qlp_coeff[ 4] * data[i- 5];
  98317. sum += qlp_coeff[ 3] * data[i- 4];
  98318. sum += qlp_coeff[ 2] * data[i- 3];
  98319. sum += qlp_coeff[ 1] * data[i- 2];
  98320. sum += qlp_coeff[ 0] * data[i- 1];
  98321. }
  98322. data[i] = residual[i] + (sum >> lp_quantization);
  98323. }
  98324. }
  98325. }
  98326. #endif
  98327. 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[])
  98328. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98329. {
  98330. unsigned i, j;
  98331. FLAC__int64 sum;
  98332. const FLAC__int32 *r = residual, *history;
  98333. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98334. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98335. for(i=0;i<order;i++)
  98336. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98337. fprintf(stderr,"\n");
  98338. #endif
  98339. FLAC__ASSERT(order > 0);
  98340. for(i = 0; i < data_len; i++) {
  98341. sum = 0;
  98342. history = data;
  98343. for(j = 0; j < order; j++)
  98344. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98345. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98346. #ifdef _MSC_VER
  98347. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98348. #else
  98349. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98350. #endif
  98351. break;
  98352. }
  98353. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98354. #ifdef _MSC_VER
  98355. 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));
  98356. #else
  98357. 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)));
  98358. #endif
  98359. break;
  98360. }
  98361. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98362. }
  98363. }
  98364. #else /* fully unrolled version for normal use */
  98365. {
  98366. int i;
  98367. FLAC__int64 sum;
  98368. FLAC__ASSERT(order > 0);
  98369. FLAC__ASSERT(order <= 32);
  98370. /*
  98371. * We do unique versions up to 12th order since that's the subset limit.
  98372. * Also they are roughly ordered to match frequency of occurrence to
  98373. * minimize branching.
  98374. */
  98375. if(order <= 12) {
  98376. if(order > 8) {
  98377. if(order > 10) {
  98378. if(order == 12) {
  98379. for(i = 0; i < (int)data_len; i++) {
  98380. sum = 0;
  98381. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98382. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98383. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98384. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98385. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98386. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98387. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98388. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98389. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98390. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98391. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98392. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98393. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98394. }
  98395. }
  98396. else { /* order == 11 */
  98397. for(i = 0; i < (int)data_len; i++) {
  98398. sum = 0;
  98399. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98400. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98401. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98402. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98403. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98404. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98405. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98406. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98407. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98408. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98409. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98410. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98411. }
  98412. }
  98413. }
  98414. else {
  98415. if(order == 10) {
  98416. for(i = 0; i < (int)data_len; i++) {
  98417. sum = 0;
  98418. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98419. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98420. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98421. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98422. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98423. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98424. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98425. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98426. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98427. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98428. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98429. }
  98430. }
  98431. else { /* order == 9 */
  98432. for(i = 0; i < (int)data_len; i++) {
  98433. sum = 0;
  98434. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98435. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98436. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98437. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98438. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98439. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98440. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98441. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98442. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98443. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98444. }
  98445. }
  98446. }
  98447. }
  98448. else if(order > 4) {
  98449. if(order > 6) {
  98450. if(order == 8) {
  98451. for(i = 0; i < (int)data_len; i++) {
  98452. sum = 0;
  98453. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98454. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98455. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98456. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98457. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98458. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98459. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98460. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98461. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98462. }
  98463. }
  98464. else { /* order == 7 */
  98465. for(i = 0; i < (int)data_len; i++) {
  98466. sum = 0;
  98467. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98468. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98469. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98470. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98471. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98472. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98473. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98474. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98475. }
  98476. }
  98477. }
  98478. else {
  98479. if(order == 6) {
  98480. for(i = 0; i < (int)data_len; i++) {
  98481. sum = 0;
  98482. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98483. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98484. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98485. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98486. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98487. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98488. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98489. }
  98490. }
  98491. else { /* order == 5 */
  98492. for(i = 0; i < (int)data_len; i++) {
  98493. sum = 0;
  98494. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98495. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98496. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98497. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98498. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98499. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98500. }
  98501. }
  98502. }
  98503. }
  98504. else {
  98505. if(order > 2) {
  98506. if(order == 4) {
  98507. for(i = 0; i < (int)data_len; i++) {
  98508. sum = 0;
  98509. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98510. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98511. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98512. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98513. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98514. }
  98515. }
  98516. else { /* order == 3 */
  98517. for(i = 0; i < (int)data_len; i++) {
  98518. sum = 0;
  98519. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98520. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98521. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98522. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98523. }
  98524. }
  98525. }
  98526. else {
  98527. if(order == 2) {
  98528. for(i = 0; i < (int)data_len; i++) {
  98529. sum = 0;
  98530. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98531. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98532. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98533. }
  98534. }
  98535. else { /* order == 1 */
  98536. for(i = 0; i < (int)data_len; i++)
  98537. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98538. }
  98539. }
  98540. }
  98541. }
  98542. else { /* order > 12 */
  98543. for(i = 0; i < (int)data_len; i++) {
  98544. sum = 0;
  98545. switch(order) {
  98546. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98547. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98548. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98549. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98550. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98551. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98552. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98553. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98554. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98555. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98556. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98557. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98558. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98559. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98560. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98561. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98562. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98563. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98564. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98565. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98566. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98567. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98568. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98569. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98570. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98571. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98572. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98573. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98574. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98575. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98576. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98577. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98578. }
  98579. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98580. }
  98581. }
  98582. }
  98583. #endif
  98584. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98585. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98586. {
  98587. FLAC__double error_scale;
  98588. FLAC__ASSERT(total_samples > 0);
  98589. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98590. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98591. }
  98592. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98593. {
  98594. if(lpc_error > 0.0) {
  98595. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98596. if(bps >= 0.0)
  98597. return bps;
  98598. else
  98599. return 0.0;
  98600. }
  98601. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98602. return 1e32;
  98603. }
  98604. else {
  98605. return 0.0;
  98606. }
  98607. }
  98608. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98609. {
  98610. 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 */
  98611. FLAC__double bits, best_bits, error_scale;
  98612. FLAC__ASSERT(max_order > 0);
  98613. FLAC__ASSERT(total_samples > 0);
  98614. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98615. best_index = 0;
  98616. best_bits = (unsigned)(-1);
  98617. for(index = 0, order = 1; index < max_order; index++, order++) {
  98618. 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);
  98619. if(bits < best_bits) {
  98620. best_index = index;
  98621. best_bits = bits;
  98622. }
  98623. }
  98624. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98625. }
  98626. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98627. #endif
  98628. /*** End of inlined file: lpc_flac.c ***/
  98629. /*** Start of inlined file: md5.c ***/
  98630. /*** Start of inlined file: juce_FlacHeader.h ***/
  98631. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98632. // tasks..
  98633. #define VERSION "1.2.1"
  98634. #define FLAC__NO_DLL 1
  98635. #if JUCE_MSVC
  98636. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98637. #endif
  98638. #if JUCE_MAC
  98639. #define FLAC__SYS_DARWIN 1
  98640. #endif
  98641. /*** End of inlined file: juce_FlacHeader.h ***/
  98642. #if JUCE_USE_FLAC
  98643. #if HAVE_CONFIG_H
  98644. # include <config.h>
  98645. #endif
  98646. #include <stdlib.h> /* for malloc() */
  98647. #include <string.h> /* for memcpy() */
  98648. /*** Start of inlined file: md5.h ***/
  98649. #ifndef FLAC__PRIVATE__MD5_H
  98650. #define FLAC__PRIVATE__MD5_H
  98651. /*
  98652. * This is the header file for the MD5 message-digest algorithm.
  98653. * The algorithm is due to Ron Rivest. This code was
  98654. * written by Colin Plumb in 1993, no copyright is claimed.
  98655. * This code is in the public domain; do with it what you wish.
  98656. *
  98657. * Equivalent code is available from RSA Data Security, Inc.
  98658. * This code has been tested against that, and is equivalent,
  98659. * except that you don't need to include two pages of legalese
  98660. * with every copy.
  98661. *
  98662. * To compute the message digest of a chunk of bytes, declare an
  98663. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98664. * needed on buffers full of bytes, and then call MD5Final, which
  98665. * will fill a supplied 16-byte array with the digest.
  98666. *
  98667. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98668. * header definitions; now uses stuff from dpkg's config.h
  98669. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98670. * Still in the public domain.
  98671. *
  98672. * Josh Coalson: made some changes to integrate with libFLAC.
  98673. * Still in the public domain, with no warranty.
  98674. */
  98675. typedef struct {
  98676. FLAC__uint32 in[16];
  98677. FLAC__uint32 buf[4];
  98678. FLAC__uint32 bytes[2];
  98679. FLAC__byte *internal_buf;
  98680. size_t capacity;
  98681. } FLAC__MD5Context;
  98682. void FLAC__MD5Init(FLAC__MD5Context *context);
  98683. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98684. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98685. #endif
  98686. /*** End of inlined file: md5.h ***/
  98687. #ifndef FLaC__INLINE
  98688. #define FLaC__INLINE
  98689. #endif
  98690. /*
  98691. * This code implements the MD5 message-digest algorithm.
  98692. * The algorithm is due to Ron Rivest. This code was
  98693. * written by Colin Plumb in 1993, no copyright is claimed.
  98694. * This code is in the public domain; do with it what you wish.
  98695. *
  98696. * Equivalent code is available from RSA Data Security, Inc.
  98697. * This code has been tested against that, and is equivalent,
  98698. * except that you don't need to include two pages of legalese
  98699. * with every copy.
  98700. *
  98701. * To compute the message digest of a chunk of bytes, declare an
  98702. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98703. * needed on buffers full of bytes, and then call MD5Final, which
  98704. * will fill a supplied 16-byte array with the digest.
  98705. *
  98706. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98707. * definitions; now uses stuff from dpkg's config.h.
  98708. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98709. * Still in the public domain.
  98710. *
  98711. * Josh Coalson: made some changes to integrate with libFLAC.
  98712. * Still in the public domain.
  98713. */
  98714. /* The four core functions - F1 is optimized somewhat */
  98715. /* #define F1(x, y, z) (x & y | ~x & z) */
  98716. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98717. #define F2(x, y, z) F1(z, x, y)
  98718. #define F3(x, y, z) (x ^ y ^ z)
  98719. #define F4(x, y, z) (y ^ (x | ~z))
  98720. /* This is the central step in the MD5 algorithm. */
  98721. #define MD5STEP(f,w,x,y,z,in,s) \
  98722. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98723. /*
  98724. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98725. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98726. * the data and converts bytes into longwords for this routine.
  98727. */
  98728. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98729. {
  98730. register FLAC__uint32 a, b, c, d;
  98731. a = buf[0];
  98732. b = buf[1];
  98733. c = buf[2];
  98734. d = buf[3];
  98735. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98736. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98737. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98738. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98739. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98740. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98741. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98742. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98743. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98744. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98745. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98746. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98747. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98748. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98749. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98750. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98751. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98752. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98753. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98754. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98755. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98756. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98757. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98758. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98759. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98760. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98761. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98762. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98763. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98764. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98765. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98766. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98767. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98768. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98769. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98770. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98771. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98772. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98773. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98774. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98775. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98776. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98777. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98778. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98779. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98780. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98781. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98782. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98783. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98784. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98785. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98786. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98787. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98788. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98789. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98790. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98791. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98792. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98793. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98794. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98795. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98796. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98797. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98798. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98799. buf[0] += a;
  98800. buf[1] += b;
  98801. buf[2] += c;
  98802. buf[3] += d;
  98803. }
  98804. #if WORDS_BIGENDIAN
  98805. //@@@@@@ OPT: use bswap/intrinsics
  98806. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98807. {
  98808. register FLAC__uint32 x;
  98809. do {
  98810. x = *buf;
  98811. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98812. *buf++ = (x >> 16) | (x << 16);
  98813. } while (--words);
  98814. }
  98815. static void byteSwapX16(FLAC__uint32 *buf)
  98816. {
  98817. register FLAC__uint32 x;
  98818. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98819. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98820. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98821. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98822. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98823. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98824. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98825. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98826. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98827. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98828. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98829. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98830. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98831. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98832. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98833. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98834. }
  98835. #else
  98836. #define byteSwap(buf, words)
  98837. #define byteSwapX16(buf)
  98838. #endif
  98839. /*
  98840. * Update context to reflect the concatenation of another buffer full
  98841. * of bytes.
  98842. */
  98843. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98844. {
  98845. FLAC__uint32 t;
  98846. /* Update byte count */
  98847. t = ctx->bytes[0];
  98848. if ((ctx->bytes[0] = t + len) < t)
  98849. ctx->bytes[1]++; /* Carry from low to high */
  98850. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98851. if (t > len) {
  98852. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98853. return;
  98854. }
  98855. /* First chunk is an odd size */
  98856. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98857. byteSwapX16(ctx->in);
  98858. FLAC__MD5Transform(ctx->buf, ctx->in);
  98859. buf += t;
  98860. len -= t;
  98861. /* Process data in 64-byte chunks */
  98862. while (len >= 64) {
  98863. memcpy(ctx->in, buf, 64);
  98864. byteSwapX16(ctx->in);
  98865. FLAC__MD5Transform(ctx->buf, ctx->in);
  98866. buf += 64;
  98867. len -= 64;
  98868. }
  98869. /* Handle any remaining bytes of data. */
  98870. memcpy(ctx->in, buf, len);
  98871. }
  98872. /*
  98873. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98874. * initialization constants.
  98875. */
  98876. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98877. {
  98878. ctx->buf[0] = 0x67452301;
  98879. ctx->buf[1] = 0xefcdab89;
  98880. ctx->buf[2] = 0x98badcfe;
  98881. ctx->buf[3] = 0x10325476;
  98882. ctx->bytes[0] = 0;
  98883. ctx->bytes[1] = 0;
  98884. ctx->internal_buf = 0;
  98885. ctx->capacity = 0;
  98886. }
  98887. /*
  98888. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98889. * 1 0* (64-bit count of bits processed, MSB-first)
  98890. */
  98891. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98892. {
  98893. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98894. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98895. /* Set the first char of padding to 0x80. There is always room. */
  98896. *p++ = 0x80;
  98897. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98898. count = 56 - 1 - count;
  98899. if (count < 0) { /* Padding forces an extra block */
  98900. memset(p, 0, count + 8);
  98901. byteSwapX16(ctx->in);
  98902. FLAC__MD5Transform(ctx->buf, ctx->in);
  98903. p = (FLAC__byte *)ctx->in;
  98904. count = 56;
  98905. }
  98906. memset(p, 0, count);
  98907. byteSwap(ctx->in, 14);
  98908. /* Append length in bits and transform */
  98909. ctx->in[14] = ctx->bytes[0] << 3;
  98910. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98911. FLAC__MD5Transform(ctx->buf, ctx->in);
  98912. byteSwap(ctx->buf, 4);
  98913. memcpy(digest, ctx->buf, 16);
  98914. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98915. if(0 != ctx->internal_buf) {
  98916. free(ctx->internal_buf);
  98917. ctx->internal_buf = 0;
  98918. ctx->capacity = 0;
  98919. }
  98920. }
  98921. /*
  98922. * Convert the incoming audio signal to a byte stream
  98923. */
  98924. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98925. {
  98926. unsigned channel, sample;
  98927. register FLAC__int32 a_word;
  98928. register FLAC__byte *buf_ = buf;
  98929. #if WORDS_BIGENDIAN
  98930. #else
  98931. if(channels == 2 && bytes_per_sample == 2) {
  98932. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98933. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98934. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98935. *buf1_ = (FLAC__int16)signal[1][sample];
  98936. }
  98937. else if(channels == 1 && bytes_per_sample == 2) {
  98938. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98939. for(sample = 0; sample < samples; sample++)
  98940. *buf1_++ = (FLAC__int16)signal[0][sample];
  98941. }
  98942. else
  98943. #endif
  98944. if(bytes_per_sample == 2) {
  98945. if(channels == 2) {
  98946. for(sample = 0; sample < samples; sample++) {
  98947. a_word = signal[0][sample];
  98948. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98949. *buf_++ = (FLAC__byte)a_word;
  98950. a_word = signal[1][sample];
  98951. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98952. *buf_++ = (FLAC__byte)a_word;
  98953. }
  98954. }
  98955. else if(channels == 1) {
  98956. for(sample = 0; sample < samples; sample++) {
  98957. a_word = signal[0][sample];
  98958. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98959. *buf_++ = (FLAC__byte)a_word;
  98960. }
  98961. }
  98962. else {
  98963. for(sample = 0; sample < samples; sample++) {
  98964. for(channel = 0; channel < channels; channel++) {
  98965. a_word = signal[channel][sample];
  98966. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98967. *buf_++ = (FLAC__byte)a_word;
  98968. }
  98969. }
  98970. }
  98971. }
  98972. else if(bytes_per_sample == 3) {
  98973. if(channels == 2) {
  98974. for(sample = 0; sample < samples; sample++) {
  98975. a_word = signal[0][sample];
  98976. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98977. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98978. *buf_++ = (FLAC__byte)a_word;
  98979. a_word = signal[1][sample];
  98980. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98981. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98982. *buf_++ = (FLAC__byte)a_word;
  98983. }
  98984. }
  98985. else if(channels == 1) {
  98986. for(sample = 0; sample < samples; sample++) {
  98987. a_word = signal[0][sample];
  98988. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98989. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98990. *buf_++ = (FLAC__byte)a_word;
  98991. }
  98992. }
  98993. else {
  98994. for(sample = 0; sample < samples; sample++) {
  98995. for(channel = 0; channel < channels; channel++) {
  98996. a_word = signal[channel][sample];
  98997. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98998. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98999. *buf_++ = (FLAC__byte)a_word;
  99000. }
  99001. }
  99002. }
  99003. }
  99004. else if(bytes_per_sample == 1) {
  99005. if(channels == 2) {
  99006. for(sample = 0; sample < samples; sample++) {
  99007. a_word = signal[0][sample];
  99008. *buf_++ = (FLAC__byte)a_word;
  99009. a_word = signal[1][sample];
  99010. *buf_++ = (FLAC__byte)a_word;
  99011. }
  99012. }
  99013. else if(channels == 1) {
  99014. for(sample = 0; sample < samples; sample++) {
  99015. a_word = signal[0][sample];
  99016. *buf_++ = (FLAC__byte)a_word;
  99017. }
  99018. }
  99019. else {
  99020. for(sample = 0; sample < samples; sample++) {
  99021. for(channel = 0; channel < channels; channel++) {
  99022. a_word = signal[channel][sample];
  99023. *buf_++ = (FLAC__byte)a_word;
  99024. }
  99025. }
  99026. }
  99027. }
  99028. else { /* bytes_per_sample == 4, maybe optimize more later */
  99029. for(sample = 0; sample < samples; sample++) {
  99030. for(channel = 0; channel < channels; channel++) {
  99031. a_word = signal[channel][sample];
  99032. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99033. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99034. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99035. *buf_++ = (FLAC__byte)a_word;
  99036. }
  99037. }
  99038. }
  99039. }
  99040. /*
  99041. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  99042. */
  99043. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  99044. {
  99045. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  99046. /* overflow check */
  99047. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  99048. return false;
  99049. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  99050. return false;
  99051. if(ctx->capacity < bytes_needed) {
  99052. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  99053. if(0 == tmp) {
  99054. free(ctx->internal_buf);
  99055. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  99056. return false;
  99057. }
  99058. ctx->internal_buf = tmp;
  99059. ctx->capacity = bytes_needed;
  99060. }
  99061. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  99062. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  99063. return true;
  99064. }
  99065. #endif
  99066. /*** End of inlined file: md5.c ***/
  99067. /*** Start of inlined file: memory.c ***/
  99068. /*** Start of inlined file: juce_FlacHeader.h ***/
  99069. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99070. // tasks..
  99071. #define VERSION "1.2.1"
  99072. #define FLAC__NO_DLL 1
  99073. #if JUCE_MSVC
  99074. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99075. #endif
  99076. #if JUCE_MAC
  99077. #define FLAC__SYS_DARWIN 1
  99078. #endif
  99079. /*** End of inlined file: juce_FlacHeader.h ***/
  99080. #if JUCE_USE_FLAC
  99081. #if HAVE_CONFIG_H
  99082. # include <config.h>
  99083. #endif
  99084. /*** Start of inlined file: memory.h ***/
  99085. #ifndef FLAC__PRIVATE__MEMORY_H
  99086. #define FLAC__PRIVATE__MEMORY_H
  99087. #ifdef HAVE_CONFIG_H
  99088. #include <config.h>
  99089. #endif
  99090. #include <stdlib.h> /* for size_t */
  99091. /* Returns the unaligned address returned by malloc.
  99092. * Use free() on this address to deallocate.
  99093. */
  99094. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  99095. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  99096. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  99097. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  99098. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  99099. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99100. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  99101. #endif
  99102. #endif
  99103. /*** End of inlined file: memory.h ***/
  99104. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  99105. {
  99106. void *x;
  99107. FLAC__ASSERT(0 != aligned_address);
  99108. #ifdef FLAC__ALIGN_MALLOC_DATA
  99109. /* align on 32-byte (256-bit) boundary */
  99110. x = safe_malloc_add_2op_(bytes, /*+*/31);
  99111. #ifdef SIZEOF_VOIDP
  99112. #if SIZEOF_VOIDP == 4
  99113. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  99114. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99115. #elif SIZEOF_VOIDP == 8
  99116. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99117. #else
  99118. # error Unsupported sizeof(void*)
  99119. #endif
  99120. #else
  99121. /* there's got to be a better way to do this right for all archs */
  99122. if(sizeof(void*) == sizeof(unsigned))
  99123. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99124. else if(sizeof(void*) == sizeof(FLAC__uint64))
  99125. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99126. else
  99127. return 0;
  99128. #endif
  99129. #else
  99130. x = safe_malloc_(bytes);
  99131. *aligned_address = x;
  99132. #endif
  99133. return x;
  99134. }
  99135. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  99136. {
  99137. FLAC__int32 *pu; /* unaligned pointer */
  99138. union { /* union needed to comply with C99 pointer aliasing rules */
  99139. FLAC__int32 *pa; /* aligned pointer */
  99140. void *pv; /* aligned pointer alias */
  99141. } u;
  99142. FLAC__ASSERT(elements > 0);
  99143. FLAC__ASSERT(0 != unaligned_pointer);
  99144. FLAC__ASSERT(0 != aligned_pointer);
  99145. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99146. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  99147. if(0 == pu) {
  99148. return false;
  99149. }
  99150. else {
  99151. if(*unaligned_pointer != 0)
  99152. free(*unaligned_pointer);
  99153. *unaligned_pointer = pu;
  99154. *aligned_pointer = u.pa;
  99155. return true;
  99156. }
  99157. }
  99158. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  99159. {
  99160. FLAC__uint32 *pu; /* unaligned pointer */
  99161. union { /* union needed to comply with C99 pointer aliasing rules */
  99162. FLAC__uint32 *pa; /* aligned pointer */
  99163. void *pv; /* aligned pointer alias */
  99164. } u;
  99165. FLAC__ASSERT(elements > 0);
  99166. FLAC__ASSERT(0 != unaligned_pointer);
  99167. FLAC__ASSERT(0 != aligned_pointer);
  99168. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99169. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99170. if(0 == pu) {
  99171. return false;
  99172. }
  99173. else {
  99174. if(*unaligned_pointer != 0)
  99175. free(*unaligned_pointer);
  99176. *unaligned_pointer = pu;
  99177. *aligned_pointer = u.pa;
  99178. return true;
  99179. }
  99180. }
  99181. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99182. {
  99183. FLAC__uint64 *pu; /* unaligned pointer */
  99184. union { /* union needed to comply with C99 pointer aliasing rules */
  99185. FLAC__uint64 *pa; /* aligned pointer */
  99186. void *pv; /* aligned pointer alias */
  99187. } u;
  99188. FLAC__ASSERT(elements > 0);
  99189. FLAC__ASSERT(0 != unaligned_pointer);
  99190. FLAC__ASSERT(0 != aligned_pointer);
  99191. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99192. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99193. if(0 == pu) {
  99194. return false;
  99195. }
  99196. else {
  99197. if(*unaligned_pointer != 0)
  99198. free(*unaligned_pointer);
  99199. *unaligned_pointer = pu;
  99200. *aligned_pointer = u.pa;
  99201. return true;
  99202. }
  99203. }
  99204. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99205. {
  99206. unsigned *pu; /* unaligned pointer */
  99207. union { /* union needed to comply with C99 pointer aliasing rules */
  99208. unsigned *pa; /* aligned pointer */
  99209. void *pv; /* aligned pointer alias */
  99210. } u;
  99211. FLAC__ASSERT(elements > 0);
  99212. FLAC__ASSERT(0 != unaligned_pointer);
  99213. FLAC__ASSERT(0 != aligned_pointer);
  99214. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99215. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99216. if(0 == pu) {
  99217. return false;
  99218. }
  99219. else {
  99220. if(*unaligned_pointer != 0)
  99221. free(*unaligned_pointer);
  99222. *unaligned_pointer = pu;
  99223. *aligned_pointer = u.pa;
  99224. return true;
  99225. }
  99226. }
  99227. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99228. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99229. {
  99230. FLAC__real *pu; /* unaligned pointer */
  99231. union { /* union needed to comply with C99 pointer aliasing rules */
  99232. FLAC__real *pa; /* aligned pointer */
  99233. void *pv; /* aligned pointer alias */
  99234. } u;
  99235. FLAC__ASSERT(elements > 0);
  99236. FLAC__ASSERT(0 != unaligned_pointer);
  99237. FLAC__ASSERT(0 != aligned_pointer);
  99238. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99239. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99240. if(0 == pu) {
  99241. return false;
  99242. }
  99243. else {
  99244. if(*unaligned_pointer != 0)
  99245. free(*unaligned_pointer);
  99246. *unaligned_pointer = pu;
  99247. *aligned_pointer = u.pa;
  99248. return true;
  99249. }
  99250. }
  99251. #endif
  99252. #endif
  99253. /*** End of inlined file: memory.c ***/
  99254. /*** Start of inlined file: stream_decoder.c ***/
  99255. /*** Start of inlined file: juce_FlacHeader.h ***/
  99256. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99257. // tasks..
  99258. #define VERSION "1.2.1"
  99259. #define FLAC__NO_DLL 1
  99260. #if JUCE_MSVC
  99261. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99262. #endif
  99263. #if JUCE_MAC
  99264. #define FLAC__SYS_DARWIN 1
  99265. #endif
  99266. /*** End of inlined file: juce_FlacHeader.h ***/
  99267. #if JUCE_USE_FLAC
  99268. #if HAVE_CONFIG_H
  99269. # include <config.h>
  99270. #endif
  99271. #if defined _MSC_VER || defined __MINGW32__
  99272. #include <io.h> /* for _setmode() */
  99273. #include <fcntl.h> /* for _O_BINARY */
  99274. #endif
  99275. #if defined __CYGWIN__ || defined __EMX__
  99276. #include <io.h> /* for setmode(), O_BINARY */
  99277. #include <fcntl.h> /* for _O_BINARY */
  99278. #endif
  99279. #include <stdio.h>
  99280. #include <stdlib.h> /* for malloc() */
  99281. #include <string.h> /* for memset/memcpy() */
  99282. #include <sys/stat.h> /* for stat() */
  99283. #include <sys/types.h> /* for off_t */
  99284. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99285. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99286. #define fseeko fseek
  99287. #define ftello ftell
  99288. #endif
  99289. #endif
  99290. /*** Start of inlined file: stream_decoder.h ***/
  99291. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99292. #define FLAC__PROTECTED__STREAM_DECODER_H
  99293. #if FLAC__HAS_OGG
  99294. #include "include/private/ogg_decoder_aspect.h"
  99295. #endif
  99296. typedef struct FLAC__StreamDecoderProtected {
  99297. FLAC__StreamDecoderState state;
  99298. unsigned channels;
  99299. FLAC__ChannelAssignment channel_assignment;
  99300. unsigned bits_per_sample;
  99301. unsigned sample_rate; /* in Hz */
  99302. unsigned blocksize; /* in samples (per channel) */
  99303. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99304. #if FLAC__HAS_OGG
  99305. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99306. #endif
  99307. } FLAC__StreamDecoderProtected;
  99308. /*
  99309. * return the number of input bytes consumed
  99310. */
  99311. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99312. #endif
  99313. /*** End of inlined file: stream_decoder.h ***/
  99314. #ifdef max
  99315. #undef max
  99316. #endif
  99317. #define max(a,b) ((a)>(b)?(a):(b))
  99318. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99319. #ifdef _MSC_VER
  99320. #define FLAC__U64L(x) x
  99321. #else
  99322. #define FLAC__U64L(x) x##LLU
  99323. #endif
  99324. /* technically this should be in an "export.c" but this is convenient enough */
  99325. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99326. #if FLAC__HAS_OGG
  99327. 1
  99328. #else
  99329. 0
  99330. #endif
  99331. ;
  99332. /***********************************************************************
  99333. *
  99334. * Private static data
  99335. *
  99336. ***********************************************************************/
  99337. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99338. /***********************************************************************
  99339. *
  99340. * Private class method prototypes
  99341. *
  99342. ***********************************************************************/
  99343. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99344. static FILE *get_binary_stdin_(void);
  99345. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99346. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99347. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99348. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99349. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99350. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99351. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99352. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99353. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99354. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99355. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99356. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99357. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99358. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99359. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99360. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99361. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99362. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99363. 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);
  99364. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99365. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99366. #if FLAC__HAS_OGG
  99367. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99368. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99369. #endif
  99370. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99371. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99372. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99373. #if FLAC__HAS_OGG
  99374. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99375. #endif
  99376. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99377. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99378. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99379. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99380. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99381. /***********************************************************************
  99382. *
  99383. * Private class data
  99384. *
  99385. ***********************************************************************/
  99386. typedef struct FLAC__StreamDecoderPrivate {
  99387. #if FLAC__HAS_OGG
  99388. FLAC__bool is_ogg;
  99389. #endif
  99390. FLAC__StreamDecoderReadCallback read_callback;
  99391. FLAC__StreamDecoderSeekCallback seek_callback;
  99392. FLAC__StreamDecoderTellCallback tell_callback;
  99393. FLAC__StreamDecoderLengthCallback length_callback;
  99394. FLAC__StreamDecoderEofCallback eof_callback;
  99395. FLAC__StreamDecoderWriteCallback write_callback;
  99396. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99397. FLAC__StreamDecoderErrorCallback error_callback;
  99398. /* generic 32-bit datapath: */
  99399. 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[]);
  99400. /* generic 64-bit datapath: */
  99401. 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[]);
  99402. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99403. 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[]);
  99404. /* 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: */
  99405. 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[]);
  99406. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99407. void *client_data;
  99408. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99409. FLAC__BitReader *input;
  99410. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99411. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99412. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99413. unsigned output_capacity, output_channels;
  99414. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99415. FLAC__uint64 samples_decoded;
  99416. FLAC__bool has_stream_info, has_seek_table;
  99417. FLAC__StreamMetadata stream_info;
  99418. FLAC__StreamMetadata seek_table;
  99419. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99420. FLAC__byte *metadata_filter_ids;
  99421. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99422. FLAC__Frame frame;
  99423. FLAC__bool cached; /* true if there is a byte in lookahead */
  99424. FLAC__CPUInfo cpuinfo;
  99425. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99426. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99427. /* unaligned (original) pointers to allocated data */
  99428. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99429. 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 */
  99430. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99431. FLAC__bool is_seeking;
  99432. FLAC__MD5Context md5context;
  99433. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99434. /* (the rest of these are only used for seeking) */
  99435. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99436. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99437. FLAC__uint64 target_sample;
  99438. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99439. #if FLAC__HAS_OGG
  99440. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99441. #endif
  99442. } FLAC__StreamDecoderPrivate;
  99443. /***********************************************************************
  99444. *
  99445. * Public static class data
  99446. *
  99447. ***********************************************************************/
  99448. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99449. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99450. "FLAC__STREAM_DECODER_READ_METADATA",
  99451. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99452. "FLAC__STREAM_DECODER_READ_FRAME",
  99453. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99454. "FLAC__STREAM_DECODER_OGG_ERROR",
  99455. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99456. "FLAC__STREAM_DECODER_ABORTED",
  99457. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99458. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99459. };
  99460. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99461. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99462. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99463. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99464. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99465. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99466. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99467. };
  99468. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99469. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99470. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99471. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99472. };
  99473. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99474. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99475. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99476. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99477. };
  99478. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99479. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99480. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99481. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99482. };
  99483. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99484. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99485. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99486. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99487. };
  99488. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99489. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99490. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99491. };
  99492. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99493. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99494. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99495. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99496. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99497. };
  99498. /***********************************************************************
  99499. *
  99500. * Class constructor/destructor
  99501. *
  99502. ***********************************************************************/
  99503. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99504. {
  99505. FLAC__StreamDecoder *decoder;
  99506. unsigned i;
  99507. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99508. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99509. if(decoder == 0) {
  99510. return 0;
  99511. }
  99512. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99513. if(decoder->protected_ == 0) {
  99514. free(decoder);
  99515. return 0;
  99516. }
  99517. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99518. if(decoder->private_ == 0) {
  99519. free(decoder->protected_);
  99520. free(decoder);
  99521. return 0;
  99522. }
  99523. decoder->private_->input = FLAC__bitreader_new();
  99524. if(decoder->private_->input == 0) {
  99525. free(decoder->private_);
  99526. free(decoder->protected_);
  99527. free(decoder);
  99528. return 0;
  99529. }
  99530. decoder->private_->metadata_filter_ids_capacity = 16;
  99531. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99532. FLAC__bitreader_delete(decoder->private_->input);
  99533. free(decoder->private_);
  99534. free(decoder->protected_);
  99535. free(decoder);
  99536. return 0;
  99537. }
  99538. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99539. decoder->private_->output[i] = 0;
  99540. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99541. }
  99542. decoder->private_->output_capacity = 0;
  99543. decoder->private_->output_channels = 0;
  99544. decoder->private_->has_seek_table = false;
  99545. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99546. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99547. decoder->private_->file = 0;
  99548. set_defaults_dec(decoder);
  99549. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99550. return decoder;
  99551. }
  99552. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99553. {
  99554. unsigned i;
  99555. FLAC__ASSERT(0 != decoder);
  99556. FLAC__ASSERT(0 != decoder->protected_);
  99557. FLAC__ASSERT(0 != decoder->private_);
  99558. FLAC__ASSERT(0 != decoder->private_->input);
  99559. (void)FLAC__stream_decoder_finish(decoder);
  99560. if(0 != decoder->private_->metadata_filter_ids)
  99561. free(decoder->private_->metadata_filter_ids);
  99562. FLAC__bitreader_delete(decoder->private_->input);
  99563. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99564. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99565. free(decoder->private_);
  99566. free(decoder->protected_);
  99567. free(decoder);
  99568. }
  99569. /***********************************************************************
  99570. *
  99571. * Public class methods
  99572. *
  99573. ***********************************************************************/
  99574. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99575. FLAC__StreamDecoder *decoder,
  99576. FLAC__StreamDecoderReadCallback read_callback,
  99577. FLAC__StreamDecoderSeekCallback seek_callback,
  99578. FLAC__StreamDecoderTellCallback tell_callback,
  99579. FLAC__StreamDecoderLengthCallback length_callback,
  99580. FLAC__StreamDecoderEofCallback eof_callback,
  99581. FLAC__StreamDecoderWriteCallback write_callback,
  99582. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99583. FLAC__StreamDecoderErrorCallback error_callback,
  99584. void *client_data,
  99585. FLAC__bool is_ogg
  99586. )
  99587. {
  99588. FLAC__ASSERT(0 != decoder);
  99589. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99590. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99591. #if !FLAC__HAS_OGG
  99592. if(is_ogg)
  99593. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99594. #endif
  99595. if(
  99596. 0 == read_callback ||
  99597. 0 == write_callback ||
  99598. 0 == error_callback ||
  99599. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99600. )
  99601. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99602. #if FLAC__HAS_OGG
  99603. decoder->private_->is_ogg = is_ogg;
  99604. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99605. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99606. #endif
  99607. /*
  99608. * get the CPU info and set the function pointers
  99609. */
  99610. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99611. /* first default to the non-asm routines */
  99612. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99613. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99614. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99615. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99616. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99617. /* now override with asm where appropriate */
  99618. #ifndef FLAC__NO_ASM
  99619. if(decoder->private_->cpuinfo.use_asm) {
  99620. #ifdef FLAC__CPU_IA32
  99621. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99622. #ifdef FLAC__HAS_NASM
  99623. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99624. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99625. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99626. #endif
  99627. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99628. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99629. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99630. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99631. }
  99632. else {
  99633. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99634. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99635. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99636. }
  99637. #endif
  99638. #elif defined FLAC__CPU_PPC
  99639. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99640. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99641. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99642. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99643. }
  99644. #endif
  99645. }
  99646. #endif
  99647. /* from here on, errors are fatal */
  99648. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99649. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99650. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99651. }
  99652. decoder->private_->read_callback = read_callback;
  99653. decoder->private_->seek_callback = seek_callback;
  99654. decoder->private_->tell_callback = tell_callback;
  99655. decoder->private_->length_callback = length_callback;
  99656. decoder->private_->eof_callback = eof_callback;
  99657. decoder->private_->write_callback = write_callback;
  99658. decoder->private_->metadata_callback = metadata_callback;
  99659. decoder->private_->error_callback = error_callback;
  99660. decoder->private_->client_data = client_data;
  99661. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99662. decoder->private_->samples_decoded = 0;
  99663. decoder->private_->has_stream_info = false;
  99664. decoder->private_->cached = false;
  99665. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99666. decoder->private_->is_seeking = false;
  99667. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99668. if(!FLAC__stream_decoder_reset(decoder)) {
  99669. /* above call sets the state for us */
  99670. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99671. }
  99672. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99673. }
  99674. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99675. FLAC__StreamDecoder *decoder,
  99676. FLAC__StreamDecoderReadCallback read_callback,
  99677. FLAC__StreamDecoderSeekCallback seek_callback,
  99678. FLAC__StreamDecoderTellCallback tell_callback,
  99679. FLAC__StreamDecoderLengthCallback length_callback,
  99680. FLAC__StreamDecoderEofCallback eof_callback,
  99681. FLAC__StreamDecoderWriteCallback write_callback,
  99682. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99683. FLAC__StreamDecoderErrorCallback error_callback,
  99684. void *client_data
  99685. )
  99686. {
  99687. return init_stream_internal_dec(
  99688. decoder,
  99689. read_callback,
  99690. seek_callback,
  99691. tell_callback,
  99692. length_callback,
  99693. eof_callback,
  99694. write_callback,
  99695. metadata_callback,
  99696. error_callback,
  99697. client_data,
  99698. /*is_ogg=*/false
  99699. );
  99700. }
  99701. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99702. FLAC__StreamDecoder *decoder,
  99703. FLAC__StreamDecoderReadCallback read_callback,
  99704. FLAC__StreamDecoderSeekCallback seek_callback,
  99705. FLAC__StreamDecoderTellCallback tell_callback,
  99706. FLAC__StreamDecoderLengthCallback length_callback,
  99707. FLAC__StreamDecoderEofCallback eof_callback,
  99708. FLAC__StreamDecoderWriteCallback write_callback,
  99709. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99710. FLAC__StreamDecoderErrorCallback error_callback,
  99711. void *client_data
  99712. )
  99713. {
  99714. return init_stream_internal_dec(
  99715. decoder,
  99716. read_callback,
  99717. seek_callback,
  99718. tell_callback,
  99719. length_callback,
  99720. eof_callback,
  99721. write_callback,
  99722. metadata_callback,
  99723. error_callback,
  99724. client_data,
  99725. /*is_ogg=*/true
  99726. );
  99727. }
  99728. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99729. FLAC__StreamDecoder *decoder,
  99730. FILE *file,
  99731. FLAC__StreamDecoderWriteCallback write_callback,
  99732. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99733. FLAC__StreamDecoderErrorCallback error_callback,
  99734. void *client_data,
  99735. FLAC__bool is_ogg
  99736. )
  99737. {
  99738. FLAC__ASSERT(0 != decoder);
  99739. FLAC__ASSERT(0 != file);
  99740. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99741. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99742. if(0 == write_callback || 0 == error_callback)
  99743. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99744. /*
  99745. * To make sure that our file does not go unclosed after an error, we
  99746. * must assign the FILE pointer before any further error can occur in
  99747. * this routine.
  99748. */
  99749. if(file == stdin)
  99750. file = get_binary_stdin_(); /* just to be safe */
  99751. decoder->private_->file = file;
  99752. return init_stream_internal_dec(
  99753. decoder,
  99754. file_read_callback_dec,
  99755. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99756. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99757. decoder->private_->file == stdin? 0: file_length_callback_,
  99758. file_eof_callback_,
  99759. write_callback,
  99760. metadata_callback,
  99761. error_callback,
  99762. client_data,
  99763. is_ogg
  99764. );
  99765. }
  99766. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99767. FLAC__StreamDecoder *decoder,
  99768. FILE *file,
  99769. FLAC__StreamDecoderWriteCallback write_callback,
  99770. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99771. FLAC__StreamDecoderErrorCallback error_callback,
  99772. void *client_data
  99773. )
  99774. {
  99775. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99776. }
  99777. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99778. FLAC__StreamDecoder *decoder,
  99779. FILE *file,
  99780. FLAC__StreamDecoderWriteCallback write_callback,
  99781. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99782. FLAC__StreamDecoderErrorCallback error_callback,
  99783. void *client_data
  99784. )
  99785. {
  99786. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99787. }
  99788. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99789. FLAC__StreamDecoder *decoder,
  99790. const char *filename,
  99791. FLAC__StreamDecoderWriteCallback write_callback,
  99792. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99793. FLAC__StreamDecoderErrorCallback error_callback,
  99794. void *client_data,
  99795. FLAC__bool is_ogg
  99796. )
  99797. {
  99798. FILE *file;
  99799. FLAC__ASSERT(0 != decoder);
  99800. /*
  99801. * To make sure that our file does not go unclosed after an error, we
  99802. * have to do the same entrance checks here that are later performed
  99803. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99804. */
  99805. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99806. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99807. if(0 == write_callback || 0 == error_callback)
  99808. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99809. file = filename? fopen(filename, "rb") : stdin;
  99810. if(0 == file)
  99811. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99812. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99813. }
  99814. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99815. FLAC__StreamDecoder *decoder,
  99816. const char *filename,
  99817. FLAC__StreamDecoderWriteCallback write_callback,
  99818. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99819. FLAC__StreamDecoderErrorCallback error_callback,
  99820. void *client_data
  99821. )
  99822. {
  99823. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99824. }
  99825. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99826. FLAC__StreamDecoder *decoder,
  99827. const char *filename,
  99828. FLAC__StreamDecoderWriteCallback write_callback,
  99829. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99830. FLAC__StreamDecoderErrorCallback error_callback,
  99831. void *client_data
  99832. )
  99833. {
  99834. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99835. }
  99836. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99837. {
  99838. FLAC__bool md5_failed = false;
  99839. unsigned i;
  99840. FLAC__ASSERT(0 != decoder);
  99841. FLAC__ASSERT(0 != decoder->private_);
  99842. FLAC__ASSERT(0 != decoder->protected_);
  99843. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99844. return true;
  99845. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99846. * always call FLAC__MD5Final()
  99847. */
  99848. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99849. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99850. free(decoder->private_->seek_table.data.seek_table.points);
  99851. decoder->private_->seek_table.data.seek_table.points = 0;
  99852. decoder->private_->has_seek_table = false;
  99853. }
  99854. FLAC__bitreader_free(decoder->private_->input);
  99855. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99856. /* WATCHOUT:
  99857. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99858. * output arrays have a buffer of up to 3 zeroes in front
  99859. * (at negative indices) for alignment purposes; we use 4
  99860. * to keep the data well-aligned.
  99861. */
  99862. if(0 != decoder->private_->output[i]) {
  99863. free(decoder->private_->output[i]-4);
  99864. decoder->private_->output[i] = 0;
  99865. }
  99866. if(0 != decoder->private_->residual_unaligned[i]) {
  99867. free(decoder->private_->residual_unaligned[i]);
  99868. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99869. }
  99870. }
  99871. decoder->private_->output_capacity = 0;
  99872. decoder->private_->output_channels = 0;
  99873. #if FLAC__HAS_OGG
  99874. if(decoder->private_->is_ogg)
  99875. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99876. #endif
  99877. if(0 != decoder->private_->file) {
  99878. if(decoder->private_->file != stdin)
  99879. fclose(decoder->private_->file);
  99880. decoder->private_->file = 0;
  99881. }
  99882. if(decoder->private_->do_md5_checking) {
  99883. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99884. md5_failed = true;
  99885. }
  99886. decoder->private_->is_seeking = false;
  99887. set_defaults_dec(decoder);
  99888. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99889. return !md5_failed;
  99890. }
  99891. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99892. {
  99893. FLAC__ASSERT(0 != decoder);
  99894. FLAC__ASSERT(0 != decoder->private_);
  99895. FLAC__ASSERT(0 != decoder->protected_);
  99896. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99897. return false;
  99898. #if FLAC__HAS_OGG
  99899. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99900. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99901. return true;
  99902. #else
  99903. (void)value;
  99904. return false;
  99905. #endif
  99906. }
  99907. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99908. {
  99909. FLAC__ASSERT(0 != decoder);
  99910. FLAC__ASSERT(0 != decoder->protected_);
  99911. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99912. return false;
  99913. decoder->protected_->md5_checking = value;
  99914. return true;
  99915. }
  99916. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99917. {
  99918. FLAC__ASSERT(0 != decoder);
  99919. FLAC__ASSERT(0 != decoder->private_);
  99920. FLAC__ASSERT(0 != decoder->protected_);
  99921. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99922. /* double protection */
  99923. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99924. return false;
  99925. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99926. return false;
  99927. decoder->private_->metadata_filter[type] = true;
  99928. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99929. decoder->private_->metadata_filter_ids_count = 0;
  99930. return true;
  99931. }
  99932. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99933. {
  99934. FLAC__ASSERT(0 != decoder);
  99935. FLAC__ASSERT(0 != decoder->private_);
  99936. FLAC__ASSERT(0 != decoder->protected_);
  99937. FLAC__ASSERT(0 != id);
  99938. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99939. return false;
  99940. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99941. return true;
  99942. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99943. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99944. 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))) {
  99945. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99946. return false;
  99947. }
  99948. decoder->private_->metadata_filter_ids_capacity *= 2;
  99949. }
  99950. 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));
  99951. decoder->private_->metadata_filter_ids_count++;
  99952. return true;
  99953. }
  99954. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99955. {
  99956. unsigned i;
  99957. FLAC__ASSERT(0 != decoder);
  99958. FLAC__ASSERT(0 != decoder->private_);
  99959. FLAC__ASSERT(0 != decoder->protected_);
  99960. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99961. return false;
  99962. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99963. decoder->private_->metadata_filter[i] = true;
  99964. decoder->private_->metadata_filter_ids_count = 0;
  99965. return true;
  99966. }
  99967. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99968. {
  99969. FLAC__ASSERT(0 != decoder);
  99970. FLAC__ASSERT(0 != decoder->private_);
  99971. FLAC__ASSERT(0 != decoder->protected_);
  99972. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99973. /* double protection */
  99974. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99975. return false;
  99976. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99977. return false;
  99978. decoder->private_->metadata_filter[type] = false;
  99979. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99980. decoder->private_->metadata_filter_ids_count = 0;
  99981. return true;
  99982. }
  99983. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99984. {
  99985. FLAC__ASSERT(0 != decoder);
  99986. FLAC__ASSERT(0 != decoder->private_);
  99987. FLAC__ASSERT(0 != decoder->protected_);
  99988. FLAC__ASSERT(0 != id);
  99989. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99990. return false;
  99991. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99992. return true;
  99993. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99994. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99995. 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))) {
  99996. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99997. return false;
  99998. }
  99999. decoder->private_->metadata_filter_ids_capacity *= 2;
  100000. }
  100001. 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));
  100002. decoder->private_->metadata_filter_ids_count++;
  100003. return true;
  100004. }
  100005. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  100006. {
  100007. FLAC__ASSERT(0 != decoder);
  100008. FLAC__ASSERT(0 != decoder->private_);
  100009. FLAC__ASSERT(0 != decoder->protected_);
  100010. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100011. return false;
  100012. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100013. decoder->private_->metadata_filter_ids_count = 0;
  100014. return true;
  100015. }
  100016. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  100017. {
  100018. FLAC__ASSERT(0 != decoder);
  100019. FLAC__ASSERT(0 != decoder->protected_);
  100020. return decoder->protected_->state;
  100021. }
  100022. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  100023. {
  100024. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  100025. }
  100026. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  100027. {
  100028. FLAC__ASSERT(0 != decoder);
  100029. FLAC__ASSERT(0 != decoder->protected_);
  100030. return decoder->protected_->md5_checking;
  100031. }
  100032. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  100033. {
  100034. FLAC__ASSERT(0 != decoder);
  100035. FLAC__ASSERT(0 != decoder->protected_);
  100036. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  100037. }
  100038. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  100039. {
  100040. FLAC__ASSERT(0 != decoder);
  100041. FLAC__ASSERT(0 != decoder->protected_);
  100042. return decoder->protected_->channels;
  100043. }
  100044. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  100045. {
  100046. FLAC__ASSERT(0 != decoder);
  100047. FLAC__ASSERT(0 != decoder->protected_);
  100048. return decoder->protected_->channel_assignment;
  100049. }
  100050. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  100051. {
  100052. FLAC__ASSERT(0 != decoder);
  100053. FLAC__ASSERT(0 != decoder->protected_);
  100054. return decoder->protected_->bits_per_sample;
  100055. }
  100056. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  100057. {
  100058. FLAC__ASSERT(0 != decoder);
  100059. FLAC__ASSERT(0 != decoder->protected_);
  100060. return decoder->protected_->sample_rate;
  100061. }
  100062. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  100063. {
  100064. FLAC__ASSERT(0 != decoder);
  100065. FLAC__ASSERT(0 != decoder->protected_);
  100066. return decoder->protected_->blocksize;
  100067. }
  100068. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  100069. {
  100070. FLAC__ASSERT(0 != decoder);
  100071. FLAC__ASSERT(0 != decoder->private_);
  100072. FLAC__ASSERT(0 != position);
  100073. #if FLAC__HAS_OGG
  100074. if(decoder->private_->is_ogg)
  100075. return false;
  100076. #endif
  100077. if(0 == decoder->private_->tell_callback)
  100078. return false;
  100079. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  100080. return false;
  100081. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  100082. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  100083. return false;
  100084. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  100085. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  100086. return true;
  100087. }
  100088. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  100089. {
  100090. FLAC__ASSERT(0 != decoder);
  100091. FLAC__ASSERT(0 != decoder->private_);
  100092. FLAC__ASSERT(0 != decoder->protected_);
  100093. decoder->private_->samples_decoded = 0;
  100094. decoder->private_->do_md5_checking = false;
  100095. #if FLAC__HAS_OGG
  100096. if(decoder->private_->is_ogg)
  100097. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  100098. #endif
  100099. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  100100. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100101. return false;
  100102. }
  100103. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100104. return true;
  100105. }
  100106. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  100107. {
  100108. FLAC__ASSERT(0 != decoder);
  100109. FLAC__ASSERT(0 != decoder->private_);
  100110. FLAC__ASSERT(0 != decoder->protected_);
  100111. if(!FLAC__stream_decoder_flush(decoder)) {
  100112. /* above call sets the state for us */
  100113. return false;
  100114. }
  100115. #if FLAC__HAS_OGG
  100116. /*@@@ could go in !internal_reset_hack block below */
  100117. if(decoder->private_->is_ogg)
  100118. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  100119. #endif
  100120. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  100121. * (internal_reset_hack) don't try to rewind since we are already at
  100122. * the beginning of the stream and don't want to fail if the input is
  100123. * not seekable.
  100124. */
  100125. if(!decoder->private_->internal_reset_hack) {
  100126. if(decoder->private_->file == stdin)
  100127. return false; /* can't rewind stdin, reset fails */
  100128. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  100129. return false; /* seekable and seek fails, reset fails */
  100130. }
  100131. else
  100132. decoder->private_->internal_reset_hack = false;
  100133. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  100134. decoder->private_->has_stream_info = false;
  100135. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  100136. free(decoder->private_->seek_table.data.seek_table.points);
  100137. decoder->private_->seek_table.data.seek_table.points = 0;
  100138. decoder->private_->has_seek_table = false;
  100139. }
  100140. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  100141. /*
  100142. * This goes in reset() and not flush() because according to the spec, a
  100143. * fixed-blocksize stream must stay that way through the whole stream.
  100144. */
  100145. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  100146. /* We initialize the FLAC__MD5Context even though we may never use it. This
  100147. * is because md5 checking may be turned on to start and then turned off if
  100148. * a seek occurs. So we init the context here and finalize it in
  100149. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  100150. * properly.
  100151. */
  100152. FLAC__MD5Init(&decoder->private_->md5context);
  100153. decoder->private_->first_frame_offset = 0;
  100154. decoder->private_->unparseable_frame_count = 0;
  100155. return true;
  100156. }
  100157. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  100158. {
  100159. FLAC__bool got_a_frame;
  100160. FLAC__ASSERT(0 != decoder);
  100161. FLAC__ASSERT(0 != decoder->protected_);
  100162. while(1) {
  100163. switch(decoder->protected_->state) {
  100164. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100165. if(!find_metadata_(decoder))
  100166. return false; /* above function sets the status for us */
  100167. break;
  100168. case FLAC__STREAM_DECODER_READ_METADATA:
  100169. if(!read_metadata_(decoder))
  100170. return false; /* above function sets the status for us */
  100171. else
  100172. return true;
  100173. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100174. if(!frame_sync_(decoder))
  100175. return true; /* above function sets the status for us */
  100176. break;
  100177. case FLAC__STREAM_DECODER_READ_FRAME:
  100178. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100179. return false; /* above function sets the status for us */
  100180. if(got_a_frame)
  100181. return true; /* above function sets the status for us */
  100182. break;
  100183. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100184. case FLAC__STREAM_DECODER_ABORTED:
  100185. return true;
  100186. default:
  100187. FLAC__ASSERT(0);
  100188. return false;
  100189. }
  100190. }
  100191. }
  100192. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100193. {
  100194. FLAC__ASSERT(0 != decoder);
  100195. FLAC__ASSERT(0 != decoder->protected_);
  100196. while(1) {
  100197. switch(decoder->protected_->state) {
  100198. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100199. if(!find_metadata_(decoder))
  100200. return false; /* above function sets the status for us */
  100201. break;
  100202. case FLAC__STREAM_DECODER_READ_METADATA:
  100203. if(!read_metadata_(decoder))
  100204. return false; /* above function sets the status for us */
  100205. break;
  100206. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100207. case FLAC__STREAM_DECODER_READ_FRAME:
  100208. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100209. case FLAC__STREAM_DECODER_ABORTED:
  100210. return true;
  100211. default:
  100212. FLAC__ASSERT(0);
  100213. return false;
  100214. }
  100215. }
  100216. }
  100217. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100218. {
  100219. FLAC__bool dummy;
  100220. FLAC__ASSERT(0 != decoder);
  100221. FLAC__ASSERT(0 != decoder->protected_);
  100222. while(1) {
  100223. switch(decoder->protected_->state) {
  100224. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100225. if(!find_metadata_(decoder))
  100226. return false; /* above function sets the status for us */
  100227. break;
  100228. case FLAC__STREAM_DECODER_READ_METADATA:
  100229. if(!read_metadata_(decoder))
  100230. return false; /* above function sets the status for us */
  100231. break;
  100232. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100233. if(!frame_sync_(decoder))
  100234. return true; /* above function sets the status for us */
  100235. break;
  100236. case FLAC__STREAM_DECODER_READ_FRAME:
  100237. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100238. return false; /* above function sets the status for us */
  100239. break;
  100240. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100241. case FLAC__STREAM_DECODER_ABORTED:
  100242. return true;
  100243. default:
  100244. FLAC__ASSERT(0);
  100245. return false;
  100246. }
  100247. }
  100248. }
  100249. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100250. {
  100251. FLAC__bool got_a_frame;
  100252. FLAC__ASSERT(0 != decoder);
  100253. FLAC__ASSERT(0 != decoder->protected_);
  100254. while(1) {
  100255. switch(decoder->protected_->state) {
  100256. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100257. case FLAC__STREAM_DECODER_READ_METADATA:
  100258. return false; /* above function sets the status for us */
  100259. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100260. if(!frame_sync_(decoder))
  100261. return true; /* above function sets the status for us */
  100262. break;
  100263. case FLAC__STREAM_DECODER_READ_FRAME:
  100264. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100265. return false; /* above function sets the status for us */
  100266. if(got_a_frame)
  100267. return true; /* above function sets the status for us */
  100268. break;
  100269. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100270. case FLAC__STREAM_DECODER_ABORTED:
  100271. return true;
  100272. default:
  100273. FLAC__ASSERT(0);
  100274. return false;
  100275. }
  100276. }
  100277. }
  100278. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100279. {
  100280. FLAC__uint64 length;
  100281. FLAC__ASSERT(0 != decoder);
  100282. if(
  100283. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100284. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100285. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100286. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100287. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100288. )
  100289. return false;
  100290. if(0 == decoder->private_->seek_callback)
  100291. return false;
  100292. FLAC__ASSERT(decoder->private_->seek_callback);
  100293. FLAC__ASSERT(decoder->private_->tell_callback);
  100294. FLAC__ASSERT(decoder->private_->length_callback);
  100295. FLAC__ASSERT(decoder->private_->eof_callback);
  100296. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100297. return false;
  100298. decoder->private_->is_seeking = true;
  100299. /* turn off md5 checking if a seek is attempted */
  100300. decoder->private_->do_md5_checking = false;
  100301. /* 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) */
  100302. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100303. decoder->private_->is_seeking = false;
  100304. return false;
  100305. }
  100306. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100307. if(
  100308. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100309. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100310. ) {
  100311. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100312. /* above call sets the state for us */
  100313. decoder->private_->is_seeking = false;
  100314. return false;
  100315. }
  100316. /* check this again in case we didn't know total_samples the first time */
  100317. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100318. decoder->private_->is_seeking = false;
  100319. return false;
  100320. }
  100321. }
  100322. {
  100323. const FLAC__bool ok =
  100324. #if FLAC__HAS_OGG
  100325. decoder->private_->is_ogg?
  100326. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100327. #endif
  100328. seek_to_absolute_sample_(decoder, length, sample)
  100329. ;
  100330. decoder->private_->is_seeking = false;
  100331. return ok;
  100332. }
  100333. }
  100334. /***********************************************************************
  100335. *
  100336. * Protected class methods
  100337. *
  100338. ***********************************************************************/
  100339. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100340. {
  100341. FLAC__ASSERT(0 != decoder);
  100342. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100343. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100344. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100345. }
  100346. /***********************************************************************
  100347. *
  100348. * Private class methods
  100349. *
  100350. ***********************************************************************/
  100351. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100352. {
  100353. #if FLAC__HAS_OGG
  100354. decoder->private_->is_ogg = false;
  100355. #endif
  100356. decoder->private_->read_callback = 0;
  100357. decoder->private_->seek_callback = 0;
  100358. decoder->private_->tell_callback = 0;
  100359. decoder->private_->length_callback = 0;
  100360. decoder->private_->eof_callback = 0;
  100361. decoder->private_->write_callback = 0;
  100362. decoder->private_->metadata_callback = 0;
  100363. decoder->private_->error_callback = 0;
  100364. decoder->private_->client_data = 0;
  100365. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100366. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100367. decoder->private_->metadata_filter_ids_count = 0;
  100368. decoder->protected_->md5_checking = false;
  100369. #if FLAC__HAS_OGG
  100370. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100371. #endif
  100372. }
  100373. /*
  100374. * This will forcibly set stdin to binary mode (for OSes that require it)
  100375. */
  100376. FILE *get_binary_stdin_(void)
  100377. {
  100378. /* if something breaks here it is probably due to the presence or
  100379. * absence of an underscore before the identifiers 'setmode',
  100380. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100381. */
  100382. #if defined _MSC_VER || defined __MINGW32__
  100383. _setmode(_fileno(stdin), _O_BINARY);
  100384. #elif defined __CYGWIN__
  100385. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100386. setmode(_fileno(stdin), _O_BINARY);
  100387. #elif defined __EMX__
  100388. setmode(fileno(stdin), O_BINARY);
  100389. #endif
  100390. return stdin;
  100391. }
  100392. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100393. {
  100394. unsigned i;
  100395. FLAC__int32 *tmp;
  100396. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100397. return true;
  100398. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100399. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100400. if(0 != decoder->private_->output[i]) {
  100401. free(decoder->private_->output[i]-4);
  100402. decoder->private_->output[i] = 0;
  100403. }
  100404. if(0 != decoder->private_->residual_unaligned[i]) {
  100405. free(decoder->private_->residual_unaligned[i]);
  100406. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100407. }
  100408. }
  100409. for(i = 0; i < channels; i++) {
  100410. /* WATCHOUT:
  100411. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100412. * output arrays have a buffer of up to 3 zeroes in front
  100413. * (at negative indices) for alignment purposes; we use 4
  100414. * to keep the data well-aligned.
  100415. */
  100416. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100417. if(tmp == 0) {
  100418. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100419. return false;
  100420. }
  100421. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100422. decoder->private_->output[i] = tmp + 4;
  100423. /* WATCHOUT:
  100424. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100425. */
  100426. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100427. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100428. return false;
  100429. }
  100430. }
  100431. decoder->private_->output_capacity = size;
  100432. decoder->private_->output_channels = channels;
  100433. return true;
  100434. }
  100435. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100436. {
  100437. size_t i;
  100438. FLAC__ASSERT(0 != decoder);
  100439. FLAC__ASSERT(0 != decoder->private_);
  100440. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100441. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100442. return true;
  100443. return false;
  100444. }
  100445. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100446. {
  100447. FLAC__uint32 x;
  100448. unsigned i, id_;
  100449. FLAC__bool first = true;
  100450. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100451. for(i = id_ = 0; i < 4; ) {
  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 == FLAC__STREAM_SYNC_STRING[i]) {
  100461. first = true;
  100462. i++;
  100463. id_ = 0;
  100464. continue;
  100465. }
  100466. if(x == ID3V2_TAG_[id_]) {
  100467. id_++;
  100468. i = 0;
  100469. if(id_ == 3) {
  100470. if(!skip_id3v2_tag_(decoder))
  100471. return false; /* skip_id3v2_tag_ sets the state for us */
  100472. }
  100473. continue;
  100474. }
  100475. id_ = 0;
  100476. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100477. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100478. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100479. return false; /* read_callback_ sets the state for us */
  100480. /* 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 */
  100481. /* else we have to check if the second byte is the end of a sync code */
  100482. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100483. decoder->private_->lookahead = (FLAC__byte)x;
  100484. decoder->private_->cached = true;
  100485. }
  100486. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100487. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100488. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100489. return true;
  100490. }
  100491. }
  100492. i = 0;
  100493. if(first) {
  100494. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100495. first = false;
  100496. }
  100497. }
  100498. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100499. return true;
  100500. }
  100501. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100502. {
  100503. FLAC__bool is_last;
  100504. FLAC__uint32 i, x, type, length;
  100505. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100506. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100507. return false; /* read_callback_ sets the state for us */
  100508. is_last = x? true : false;
  100509. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100510. return false; /* read_callback_ sets the state for us */
  100511. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100512. return false; /* read_callback_ sets the state for us */
  100513. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100514. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100515. return false;
  100516. decoder->private_->has_stream_info = true;
  100517. 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))
  100518. decoder->private_->do_md5_checking = false;
  100519. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100520. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100521. }
  100522. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100523. if(!read_metadata_seektable_(decoder, is_last, length))
  100524. return false;
  100525. decoder->private_->has_seek_table = true;
  100526. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100527. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100528. }
  100529. else {
  100530. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100531. unsigned real_length = length;
  100532. FLAC__StreamMetadata block;
  100533. block.is_last = is_last;
  100534. block.type = (FLAC__MetadataType)type;
  100535. block.length = length;
  100536. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100537. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100538. return false; /* read_callback_ sets the state for us */
  100539. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100540. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100541. return false;
  100542. }
  100543. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100544. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100545. skip_it = !skip_it;
  100546. }
  100547. if(skip_it) {
  100548. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100549. return false; /* read_callback_ sets the state for us */
  100550. }
  100551. else {
  100552. switch(type) {
  100553. case FLAC__METADATA_TYPE_PADDING:
  100554. /* skip the padding bytes */
  100555. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100556. return false; /* read_callback_ sets the state for us */
  100557. break;
  100558. case FLAC__METADATA_TYPE_APPLICATION:
  100559. /* remember, we read the ID already */
  100560. if(real_length > 0) {
  100561. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100562. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100563. return false;
  100564. }
  100565. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100566. return false; /* read_callback_ sets the state for us */
  100567. }
  100568. else
  100569. block.data.application.data = 0;
  100570. break;
  100571. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100572. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100573. return false;
  100574. break;
  100575. case FLAC__METADATA_TYPE_CUESHEET:
  100576. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100577. return false;
  100578. break;
  100579. case FLAC__METADATA_TYPE_PICTURE:
  100580. if(!read_metadata_picture_(decoder, &block.data.picture))
  100581. return false;
  100582. break;
  100583. case FLAC__METADATA_TYPE_STREAMINFO:
  100584. case FLAC__METADATA_TYPE_SEEKTABLE:
  100585. FLAC__ASSERT(0);
  100586. break;
  100587. default:
  100588. if(real_length > 0) {
  100589. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100590. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100591. return false;
  100592. }
  100593. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100594. return false; /* read_callback_ sets the state for us */
  100595. }
  100596. else
  100597. block.data.unknown.data = 0;
  100598. break;
  100599. }
  100600. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100601. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100602. /* now we have to free any malloc()ed data in the block */
  100603. switch(type) {
  100604. case FLAC__METADATA_TYPE_PADDING:
  100605. break;
  100606. case FLAC__METADATA_TYPE_APPLICATION:
  100607. if(0 != block.data.application.data)
  100608. free(block.data.application.data);
  100609. break;
  100610. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100611. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100612. free(block.data.vorbis_comment.vendor_string.entry);
  100613. if(block.data.vorbis_comment.num_comments > 0)
  100614. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100615. if(0 != block.data.vorbis_comment.comments[i].entry)
  100616. free(block.data.vorbis_comment.comments[i].entry);
  100617. if(0 != block.data.vorbis_comment.comments)
  100618. free(block.data.vorbis_comment.comments);
  100619. break;
  100620. case FLAC__METADATA_TYPE_CUESHEET:
  100621. if(block.data.cue_sheet.num_tracks > 0)
  100622. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100623. if(0 != block.data.cue_sheet.tracks[i].indices)
  100624. free(block.data.cue_sheet.tracks[i].indices);
  100625. if(0 != block.data.cue_sheet.tracks)
  100626. free(block.data.cue_sheet.tracks);
  100627. break;
  100628. case FLAC__METADATA_TYPE_PICTURE:
  100629. if(0 != block.data.picture.mime_type)
  100630. free(block.data.picture.mime_type);
  100631. if(0 != block.data.picture.description)
  100632. free(block.data.picture.description);
  100633. if(0 != block.data.picture.data)
  100634. free(block.data.picture.data);
  100635. break;
  100636. case FLAC__METADATA_TYPE_STREAMINFO:
  100637. case FLAC__METADATA_TYPE_SEEKTABLE:
  100638. FLAC__ASSERT(0);
  100639. default:
  100640. if(0 != block.data.unknown.data)
  100641. free(block.data.unknown.data);
  100642. break;
  100643. }
  100644. }
  100645. }
  100646. if(is_last) {
  100647. /* if this fails, it's OK, it's just a hint for the seek routine */
  100648. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100649. decoder->private_->first_frame_offset = 0;
  100650. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100651. }
  100652. return true;
  100653. }
  100654. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100655. {
  100656. FLAC__uint32 x;
  100657. unsigned bits, used_bits = 0;
  100658. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100659. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100660. decoder->private_->stream_info.is_last = is_last;
  100661. decoder->private_->stream_info.length = length;
  100662. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100663. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100664. return false; /* read_callback_ sets the state for us */
  100665. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100666. used_bits += bits;
  100667. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100668. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100669. return false; /* read_callback_ sets the state for us */
  100670. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100671. used_bits += bits;
  100672. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100673. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100674. return false; /* read_callback_ sets the state for us */
  100675. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100676. used_bits += bits;
  100677. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100678. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100679. return false; /* read_callback_ sets the state for us */
  100680. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100681. used_bits += bits;
  100682. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100683. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100684. return false; /* read_callback_ sets the state for us */
  100685. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100686. used_bits += bits;
  100687. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100688. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100689. return false; /* read_callback_ sets the state for us */
  100690. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100691. used_bits += bits;
  100692. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100693. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100694. return false; /* read_callback_ sets the state for us */
  100695. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100696. used_bits += bits;
  100697. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100698. 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))
  100699. return false; /* read_callback_ sets the state for us */
  100700. used_bits += bits;
  100701. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100702. return false; /* read_callback_ sets the state for us */
  100703. used_bits += 16*8;
  100704. /* skip the rest of the block */
  100705. FLAC__ASSERT(used_bits % 8 == 0);
  100706. length -= (used_bits / 8);
  100707. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100708. return false; /* read_callback_ sets the state for us */
  100709. return true;
  100710. }
  100711. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100712. {
  100713. FLAC__uint32 i, x;
  100714. FLAC__uint64 xx;
  100715. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100716. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100717. decoder->private_->seek_table.is_last = is_last;
  100718. decoder->private_->seek_table.length = length;
  100719. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100720. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100721. 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)))) {
  100722. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100723. return false;
  100724. }
  100725. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100726. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100727. return false; /* read_callback_ sets the state for us */
  100728. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100729. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100730. return false; /* read_callback_ sets the state for us */
  100731. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100732. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100733. return false; /* read_callback_ sets the state for us */
  100734. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100735. }
  100736. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100737. /* if there is a partial point left, skip over it */
  100738. if(length > 0) {
  100739. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100740. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100741. return false; /* read_callback_ sets the state for us */
  100742. }
  100743. return true;
  100744. }
  100745. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100746. {
  100747. FLAC__uint32 i;
  100748. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100749. /* read vendor string */
  100750. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100751. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100752. return false; /* read_callback_ sets the state for us */
  100753. if(obj->vendor_string.length > 0) {
  100754. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100755. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100756. return false;
  100757. }
  100758. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100759. return false; /* read_callback_ sets the state for us */
  100760. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100761. }
  100762. else
  100763. obj->vendor_string.entry = 0;
  100764. /* read num comments */
  100765. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100766. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100767. return false; /* read_callback_ sets the state for us */
  100768. /* read comments */
  100769. if(obj->num_comments > 0) {
  100770. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100771. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100772. return false;
  100773. }
  100774. for(i = 0; i < obj->num_comments; i++) {
  100775. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100776. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100777. return false; /* read_callback_ sets the state for us */
  100778. if(obj->comments[i].length > 0) {
  100779. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100780. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100781. return false;
  100782. }
  100783. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100784. return false; /* read_callback_ sets the state for us */
  100785. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100786. }
  100787. else
  100788. obj->comments[i].entry = 0;
  100789. }
  100790. }
  100791. else {
  100792. obj->comments = 0;
  100793. }
  100794. return true;
  100795. }
  100796. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100797. {
  100798. FLAC__uint32 i, j, x;
  100799. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100800. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100801. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100802. 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))
  100803. return false; /* read_callback_ sets the state for us */
  100804. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100805. return false; /* read_callback_ sets the state for us */
  100806. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100807. return false; /* read_callback_ sets the state for us */
  100808. obj->is_cd = x? true : false;
  100809. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100810. return false; /* read_callback_ sets the state for us */
  100811. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100812. return false; /* read_callback_ sets the state for us */
  100813. obj->num_tracks = x;
  100814. if(obj->num_tracks > 0) {
  100815. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100816. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100817. return false;
  100818. }
  100819. for(i = 0; i < obj->num_tracks; i++) {
  100820. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100821. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100822. return false; /* read_callback_ sets the state for us */
  100823. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100824. return false; /* read_callback_ sets the state for us */
  100825. track->number = (FLAC__byte)x;
  100826. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100827. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100828. return false; /* read_callback_ sets the state for us */
  100829. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100830. return false; /* read_callback_ sets the state for us */
  100831. track->type = x;
  100832. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100833. return false; /* read_callback_ sets the state for us */
  100834. track->pre_emphasis = x;
  100835. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100836. return false; /* read_callback_ sets the state for us */
  100837. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100838. return false; /* read_callback_ sets the state for us */
  100839. track->num_indices = (FLAC__byte)x;
  100840. if(track->num_indices > 0) {
  100841. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100842. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100843. return false;
  100844. }
  100845. for(j = 0; j < track->num_indices; j++) {
  100846. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100847. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100848. return false; /* read_callback_ sets the state for us */
  100849. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100850. return false; /* read_callback_ sets the state for us */
  100851. index->number = (FLAC__byte)x;
  100852. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100853. return false; /* read_callback_ sets the state for us */
  100854. }
  100855. }
  100856. }
  100857. }
  100858. return true;
  100859. }
  100860. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100861. {
  100862. FLAC__uint32 x;
  100863. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100864. /* read type */
  100865. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100866. return false; /* read_callback_ sets the state for us */
  100867. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100868. /* read MIME type */
  100869. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100870. return false; /* read_callback_ sets the state for us */
  100871. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100872. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100873. return false;
  100874. }
  100875. if(x > 0) {
  100876. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100877. return false; /* read_callback_ sets the state for us */
  100878. }
  100879. obj->mime_type[x] = '\0';
  100880. /* read description */
  100881. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100882. return false; /* read_callback_ sets the state for us */
  100883. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100884. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100885. return false;
  100886. }
  100887. if(x > 0) {
  100888. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100889. return false; /* read_callback_ sets the state for us */
  100890. }
  100891. obj->description[x] = '\0';
  100892. /* read width */
  100893. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100894. return false; /* read_callback_ sets the state for us */
  100895. /* read height */
  100896. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100897. return false; /* read_callback_ sets the state for us */
  100898. /* read depth */
  100899. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100900. return false; /* read_callback_ sets the state for us */
  100901. /* read colors */
  100902. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100903. return false; /* read_callback_ sets the state for us */
  100904. /* read data */
  100905. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100906. return false; /* read_callback_ sets the state for us */
  100907. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100908. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100909. return false;
  100910. }
  100911. if(obj->data_length > 0) {
  100912. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100913. return false; /* read_callback_ sets the state for us */
  100914. }
  100915. return true;
  100916. }
  100917. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100918. {
  100919. FLAC__uint32 x;
  100920. unsigned i, skip;
  100921. /* skip the version and flags bytes */
  100922. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100923. return false; /* read_callback_ sets the state for us */
  100924. /* get the size (in bytes) to skip */
  100925. skip = 0;
  100926. for(i = 0; i < 4; i++) {
  100927. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100928. return false; /* read_callback_ sets the state for us */
  100929. skip <<= 7;
  100930. skip |= (x & 0x7f);
  100931. }
  100932. /* skip the rest of the tag */
  100933. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100934. return false; /* read_callback_ sets the state for us */
  100935. return true;
  100936. }
  100937. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100938. {
  100939. FLAC__uint32 x;
  100940. FLAC__bool first = true;
  100941. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100942. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100943. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100944. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100945. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100946. return true;
  100947. }
  100948. }
  100949. /* make sure we're byte aligned */
  100950. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100951. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100952. return false; /* read_callback_ sets the state for us */
  100953. }
  100954. while(1) {
  100955. if(decoder->private_->cached) {
  100956. x = (FLAC__uint32)decoder->private_->lookahead;
  100957. decoder->private_->cached = false;
  100958. }
  100959. else {
  100960. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100961. return false; /* read_callback_ sets the state for us */
  100962. }
  100963. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100964. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100965. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100966. return false; /* read_callback_ sets the state for us */
  100967. /* 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 */
  100968. /* else we have to check if the second byte is the end of a sync code */
  100969. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100970. decoder->private_->lookahead = (FLAC__byte)x;
  100971. decoder->private_->cached = true;
  100972. }
  100973. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100974. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100975. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100976. return true;
  100977. }
  100978. }
  100979. if(first) {
  100980. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100981. first = false;
  100982. }
  100983. }
  100984. return true;
  100985. }
  100986. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100987. {
  100988. unsigned channel;
  100989. unsigned i;
  100990. FLAC__int32 mid, side;
  100991. unsigned frame_crc; /* the one we calculate from the input stream */
  100992. FLAC__uint32 x;
  100993. *got_a_frame = false;
  100994. /* init the CRC */
  100995. frame_crc = 0;
  100996. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100997. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100998. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100999. if(!read_frame_header_(decoder))
  101000. return false;
  101001. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  101002. return true;
  101003. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  101004. return false;
  101005. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101006. /*
  101007. * first figure the correct bits-per-sample of the subframe
  101008. */
  101009. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  101010. switch(decoder->private_->frame.header.channel_assignment) {
  101011. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101012. /* no adjustment needed */
  101013. break;
  101014. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101015. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101016. if(channel == 1)
  101017. bps++;
  101018. break;
  101019. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101020. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101021. if(channel == 0)
  101022. bps++;
  101023. break;
  101024. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101025. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101026. if(channel == 1)
  101027. bps++;
  101028. break;
  101029. default:
  101030. FLAC__ASSERT(0);
  101031. }
  101032. /*
  101033. * now read it
  101034. */
  101035. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  101036. return false;
  101037. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101038. return true;
  101039. }
  101040. if(!read_zero_padding_(decoder))
  101041. return false;
  101042. 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) */
  101043. return true;
  101044. /*
  101045. * Read the frame CRC-16 from the footer and check
  101046. */
  101047. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  101048. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  101049. return false; /* read_callback_ sets the state for us */
  101050. if(frame_crc == x) {
  101051. if(do_full_decode) {
  101052. /* Undo any special channel coding */
  101053. switch(decoder->private_->frame.header.channel_assignment) {
  101054. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101055. /* do nothing */
  101056. break;
  101057. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101058. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101059. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101060. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  101061. break;
  101062. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101063. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101064. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101065. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  101066. break;
  101067. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101068. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101069. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101070. #if 1
  101071. mid = decoder->private_->output[0][i];
  101072. side = decoder->private_->output[1][i];
  101073. mid <<= 1;
  101074. mid |= (side & 1); /* i.e. if 'side' is odd... */
  101075. decoder->private_->output[0][i] = (mid + side) >> 1;
  101076. decoder->private_->output[1][i] = (mid - side) >> 1;
  101077. #else
  101078. /* OPT: without 'side' temp variable */
  101079. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  101080. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  101081. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  101082. #endif
  101083. }
  101084. break;
  101085. default:
  101086. FLAC__ASSERT(0);
  101087. break;
  101088. }
  101089. }
  101090. }
  101091. else {
  101092. /* Bad frame, emit error and zero the output signal */
  101093. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  101094. if(do_full_decode) {
  101095. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101096. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101097. }
  101098. }
  101099. }
  101100. *got_a_frame = true;
  101101. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  101102. if(decoder->private_->next_fixed_block_size)
  101103. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  101104. /* put the latest values into the public section of the decoder instance */
  101105. decoder->protected_->channels = decoder->private_->frame.header.channels;
  101106. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  101107. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  101108. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  101109. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  101110. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101111. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  101112. /* write it */
  101113. if(do_full_decode) {
  101114. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  101115. return false;
  101116. }
  101117. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101118. return true;
  101119. }
  101120. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  101121. {
  101122. FLAC__uint32 x;
  101123. FLAC__uint64 xx;
  101124. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  101125. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  101126. unsigned raw_header_len;
  101127. FLAC__bool is_unparseable = false;
  101128. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  101129. /* init the raw header with the saved bits from synchronization */
  101130. raw_header[0] = decoder->private_->header_warmup[0];
  101131. raw_header[1] = decoder->private_->header_warmup[1];
  101132. raw_header_len = 2;
  101133. /* check to make sure that reserved bit is 0 */
  101134. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  101135. is_unparseable = true;
  101136. /*
  101137. * Note that along the way as we read the header, we look for a sync
  101138. * code inside. If we find one it would indicate that our original
  101139. * sync was bad since there cannot be a sync code in a valid header.
  101140. *
  101141. * Three kinds of things can go wrong when reading the frame header:
  101142. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  101143. * If we don't find a sync code, it can end up looking like we read
  101144. * a valid but unparseable header, until getting to the frame header
  101145. * CRC. Even then we could get a false positive on the CRC.
  101146. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  101147. * future encoder).
  101148. * 3) We may be on a damaged frame which appears valid but unparseable.
  101149. *
  101150. * For all these reasons, we try and read a complete frame header as
  101151. * long as it seems valid, even if unparseable, up until the frame
  101152. * header CRC.
  101153. */
  101154. /*
  101155. * read in the raw header as bytes so we can CRC it, and parse it on the way
  101156. */
  101157. for(i = 0; i < 2; i++) {
  101158. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101159. return false; /* read_callback_ sets the state for us */
  101160. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101161. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101162. decoder->private_->lookahead = (FLAC__byte)x;
  101163. decoder->private_->cached = true;
  101164. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101165. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101166. return true;
  101167. }
  101168. raw_header[raw_header_len++] = (FLAC__byte)x;
  101169. }
  101170. switch(x = raw_header[2] >> 4) {
  101171. case 0:
  101172. is_unparseable = true;
  101173. break;
  101174. case 1:
  101175. decoder->private_->frame.header.blocksize = 192;
  101176. break;
  101177. case 2:
  101178. case 3:
  101179. case 4:
  101180. case 5:
  101181. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101182. break;
  101183. case 6:
  101184. case 7:
  101185. blocksize_hint = x;
  101186. break;
  101187. case 8:
  101188. case 9:
  101189. case 10:
  101190. case 11:
  101191. case 12:
  101192. case 13:
  101193. case 14:
  101194. case 15:
  101195. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101196. break;
  101197. default:
  101198. FLAC__ASSERT(0);
  101199. break;
  101200. }
  101201. switch(x = raw_header[2] & 0x0f) {
  101202. case 0:
  101203. if(decoder->private_->has_stream_info)
  101204. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101205. else
  101206. is_unparseable = true;
  101207. break;
  101208. case 1:
  101209. decoder->private_->frame.header.sample_rate = 88200;
  101210. break;
  101211. case 2:
  101212. decoder->private_->frame.header.sample_rate = 176400;
  101213. break;
  101214. case 3:
  101215. decoder->private_->frame.header.sample_rate = 192000;
  101216. break;
  101217. case 4:
  101218. decoder->private_->frame.header.sample_rate = 8000;
  101219. break;
  101220. case 5:
  101221. decoder->private_->frame.header.sample_rate = 16000;
  101222. break;
  101223. case 6:
  101224. decoder->private_->frame.header.sample_rate = 22050;
  101225. break;
  101226. case 7:
  101227. decoder->private_->frame.header.sample_rate = 24000;
  101228. break;
  101229. case 8:
  101230. decoder->private_->frame.header.sample_rate = 32000;
  101231. break;
  101232. case 9:
  101233. decoder->private_->frame.header.sample_rate = 44100;
  101234. break;
  101235. case 10:
  101236. decoder->private_->frame.header.sample_rate = 48000;
  101237. break;
  101238. case 11:
  101239. decoder->private_->frame.header.sample_rate = 96000;
  101240. break;
  101241. case 12:
  101242. case 13:
  101243. case 14:
  101244. sample_rate_hint = x;
  101245. break;
  101246. case 15:
  101247. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101248. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101249. return true;
  101250. default:
  101251. FLAC__ASSERT(0);
  101252. }
  101253. x = (unsigned)(raw_header[3] >> 4);
  101254. if(x & 8) {
  101255. decoder->private_->frame.header.channels = 2;
  101256. switch(x & 7) {
  101257. case 0:
  101258. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101259. break;
  101260. case 1:
  101261. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101262. break;
  101263. case 2:
  101264. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101265. break;
  101266. default:
  101267. is_unparseable = true;
  101268. break;
  101269. }
  101270. }
  101271. else {
  101272. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101273. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101274. }
  101275. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101276. case 0:
  101277. if(decoder->private_->has_stream_info)
  101278. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101279. else
  101280. is_unparseable = true;
  101281. break;
  101282. case 1:
  101283. decoder->private_->frame.header.bits_per_sample = 8;
  101284. break;
  101285. case 2:
  101286. decoder->private_->frame.header.bits_per_sample = 12;
  101287. break;
  101288. case 4:
  101289. decoder->private_->frame.header.bits_per_sample = 16;
  101290. break;
  101291. case 5:
  101292. decoder->private_->frame.header.bits_per_sample = 20;
  101293. break;
  101294. case 6:
  101295. decoder->private_->frame.header.bits_per_sample = 24;
  101296. break;
  101297. case 3:
  101298. case 7:
  101299. is_unparseable = true;
  101300. break;
  101301. default:
  101302. FLAC__ASSERT(0);
  101303. break;
  101304. }
  101305. /* check to make sure that reserved bit is 0 */
  101306. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101307. is_unparseable = true;
  101308. /* read the frame's starting sample number (or frame number as the case may be) */
  101309. if(
  101310. raw_header[1] & 0x01 ||
  101311. /*@@@ 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 */
  101312. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101313. ) { /* variable blocksize */
  101314. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101315. return false; /* read_callback_ sets the state for us */
  101316. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101317. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101318. decoder->private_->cached = true;
  101319. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101320. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101321. return true;
  101322. }
  101323. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101324. decoder->private_->frame.header.number.sample_number = xx;
  101325. }
  101326. else { /* fixed blocksize */
  101327. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101328. return false; /* read_callback_ sets the state for us */
  101329. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101330. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101331. decoder->private_->cached = true;
  101332. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101333. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101334. return true;
  101335. }
  101336. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101337. decoder->private_->frame.header.number.frame_number = x;
  101338. }
  101339. if(blocksize_hint) {
  101340. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101341. return false; /* read_callback_ sets the state for us */
  101342. raw_header[raw_header_len++] = (FLAC__byte)x;
  101343. if(blocksize_hint == 7) {
  101344. FLAC__uint32 _x;
  101345. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101346. return false; /* read_callback_ sets the state for us */
  101347. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101348. x = (x << 8) | _x;
  101349. }
  101350. decoder->private_->frame.header.blocksize = x+1;
  101351. }
  101352. if(sample_rate_hint) {
  101353. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101354. return false; /* read_callback_ sets the state for us */
  101355. raw_header[raw_header_len++] = (FLAC__byte)x;
  101356. if(sample_rate_hint != 12) {
  101357. FLAC__uint32 _x;
  101358. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101359. return false; /* read_callback_ sets the state for us */
  101360. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101361. x = (x << 8) | _x;
  101362. }
  101363. if(sample_rate_hint == 12)
  101364. decoder->private_->frame.header.sample_rate = x*1000;
  101365. else if(sample_rate_hint == 13)
  101366. decoder->private_->frame.header.sample_rate = x;
  101367. else
  101368. decoder->private_->frame.header.sample_rate = x*10;
  101369. }
  101370. /* read the CRC-8 byte */
  101371. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101372. return false; /* read_callback_ sets the state for us */
  101373. crc8 = (FLAC__byte)x;
  101374. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101375. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101376. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101377. return true;
  101378. }
  101379. /* calculate the sample number from the frame number if needed */
  101380. decoder->private_->next_fixed_block_size = 0;
  101381. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101382. x = decoder->private_->frame.header.number.frame_number;
  101383. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101384. if(decoder->private_->fixed_block_size)
  101385. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101386. else if(decoder->private_->has_stream_info) {
  101387. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101388. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101389. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101390. }
  101391. else
  101392. is_unparseable = true;
  101393. }
  101394. else if(x == 0) {
  101395. decoder->private_->frame.header.number.sample_number = 0;
  101396. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101397. }
  101398. else {
  101399. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101400. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101401. }
  101402. }
  101403. if(is_unparseable) {
  101404. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101405. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101406. return true;
  101407. }
  101408. return true;
  101409. }
  101410. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101411. {
  101412. FLAC__uint32 x;
  101413. FLAC__bool wasted_bits;
  101414. unsigned i;
  101415. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101416. return false; /* read_callback_ sets the state for us */
  101417. wasted_bits = (x & 1);
  101418. x &= 0xfe;
  101419. if(wasted_bits) {
  101420. unsigned u;
  101421. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101422. return false; /* read_callback_ sets the state for us */
  101423. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101424. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101425. }
  101426. else
  101427. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101428. /*
  101429. * Lots of magic numbers here
  101430. */
  101431. if(x & 0x80) {
  101432. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101433. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101434. return true;
  101435. }
  101436. else if(x == 0) {
  101437. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101438. return false;
  101439. }
  101440. else if(x == 2) {
  101441. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101442. return false;
  101443. }
  101444. else if(x < 16) {
  101445. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101446. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101447. return true;
  101448. }
  101449. else if(x <= 24) {
  101450. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101451. return false;
  101452. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101453. return true;
  101454. }
  101455. else if(x < 64) {
  101456. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101457. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101458. return true;
  101459. }
  101460. else {
  101461. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101462. return false;
  101463. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101464. return true;
  101465. }
  101466. if(wasted_bits && do_full_decode) {
  101467. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101468. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101469. decoder->private_->output[channel][i] <<= x;
  101470. }
  101471. return true;
  101472. }
  101473. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101474. {
  101475. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101476. FLAC__int32 x;
  101477. unsigned i;
  101478. FLAC__int32 *output = decoder->private_->output[channel];
  101479. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101480. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101481. return false; /* read_callback_ sets the state for us */
  101482. subframe->value = x;
  101483. /* decode the subframe */
  101484. if(do_full_decode) {
  101485. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101486. output[i] = x;
  101487. }
  101488. return true;
  101489. }
  101490. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101491. {
  101492. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101493. FLAC__int32 i32;
  101494. FLAC__uint32 u32;
  101495. unsigned u;
  101496. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101497. subframe->residual = decoder->private_->residual[channel];
  101498. subframe->order = order;
  101499. /* read warm-up samples */
  101500. for(u = 0; u < order; u++) {
  101501. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101502. return false; /* read_callback_ sets the state for us */
  101503. subframe->warmup[u] = i32;
  101504. }
  101505. /* read entropy coding method info */
  101506. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101507. return false; /* read_callback_ sets the state for us */
  101508. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101509. switch(subframe->entropy_coding_method.type) {
  101510. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101511. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101512. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101513. return false; /* read_callback_ sets the state for us */
  101514. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101515. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101516. break;
  101517. default:
  101518. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101519. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101520. return true;
  101521. }
  101522. /* read residual */
  101523. switch(subframe->entropy_coding_method.type) {
  101524. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101525. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101526. 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))
  101527. return false;
  101528. break;
  101529. default:
  101530. FLAC__ASSERT(0);
  101531. }
  101532. /* decode the subframe */
  101533. if(do_full_decode) {
  101534. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101535. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101536. }
  101537. return true;
  101538. }
  101539. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101540. {
  101541. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101542. FLAC__int32 i32;
  101543. FLAC__uint32 u32;
  101544. unsigned u;
  101545. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101546. subframe->residual = decoder->private_->residual[channel];
  101547. subframe->order = order;
  101548. /* read warm-up samples */
  101549. for(u = 0; u < order; u++) {
  101550. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101551. return false; /* read_callback_ sets the state for us */
  101552. subframe->warmup[u] = i32;
  101553. }
  101554. /* read qlp coeff precision */
  101555. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101556. return false; /* read_callback_ sets the state for us */
  101557. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101558. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101559. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101560. return true;
  101561. }
  101562. subframe->qlp_coeff_precision = u32+1;
  101563. /* read qlp shift */
  101564. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101565. return false; /* read_callback_ sets the state for us */
  101566. subframe->quantization_level = i32;
  101567. /* read quantized lp coefficiencts */
  101568. for(u = 0; u < order; u++) {
  101569. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101570. return false; /* read_callback_ sets the state for us */
  101571. subframe->qlp_coeff[u] = i32;
  101572. }
  101573. /* read entropy coding method info */
  101574. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101575. return false; /* read_callback_ sets the state for us */
  101576. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101577. switch(subframe->entropy_coding_method.type) {
  101578. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101579. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101580. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101581. return false; /* read_callback_ sets the state for us */
  101582. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101583. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101584. break;
  101585. default:
  101586. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101587. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101588. return true;
  101589. }
  101590. /* read residual */
  101591. switch(subframe->entropy_coding_method.type) {
  101592. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101593. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101594. 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))
  101595. return false;
  101596. break;
  101597. default:
  101598. FLAC__ASSERT(0);
  101599. }
  101600. /* decode the subframe */
  101601. if(do_full_decode) {
  101602. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101603. /*@@@@@@ technically not pessimistic enough, should be more like
  101604. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101605. */
  101606. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101607. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101608. if(order <= 8)
  101609. 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);
  101610. else
  101611. 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);
  101612. }
  101613. else
  101614. 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);
  101615. else
  101616. 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);
  101617. }
  101618. return true;
  101619. }
  101620. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101621. {
  101622. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101623. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101624. unsigned i;
  101625. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101626. subframe->data = residual;
  101627. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101628. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101629. return false; /* read_callback_ sets the state for us */
  101630. residual[i] = x;
  101631. }
  101632. /* decode the subframe */
  101633. if(do_full_decode)
  101634. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101635. return true;
  101636. }
  101637. 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)
  101638. {
  101639. FLAC__uint32 rice_parameter;
  101640. int i;
  101641. unsigned partition, sample, u;
  101642. const unsigned partitions = 1u << partition_order;
  101643. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101644. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101645. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101646. /* sanity checks */
  101647. if(partition_order == 0) {
  101648. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101649. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101650. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101651. return true;
  101652. }
  101653. }
  101654. else {
  101655. if(partition_samples < predictor_order) {
  101656. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101657. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101658. return true;
  101659. }
  101660. }
  101661. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101662. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101663. return false;
  101664. }
  101665. sample = 0;
  101666. for(partition = 0; partition < partitions; partition++) {
  101667. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101668. return false; /* read_callback_ sets the state for us */
  101669. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101670. if(rice_parameter < pesc) {
  101671. partitioned_rice_contents->raw_bits[partition] = 0;
  101672. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101673. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101674. return false; /* read_callback_ sets the state for us */
  101675. sample += u;
  101676. }
  101677. else {
  101678. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101679. return false; /* read_callback_ sets the state for us */
  101680. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101681. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101682. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101683. return false; /* read_callback_ sets the state for us */
  101684. residual[sample] = i;
  101685. }
  101686. }
  101687. }
  101688. return true;
  101689. }
  101690. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101691. {
  101692. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101693. FLAC__uint32 zero = 0;
  101694. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101695. return false; /* read_callback_ sets the state for us */
  101696. if(zero != 0) {
  101697. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101698. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101699. }
  101700. }
  101701. return true;
  101702. }
  101703. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101704. {
  101705. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101706. if(
  101707. #if FLAC__HAS_OGG
  101708. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101709. !decoder->private_->is_ogg &&
  101710. #endif
  101711. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101712. ) {
  101713. *bytes = 0;
  101714. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101715. return false;
  101716. }
  101717. else if(*bytes > 0) {
  101718. /* While seeking, it is possible for our seek to land in the
  101719. * middle of audio data that looks exactly like a frame header
  101720. * from a future version of an encoder. When that happens, our
  101721. * error callback will get an
  101722. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101723. * unparseable_frame_count. But there is a remote possibility
  101724. * that it is properly synced at such a "future-codec frame",
  101725. * so to make sure, we wait to see many "unparseable" errors in
  101726. * a row before bailing out.
  101727. */
  101728. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101729. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101730. return false;
  101731. }
  101732. else {
  101733. const FLAC__StreamDecoderReadStatus status =
  101734. #if FLAC__HAS_OGG
  101735. decoder->private_->is_ogg?
  101736. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101737. #endif
  101738. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101739. ;
  101740. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101741. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101742. return false;
  101743. }
  101744. else if(*bytes == 0) {
  101745. if(
  101746. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101747. (
  101748. #if FLAC__HAS_OGG
  101749. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101750. !decoder->private_->is_ogg &&
  101751. #endif
  101752. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101753. )
  101754. ) {
  101755. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101756. return false;
  101757. }
  101758. else
  101759. return true;
  101760. }
  101761. else
  101762. return true;
  101763. }
  101764. }
  101765. else {
  101766. /* abort to avoid a deadlock */
  101767. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101768. return false;
  101769. }
  101770. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101771. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101772. * and at the same time hit the end of the stream (for example, seeking
  101773. * to a point that is after the beginning of the last Ogg page). There
  101774. * is no way to report an Ogg sync loss through the callbacks (see note
  101775. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101776. * So to keep the decoder from stopping at this point we gate the call
  101777. * to the eof_callback and let the Ogg decoder aspect set the
  101778. * end-of-stream state when it is needed.
  101779. */
  101780. }
  101781. #if FLAC__HAS_OGG
  101782. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101783. {
  101784. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101785. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101786. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101787. /* we don't really have a way to handle lost sync via read
  101788. * callback so we'll let it pass and let the underlying
  101789. * FLAC decoder catch the error
  101790. */
  101791. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101792. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101793. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101794. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101795. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101796. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101797. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101798. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101799. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101800. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101801. default:
  101802. FLAC__ASSERT(0);
  101803. /* double protection */
  101804. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101805. }
  101806. }
  101807. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101808. {
  101809. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101810. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101811. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101812. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101813. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101814. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101815. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101816. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101817. default:
  101818. /* double protection: */
  101819. FLAC__ASSERT(0);
  101820. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101821. }
  101822. }
  101823. #endif
  101824. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101825. {
  101826. if(decoder->private_->is_seeking) {
  101827. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101828. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101829. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101830. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101831. #if FLAC__HAS_OGG
  101832. decoder->private_->got_a_frame = true;
  101833. #endif
  101834. decoder->private_->last_frame = *frame; /* save the frame */
  101835. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101836. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101837. /* kick out of seek mode */
  101838. decoder->private_->is_seeking = false;
  101839. /* shift out the samples before target_sample */
  101840. if(delta > 0) {
  101841. unsigned channel;
  101842. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101843. for(channel = 0; channel < frame->header.channels; channel++)
  101844. newbuffer[channel] = buffer[channel] + delta;
  101845. decoder->private_->last_frame.header.blocksize -= delta;
  101846. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101847. /* write the relevant samples */
  101848. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101849. }
  101850. else {
  101851. /* write the relevant samples */
  101852. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101853. }
  101854. }
  101855. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101856. }
  101857. /*
  101858. * If we never got STREAMINFO, turn off MD5 checking to save
  101859. * cycles since we don't have a sum to compare to anyway
  101860. */
  101861. if(!decoder->private_->has_stream_info)
  101862. decoder->private_->do_md5_checking = false;
  101863. if(decoder->private_->do_md5_checking) {
  101864. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101865. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101866. }
  101867. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101868. }
  101869. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101870. {
  101871. if(!decoder->private_->is_seeking)
  101872. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101873. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101874. decoder->private_->unparseable_frame_count++;
  101875. }
  101876. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101877. {
  101878. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101879. FLAC__int64 pos = -1;
  101880. int i;
  101881. unsigned approx_bytes_per_frame;
  101882. FLAC__bool first_seek = true;
  101883. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101884. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101885. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101886. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101887. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101888. /* take these from the current frame in case they've changed mid-stream */
  101889. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101890. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101891. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101892. /* use values from stream info if we didn't decode a frame */
  101893. if(channels == 0)
  101894. channels = decoder->private_->stream_info.data.stream_info.channels;
  101895. if(bps == 0)
  101896. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101897. /* we are just guessing here */
  101898. if(max_framesize > 0)
  101899. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101900. /*
  101901. * Check if it's a known fixed-blocksize stream. Note that though
  101902. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101903. * never get a STREAMINFO block when decoding so the value of
  101904. * min_blocksize might be zero.
  101905. */
  101906. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101907. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101908. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101909. }
  101910. else
  101911. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101912. /*
  101913. * First, we set an upper and lower bound on where in the
  101914. * stream we will search. For now we assume the worst case
  101915. * scenario, which is our best guess at the beginning of
  101916. * the first frame and end of the stream.
  101917. */
  101918. lower_bound = first_frame_offset;
  101919. lower_bound_sample = 0;
  101920. upper_bound = stream_length;
  101921. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101922. /*
  101923. * Now we refine the bounds if we have a seektable with
  101924. * suitable points. Note that according to the spec they
  101925. * must be ordered by ascending sample number.
  101926. *
  101927. * Note: to protect against invalid seek tables we will ignore points
  101928. * that have frame_samples==0 or sample_number>=total_samples
  101929. */
  101930. if(seek_table) {
  101931. FLAC__uint64 new_lower_bound = lower_bound;
  101932. FLAC__uint64 new_upper_bound = upper_bound;
  101933. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101934. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101935. /* find the closest seek point <= target_sample, if it exists */
  101936. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101937. if(
  101938. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101939. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101940. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101941. seek_table->points[i].sample_number <= target_sample
  101942. )
  101943. break;
  101944. }
  101945. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101946. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101947. new_lower_bound_sample = seek_table->points[i].sample_number;
  101948. }
  101949. /* find the closest seek point > target_sample, if it exists */
  101950. for(i = 0; i < (int)seek_table->num_points; i++) {
  101951. if(
  101952. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101953. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101954. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101955. seek_table->points[i].sample_number > target_sample
  101956. )
  101957. break;
  101958. }
  101959. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101960. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101961. new_upper_bound_sample = seek_table->points[i].sample_number;
  101962. }
  101963. /* final protection against unsorted seek tables; keep original values if bogus */
  101964. if(new_upper_bound >= new_lower_bound) {
  101965. lower_bound = new_lower_bound;
  101966. upper_bound = new_upper_bound;
  101967. lower_bound_sample = new_lower_bound_sample;
  101968. upper_bound_sample = new_upper_bound_sample;
  101969. }
  101970. }
  101971. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101972. /* there are 2 insidious ways that the following equality occurs, which
  101973. * we need to fix:
  101974. * 1) total_samples is 0 (unknown) and target_sample is 0
  101975. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101976. * exactly equal to the last seek point in the seek table; this
  101977. * means there is no seek point above it, and upper_bound_samples
  101978. * remains equal to the estimate (of target_samples) we made above
  101979. * in either case it does not hurt to move upper_bound_sample up by 1
  101980. */
  101981. if(upper_bound_sample == lower_bound_sample)
  101982. upper_bound_sample++;
  101983. decoder->private_->target_sample = target_sample;
  101984. while(1) {
  101985. /* check if the bounds are still ok */
  101986. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101987. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101988. return false;
  101989. }
  101990. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101991. #if defined _MSC_VER || defined __MINGW32__
  101992. /* with VC++ you have to spoon feed it the casting */
  101993. 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;
  101994. #else
  101995. 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;
  101996. #endif
  101997. #else
  101998. /* a little less accurate: */
  101999. if(upper_bound - lower_bound < 0xffffffff)
  102000. 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;
  102001. else /* @@@ WATCHOUT, ~2TB limit */
  102002. 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;
  102003. #endif
  102004. if(pos >= (FLAC__int64)upper_bound)
  102005. pos = (FLAC__int64)upper_bound - 1;
  102006. if(pos < (FLAC__int64)lower_bound)
  102007. pos = (FLAC__int64)lower_bound;
  102008. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102009. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102010. return false;
  102011. }
  102012. if(!FLAC__stream_decoder_flush(decoder)) {
  102013. /* above call sets the state for us */
  102014. return false;
  102015. }
  102016. /* Now we need to get a frame. First we need to reset our
  102017. * unparseable_frame_count; if we get too many unparseable
  102018. * frames in a row, the read callback will return
  102019. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  102020. * FLAC__stream_decoder_process_single() to return false.
  102021. */
  102022. decoder->private_->unparseable_frame_count = 0;
  102023. if(!FLAC__stream_decoder_process_single(decoder)) {
  102024. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102025. return false;
  102026. }
  102027. /* our write callback will change the state when it gets to the target frame */
  102028. /* 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 */
  102029. #if 0
  102030. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  102031. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  102032. break;
  102033. #endif
  102034. if(!decoder->private_->is_seeking)
  102035. break;
  102036. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102037. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102038. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  102039. if (pos == (FLAC__int64)lower_bound) {
  102040. /* can't move back any more than the first frame, something is fatally wrong */
  102041. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102042. return false;
  102043. }
  102044. /* our last move backwards wasn't big enough, try again */
  102045. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  102046. continue;
  102047. }
  102048. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  102049. first_seek = false;
  102050. /* make sure we are not seeking in corrupted stream */
  102051. if (this_frame_sample < lower_bound_sample) {
  102052. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102053. return false;
  102054. }
  102055. /* we need to narrow the search */
  102056. if(target_sample < this_frame_sample) {
  102057. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102058. /*@@@@@@ what will decode position be if at end of stream? */
  102059. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  102060. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102061. return false;
  102062. }
  102063. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  102064. }
  102065. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  102066. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102067. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  102068. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102069. return false;
  102070. }
  102071. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  102072. }
  102073. }
  102074. return true;
  102075. }
  102076. #if FLAC__HAS_OGG
  102077. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  102078. {
  102079. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  102080. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  102081. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  102082. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  102083. FLAC__bool did_a_seek;
  102084. unsigned iteration = 0;
  102085. /* In the first iterations, we will calculate the target byte position
  102086. * by the distance from the target sample to left_sample and
  102087. * right_sample (let's call it "proportional search"). After that, we
  102088. * will switch to binary search.
  102089. */
  102090. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  102091. /* We will switch to a linear search once our current sample is less
  102092. * than this number of samples ahead of the target sample
  102093. */
  102094. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  102095. /* If the total number of samples is unknown, use a large value, and
  102096. * force binary search immediately.
  102097. */
  102098. if(right_sample == 0) {
  102099. right_sample = (FLAC__uint64)(-1);
  102100. BINARY_SEARCH_AFTER_ITERATION = 0;
  102101. }
  102102. decoder->private_->target_sample = target_sample;
  102103. for( ; ; iteration++) {
  102104. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  102105. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  102106. pos = (right_pos + left_pos) / 2;
  102107. }
  102108. else {
  102109. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102110. #if defined _MSC_VER || defined __MINGW32__
  102111. /* with MSVC you have to spoon feed it the casting */
  102112. 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));
  102113. #else
  102114. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  102115. #endif
  102116. #else
  102117. /* a little less accurate: */
  102118. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  102119. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  102120. else /* @@@ WATCHOUT, ~2TB limit */
  102121. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  102122. #endif
  102123. /* @@@ TODO: might want to limit pos to some distance
  102124. * before EOF, to make sure we land before the last frame,
  102125. * thereby getting a this_frame_sample and so having a better
  102126. * estimate.
  102127. */
  102128. }
  102129. /* physical seek */
  102130. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102131. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102132. return false;
  102133. }
  102134. if(!FLAC__stream_decoder_flush(decoder)) {
  102135. /* above call sets the state for us */
  102136. return false;
  102137. }
  102138. did_a_seek = true;
  102139. }
  102140. else
  102141. did_a_seek = false;
  102142. decoder->private_->got_a_frame = false;
  102143. if(!FLAC__stream_decoder_process_single(decoder)) {
  102144. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102145. return false;
  102146. }
  102147. if(!decoder->private_->got_a_frame) {
  102148. if(did_a_seek) {
  102149. /* this can happen if we seek to a point after the last frame; we drop
  102150. * to binary search right away in this case to avoid any wasted
  102151. * iterations of proportional search.
  102152. */
  102153. right_pos = pos;
  102154. BINARY_SEARCH_AFTER_ITERATION = 0;
  102155. }
  102156. else {
  102157. /* this can probably only happen if total_samples is unknown and the
  102158. * target_sample is past the end of the stream
  102159. */
  102160. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102161. return false;
  102162. }
  102163. }
  102164. /* our write callback will change the state when it gets to the target frame */
  102165. else if(!decoder->private_->is_seeking) {
  102166. break;
  102167. }
  102168. else {
  102169. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102170. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102171. if (did_a_seek) {
  102172. if (this_frame_sample <= target_sample) {
  102173. /* The 'equal' case should not happen, since
  102174. * FLAC__stream_decoder_process_single()
  102175. * should recognize that it has hit the
  102176. * target sample and we would exit through
  102177. * the 'break' above.
  102178. */
  102179. FLAC__ASSERT(this_frame_sample != target_sample);
  102180. left_sample = this_frame_sample;
  102181. /* sanity check to avoid infinite loop */
  102182. if (left_pos == pos) {
  102183. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102184. return false;
  102185. }
  102186. left_pos = pos;
  102187. }
  102188. else if(this_frame_sample > target_sample) {
  102189. right_sample = this_frame_sample;
  102190. /* sanity check to avoid infinite loop */
  102191. if (right_pos == pos) {
  102192. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102193. return false;
  102194. }
  102195. right_pos = pos;
  102196. }
  102197. }
  102198. }
  102199. }
  102200. return true;
  102201. }
  102202. #endif
  102203. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102204. {
  102205. (void)client_data;
  102206. if(*bytes > 0) {
  102207. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102208. if(ferror(decoder->private_->file))
  102209. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102210. else if(*bytes == 0)
  102211. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102212. else
  102213. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102214. }
  102215. else
  102216. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102217. }
  102218. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102219. {
  102220. (void)client_data;
  102221. if(decoder->private_->file == stdin)
  102222. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102223. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102224. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102225. else
  102226. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102227. }
  102228. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102229. {
  102230. off_t pos;
  102231. (void)client_data;
  102232. if(decoder->private_->file == stdin)
  102233. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102234. else if((pos = ftello(decoder->private_->file)) < 0)
  102235. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102236. else {
  102237. *absolute_byte_offset = (FLAC__uint64)pos;
  102238. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102239. }
  102240. }
  102241. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102242. {
  102243. struct stat filestats;
  102244. (void)client_data;
  102245. if(decoder->private_->file == stdin)
  102246. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102247. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102248. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102249. else {
  102250. *stream_length = (FLAC__uint64)filestats.st_size;
  102251. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102252. }
  102253. }
  102254. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102255. {
  102256. (void)client_data;
  102257. return feof(decoder->private_->file)? true : false;
  102258. }
  102259. #endif
  102260. /*** End of inlined file: stream_decoder.c ***/
  102261. /*** Start of inlined file: stream_encoder.c ***/
  102262. /*** Start of inlined file: juce_FlacHeader.h ***/
  102263. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102264. // tasks..
  102265. #define VERSION "1.2.1"
  102266. #define FLAC__NO_DLL 1
  102267. #if JUCE_MSVC
  102268. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102269. #endif
  102270. #if JUCE_MAC
  102271. #define FLAC__SYS_DARWIN 1
  102272. #endif
  102273. /*** End of inlined file: juce_FlacHeader.h ***/
  102274. #if JUCE_USE_FLAC
  102275. #if HAVE_CONFIG_H
  102276. # include <config.h>
  102277. #endif
  102278. #if defined _MSC_VER || defined __MINGW32__
  102279. #include <io.h> /* for _setmode() */
  102280. #include <fcntl.h> /* for _O_BINARY */
  102281. #endif
  102282. #if defined __CYGWIN__ || defined __EMX__
  102283. #include <io.h> /* for setmode(), O_BINARY */
  102284. #include <fcntl.h> /* for _O_BINARY */
  102285. #endif
  102286. #include <limits.h>
  102287. #include <stdio.h>
  102288. #include <stdlib.h> /* for malloc() */
  102289. #include <string.h> /* for memcpy() */
  102290. #include <sys/types.h> /* for off_t */
  102291. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102292. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102293. #define fseeko fseek
  102294. #define ftello ftell
  102295. #endif
  102296. #endif
  102297. /*** Start of inlined file: stream_encoder.h ***/
  102298. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102299. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102300. #if FLAC__HAS_OGG
  102301. #include "private/ogg_encoder_aspect.h"
  102302. #endif
  102303. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102304. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102305. typedef enum {
  102306. FLAC__APODIZATION_BARTLETT,
  102307. FLAC__APODIZATION_BARTLETT_HANN,
  102308. FLAC__APODIZATION_BLACKMAN,
  102309. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102310. FLAC__APODIZATION_CONNES,
  102311. FLAC__APODIZATION_FLATTOP,
  102312. FLAC__APODIZATION_GAUSS,
  102313. FLAC__APODIZATION_HAMMING,
  102314. FLAC__APODIZATION_HANN,
  102315. FLAC__APODIZATION_KAISER_BESSEL,
  102316. FLAC__APODIZATION_NUTTALL,
  102317. FLAC__APODIZATION_RECTANGLE,
  102318. FLAC__APODIZATION_TRIANGLE,
  102319. FLAC__APODIZATION_TUKEY,
  102320. FLAC__APODIZATION_WELCH
  102321. } FLAC__ApodizationFunction;
  102322. typedef struct {
  102323. FLAC__ApodizationFunction type;
  102324. union {
  102325. struct {
  102326. FLAC__real stddev;
  102327. } gauss;
  102328. struct {
  102329. FLAC__real p;
  102330. } tukey;
  102331. } parameters;
  102332. } FLAC__ApodizationSpecification;
  102333. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102334. typedef struct FLAC__StreamEncoderProtected {
  102335. FLAC__StreamEncoderState state;
  102336. FLAC__bool verify;
  102337. FLAC__bool streamable_subset;
  102338. FLAC__bool do_md5;
  102339. FLAC__bool do_mid_side_stereo;
  102340. FLAC__bool loose_mid_side_stereo;
  102341. unsigned channels;
  102342. unsigned bits_per_sample;
  102343. unsigned sample_rate;
  102344. unsigned blocksize;
  102345. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102346. unsigned num_apodizations;
  102347. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102348. #endif
  102349. unsigned max_lpc_order;
  102350. unsigned qlp_coeff_precision;
  102351. FLAC__bool do_qlp_coeff_prec_search;
  102352. FLAC__bool do_exhaustive_model_search;
  102353. FLAC__bool do_escape_coding;
  102354. unsigned min_residual_partition_order;
  102355. unsigned max_residual_partition_order;
  102356. unsigned rice_parameter_search_dist;
  102357. FLAC__uint64 total_samples_estimate;
  102358. FLAC__StreamMetadata **metadata;
  102359. unsigned num_metadata_blocks;
  102360. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102361. #if FLAC__HAS_OGG
  102362. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102363. #endif
  102364. } FLAC__StreamEncoderProtected;
  102365. #endif
  102366. /*** End of inlined file: stream_encoder.h ***/
  102367. #if FLAC__HAS_OGG
  102368. #include "include/private/ogg_helper.h"
  102369. #include "include/private/ogg_mapping.h"
  102370. #endif
  102371. /*** Start of inlined file: stream_encoder_framing.h ***/
  102372. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102373. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102374. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102375. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102376. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102377. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102378. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102379. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102380. #endif
  102381. /*** End of inlined file: stream_encoder_framing.h ***/
  102382. /*** Start of inlined file: window.h ***/
  102383. #ifndef FLAC__PRIVATE__WINDOW_H
  102384. #define FLAC__PRIVATE__WINDOW_H
  102385. #ifdef HAVE_CONFIG_H
  102386. #include <config.h>
  102387. #endif
  102388. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102389. /*
  102390. * FLAC__window_*()
  102391. * --------------------------------------------------------------------
  102392. * Calculates window coefficients according to different apodization
  102393. * functions.
  102394. *
  102395. * OUT window[0,L-1]
  102396. * IN L (number of points in window)
  102397. */
  102398. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102399. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102400. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102401. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102402. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102403. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102404. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102405. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102406. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102407. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102408. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102409. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102410. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102411. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102412. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102413. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102414. #endif
  102415. /*** End of inlined file: window.h ***/
  102416. #ifndef FLaC__INLINE
  102417. #define FLaC__INLINE
  102418. #endif
  102419. #ifdef min
  102420. #undef min
  102421. #endif
  102422. #define min(x,y) ((x)<(y)?(x):(y))
  102423. #ifdef max
  102424. #undef max
  102425. #endif
  102426. #define max(x,y) ((x)>(y)?(x):(y))
  102427. /* Exact Rice codeword length calculation is off by default. The simple
  102428. * (and fast) estimation (of how many bits a residual value will be
  102429. * encoded with) in this encoder is very good, almost always yielding
  102430. * compression within 0.1% of exact calculation.
  102431. */
  102432. #undef EXACT_RICE_BITS_CALCULATION
  102433. /* Rice parameter searching is off by default. The simple (and fast)
  102434. * parameter estimation in this encoder is very good, almost always
  102435. * yielding compression within 0.1% of the optimal parameters.
  102436. */
  102437. #undef ENABLE_RICE_PARAMETER_SEARCH
  102438. typedef struct {
  102439. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102440. unsigned size; /* of each data[] in samples */
  102441. unsigned tail;
  102442. } verify_input_fifo;
  102443. typedef struct {
  102444. const FLAC__byte *data;
  102445. unsigned capacity;
  102446. unsigned bytes;
  102447. } verify_output;
  102448. typedef enum {
  102449. ENCODER_IN_MAGIC = 0,
  102450. ENCODER_IN_METADATA = 1,
  102451. ENCODER_IN_AUDIO = 2
  102452. } EncoderStateHint;
  102453. static struct CompressionLevels {
  102454. FLAC__bool do_mid_side_stereo;
  102455. FLAC__bool loose_mid_side_stereo;
  102456. unsigned max_lpc_order;
  102457. unsigned qlp_coeff_precision;
  102458. FLAC__bool do_qlp_coeff_prec_search;
  102459. FLAC__bool do_escape_coding;
  102460. FLAC__bool do_exhaustive_model_search;
  102461. unsigned min_residual_partition_order;
  102462. unsigned max_residual_partition_order;
  102463. unsigned rice_parameter_search_dist;
  102464. } compression_levels_[] = {
  102465. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102466. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102467. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102468. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102469. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102470. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102471. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102472. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102473. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102474. };
  102475. /***********************************************************************
  102476. *
  102477. * Private class method prototypes
  102478. *
  102479. ***********************************************************************/
  102480. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102481. static void free_(FLAC__StreamEncoder *encoder);
  102482. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102483. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102484. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102485. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102486. #if FLAC__HAS_OGG
  102487. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102488. #endif
  102489. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102490. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102491. static FLAC__bool process_subframe_(
  102492. FLAC__StreamEncoder *encoder,
  102493. unsigned min_partition_order,
  102494. unsigned max_partition_order,
  102495. const FLAC__FrameHeader *frame_header,
  102496. unsigned subframe_bps,
  102497. const FLAC__int32 integer_signal[],
  102498. FLAC__Subframe *subframe[2],
  102499. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102500. FLAC__int32 *residual[2],
  102501. unsigned *best_subframe,
  102502. unsigned *best_bits
  102503. );
  102504. static FLAC__bool add_subframe_(
  102505. FLAC__StreamEncoder *encoder,
  102506. unsigned blocksize,
  102507. unsigned subframe_bps,
  102508. const FLAC__Subframe *subframe,
  102509. FLAC__BitWriter *frame
  102510. );
  102511. static unsigned evaluate_constant_subframe_(
  102512. FLAC__StreamEncoder *encoder,
  102513. const FLAC__int32 signal,
  102514. unsigned blocksize,
  102515. unsigned subframe_bps,
  102516. FLAC__Subframe *subframe
  102517. );
  102518. static unsigned evaluate_fixed_subframe_(
  102519. FLAC__StreamEncoder *encoder,
  102520. const FLAC__int32 signal[],
  102521. FLAC__int32 residual[],
  102522. FLAC__uint64 abs_residual_partition_sums[],
  102523. unsigned raw_bits_per_partition[],
  102524. unsigned blocksize,
  102525. unsigned subframe_bps,
  102526. unsigned order,
  102527. unsigned rice_parameter,
  102528. unsigned rice_parameter_limit,
  102529. unsigned min_partition_order,
  102530. unsigned max_partition_order,
  102531. FLAC__bool do_escape_coding,
  102532. unsigned rice_parameter_search_dist,
  102533. FLAC__Subframe *subframe,
  102534. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102535. );
  102536. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102537. static unsigned evaluate_lpc_subframe_(
  102538. FLAC__StreamEncoder *encoder,
  102539. const FLAC__int32 signal[],
  102540. FLAC__int32 residual[],
  102541. FLAC__uint64 abs_residual_partition_sums[],
  102542. unsigned raw_bits_per_partition[],
  102543. const FLAC__real lp_coeff[],
  102544. unsigned blocksize,
  102545. unsigned subframe_bps,
  102546. unsigned order,
  102547. unsigned qlp_coeff_precision,
  102548. unsigned rice_parameter,
  102549. unsigned rice_parameter_limit,
  102550. unsigned min_partition_order,
  102551. unsigned max_partition_order,
  102552. FLAC__bool do_escape_coding,
  102553. unsigned rice_parameter_search_dist,
  102554. FLAC__Subframe *subframe,
  102555. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102556. );
  102557. #endif
  102558. static unsigned evaluate_verbatim_subframe_(
  102559. FLAC__StreamEncoder *encoder,
  102560. const FLAC__int32 signal[],
  102561. unsigned blocksize,
  102562. unsigned subframe_bps,
  102563. FLAC__Subframe *subframe
  102564. );
  102565. static unsigned find_best_partition_order_(
  102566. struct FLAC__StreamEncoderPrivate *private_,
  102567. const FLAC__int32 residual[],
  102568. FLAC__uint64 abs_residual_partition_sums[],
  102569. unsigned raw_bits_per_partition[],
  102570. unsigned residual_samples,
  102571. unsigned predictor_order,
  102572. unsigned rice_parameter,
  102573. unsigned rice_parameter_limit,
  102574. unsigned min_partition_order,
  102575. unsigned max_partition_order,
  102576. unsigned bps,
  102577. FLAC__bool do_escape_coding,
  102578. unsigned rice_parameter_search_dist,
  102579. FLAC__EntropyCodingMethod *best_ecm
  102580. );
  102581. static void precompute_partition_info_sums_(
  102582. const FLAC__int32 residual[],
  102583. FLAC__uint64 abs_residual_partition_sums[],
  102584. unsigned residual_samples,
  102585. unsigned predictor_order,
  102586. unsigned min_partition_order,
  102587. unsigned max_partition_order,
  102588. unsigned bps
  102589. );
  102590. static void precompute_partition_info_escapes_(
  102591. const FLAC__int32 residual[],
  102592. unsigned raw_bits_per_partition[],
  102593. unsigned residual_samples,
  102594. unsigned predictor_order,
  102595. unsigned min_partition_order,
  102596. unsigned max_partition_order
  102597. );
  102598. static FLAC__bool set_partitioned_rice_(
  102599. #ifdef EXACT_RICE_BITS_CALCULATION
  102600. const FLAC__int32 residual[],
  102601. #endif
  102602. const FLAC__uint64 abs_residual_partition_sums[],
  102603. const unsigned raw_bits_per_partition[],
  102604. const unsigned residual_samples,
  102605. const unsigned predictor_order,
  102606. const unsigned suggested_rice_parameter,
  102607. const unsigned rice_parameter_limit,
  102608. const unsigned rice_parameter_search_dist,
  102609. const unsigned partition_order,
  102610. const FLAC__bool search_for_escapes,
  102611. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102612. unsigned *bits
  102613. );
  102614. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102615. /* verify-related routines: */
  102616. static void append_to_verify_fifo_(
  102617. verify_input_fifo *fifo,
  102618. const FLAC__int32 * const input[],
  102619. unsigned input_offset,
  102620. unsigned channels,
  102621. unsigned wide_samples
  102622. );
  102623. static void append_to_verify_fifo_interleaved_(
  102624. verify_input_fifo *fifo,
  102625. const FLAC__int32 input[],
  102626. unsigned input_offset,
  102627. unsigned channels,
  102628. unsigned wide_samples
  102629. );
  102630. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102631. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102632. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102633. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102634. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102635. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102636. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102637. 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);
  102638. static FILE *get_binary_stdout_(void);
  102639. /***********************************************************************
  102640. *
  102641. * Private class data
  102642. *
  102643. ***********************************************************************/
  102644. typedef struct FLAC__StreamEncoderPrivate {
  102645. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102646. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102647. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102648. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102649. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102650. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102651. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102652. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102653. #endif
  102654. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102655. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102656. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102657. FLAC__int32 *residual_workspace_mid_side[2][2];
  102658. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102659. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102660. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102661. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102662. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102663. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102664. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102665. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102666. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102667. unsigned best_subframe_mid_side[2];
  102668. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102669. unsigned best_subframe_bits_mid_side[2];
  102670. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102671. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102672. FLAC__BitWriter *frame; /* the current frame being worked on */
  102673. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102674. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102675. FLAC__ChannelAssignment last_channel_assignment;
  102676. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102677. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102678. unsigned current_sample_number;
  102679. unsigned current_frame_number;
  102680. FLAC__MD5Context md5context;
  102681. FLAC__CPUInfo cpuinfo;
  102682. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102683. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102684. #else
  102685. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102686. #endif
  102687. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102688. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102689. 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[]);
  102690. 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[]);
  102691. 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[]);
  102692. #endif
  102693. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102694. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102695. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102696. FLAC__bool disable_constant_subframes;
  102697. FLAC__bool disable_fixed_subframes;
  102698. FLAC__bool disable_verbatim_subframes;
  102699. #if FLAC__HAS_OGG
  102700. FLAC__bool is_ogg;
  102701. #endif
  102702. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102703. FLAC__StreamEncoderSeekCallback seek_callback;
  102704. FLAC__StreamEncoderTellCallback tell_callback;
  102705. FLAC__StreamEncoderWriteCallback write_callback;
  102706. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102707. FLAC__StreamEncoderProgressCallback progress_callback;
  102708. void *client_data;
  102709. unsigned first_seekpoint_to_check;
  102710. FILE *file; /* only used when encoding to a file */
  102711. FLAC__uint64 bytes_written;
  102712. FLAC__uint64 samples_written;
  102713. unsigned frames_written;
  102714. unsigned total_frames_estimate;
  102715. /* unaligned (original) pointers to allocated data */
  102716. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102717. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102718. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102719. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102720. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102721. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102722. FLAC__real *windowed_signal_unaligned;
  102723. #endif
  102724. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102725. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102726. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102727. unsigned *raw_bits_per_partition_unaligned;
  102728. /*
  102729. * These fields have been moved here from private function local
  102730. * declarations merely to save stack space during encoding.
  102731. */
  102732. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102733. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102734. #endif
  102735. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102736. /*
  102737. * The data for the verify section
  102738. */
  102739. struct {
  102740. FLAC__StreamDecoder *decoder;
  102741. EncoderStateHint state_hint;
  102742. FLAC__bool needs_magic_hack;
  102743. verify_input_fifo input_fifo;
  102744. verify_output output;
  102745. struct {
  102746. FLAC__uint64 absolute_sample;
  102747. unsigned frame_number;
  102748. unsigned channel;
  102749. unsigned sample;
  102750. FLAC__int32 expected;
  102751. FLAC__int32 got;
  102752. } error_stats;
  102753. } verify;
  102754. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102755. } FLAC__StreamEncoderPrivate;
  102756. /***********************************************************************
  102757. *
  102758. * Public static class data
  102759. *
  102760. ***********************************************************************/
  102761. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102762. "FLAC__STREAM_ENCODER_OK",
  102763. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102764. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102765. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102766. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102767. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102768. "FLAC__STREAM_ENCODER_IO_ERROR",
  102769. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102770. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102771. };
  102772. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102773. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102774. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102775. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102776. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102777. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102778. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102779. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102780. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102781. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102782. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102783. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102784. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102785. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102786. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102787. };
  102788. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102789. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102790. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102791. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102792. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102793. };
  102794. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102795. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102796. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102797. };
  102798. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102799. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102800. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102801. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102802. };
  102803. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102804. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102805. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102806. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102807. };
  102808. /* Number of samples that will be overread to watch for end of stream. By
  102809. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102810. * always try to read blocksize+1 samples before encoding a block, so that
  102811. * even if the stream has a total sample count that is an integral multiple
  102812. * of the blocksize, we will still notice when we are encoding the last
  102813. * block. This is needed, for example, to correctly set the end-of-stream
  102814. * marker in Ogg FLAC.
  102815. *
  102816. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102817. * not really any reason to change it.
  102818. */
  102819. static const unsigned OVERREAD_ = 1;
  102820. /***********************************************************************
  102821. *
  102822. * Class constructor/destructor
  102823. *
  102824. */
  102825. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102826. {
  102827. FLAC__StreamEncoder *encoder;
  102828. unsigned i;
  102829. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102830. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102831. if(encoder == 0) {
  102832. return 0;
  102833. }
  102834. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102835. if(encoder->protected_ == 0) {
  102836. free(encoder);
  102837. return 0;
  102838. }
  102839. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102840. if(encoder->private_ == 0) {
  102841. free(encoder->protected_);
  102842. free(encoder);
  102843. return 0;
  102844. }
  102845. encoder->private_->frame = FLAC__bitwriter_new();
  102846. if(encoder->private_->frame == 0) {
  102847. free(encoder->private_);
  102848. free(encoder->protected_);
  102849. free(encoder);
  102850. return 0;
  102851. }
  102852. encoder->private_->file = 0;
  102853. set_defaults_enc(encoder);
  102854. encoder->private_->is_being_deleted = false;
  102855. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102856. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102857. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102858. }
  102859. for(i = 0; i < 2; i++) {
  102860. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102861. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102862. }
  102863. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102864. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102865. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102866. }
  102867. for(i = 0; i < 2; i++) {
  102868. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102869. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102870. }
  102871. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102872. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102873. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102874. }
  102875. for(i = 0; i < 2; i++) {
  102876. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102877. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102878. }
  102879. for(i = 0; i < 2; i++)
  102880. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102881. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102882. return encoder;
  102883. }
  102884. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102885. {
  102886. unsigned i;
  102887. FLAC__ASSERT(0 != encoder);
  102888. FLAC__ASSERT(0 != encoder->protected_);
  102889. FLAC__ASSERT(0 != encoder->private_);
  102890. FLAC__ASSERT(0 != encoder->private_->frame);
  102891. encoder->private_->is_being_deleted = true;
  102892. (void)FLAC__stream_encoder_finish(encoder);
  102893. if(0 != encoder->private_->verify.decoder)
  102894. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102895. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102896. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102897. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102898. }
  102899. for(i = 0; i < 2; i++) {
  102900. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102901. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102902. }
  102903. for(i = 0; i < 2; i++)
  102904. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102905. FLAC__bitwriter_delete(encoder->private_->frame);
  102906. free(encoder->private_);
  102907. free(encoder->protected_);
  102908. free(encoder);
  102909. }
  102910. /***********************************************************************
  102911. *
  102912. * Public class methods
  102913. *
  102914. ***********************************************************************/
  102915. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102916. FLAC__StreamEncoder *encoder,
  102917. FLAC__StreamEncoderReadCallback read_callback,
  102918. FLAC__StreamEncoderWriteCallback write_callback,
  102919. FLAC__StreamEncoderSeekCallback seek_callback,
  102920. FLAC__StreamEncoderTellCallback tell_callback,
  102921. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102922. void *client_data,
  102923. FLAC__bool is_ogg
  102924. )
  102925. {
  102926. unsigned i;
  102927. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102928. FLAC__ASSERT(0 != encoder);
  102929. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102930. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102931. #if !FLAC__HAS_OGG
  102932. if(is_ogg)
  102933. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102934. #endif
  102935. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102936. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102937. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102938. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102939. if(encoder->protected_->channels != 2) {
  102940. encoder->protected_->do_mid_side_stereo = false;
  102941. encoder->protected_->loose_mid_side_stereo = false;
  102942. }
  102943. else if(!encoder->protected_->do_mid_side_stereo)
  102944. encoder->protected_->loose_mid_side_stereo = false;
  102945. if(encoder->protected_->bits_per_sample >= 32)
  102946. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102947. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102948. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102949. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102950. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102951. if(encoder->protected_->blocksize == 0) {
  102952. if(encoder->protected_->max_lpc_order == 0)
  102953. encoder->protected_->blocksize = 1152;
  102954. else
  102955. encoder->protected_->blocksize = 4096;
  102956. }
  102957. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102958. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102959. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102960. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102961. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102962. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102963. if(encoder->protected_->qlp_coeff_precision == 0) {
  102964. if(encoder->protected_->bits_per_sample < 16) {
  102965. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102966. /* @@@ until then we'll make a guess */
  102967. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102968. }
  102969. else if(encoder->protected_->bits_per_sample == 16) {
  102970. if(encoder->protected_->blocksize <= 192)
  102971. encoder->protected_->qlp_coeff_precision = 7;
  102972. else if(encoder->protected_->blocksize <= 384)
  102973. encoder->protected_->qlp_coeff_precision = 8;
  102974. else if(encoder->protected_->blocksize <= 576)
  102975. encoder->protected_->qlp_coeff_precision = 9;
  102976. else if(encoder->protected_->blocksize <= 1152)
  102977. encoder->protected_->qlp_coeff_precision = 10;
  102978. else if(encoder->protected_->blocksize <= 2304)
  102979. encoder->protected_->qlp_coeff_precision = 11;
  102980. else if(encoder->protected_->blocksize <= 4608)
  102981. encoder->protected_->qlp_coeff_precision = 12;
  102982. else
  102983. encoder->protected_->qlp_coeff_precision = 13;
  102984. }
  102985. else {
  102986. if(encoder->protected_->blocksize <= 384)
  102987. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102988. else if(encoder->protected_->blocksize <= 1152)
  102989. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102990. else
  102991. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102992. }
  102993. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102994. }
  102995. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102996. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102997. if(encoder->protected_->streamable_subset) {
  102998. if(
  102999. encoder->protected_->blocksize != 192 &&
  103000. encoder->protected_->blocksize != 576 &&
  103001. encoder->protected_->blocksize != 1152 &&
  103002. encoder->protected_->blocksize != 2304 &&
  103003. encoder->protected_->blocksize != 4608 &&
  103004. encoder->protected_->blocksize != 256 &&
  103005. encoder->protected_->blocksize != 512 &&
  103006. encoder->protected_->blocksize != 1024 &&
  103007. encoder->protected_->blocksize != 2048 &&
  103008. encoder->protected_->blocksize != 4096 &&
  103009. encoder->protected_->blocksize != 8192 &&
  103010. encoder->protected_->blocksize != 16384
  103011. )
  103012. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103013. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  103014. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103015. if(
  103016. encoder->protected_->bits_per_sample != 8 &&
  103017. encoder->protected_->bits_per_sample != 12 &&
  103018. encoder->protected_->bits_per_sample != 16 &&
  103019. encoder->protected_->bits_per_sample != 20 &&
  103020. encoder->protected_->bits_per_sample != 24
  103021. )
  103022. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103023. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  103024. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103025. if(
  103026. encoder->protected_->sample_rate <= 48000 &&
  103027. (
  103028. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  103029. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  103030. )
  103031. ) {
  103032. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103033. }
  103034. }
  103035. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103036. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  103037. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  103038. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  103039. #if FLAC__HAS_OGG
  103040. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  103041. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  103042. unsigned i;
  103043. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  103044. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103045. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  103046. for( ; i > 0; i--)
  103047. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  103048. encoder->protected_->metadata[0] = vc;
  103049. break;
  103050. }
  103051. }
  103052. }
  103053. #endif
  103054. /* keep track of any SEEKTABLE block */
  103055. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  103056. unsigned i;
  103057. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103058. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103059. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  103060. break; /* take only the first one */
  103061. }
  103062. }
  103063. }
  103064. /* validate metadata */
  103065. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  103066. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103067. metadata_has_seektable = false;
  103068. metadata_has_vorbis_comment = false;
  103069. metadata_picture_has_type1 = false;
  103070. metadata_picture_has_type2 = false;
  103071. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103072. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  103073. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  103074. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103075. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103076. if(metadata_has_seektable) /* only one is allowed */
  103077. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103078. metadata_has_seektable = true;
  103079. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  103080. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103081. }
  103082. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103083. if(metadata_has_vorbis_comment) /* only one is allowed */
  103084. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103085. metadata_has_vorbis_comment = true;
  103086. }
  103087. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  103088. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  103089. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103090. }
  103091. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  103092. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  103093. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103094. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  103095. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  103096. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103097. metadata_picture_has_type1 = true;
  103098. /* standard icon must be 32x32 pixel PNG */
  103099. if(
  103100. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  103101. (
  103102. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  103103. m->data.picture.width != 32 ||
  103104. m->data.picture.height != 32
  103105. )
  103106. )
  103107. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103108. }
  103109. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  103110. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  103111. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103112. metadata_picture_has_type2 = true;
  103113. }
  103114. }
  103115. }
  103116. encoder->private_->input_capacity = 0;
  103117. for(i = 0; i < encoder->protected_->channels; i++) {
  103118. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  103119. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103120. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  103121. #endif
  103122. }
  103123. for(i = 0; i < 2; i++) {
  103124. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  103125. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103126. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  103127. #endif
  103128. }
  103129. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103130. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  103131. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  103132. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  103133. #endif
  103134. for(i = 0; i < encoder->protected_->channels; i++) {
  103135. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  103136. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  103137. encoder->private_->best_subframe[i] = 0;
  103138. }
  103139. for(i = 0; i < 2; i++) {
  103140. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  103141. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  103142. encoder->private_->best_subframe_mid_side[i] = 0;
  103143. }
  103144. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  103145. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  103146. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103147. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  103148. #else
  103149. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  103150. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  103151. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  103152. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  103153. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  103154. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  103155. 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);
  103156. #endif
  103157. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  103158. encoder->private_->loose_mid_side_stereo_frames = 1;
  103159. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103160. encoder->private_->current_sample_number = 0;
  103161. encoder->private_->current_frame_number = 0;
  103162. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103163. 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? */
  103164. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103165. /*
  103166. * get the CPU info and set the function pointers
  103167. */
  103168. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103169. /* first default to the non-asm routines */
  103170. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103171. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103172. #endif
  103173. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103174. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103175. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103176. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103177. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103178. #endif
  103179. /* now override with asm where appropriate */
  103180. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103181. # ifndef FLAC__NO_ASM
  103182. if(encoder->private_->cpuinfo.use_asm) {
  103183. # ifdef FLAC__CPU_IA32
  103184. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103185. # ifdef FLAC__HAS_NASM
  103186. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103187. if(encoder->protected_->max_lpc_order < 4)
  103188. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103189. else if(encoder->protected_->max_lpc_order < 8)
  103190. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103191. else if(encoder->protected_->max_lpc_order < 12)
  103192. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103193. else
  103194. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103195. }
  103196. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103197. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103198. else
  103199. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103200. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103201. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103202. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103203. }
  103204. else {
  103205. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103206. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103207. }
  103208. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103209. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103210. # endif /* FLAC__HAS_NASM */
  103211. # endif /* FLAC__CPU_IA32 */
  103212. }
  103213. # endif /* !FLAC__NO_ASM */
  103214. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103215. /* finally override based on wide-ness if necessary */
  103216. if(encoder->private_->use_wide_by_block) {
  103217. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103218. }
  103219. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103220. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103221. #if FLAC__HAS_OGG
  103222. encoder->private_->is_ogg = is_ogg;
  103223. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103224. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103225. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103226. }
  103227. #endif
  103228. encoder->private_->read_callback = read_callback;
  103229. encoder->private_->write_callback = write_callback;
  103230. encoder->private_->seek_callback = seek_callback;
  103231. encoder->private_->tell_callback = tell_callback;
  103232. encoder->private_->metadata_callback = metadata_callback;
  103233. encoder->private_->client_data = client_data;
  103234. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103235. /* the above function sets the state for us in case of an error */
  103236. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103237. }
  103238. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103239. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103240. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103241. }
  103242. /*
  103243. * Set up the verify stuff if necessary
  103244. */
  103245. if(encoder->protected_->verify) {
  103246. /*
  103247. * First, set up the fifo which will hold the
  103248. * original signal to compare against
  103249. */
  103250. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103251. for(i = 0; i < encoder->protected_->channels; i++) {
  103252. 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))) {
  103253. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103254. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103255. }
  103256. }
  103257. encoder->private_->verify.input_fifo.tail = 0;
  103258. /*
  103259. * Now set up a stream decoder for verification
  103260. */
  103261. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103262. if(0 == encoder->private_->verify.decoder) {
  103263. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103264. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103265. }
  103266. 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) {
  103267. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103268. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103269. }
  103270. }
  103271. encoder->private_->verify.error_stats.absolute_sample = 0;
  103272. encoder->private_->verify.error_stats.frame_number = 0;
  103273. encoder->private_->verify.error_stats.channel = 0;
  103274. encoder->private_->verify.error_stats.sample = 0;
  103275. encoder->private_->verify.error_stats.expected = 0;
  103276. encoder->private_->verify.error_stats.got = 0;
  103277. /*
  103278. * These must be done before we write any metadata, because that
  103279. * calls the write_callback, which uses these values.
  103280. */
  103281. encoder->private_->first_seekpoint_to_check = 0;
  103282. encoder->private_->samples_written = 0;
  103283. encoder->protected_->streaminfo_offset = 0;
  103284. encoder->protected_->seektable_offset = 0;
  103285. encoder->protected_->audio_offset = 0;
  103286. /*
  103287. * write the stream header
  103288. */
  103289. if(encoder->protected_->verify)
  103290. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103291. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103292. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103293. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103294. }
  103295. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103296. /* the above function sets the state for us in case of an error */
  103297. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103298. }
  103299. /*
  103300. * write the STREAMINFO metadata block
  103301. */
  103302. if(encoder->protected_->verify)
  103303. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103304. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103305. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103306. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103307. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103308. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103309. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103310. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103311. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103312. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103313. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103314. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103315. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103316. if(encoder->protected_->do_md5)
  103317. FLAC__MD5Init(&encoder->private_->md5context);
  103318. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103319. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103320. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103321. }
  103322. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103323. /* the above function sets the state for us in case of an error */
  103324. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103325. }
  103326. /*
  103327. * Now that the STREAMINFO block is written, we can init this to an
  103328. * absurdly-high value...
  103329. */
  103330. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103331. /* ... and clear this to 0 */
  103332. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103333. /*
  103334. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103335. * if not, we will write an empty one (FLAC__add_metadata_block()
  103336. * automatically supplies the vendor string).
  103337. *
  103338. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103339. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103340. * true it will have already insured that the metadata list is properly
  103341. * ordered.)
  103342. */
  103343. if(!metadata_has_vorbis_comment) {
  103344. FLAC__StreamMetadata vorbis_comment;
  103345. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103346. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103347. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103348. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103349. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103350. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103351. vorbis_comment.data.vorbis_comment.comments = 0;
  103352. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103353. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103354. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103355. }
  103356. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103357. /* the above function sets the state for us in case of an error */
  103358. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103359. }
  103360. }
  103361. /*
  103362. * write the user's metadata blocks
  103363. */
  103364. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103365. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103366. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103367. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103368. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103369. }
  103370. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103371. /* the above function sets the state for us in case of an error */
  103372. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103373. }
  103374. }
  103375. /* now that all the metadata is written, we save the stream offset */
  103376. 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 */
  103377. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103378. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103379. }
  103380. if(encoder->protected_->verify)
  103381. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103382. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103383. }
  103384. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103385. FLAC__StreamEncoder *encoder,
  103386. FLAC__StreamEncoderWriteCallback write_callback,
  103387. FLAC__StreamEncoderSeekCallback seek_callback,
  103388. FLAC__StreamEncoderTellCallback tell_callback,
  103389. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103390. void *client_data
  103391. )
  103392. {
  103393. return init_stream_internal_enc(
  103394. encoder,
  103395. /*read_callback=*/0,
  103396. write_callback,
  103397. seek_callback,
  103398. tell_callback,
  103399. metadata_callback,
  103400. client_data,
  103401. /*is_ogg=*/false
  103402. );
  103403. }
  103404. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103405. FLAC__StreamEncoder *encoder,
  103406. FLAC__StreamEncoderReadCallback read_callback,
  103407. FLAC__StreamEncoderWriteCallback write_callback,
  103408. FLAC__StreamEncoderSeekCallback seek_callback,
  103409. FLAC__StreamEncoderTellCallback tell_callback,
  103410. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103411. void *client_data
  103412. )
  103413. {
  103414. return init_stream_internal_enc(
  103415. encoder,
  103416. read_callback,
  103417. write_callback,
  103418. seek_callback,
  103419. tell_callback,
  103420. metadata_callback,
  103421. client_data,
  103422. /*is_ogg=*/true
  103423. );
  103424. }
  103425. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103426. FLAC__StreamEncoder *encoder,
  103427. FILE *file,
  103428. FLAC__StreamEncoderProgressCallback progress_callback,
  103429. void *client_data,
  103430. FLAC__bool is_ogg
  103431. )
  103432. {
  103433. FLAC__StreamEncoderInitStatus init_status;
  103434. FLAC__ASSERT(0 != encoder);
  103435. FLAC__ASSERT(0 != file);
  103436. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103437. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103438. /* double protection */
  103439. if(file == 0) {
  103440. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103441. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103442. }
  103443. /*
  103444. * To make sure that our file does not go unclosed after an error, we
  103445. * must assign the FILE pointer before any further error can occur in
  103446. * this routine.
  103447. */
  103448. if(file == stdout)
  103449. file = get_binary_stdout_(); /* just to be safe */
  103450. encoder->private_->file = file;
  103451. encoder->private_->progress_callback = progress_callback;
  103452. encoder->private_->bytes_written = 0;
  103453. encoder->private_->samples_written = 0;
  103454. encoder->private_->frames_written = 0;
  103455. init_status = init_stream_internal_enc(
  103456. encoder,
  103457. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103458. file_write_callback_,
  103459. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103460. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103461. /*metadata_callback=*/0,
  103462. client_data,
  103463. is_ogg
  103464. );
  103465. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103466. /* the above function sets the state for us in case of an error */
  103467. return init_status;
  103468. }
  103469. {
  103470. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103471. FLAC__ASSERT(blocksize != 0);
  103472. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103473. }
  103474. return init_status;
  103475. }
  103476. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103477. FLAC__StreamEncoder *encoder,
  103478. FILE *file,
  103479. FLAC__StreamEncoderProgressCallback progress_callback,
  103480. void *client_data
  103481. )
  103482. {
  103483. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103484. }
  103485. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103486. FLAC__StreamEncoder *encoder,
  103487. FILE *file,
  103488. FLAC__StreamEncoderProgressCallback progress_callback,
  103489. void *client_data
  103490. )
  103491. {
  103492. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103493. }
  103494. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103495. FLAC__StreamEncoder *encoder,
  103496. const char *filename,
  103497. FLAC__StreamEncoderProgressCallback progress_callback,
  103498. void *client_data,
  103499. FLAC__bool is_ogg
  103500. )
  103501. {
  103502. FILE *file;
  103503. FLAC__ASSERT(0 != encoder);
  103504. /*
  103505. * To make sure that our file does not go unclosed after an error, we
  103506. * have to do the same entrance checks here that are later performed
  103507. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103508. */
  103509. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103510. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103511. file = filename? fopen(filename, "w+b") : stdout;
  103512. if(file == 0) {
  103513. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103514. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103515. }
  103516. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103517. }
  103518. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103519. FLAC__StreamEncoder *encoder,
  103520. const char *filename,
  103521. FLAC__StreamEncoderProgressCallback progress_callback,
  103522. void *client_data
  103523. )
  103524. {
  103525. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103526. }
  103527. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103528. FLAC__StreamEncoder *encoder,
  103529. const char *filename,
  103530. FLAC__StreamEncoderProgressCallback progress_callback,
  103531. void *client_data
  103532. )
  103533. {
  103534. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103535. }
  103536. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103537. {
  103538. FLAC__bool error = false;
  103539. FLAC__ASSERT(0 != encoder);
  103540. FLAC__ASSERT(0 != encoder->private_);
  103541. FLAC__ASSERT(0 != encoder->protected_);
  103542. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103543. return true;
  103544. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103545. if(encoder->private_->current_sample_number != 0) {
  103546. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103547. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103548. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103549. error = true;
  103550. }
  103551. }
  103552. if(encoder->protected_->do_md5)
  103553. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103554. if(!encoder->private_->is_being_deleted) {
  103555. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103556. if(encoder->private_->seek_callback) {
  103557. #if FLAC__HAS_OGG
  103558. if(encoder->private_->is_ogg)
  103559. update_ogg_metadata_(encoder);
  103560. else
  103561. #endif
  103562. update_metadata_(encoder);
  103563. /* check if an error occurred while updating metadata */
  103564. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103565. error = true;
  103566. }
  103567. if(encoder->private_->metadata_callback)
  103568. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103569. }
  103570. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103571. if(!error)
  103572. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103573. error = true;
  103574. }
  103575. }
  103576. if(0 != encoder->private_->file) {
  103577. if(encoder->private_->file != stdout)
  103578. fclose(encoder->private_->file);
  103579. encoder->private_->file = 0;
  103580. }
  103581. #if FLAC__HAS_OGG
  103582. if(encoder->private_->is_ogg)
  103583. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103584. #endif
  103585. free_(encoder);
  103586. set_defaults_enc(encoder);
  103587. if(!error)
  103588. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103589. return !error;
  103590. }
  103591. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103592. {
  103593. FLAC__ASSERT(0 != encoder);
  103594. FLAC__ASSERT(0 != encoder->private_);
  103595. FLAC__ASSERT(0 != encoder->protected_);
  103596. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103597. return false;
  103598. #if FLAC__HAS_OGG
  103599. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103600. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103601. return true;
  103602. #else
  103603. (void)value;
  103604. return false;
  103605. #endif
  103606. }
  103607. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103608. {
  103609. FLAC__ASSERT(0 != encoder);
  103610. FLAC__ASSERT(0 != encoder->private_);
  103611. FLAC__ASSERT(0 != encoder->protected_);
  103612. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103613. return false;
  103614. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103615. encoder->protected_->verify = value;
  103616. #endif
  103617. return true;
  103618. }
  103619. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103620. {
  103621. FLAC__ASSERT(0 != encoder);
  103622. FLAC__ASSERT(0 != encoder->private_);
  103623. FLAC__ASSERT(0 != encoder->protected_);
  103624. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103625. return false;
  103626. encoder->protected_->streamable_subset = value;
  103627. return true;
  103628. }
  103629. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103630. {
  103631. FLAC__ASSERT(0 != encoder);
  103632. FLAC__ASSERT(0 != encoder->private_);
  103633. FLAC__ASSERT(0 != encoder->protected_);
  103634. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103635. return false;
  103636. encoder->protected_->do_md5 = value;
  103637. return true;
  103638. }
  103639. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103640. {
  103641. FLAC__ASSERT(0 != encoder);
  103642. FLAC__ASSERT(0 != encoder->private_);
  103643. FLAC__ASSERT(0 != encoder->protected_);
  103644. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103645. return false;
  103646. encoder->protected_->channels = value;
  103647. return true;
  103648. }
  103649. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103650. {
  103651. FLAC__ASSERT(0 != encoder);
  103652. FLAC__ASSERT(0 != encoder->private_);
  103653. FLAC__ASSERT(0 != encoder->protected_);
  103654. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103655. return false;
  103656. encoder->protected_->bits_per_sample = value;
  103657. return true;
  103658. }
  103659. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103660. {
  103661. FLAC__ASSERT(0 != encoder);
  103662. FLAC__ASSERT(0 != encoder->private_);
  103663. FLAC__ASSERT(0 != encoder->protected_);
  103664. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103665. return false;
  103666. encoder->protected_->sample_rate = value;
  103667. return true;
  103668. }
  103669. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103670. {
  103671. FLAC__bool ok = true;
  103672. FLAC__ASSERT(0 != encoder);
  103673. FLAC__ASSERT(0 != encoder->private_);
  103674. FLAC__ASSERT(0 != encoder->protected_);
  103675. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103676. return false;
  103677. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103678. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103679. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103680. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103681. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103682. #if 0
  103683. /* was: */
  103684. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103685. /* but it's too hard to specify the string in a locale-specific way */
  103686. #else
  103687. encoder->protected_->num_apodizations = 1;
  103688. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103689. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103690. #endif
  103691. #endif
  103692. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103693. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103694. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103695. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103696. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103697. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103698. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103699. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103700. return ok;
  103701. }
  103702. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103703. {
  103704. FLAC__ASSERT(0 != encoder);
  103705. FLAC__ASSERT(0 != encoder->private_);
  103706. FLAC__ASSERT(0 != encoder->protected_);
  103707. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103708. return false;
  103709. encoder->protected_->blocksize = value;
  103710. return true;
  103711. }
  103712. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103713. {
  103714. FLAC__ASSERT(0 != encoder);
  103715. FLAC__ASSERT(0 != encoder->private_);
  103716. FLAC__ASSERT(0 != encoder->protected_);
  103717. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103718. return false;
  103719. encoder->protected_->do_mid_side_stereo = value;
  103720. return true;
  103721. }
  103722. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103723. {
  103724. FLAC__ASSERT(0 != encoder);
  103725. FLAC__ASSERT(0 != encoder->private_);
  103726. FLAC__ASSERT(0 != encoder->protected_);
  103727. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103728. return false;
  103729. encoder->protected_->loose_mid_side_stereo = value;
  103730. return true;
  103731. }
  103732. /*@@@@add to tests*/
  103733. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103734. {
  103735. FLAC__ASSERT(0 != encoder);
  103736. FLAC__ASSERT(0 != encoder->private_);
  103737. FLAC__ASSERT(0 != encoder->protected_);
  103738. FLAC__ASSERT(0 != specification);
  103739. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103740. return false;
  103741. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103742. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103743. #else
  103744. encoder->protected_->num_apodizations = 0;
  103745. while(1) {
  103746. const char *s = strchr(specification, ';');
  103747. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103748. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103749. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103750. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103751. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103752. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103753. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103754. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103755. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103756. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103757. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103758. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103759. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103760. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103761. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103762. if (stddev > 0.0 && stddev <= 0.5) {
  103763. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103764. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103765. }
  103766. }
  103767. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103768. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103769. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103770. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103771. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103772. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103773. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103774. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103775. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103776. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103777. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103778. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103779. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103780. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103781. if (p >= 0.0 && p <= 1.0) {
  103782. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103783. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103784. }
  103785. }
  103786. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103787. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103788. if (encoder->protected_->num_apodizations == 32)
  103789. break;
  103790. if (s)
  103791. specification = s+1;
  103792. else
  103793. break;
  103794. }
  103795. if(encoder->protected_->num_apodizations == 0) {
  103796. encoder->protected_->num_apodizations = 1;
  103797. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103798. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103799. }
  103800. #endif
  103801. return true;
  103802. }
  103803. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103804. {
  103805. FLAC__ASSERT(0 != encoder);
  103806. FLAC__ASSERT(0 != encoder->private_);
  103807. FLAC__ASSERT(0 != encoder->protected_);
  103808. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103809. return false;
  103810. encoder->protected_->max_lpc_order = value;
  103811. return true;
  103812. }
  103813. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103814. {
  103815. FLAC__ASSERT(0 != encoder);
  103816. FLAC__ASSERT(0 != encoder->private_);
  103817. FLAC__ASSERT(0 != encoder->protected_);
  103818. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103819. return false;
  103820. encoder->protected_->qlp_coeff_precision = value;
  103821. return true;
  103822. }
  103823. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103824. {
  103825. FLAC__ASSERT(0 != encoder);
  103826. FLAC__ASSERT(0 != encoder->private_);
  103827. FLAC__ASSERT(0 != encoder->protected_);
  103828. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103829. return false;
  103830. encoder->protected_->do_qlp_coeff_prec_search = value;
  103831. return true;
  103832. }
  103833. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103834. {
  103835. FLAC__ASSERT(0 != encoder);
  103836. FLAC__ASSERT(0 != encoder->private_);
  103837. FLAC__ASSERT(0 != encoder->protected_);
  103838. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103839. return false;
  103840. #if 0
  103841. /*@@@ deprecated: */
  103842. encoder->protected_->do_escape_coding = value;
  103843. #else
  103844. (void)value;
  103845. #endif
  103846. return true;
  103847. }
  103848. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103849. {
  103850. FLAC__ASSERT(0 != encoder);
  103851. FLAC__ASSERT(0 != encoder->private_);
  103852. FLAC__ASSERT(0 != encoder->protected_);
  103853. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103854. return false;
  103855. encoder->protected_->do_exhaustive_model_search = value;
  103856. return true;
  103857. }
  103858. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103859. {
  103860. FLAC__ASSERT(0 != encoder);
  103861. FLAC__ASSERT(0 != encoder->private_);
  103862. FLAC__ASSERT(0 != encoder->protected_);
  103863. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103864. return false;
  103865. encoder->protected_->min_residual_partition_order = value;
  103866. return true;
  103867. }
  103868. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103869. {
  103870. FLAC__ASSERT(0 != encoder);
  103871. FLAC__ASSERT(0 != encoder->private_);
  103872. FLAC__ASSERT(0 != encoder->protected_);
  103873. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103874. return false;
  103875. encoder->protected_->max_residual_partition_order = value;
  103876. return true;
  103877. }
  103878. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103879. {
  103880. FLAC__ASSERT(0 != encoder);
  103881. FLAC__ASSERT(0 != encoder->private_);
  103882. FLAC__ASSERT(0 != encoder->protected_);
  103883. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103884. return false;
  103885. #if 0
  103886. /*@@@ deprecated: */
  103887. encoder->protected_->rice_parameter_search_dist = value;
  103888. #else
  103889. (void)value;
  103890. #endif
  103891. return true;
  103892. }
  103893. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103894. {
  103895. FLAC__ASSERT(0 != encoder);
  103896. FLAC__ASSERT(0 != encoder->private_);
  103897. FLAC__ASSERT(0 != encoder->protected_);
  103898. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103899. return false;
  103900. encoder->protected_->total_samples_estimate = value;
  103901. return true;
  103902. }
  103903. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103904. {
  103905. FLAC__ASSERT(0 != encoder);
  103906. FLAC__ASSERT(0 != encoder->private_);
  103907. FLAC__ASSERT(0 != encoder->protected_);
  103908. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103909. return false;
  103910. if(0 == metadata)
  103911. num_blocks = 0;
  103912. if(0 == num_blocks)
  103913. metadata = 0;
  103914. /* realloc() does not do exactly what we want so... */
  103915. if(encoder->protected_->metadata) {
  103916. free(encoder->protected_->metadata);
  103917. encoder->protected_->metadata = 0;
  103918. encoder->protected_->num_metadata_blocks = 0;
  103919. }
  103920. if(num_blocks) {
  103921. FLAC__StreamMetadata **m;
  103922. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103923. return false;
  103924. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103925. encoder->protected_->metadata = m;
  103926. encoder->protected_->num_metadata_blocks = num_blocks;
  103927. }
  103928. #if FLAC__HAS_OGG
  103929. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103930. return false;
  103931. #endif
  103932. return true;
  103933. }
  103934. /*
  103935. * These three functions are not static, but not publically exposed in
  103936. * include/FLAC/ either. They are used by the test suite.
  103937. */
  103938. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103939. {
  103940. FLAC__ASSERT(0 != encoder);
  103941. FLAC__ASSERT(0 != encoder->private_);
  103942. FLAC__ASSERT(0 != encoder->protected_);
  103943. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103944. return false;
  103945. encoder->private_->disable_constant_subframes = value;
  103946. return true;
  103947. }
  103948. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103949. {
  103950. FLAC__ASSERT(0 != encoder);
  103951. FLAC__ASSERT(0 != encoder->private_);
  103952. FLAC__ASSERT(0 != encoder->protected_);
  103953. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103954. return false;
  103955. encoder->private_->disable_fixed_subframes = value;
  103956. return true;
  103957. }
  103958. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103959. {
  103960. FLAC__ASSERT(0 != encoder);
  103961. FLAC__ASSERT(0 != encoder->private_);
  103962. FLAC__ASSERT(0 != encoder->protected_);
  103963. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103964. return false;
  103965. encoder->private_->disable_verbatim_subframes = value;
  103966. return true;
  103967. }
  103968. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103969. {
  103970. FLAC__ASSERT(0 != encoder);
  103971. FLAC__ASSERT(0 != encoder->private_);
  103972. FLAC__ASSERT(0 != encoder->protected_);
  103973. return encoder->protected_->state;
  103974. }
  103975. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103976. {
  103977. FLAC__ASSERT(0 != encoder);
  103978. FLAC__ASSERT(0 != encoder->private_);
  103979. FLAC__ASSERT(0 != encoder->protected_);
  103980. if(encoder->protected_->verify)
  103981. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103982. else
  103983. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103984. }
  103985. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103986. {
  103987. FLAC__ASSERT(0 != encoder);
  103988. FLAC__ASSERT(0 != encoder->private_);
  103989. FLAC__ASSERT(0 != encoder->protected_);
  103990. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103991. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103992. else
  103993. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103994. }
  103995. 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)
  103996. {
  103997. FLAC__ASSERT(0 != encoder);
  103998. FLAC__ASSERT(0 != encoder->private_);
  103999. FLAC__ASSERT(0 != encoder->protected_);
  104000. if(0 != absolute_sample)
  104001. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  104002. if(0 != frame_number)
  104003. *frame_number = encoder->private_->verify.error_stats.frame_number;
  104004. if(0 != channel)
  104005. *channel = encoder->private_->verify.error_stats.channel;
  104006. if(0 != sample)
  104007. *sample = encoder->private_->verify.error_stats.sample;
  104008. if(0 != expected)
  104009. *expected = encoder->private_->verify.error_stats.expected;
  104010. if(0 != got)
  104011. *got = encoder->private_->verify.error_stats.got;
  104012. }
  104013. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  104014. {
  104015. FLAC__ASSERT(0 != encoder);
  104016. FLAC__ASSERT(0 != encoder->private_);
  104017. FLAC__ASSERT(0 != encoder->protected_);
  104018. return encoder->protected_->verify;
  104019. }
  104020. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  104021. {
  104022. FLAC__ASSERT(0 != encoder);
  104023. FLAC__ASSERT(0 != encoder->private_);
  104024. FLAC__ASSERT(0 != encoder->protected_);
  104025. return encoder->protected_->streamable_subset;
  104026. }
  104027. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  104028. {
  104029. FLAC__ASSERT(0 != encoder);
  104030. FLAC__ASSERT(0 != encoder->private_);
  104031. FLAC__ASSERT(0 != encoder->protected_);
  104032. return encoder->protected_->do_md5;
  104033. }
  104034. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  104035. {
  104036. FLAC__ASSERT(0 != encoder);
  104037. FLAC__ASSERT(0 != encoder->private_);
  104038. FLAC__ASSERT(0 != encoder->protected_);
  104039. return encoder->protected_->channels;
  104040. }
  104041. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  104042. {
  104043. FLAC__ASSERT(0 != encoder);
  104044. FLAC__ASSERT(0 != encoder->private_);
  104045. FLAC__ASSERT(0 != encoder->protected_);
  104046. return encoder->protected_->bits_per_sample;
  104047. }
  104048. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  104049. {
  104050. FLAC__ASSERT(0 != encoder);
  104051. FLAC__ASSERT(0 != encoder->private_);
  104052. FLAC__ASSERT(0 != encoder->protected_);
  104053. return encoder->protected_->sample_rate;
  104054. }
  104055. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  104056. {
  104057. FLAC__ASSERT(0 != encoder);
  104058. FLAC__ASSERT(0 != encoder->private_);
  104059. FLAC__ASSERT(0 != encoder->protected_);
  104060. return encoder->protected_->blocksize;
  104061. }
  104062. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104063. {
  104064. FLAC__ASSERT(0 != encoder);
  104065. FLAC__ASSERT(0 != encoder->private_);
  104066. FLAC__ASSERT(0 != encoder->protected_);
  104067. return encoder->protected_->do_mid_side_stereo;
  104068. }
  104069. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104070. {
  104071. FLAC__ASSERT(0 != encoder);
  104072. FLAC__ASSERT(0 != encoder->private_);
  104073. FLAC__ASSERT(0 != encoder->protected_);
  104074. return encoder->protected_->loose_mid_side_stereo;
  104075. }
  104076. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  104077. {
  104078. FLAC__ASSERT(0 != encoder);
  104079. FLAC__ASSERT(0 != encoder->private_);
  104080. FLAC__ASSERT(0 != encoder->protected_);
  104081. return encoder->protected_->max_lpc_order;
  104082. }
  104083. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  104084. {
  104085. FLAC__ASSERT(0 != encoder);
  104086. FLAC__ASSERT(0 != encoder->private_);
  104087. FLAC__ASSERT(0 != encoder->protected_);
  104088. return encoder->protected_->qlp_coeff_precision;
  104089. }
  104090. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  104091. {
  104092. FLAC__ASSERT(0 != encoder);
  104093. FLAC__ASSERT(0 != encoder->private_);
  104094. FLAC__ASSERT(0 != encoder->protected_);
  104095. return encoder->protected_->do_qlp_coeff_prec_search;
  104096. }
  104097. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  104098. {
  104099. FLAC__ASSERT(0 != encoder);
  104100. FLAC__ASSERT(0 != encoder->private_);
  104101. FLAC__ASSERT(0 != encoder->protected_);
  104102. return encoder->protected_->do_escape_coding;
  104103. }
  104104. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  104105. {
  104106. FLAC__ASSERT(0 != encoder);
  104107. FLAC__ASSERT(0 != encoder->private_);
  104108. FLAC__ASSERT(0 != encoder->protected_);
  104109. return encoder->protected_->do_exhaustive_model_search;
  104110. }
  104111. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104112. {
  104113. FLAC__ASSERT(0 != encoder);
  104114. FLAC__ASSERT(0 != encoder->private_);
  104115. FLAC__ASSERT(0 != encoder->protected_);
  104116. return encoder->protected_->min_residual_partition_order;
  104117. }
  104118. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104119. {
  104120. FLAC__ASSERT(0 != encoder);
  104121. FLAC__ASSERT(0 != encoder->private_);
  104122. FLAC__ASSERT(0 != encoder->protected_);
  104123. return encoder->protected_->max_residual_partition_order;
  104124. }
  104125. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  104126. {
  104127. FLAC__ASSERT(0 != encoder);
  104128. FLAC__ASSERT(0 != encoder->private_);
  104129. FLAC__ASSERT(0 != encoder->protected_);
  104130. return encoder->protected_->rice_parameter_search_dist;
  104131. }
  104132. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  104133. {
  104134. FLAC__ASSERT(0 != encoder);
  104135. FLAC__ASSERT(0 != encoder->private_);
  104136. FLAC__ASSERT(0 != encoder->protected_);
  104137. return encoder->protected_->total_samples_estimate;
  104138. }
  104139. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  104140. {
  104141. unsigned i, j = 0, channel;
  104142. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104143. FLAC__ASSERT(0 != encoder);
  104144. FLAC__ASSERT(0 != encoder->private_);
  104145. FLAC__ASSERT(0 != encoder->protected_);
  104146. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104147. do {
  104148. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  104149. if(encoder->protected_->verify)
  104150. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  104151. for(channel = 0; channel < channels; channel++)
  104152. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  104153. if(encoder->protected_->do_mid_side_stereo) {
  104154. FLAC__ASSERT(channels == 2);
  104155. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104156. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104157. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  104158. 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' ! */
  104159. }
  104160. }
  104161. else
  104162. j += n;
  104163. encoder->private_->current_sample_number += n;
  104164. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104165. if(encoder->private_->current_sample_number > blocksize) {
  104166. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104167. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104168. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104169. return false;
  104170. /* move unprocessed overread samples to beginnings of arrays */
  104171. for(channel = 0; channel < channels; channel++)
  104172. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104173. if(encoder->protected_->do_mid_side_stereo) {
  104174. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104175. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104176. }
  104177. encoder->private_->current_sample_number = 1;
  104178. }
  104179. } while(j < samples);
  104180. return true;
  104181. }
  104182. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104183. {
  104184. unsigned i, j, k, channel;
  104185. FLAC__int32 x, mid, side;
  104186. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104187. FLAC__ASSERT(0 != encoder);
  104188. FLAC__ASSERT(0 != encoder->private_);
  104189. FLAC__ASSERT(0 != encoder->protected_);
  104190. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104191. j = k = 0;
  104192. /*
  104193. * we have several flavors of the same basic loop, optimized for
  104194. * different conditions:
  104195. */
  104196. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104197. /*
  104198. * stereo coding: unroll channel loop
  104199. */
  104200. do {
  104201. if(encoder->protected_->verify)
  104202. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104203. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104204. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104205. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104206. x = buffer[k++];
  104207. encoder->private_->integer_signal[1][i] = x;
  104208. mid += x;
  104209. side -= x;
  104210. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104211. encoder->private_->integer_signal_mid_side[1][i] = side;
  104212. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104213. }
  104214. encoder->private_->current_sample_number = i;
  104215. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104216. if(i > blocksize) {
  104217. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104218. return false;
  104219. /* move unprocessed overread samples to beginnings of arrays */
  104220. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104221. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104222. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104223. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104224. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104225. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104226. encoder->private_->current_sample_number = 1;
  104227. }
  104228. } while(j < samples);
  104229. }
  104230. else {
  104231. /*
  104232. * independent channel coding: buffer each channel in inner loop
  104233. */
  104234. do {
  104235. if(encoder->protected_->verify)
  104236. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104237. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104238. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104239. for(channel = 0; channel < channels; channel++)
  104240. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104241. }
  104242. encoder->private_->current_sample_number = i;
  104243. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104244. if(i > blocksize) {
  104245. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104246. return false;
  104247. /* move unprocessed overread samples to beginnings of arrays */
  104248. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104249. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104250. for(channel = 0; channel < channels; channel++)
  104251. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104252. encoder->private_->current_sample_number = 1;
  104253. }
  104254. } while(j < samples);
  104255. }
  104256. return true;
  104257. }
  104258. /***********************************************************************
  104259. *
  104260. * Private class methods
  104261. *
  104262. ***********************************************************************/
  104263. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104264. {
  104265. FLAC__ASSERT(0 != encoder);
  104266. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104267. encoder->protected_->verify = true;
  104268. #else
  104269. encoder->protected_->verify = false;
  104270. #endif
  104271. encoder->protected_->streamable_subset = true;
  104272. encoder->protected_->do_md5 = true;
  104273. encoder->protected_->do_mid_side_stereo = false;
  104274. encoder->protected_->loose_mid_side_stereo = false;
  104275. encoder->protected_->channels = 2;
  104276. encoder->protected_->bits_per_sample = 16;
  104277. encoder->protected_->sample_rate = 44100;
  104278. encoder->protected_->blocksize = 0;
  104279. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104280. encoder->protected_->num_apodizations = 1;
  104281. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104282. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104283. #endif
  104284. encoder->protected_->max_lpc_order = 0;
  104285. encoder->protected_->qlp_coeff_precision = 0;
  104286. encoder->protected_->do_qlp_coeff_prec_search = false;
  104287. encoder->protected_->do_exhaustive_model_search = false;
  104288. encoder->protected_->do_escape_coding = false;
  104289. encoder->protected_->min_residual_partition_order = 0;
  104290. encoder->protected_->max_residual_partition_order = 0;
  104291. encoder->protected_->rice_parameter_search_dist = 0;
  104292. encoder->protected_->total_samples_estimate = 0;
  104293. encoder->protected_->metadata = 0;
  104294. encoder->protected_->num_metadata_blocks = 0;
  104295. encoder->private_->seek_table = 0;
  104296. encoder->private_->disable_constant_subframes = false;
  104297. encoder->private_->disable_fixed_subframes = false;
  104298. encoder->private_->disable_verbatim_subframes = false;
  104299. #if FLAC__HAS_OGG
  104300. encoder->private_->is_ogg = false;
  104301. #endif
  104302. encoder->private_->read_callback = 0;
  104303. encoder->private_->write_callback = 0;
  104304. encoder->private_->seek_callback = 0;
  104305. encoder->private_->tell_callback = 0;
  104306. encoder->private_->metadata_callback = 0;
  104307. encoder->private_->progress_callback = 0;
  104308. encoder->private_->client_data = 0;
  104309. #if FLAC__HAS_OGG
  104310. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104311. #endif
  104312. }
  104313. void free_(FLAC__StreamEncoder *encoder)
  104314. {
  104315. unsigned i, channel;
  104316. FLAC__ASSERT(0 != encoder);
  104317. if(encoder->protected_->metadata) {
  104318. free(encoder->protected_->metadata);
  104319. encoder->protected_->metadata = 0;
  104320. encoder->protected_->num_metadata_blocks = 0;
  104321. }
  104322. for(i = 0; i < encoder->protected_->channels; i++) {
  104323. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104324. free(encoder->private_->integer_signal_unaligned[i]);
  104325. encoder->private_->integer_signal_unaligned[i] = 0;
  104326. }
  104327. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104328. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104329. free(encoder->private_->real_signal_unaligned[i]);
  104330. encoder->private_->real_signal_unaligned[i] = 0;
  104331. }
  104332. #endif
  104333. }
  104334. for(i = 0; i < 2; i++) {
  104335. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104336. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104337. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104338. }
  104339. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104340. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104341. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104342. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104343. }
  104344. #endif
  104345. }
  104346. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104347. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104348. if(0 != encoder->private_->window_unaligned[i]) {
  104349. free(encoder->private_->window_unaligned[i]);
  104350. encoder->private_->window_unaligned[i] = 0;
  104351. }
  104352. }
  104353. if(0 != encoder->private_->windowed_signal_unaligned) {
  104354. free(encoder->private_->windowed_signal_unaligned);
  104355. encoder->private_->windowed_signal_unaligned = 0;
  104356. }
  104357. #endif
  104358. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104359. for(i = 0; i < 2; i++) {
  104360. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104361. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104362. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104363. }
  104364. }
  104365. }
  104366. for(channel = 0; channel < 2; channel++) {
  104367. for(i = 0; i < 2; i++) {
  104368. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104369. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104370. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104371. }
  104372. }
  104373. }
  104374. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104375. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104376. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104377. }
  104378. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104379. free(encoder->private_->raw_bits_per_partition_unaligned);
  104380. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104381. }
  104382. if(encoder->protected_->verify) {
  104383. for(i = 0; i < encoder->protected_->channels; i++) {
  104384. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104385. free(encoder->private_->verify.input_fifo.data[i]);
  104386. encoder->private_->verify.input_fifo.data[i] = 0;
  104387. }
  104388. }
  104389. }
  104390. FLAC__bitwriter_free(encoder->private_->frame);
  104391. }
  104392. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104393. {
  104394. FLAC__bool ok;
  104395. unsigned i, channel;
  104396. FLAC__ASSERT(new_blocksize > 0);
  104397. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104398. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104399. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104400. if(new_blocksize <= encoder->private_->input_capacity)
  104401. return true;
  104402. ok = true;
  104403. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104404. * requires that the input arrays (in our case the integer signals)
  104405. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104406. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104407. */
  104408. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104409. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104410. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104411. encoder->private_->integer_signal[i] += 4;
  104412. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104413. #if 0 /* @@@ currently unused */
  104414. if(encoder->protected_->max_lpc_order > 0)
  104415. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104416. #endif
  104417. #endif
  104418. }
  104419. for(i = 0; ok && i < 2; i++) {
  104420. 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]);
  104421. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104422. encoder->private_->integer_signal_mid_side[i] += 4;
  104423. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104424. #if 0 /* @@@ currently unused */
  104425. if(encoder->protected_->max_lpc_order > 0)
  104426. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
  104427. #endif
  104428. #endif
  104429. }
  104430. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104431. if(ok && encoder->protected_->max_lpc_order > 0) {
  104432. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104433. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104434. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104435. }
  104436. #endif
  104437. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104438. for(i = 0; ok && i < 2; i++) {
  104439. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104440. }
  104441. }
  104442. for(channel = 0; ok && channel < 2; channel++) {
  104443. for(i = 0; ok && i < 2; i++) {
  104444. 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]);
  104445. }
  104446. }
  104447. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104448. /*@@@ 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) */
  104449. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104450. if(encoder->protected_->do_escape_coding)
  104451. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104452. /* now adjust the windows if the blocksize has changed */
  104453. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104454. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104455. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104456. switch(encoder->protected_->apodizations[i].type) {
  104457. case FLAC__APODIZATION_BARTLETT:
  104458. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104459. break;
  104460. case FLAC__APODIZATION_BARTLETT_HANN:
  104461. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104462. break;
  104463. case FLAC__APODIZATION_BLACKMAN:
  104464. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104465. break;
  104466. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104467. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104468. break;
  104469. case FLAC__APODIZATION_CONNES:
  104470. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104471. break;
  104472. case FLAC__APODIZATION_FLATTOP:
  104473. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104474. break;
  104475. case FLAC__APODIZATION_GAUSS:
  104476. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104477. break;
  104478. case FLAC__APODIZATION_HAMMING:
  104479. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104480. break;
  104481. case FLAC__APODIZATION_HANN:
  104482. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104483. break;
  104484. case FLAC__APODIZATION_KAISER_BESSEL:
  104485. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104486. break;
  104487. case FLAC__APODIZATION_NUTTALL:
  104488. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104489. break;
  104490. case FLAC__APODIZATION_RECTANGLE:
  104491. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104492. break;
  104493. case FLAC__APODIZATION_TRIANGLE:
  104494. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104495. break;
  104496. case FLAC__APODIZATION_TUKEY:
  104497. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104498. break;
  104499. case FLAC__APODIZATION_WELCH:
  104500. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104501. break;
  104502. default:
  104503. FLAC__ASSERT(0);
  104504. /* double protection */
  104505. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104506. break;
  104507. }
  104508. }
  104509. }
  104510. #endif
  104511. if(ok)
  104512. encoder->private_->input_capacity = new_blocksize;
  104513. else
  104514. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104515. return ok;
  104516. }
  104517. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104518. {
  104519. const FLAC__byte *buffer;
  104520. size_t bytes;
  104521. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104522. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104523. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104524. return false;
  104525. }
  104526. if(encoder->protected_->verify) {
  104527. encoder->private_->verify.output.data = buffer;
  104528. encoder->private_->verify.output.bytes = bytes;
  104529. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104530. encoder->private_->verify.needs_magic_hack = true;
  104531. }
  104532. else {
  104533. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104534. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104535. FLAC__bitwriter_clear(encoder->private_->frame);
  104536. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104537. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104538. return false;
  104539. }
  104540. }
  104541. }
  104542. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104543. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104544. FLAC__bitwriter_clear(encoder->private_->frame);
  104545. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104546. return false;
  104547. }
  104548. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104549. FLAC__bitwriter_clear(encoder->private_->frame);
  104550. if(samples > 0) {
  104551. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104552. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104553. }
  104554. return true;
  104555. }
  104556. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104557. {
  104558. FLAC__StreamEncoderWriteStatus status;
  104559. FLAC__uint64 output_position = 0;
  104560. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104561. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104562. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104563. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104564. }
  104565. /*
  104566. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104567. */
  104568. if(samples == 0) {
  104569. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104570. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104571. encoder->protected_->streaminfo_offset = output_position;
  104572. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104573. encoder->protected_->seektable_offset = output_position;
  104574. }
  104575. /*
  104576. * Mark the current seek point if hit (if audio_offset == 0 that
  104577. * means we're still writing metadata and haven't hit the first
  104578. * frame yet)
  104579. */
  104580. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104581. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104582. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104583. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104584. FLAC__uint64 test_sample;
  104585. unsigned i;
  104586. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104587. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104588. if(test_sample > frame_last_sample) {
  104589. break;
  104590. }
  104591. else if(test_sample >= frame_first_sample) {
  104592. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104593. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104594. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104595. encoder->private_->first_seekpoint_to_check++;
  104596. /* DO NOT: "break;" and here's why:
  104597. * The seektable template may contain more than one target
  104598. * sample for any given frame; we will keep looping, generating
  104599. * duplicate seekpoints for them, and we'll clean it up later,
  104600. * just before writing the seektable back to the metadata.
  104601. */
  104602. }
  104603. else {
  104604. encoder->private_->first_seekpoint_to_check++;
  104605. }
  104606. }
  104607. }
  104608. #if FLAC__HAS_OGG
  104609. if(encoder->private_->is_ogg) {
  104610. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104611. &encoder->protected_->ogg_encoder_aspect,
  104612. buffer,
  104613. bytes,
  104614. samples,
  104615. encoder->private_->current_frame_number,
  104616. is_last_block,
  104617. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104618. encoder,
  104619. encoder->private_->client_data
  104620. );
  104621. }
  104622. else
  104623. #endif
  104624. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104625. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104626. encoder->private_->bytes_written += bytes;
  104627. encoder->private_->samples_written += samples;
  104628. /* we keep a high watermark on the number of frames written because
  104629. * when the encoder goes back to write metadata, 'current_frame'
  104630. * will drop back to 0.
  104631. */
  104632. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104633. }
  104634. else
  104635. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104636. return status;
  104637. }
  104638. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104639. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104640. {
  104641. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104642. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104643. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104644. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104645. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104646. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104647. FLAC__StreamEncoderSeekStatus seek_status;
  104648. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104649. /* All this is based on intimate knowledge of the stream header
  104650. * layout, but a change to the header format that would break this
  104651. * would also break all streams encoded in the previous format.
  104652. */
  104653. /*
  104654. * Write MD5 signature
  104655. */
  104656. {
  104657. const unsigned md5_offset =
  104658. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104659. (
  104660. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104661. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104662. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104663. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104664. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104665. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104666. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104667. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104668. ) / 8;
  104669. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104670. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104671. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104672. return;
  104673. }
  104674. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104675. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104676. return;
  104677. }
  104678. }
  104679. /*
  104680. * Write total samples
  104681. */
  104682. {
  104683. const unsigned total_samples_byte_offset =
  104684. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104685. (
  104686. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104687. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104688. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104689. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104690. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104691. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104692. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104693. - 4
  104694. ) / 8;
  104695. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104696. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104697. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104698. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104699. b[4] = (FLAC__byte)(samples & 0xFF);
  104700. 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) {
  104701. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104702. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104703. return;
  104704. }
  104705. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104706. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104707. return;
  104708. }
  104709. }
  104710. /*
  104711. * Write min/max framesize
  104712. */
  104713. {
  104714. const unsigned min_framesize_offset =
  104715. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104716. (
  104717. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104718. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104719. ) / 8;
  104720. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104721. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104722. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104723. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104724. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104725. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104726. 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) {
  104727. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104728. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104729. return;
  104730. }
  104731. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104732. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104733. return;
  104734. }
  104735. }
  104736. /*
  104737. * Write seektable
  104738. */
  104739. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104740. unsigned i;
  104741. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104742. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104743. 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) {
  104744. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104745. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104746. return;
  104747. }
  104748. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104749. FLAC__uint64 xx;
  104750. unsigned x;
  104751. xx = encoder->private_->seek_table->points[i].sample_number;
  104752. b[7] = (FLAC__byte)xx; xx >>= 8;
  104753. b[6] = (FLAC__byte)xx; xx >>= 8;
  104754. b[5] = (FLAC__byte)xx; xx >>= 8;
  104755. b[4] = (FLAC__byte)xx; xx >>= 8;
  104756. b[3] = (FLAC__byte)xx; xx >>= 8;
  104757. b[2] = (FLAC__byte)xx; xx >>= 8;
  104758. b[1] = (FLAC__byte)xx; xx >>= 8;
  104759. b[0] = (FLAC__byte)xx; xx >>= 8;
  104760. xx = encoder->private_->seek_table->points[i].stream_offset;
  104761. b[15] = (FLAC__byte)xx; xx >>= 8;
  104762. b[14] = (FLAC__byte)xx; xx >>= 8;
  104763. b[13] = (FLAC__byte)xx; xx >>= 8;
  104764. b[12] = (FLAC__byte)xx; xx >>= 8;
  104765. b[11] = (FLAC__byte)xx; xx >>= 8;
  104766. b[10] = (FLAC__byte)xx; xx >>= 8;
  104767. b[9] = (FLAC__byte)xx; xx >>= 8;
  104768. b[8] = (FLAC__byte)xx; xx >>= 8;
  104769. x = encoder->private_->seek_table->points[i].frame_samples;
  104770. b[17] = (FLAC__byte)x; x >>= 8;
  104771. b[16] = (FLAC__byte)x; x >>= 8;
  104772. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104773. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104774. return;
  104775. }
  104776. }
  104777. }
  104778. }
  104779. #if FLAC__HAS_OGG
  104780. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104781. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104782. {
  104783. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104784. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104785. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104786. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104787. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104788. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104789. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104790. FLAC__STREAM_SYNC_LENGTH
  104791. ;
  104792. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104793. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104794. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104795. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104796. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104797. ogg_page page;
  104798. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104799. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104800. /* Pre-check that client supports seeking, since we don't want the
  104801. * ogg_helper code to ever have to deal with this condition.
  104802. */
  104803. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104804. return;
  104805. /* All this is based on intimate knowledge of the stream header
  104806. * layout, but a change to the header format that would break this
  104807. * would also break all streams encoded in the previous format.
  104808. */
  104809. /**
  104810. ** Write STREAMINFO stats
  104811. **/
  104812. simple_ogg_page__init(&page);
  104813. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104814. simple_ogg_page__clear(&page);
  104815. return; /* state already set */
  104816. }
  104817. /*
  104818. * Write MD5 signature
  104819. */
  104820. {
  104821. const unsigned md5_offset =
  104822. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104823. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104824. (
  104825. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104826. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104827. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104828. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104829. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104830. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104831. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104832. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104833. ) / 8;
  104834. if(md5_offset + 16 > (unsigned)page.body_len) {
  104835. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104836. simple_ogg_page__clear(&page);
  104837. return;
  104838. }
  104839. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104840. }
  104841. /*
  104842. * Write total samples
  104843. */
  104844. {
  104845. const unsigned total_samples_byte_offset =
  104846. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104847. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104848. (
  104849. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104850. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104851. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104852. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104853. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104854. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104855. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104856. - 4
  104857. ) / 8;
  104858. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104859. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104860. simple_ogg_page__clear(&page);
  104861. return;
  104862. }
  104863. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104864. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104865. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104866. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104867. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104868. b[4] = (FLAC__byte)(samples & 0xFF);
  104869. memcpy(page.body + total_samples_byte_offset, b, 5);
  104870. }
  104871. /*
  104872. * Write min/max framesize
  104873. */
  104874. {
  104875. const unsigned min_framesize_offset =
  104876. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104877. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104878. (
  104879. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104880. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104881. ) / 8;
  104882. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104883. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104884. simple_ogg_page__clear(&page);
  104885. return;
  104886. }
  104887. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104888. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104889. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104890. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104891. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104892. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104893. memcpy(page.body + min_framesize_offset, b, 6);
  104894. }
  104895. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104896. simple_ogg_page__clear(&page);
  104897. return; /* state already set */
  104898. }
  104899. simple_ogg_page__clear(&page);
  104900. /*
  104901. * Write seektable
  104902. */
  104903. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104904. unsigned i;
  104905. FLAC__byte *p;
  104906. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104907. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104908. simple_ogg_page__init(&page);
  104909. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104910. simple_ogg_page__clear(&page);
  104911. return; /* state already set */
  104912. }
  104913. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104914. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104915. simple_ogg_page__clear(&page);
  104916. return;
  104917. }
  104918. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104919. FLAC__uint64 xx;
  104920. unsigned x;
  104921. xx = encoder->private_->seek_table->points[i].sample_number;
  104922. b[7] = (FLAC__byte)xx; xx >>= 8;
  104923. b[6] = (FLAC__byte)xx; xx >>= 8;
  104924. b[5] = (FLAC__byte)xx; xx >>= 8;
  104925. b[4] = (FLAC__byte)xx; xx >>= 8;
  104926. b[3] = (FLAC__byte)xx; xx >>= 8;
  104927. b[2] = (FLAC__byte)xx; xx >>= 8;
  104928. b[1] = (FLAC__byte)xx; xx >>= 8;
  104929. b[0] = (FLAC__byte)xx; xx >>= 8;
  104930. xx = encoder->private_->seek_table->points[i].stream_offset;
  104931. b[15] = (FLAC__byte)xx; xx >>= 8;
  104932. b[14] = (FLAC__byte)xx; xx >>= 8;
  104933. b[13] = (FLAC__byte)xx; xx >>= 8;
  104934. b[12] = (FLAC__byte)xx; xx >>= 8;
  104935. b[11] = (FLAC__byte)xx; xx >>= 8;
  104936. b[10] = (FLAC__byte)xx; xx >>= 8;
  104937. b[9] = (FLAC__byte)xx; xx >>= 8;
  104938. b[8] = (FLAC__byte)xx; xx >>= 8;
  104939. x = encoder->private_->seek_table->points[i].frame_samples;
  104940. b[17] = (FLAC__byte)x; x >>= 8;
  104941. b[16] = (FLAC__byte)x; x >>= 8;
  104942. memcpy(p, b, 18);
  104943. }
  104944. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104945. simple_ogg_page__clear(&page);
  104946. return; /* state already set */
  104947. }
  104948. simple_ogg_page__clear(&page);
  104949. }
  104950. }
  104951. #endif
  104952. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104953. {
  104954. FLAC__uint16 crc;
  104955. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104956. /*
  104957. * Accumulate raw signal to the MD5 signature
  104958. */
  104959. 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)) {
  104960. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104961. return false;
  104962. }
  104963. /*
  104964. * Process the frame header and subframes into the frame bitbuffer
  104965. */
  104966. if(!process_subframes_(encoder, is_fractional_block)) {
  104967. /* the above function sets the state for us in case of an error */
  104968. return false;
  104969. }
  104970. /*
  104971. * Zero-pad the frame to a byte_boundary
  104972. */
  104973. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104974. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104975. return false;
  104976. }
  104977. /*
  104978. * CRC-16 the whole thing
  104979. */
  104980. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104981. if(
  104982. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104983. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104984. ) {
  104985. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104986. return false;
  104987. }
  104988. /*
  104989. * Write it
  104990. */
  104991. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104992. /* the above function sets the state for us in case of an error */
  104993. return false;
  104994. }
  104995. /*
  104996. * Get ready for the next frame
  104997. */
  104998. encoder->private_->current_sample_number = 0;
  104999. encoder->private_->current_frame_number++;
  105000. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  105001. return true;
  105002. }
  105003. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  105004. {
  105005. FLAC__FrameHeader frame_header;
  105006. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  105007. FLAC__bool do_independent, do_mid_side;
  105008. /*
  105009. * Calculate the min,max Rice partition orders
  105010. */
  105011. if(is_fractional_block) {
  105012. max_partition_order = 0;
  105013. }
  105014. else {
  105015. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  105016. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  105017. }
  105018. min_partition_order = min(min_partition_order, max_partition_order);
  105019. /*
  105020. * Setup the frame
  105021. */
  105022. frame_header.blocksize = encoder->protected_->blocksize;
  105023. frame_header.sample_rate = encoder->protected_->sample_rate;
  105024. frame_header.channels = encoder->protected_->channels;
  105025. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  105026. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  105027. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  105028. frame_header.number.frame_number = encoder->private_->current_frame_number;
  105029. /*
  105030. * Figure out what channel assignments to try
  105031. */
  105032. if(encoder->protected_->do_mid_side_stereo) {
  105033. if(encoder->protected_->loose_mid_side_stereo) {
  105034. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  105035. do_independent = true;
  105036. do_mid_side = true;
  105037. }
  105038. else {
  105039. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  105040. do_mid_side = !do_independent;
  105041. }
  105042. }
  105043. else {
  105044. do_independent = true;
  105045. do_mid_side = true;
  105046. }
  105047. }
  105048. else {
  105049. do_independent = true;
  105050. do_mid_side = false;
  105051. }
  105052. FLAC__ASSERT(do_independent || do_mid_side);
  105053. /*
  105054. * Check for wasted bits; set effective bps for each subframe
  105055. */
  105056. if(do_independent) {
  105057. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105058. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  105059. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  105060. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  105061. }
  105062. }
  105063. if(do_mid_side) {
  105064. FLAC__ASSERT(encoder->protected_->channels == 2);
  105065. for(channel = 0; channel < 2; channel++) {
  105066. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  105067. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  105068. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  105069. }
  105070. }
  105071. /*
  105072. * First do a normal encoding pass of each independent channel
  105073. */
  105074. if(do_independent) {
  105075. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105076. if(!
  105077. process_subframe_(
  105078. encoder,
  105079. min_partition_order,
  105080. max_partition_order,
  105081. &frame_header,
  105082. encoder->private_->subframe_bps[channel],
  105083. encoder->private_->integer_signal[channel],
  105084. encoder->private_->subframe_workspace_ptr[channel],
  105085. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  105086. encoder->private_->residual_workspace[channel],
  105087. encoder->private_->best_subframe+channel,
  105088. encoder->private_->best_subframe_bits+channel
  105089. )
  105090. )
  105091. return false;
  105092. }
  105093. }
  105094. /*
  105095. * Now do mid and side channels if requested
  105096. */
  105097. if(do_mid_side) {
  105098. FLAC__ASSERT(encoder->protected_->channels == 2);
  105099. for(channel = 0; channel < 2; channel++) {
  105100. if(!
  105101. process_subframe_(
  105102. encoder,
  105103. min_partition_order,
  105104. max_partition_order,
  105105. &frame_header,
  105106. encoder->private_->subframe_bps_mid_side[channel],
  105107. encoder->private_->integer_signal_mid_side[channel],
  105108. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  105109. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  105110. encoder->private_->residual_workspace_mid_side[channel],
  105111. encoder->private_->best_subframe_mid_side+channel,
  105112. encoder->private_->best_subframe_bits_mid_side+channel
  105113. )
  105114. )
  105115. return false;
  105116. }
  105117. }
  105118. /*
  105119. * Compose the frame bitbuffer
  105120. */
  105121. if(do_mid_side) {
  105122. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  105123. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  105124. FLAC__ChannelAssignment channel_assignment;
  105125. FLAC__ASSERT(encoder->protected_->channels == 2);
  105126. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  105127. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  105128. }
  105129. else {
  105130. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  105131. unsigned min_bits;
  105132. int ca;
  105133. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  105134. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  105135. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  105136. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  105137. FLAC__ASSERT(do_independent && do_mid_side);
  105138. /* We have to figure out which channel assignent results in the smallest frame */
  105139. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  105140. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  105141. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  105142. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  105143. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  105144. min_bits = bits[channel_assignment];
  105145. for(ca = 1; ca <= 3; ca++) {
  105146. if(bits[ca] < min_bits) {
  105147. min_bits = bits[ca];
  105148. channel_assignment = (FLAC__ChannelAssignment)ca;
  105149. }
  105150. }
  105151. }
  105152. frame_header.channel_assignment = channel_assignment;
  105153. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105154. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105155. return false;
  105156. }
  105157. switch(channel_assignment) {
  105158. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105159. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105160. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105161. break;
  105162. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105163. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105164. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105165. break;
  105166. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105167. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105168. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105169. break;
  105170. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105171. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105172. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105173. break;
  105174. default:
  105175. FLAC__ASSERT(0);
  105176. }
  105177. switch(channel_assignment) {
  105178. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105179. left_bps = encoder->private_->subframe_bps [0];
  105180. right_bps = encoder->private_->subframe_bps [1];
  105181. break;
  105182. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105183. left_bps = encoder->private_->subframe_bps [0];
  105184. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105185. break;
  105186. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105187. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105188. right_bps = encoder->private_->subframe_bps [1];
  105189. break;
  105190. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105191. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105192. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105193. break;
  105194. default:
  105195. FLAC__ASSERT(0);
  105196. }
  105197. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105198. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105199. return false;
  105200. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105201. return false;
  105202. }
  105203. else {
  105204. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105205. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105206. return false;
  105207. }
  105208. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105209. 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)) {
  105210. /* the above function sets the state for us in case of an error */
  105211. return false;
  105212. }
  105213. }
  105214. }
  105215. if(encoder->protected_->loose_mid_side_stereo) {
  105216. encoder->private_->loose_mid_side_stereo_frame_count++;
  105217. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105218. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105219. }
  105220. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105221. return true;
  105222. }
  105223. FLAC__bool process_subframe_(
  105224. FLAC__StreamEncoder *encoder,
  105225. unsigned min_partition_order,
  105226. unsigned max_partition_order,
  105227. const FLAC__FrameHeader *frame_header,
  105228. unsigned subframe_bps,
  105229. const FLAC__int32 integer_signal[],
  105230. FLAC__Subframe *subframe[2],
  105231. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105232. FLAC__int32 *residual[2],
  105233. unsigned *best_subframe,
  105234. unsigned *best_bits
  105235. )
  105236. {
  105237. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105238. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105239. #else
  105240. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105241. #endif
  105242. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105243. FLAC__double lpc_residual_bits_per_sample;
  105244. 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 */
  105245. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105246. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105247. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105248. #endif
  105249. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105250. unsigned rice_parameter;
  105251. unsigned _candidate_bits, _best_bits;
  105252. unsigned _best_subframe;
  105253. /* only use RICE2 partitions if stream bps > 16 */
  105254. 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;
  105255. FLAC__ASSERT(frame_header->blocksize > 0);
  105256. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105257. _best_subframe = 0;
  105258. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105259. _best_bits = UINT_MAX;
  105260. else
  105261. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105262. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105263. unsigned signal_is_constant = false;
  105264. 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);
  105265. /* check for constant subframe */
  105266. if(
  105267. !encoder->private_->disable_constant_subframes &&
  105268. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105269. fixed_residual_bits_per_sample[1] == 0.0
  105270. #else
  105271. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105272. #endif
  105273. ) {
  105274. /* the above means it's possible all samples are the same value; now double-check it: */
  105275. unsigned i;
  105276. signal_is_constant = true;
  105277. for(i = 1; i < frame_header->blocksize; i++) {
  105278. if(integer_signal[0] != integer_signal[i]) {
  105279. signal_is_constant = false;
  105280. break;
  105281. }
  105282. }
  105283. }
  105284. if(signal_is_constant) {
  105285. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105286. if(_candidate_bits < _best_bits) {
  105287. _best_subframe = !_best_subframe;
  105288. _best_bits = _candidate_bits;
  105289. }
  105290. }
  105291. else {
  105292. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105293. /* encode fixed */
  105294. if(encoder->protected_->do_exhaustive_model_search) {
  105295. min_fixed_order = 0;
  105296. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105297. }
  105298. else {
  105299. min_fixed_order = max_fixed_order = guess_fixed_order;
  105300. }
  105301. if(max_fixed_order >= frame_header->blocksize)
  105302. max_fixed_order = frame_header->blocksize - 1;
  105303. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105304. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105305. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105306. continue; /* don't even try */
  105307. 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 */
  105308. #else
  105309. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105310. continue; /* don't even try */
  105311. 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 */
  105312. #endif
  105313. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105314. if(rice_parameter >= rice_parameter_limit) {
  105315. #ifdef DEBUG_VERBOSE
  105316. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105317. #endif
  105318. rice_parameter = rice_parameter_limit - 1;
  105319. }
  105320. _candidate_bits =
  105321. evaluate_fixed_subframe_(
  105322. encoder,
  105323. integer_signal,
  105324. residual[!_best_subframe],
  105325. encoder->private_->abs_residual_partition_sums,
  105326. encoder->private_->raw_bits_per_partition,
  105327. frame_header->blocksize,
  105328. subframe_bps,
  105329. fixed_order,
  105330. rice_parameter,
  105331. rice_parameter_limit,
  105332. min_partition_order,
  105333. max_partition_order,
  105334. encoder->protected_->do_escape_coding,
  105335. encoder->protected_->rice_parameter_search_dist,
  105336. subframe[!_best_subframe],
  105337. partitioned_rice_contents[!_best_subframe]
  105338. );
  105339. if(_candidate_bits < _best_bits) {
  105340. _best_subframe = !_best_subframe;
  105341. _best_bits = _candidate_bits;
  105342. }
  105343. }
  105344. }
  105345. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105346. /* encode lpc */
  105347. if(encoder->protected_->max_lpc_order > 0) {
  105348. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105349. max_lpc_order = frame_header->blocksize-1;
  105350. else
  105351. max_lpc_order = encoder->protected_->max_lpc_order;
  105352. if(max_lpc_order > 0) {
  105353. unsigned a;
  105354. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105355. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105356. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105357. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105358. if(autoc[0] != 0.0) {
  105359. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105360. if(encoder->protected_->do_exhaustive_model_search) {
  105361. min_lpc_order = 1;
  105362. }
  105363. else {
  105364. const unsigned guess_lpc_order =
  105365. FLAC__lpc_compute_best_order(
  105366. lpc_error,
  105367. max_lpc_order,
  105368. frame_header->blocksize,
  105369. subframe_bps + (
  105370. encoder->protected_->do_qlp_coeff_prec_search?
  105371. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105372. encoder->protected_->qlp_coeff_precision
  105373. )
  105374. );
  105375. min_lpc_order = max_lpc_order = guess_lpc_order;
  105376. }
  105377. if(max_lpc_order >= frame_header->blocksize)
  105378. max_lpc_order = frame_header->blocksize - 1;
  105379. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105380. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105381. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105382. continue; /* don't even try */
  105383. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105384. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105385. if(rice_parameter >= rice_parameter_limit) {
  105386. #ifdef DEBUG_VERBOSE
  105387. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105388. #endif
  105389. rice_parameter = rice_parameter_limit - 1;
  105390. }
  105391. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105392. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105393. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105394. if(subframe_bps <= 17) {
  105395. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105396. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105397. }
  105398. else
  105399. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105400. }
  105401. else {
  105402. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105403. }
  105404. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105405. _candidate_bits =
  105406. evaluate_lpc_subframe_(
  105407. encoder,
  105408. integer_signal,
  105409. residual[!_best_subframe],
  105410. encoder->private_->abs_residual_partition_sums,
  105411. encoder->private_->raw_bits_per_partition,
  105412. encoder->private_->lp_coeff[lpc_order-1],
  105413. frame_header->blocksize,
  105414. subframe_bps,
  105415. lpc_order,
  105416. qlp_coeff_precision,
  105417. rice_parameter,
  105418. rice_parameter_limit,
  105419. min_partition_order,
  105420. max_partition_order,
  105421. encoder->protected_->do_escape_coding,
  105422. encoder->protected_->rice_parameter_search_dist,
  105423. subframe[!_best_subframe],
  105424. partitioned_rice_contents[!_best_subframe]
  105425. );
  105426. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105427. if(_candidate_bits < _best_bits) {
  105428. _best_subframe = !_best_subframe;
  105429. _best_bits = _candidate_bits;
  105430. }
  105431. }
  105432. }
  105433. }
  105434. }
  105435. }
  105436. }
  105437. }
  105438. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105439. }
  105440. }
  105441. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105442. if(_best_bits == UINT_MAX) {
  105443. FLAC__ASSERT(_best_subframe == 0);
  105444. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105445. }
  105446. *best_subframe = _best_subframe;
  105447. *best_bits = _best_bits;
  105448. return true;
  105449. }
  105450. FLAC__bool add_subframe_(
  105451. FLAC__StreamEncoder *encoder,
  105452. unsigned blocksize,
  105453. unsigned subframe_bps,
  105454. const FLAC__Subframe *subframe,
  105455. FLAC__BitWriter *frame
  105456. )
  105457. {
  105458. switch(subframe->type) {
  105459. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105460. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105461. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105462. return false;
  105463. }
  105464. break;
  105465. case FLAC__SUBFRAME_TYPE_FIXED:
  105466. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105467. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105468. return false;
  105469. }
  105470. break;
  105471. case FLAC__SUBFRAME_TYPE_LPC:
  105472. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105473. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105474. return false;
  105475. }
  105476. break;
  105477. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105478. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105479. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105480. return false;
  105481. }
  105482. break;
  105483. default:
  105484. FLAC__ASSERT(0);
  105485. }
  105486. return true;
  105487. }
  105488. #define SPOTCHECK_ESTIMATE 0
  105489. #if SPOTCHECK_ESTIMATE
  105490. static void spotcheck_subframe_estimate_(
  105491. FLAC__StreamEncoder *encoder,
  105492. unsigned blocksize,
  105493. unsigned subframe_bps,
  105494. const FLAC__Subframe *subframe,
  105495. unsigned estimate
  105496. )
  105497. {
  105498. FLAC__bool ret;
  105499. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105500. if(frame == 0) {
  105501. fprintf(stderr, "EST: can't allocate frame\n");
  105502. return;
  105503. }
  105504. if(!FLAC__bitwriter_init(frame)) {
  105505. fprintf(stderr, "EST: can't init frame\n");
  105506. return;
  105507. }
  105508. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105509. FLAC__ASSERT(ret);
  105510. {
  105511. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105512. if(estimate != actual)
  105513. 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);
  105514. }
  105515. FLAC__bitwriter_delete(frame);
  105516. }
  105517. #endif
  105518. unsigned evaluate_constant_subframe_(
  105519. FLAC__StreamEncoder *encoder,
  105520. const FLAC__int32 signal,
  105521. unsigned blocksize,
  105522. unsigned subframe_bps,
  105523. FLAC__Subframe *subframe
  105524. )
  105525. {
  105526. unsigned estimate;
  105527. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105528. subframe->data.constant.value = signal;
  105529. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105530. #if SPOTCHECK_ESTIMATE
  105531. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105532. #else
  105533. (void)encoder, (void)blocksize;
  105534. #endif
  105535. return estimate;
  105536. }
  105537. unsigned evaluate_fixed_subframe_(
  105538. FLAC__StreamEncoder *encoder,
  105539. const FLAC__int32 signal[],
  105540. FLAC__int32 residual[],
  105541. FLAC__uint64 abs_residual_partition_sums[],
  105542. unsigned raw_bits_per_partition[],
  105543. unsigned blocksize,
  105544. unsigned subframe_bps,
  105545. unsigned order,
  105546. unsigned rice_parameter,
  105547. unsigned rice_parameter_limit,
  105548. unsigned min_partition_order,
  105549. unsigned max_partition_order,
  105550. FLAC__bool do_escape_coding,
  105551. unsigned rice_parameter_search_dist,
  105552. FLAC__Subframe *subframe,
  105553. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105554. )
  105555. {
  105556. unsigned i, residual_bits, estimate;
  105557. const unsigned residual_samples = blocksize - order;
  105558. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105559. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105560. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105561. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105562. subframe->data.fixed.residual = residual;
  105563. residual_bits =
  105564. find_best_partition_order_(
  105565. encoder->private_,
  105566. residual,
  105567. abs_residual_partition_sums,
  105568. raw_bits_per_partition,
  105569. residual_samples,
  105570. order,
  105571. rice_parameter,
  105572. rice_parameter_limit,
  105573. min_partition_order,
  105574. max_partition_order,
  105575. subframe_bps,
  105576. do_escape_coding,
  105577. rice_parameter_search_dist,
  105578. &subframe->data.fixed.entropy_coding_method
  105579. );
  105580. subframe->data.fixed.order = order;
  105581. for(i = 0; i < order; i++)
  105582. subframe->data.fixed.warmup[i] = signal[i];
  105583. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105584. #if SPOTCHECK_ESTIMATE
  105585. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105586. #endif
  105587. return estimate;
  105588. }
  105589. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105590. unsigned evaluate_lpc_subframe_(
  105591. FLAC__StreamEncoder *encoder,
  105592. const FLAC__int32 signal[],
  105593. FLAC__int32 residual[],
  105594. FLAC__uint64 abs_residual_partition_sums[],
  105595. unsigned raw_bits_per_partition[],
  105596. const FLAC__real lp_coeff[],
  105597. unsigned blocksize,
  105598. unsigned subframe_bps,
  105599. unsigned order,
  105600. unsigned qlp_coeff_precision,
  105601. unsigned rice_parameter,
  105602. unsigned rice_parameter_limit,
  105603. unsigned min_partition_order,
  105604. unsigned max_partition_order,
  105605. FLAC__bool do_escape_coding,
  105606. unsigned rice_parameter_search_dist,
  105607. FLAC__Subframe *subframe,
  105608. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105609. )
  105610. {
  105611. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105612. unsigned i, residual_bits, estimate;
  105613. int quantization, ret;
  105614. const unsigned residual_samples = blocksize - order;
  105615. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105616. if(subframe_bps <= 16) {
  105617. FLAC__ASSERT(order > 0);
  105618. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105619. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105620. }
  105621. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105622. if(ret != 0)
  105623. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105624. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105625. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105626. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105627. else
  105628. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105629. else
  105630. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105631. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105632. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105633. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105634. subframe->data.lpc.residual = residual;
  105635. residual_bits =
  105636. find_best_partition_order_(
  105637. encoder->private_,
  105638. residual,
  105639. abs_residual_partition_sums,
  105640. raw_bits_per_partition,
  105641. residual_samples,
  105642. order,
  105643. rice_parameter,
  105644. rice_parameter_limit,
  105645. min_partition_order,
  105646. max_partition_order,
  105647. subframe_bps,
  105648. do_escape_coding,
  105649. rice_parameter_search_dist,
  105650. &subframe->data.lpc.entropy_coding_method
  105651. );
  105652. subframe->data.lpc.order = order;
  105653. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105654. subframe->data.lpc.quantization_level = quantization;
  105655. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105656. for(i = 0; i < order; i++)
  105657. subframe->data.lpc.warmup[i] = signal[i];
  105658. 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;
  105659. #if SPOTCHECK_ESTIMATE
  105660. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105661. #endif
  105662. return estimate;
  105663. }
  105664. #endif
  105665. unsigned evaluate_verbatim_subframe_(
  105666. FLAC__StreamEncoder *encoder,
  105667. const FLAC__int32 signal[],
  105668. unsigned blocksize,
  105669. unsigned subframe_bps,
  105670. FLAC__Subframe *subframe
  105671. )
  105672. {
  105673. unsigned estimate;
  105674. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105675. subframe->data.verbatim.data = signal;
  105676. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105677. #if SPOTCHECK_ESTIMATE
  105678. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105679. #else
  105680. (void)encoder;
  105681. #endif
  105682. return estimate;
  105683. }
  105684. unsigned find_best_partition_order_(
  105685. FLAC__StreamEncoderPrivate *private_,
  105686. const FLAC__int32 residual[],
  105687. FLAC__uint64 abs_residual_partition_sums[],
  105688. unsigned raw_bits_per_partition[],
  105689. unsigned residual_samples,
  105690. unsigned predictor_order,
  105691. unsigned rice_parameter,
  105692. unsigned rice_parameter_limit,
  105693. unsigned min_partition_order,
  105694. unsigned max_partition_order,
  105695. unsigned bps,
  105696. FLAC__bool do_escape_coding,
  105697. unsigned rice_parameter_search_dist,
  105698. FLAC__EntropyCodingMethod *best_ecm
  105699. )
  105700. {
  105701. unsigned residual_bits, best_residual_bits = 0;
  105702. unsigned best_parameters_index = 0;
  105703. unsigned best_partition_order = 0;
  105704. const unsigned blocksize = residual_samples + predictor_order;
  105705. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105706. min_partition_order = min(min_partition_order, max_partition_order);
  105707. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105708. if(do_escape_coding)
  105709. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105710. {
  105711. int partition_order;
  105712. unsigned sum;
  105713. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105714. if(!
  105715. set_partitioned_rice_(
  105716. #ifdef EXACT_RICE_BITS_CALCULATION
  105717. residual,
  105718. #endif
  105719. abs_residual_partition_sums+sum,
  105720. raw_bits_per_partition+sum,
  105721. residual_samples,
  105722. predictor_order,
  105723. rice_parameter,
  105724. rice_parameter_limit,
  105725. rice_parameter_search_dist,
  105726. (unsigned)partition_order,
  105727. do_escape_coding,
  105728. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105729. &residual_bits
  105730. )
  105731. )
  105732. {
  105733. FLAC__ASSERT(best_residual_bits != 0);
  105734. break;
  105735. }
  105736. sum += 1u << partition_order;
  105737. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105738. best_residual_bits = residual_bits;
  105739. best_parameters_index = !best_parameters_index;
  105740. best_partition_order = partition_order;
  105741. }
  105742. }
  105743. }
  105744. best_ecm->data.partitioned_rice.order = best_partition_order;
  105745. {
  105746. /*
  105747. * We are allowed to de-const the pointer based on our special
  105748. * knowledge; it is const to the outside world.
  105749. */
  105750. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105751. unsigned partition;
  105752. /* save best parameters and raw_bits */
  105753. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105754. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105755. if(do_escape_coding)
  105756. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105757. /*
  105758. * Now need to check if the type should be changed to
  105759. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105760. * size of the rice parameters.
  105761. */
  105762. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105763. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105764. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105765. break;
  105766. }
  105767. }
  105768. }
  105769. return best_residual_bits;
  105770. }
  105771. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105772. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105773. const FLAC__int32 residual[],
  105774. FLAC__uint64 abs_residual_partition_sums[],
  105775. unsigned blocksize,
  105776. unsigned predictor_order,
  105777. unsigned min_partition_order,
  105778. unsigned max_partition_order
  105779. );
  105780. #endif
  105781. void precompute_partition_info_sums_(
  105782. const FLAC__int32 residual[],
  105783. FLAC__uint64 abs_residual_partition_sums[],
  105784. unsigned residual_samples,
  105785. unsigned predictor_order,
  105786. unsigned min_partition_order,
  105787. unsigned max_partition_order,
  105788. unsigned bps
  105789. )
  105790. {
  105791. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105792. unsigned partitions = 1u << max_partition_order;
  105793. FLAC__ASSERT(default_partition_samples > predictor_order);
  105794. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105795. /* slightly pessimistic but still catches all common cases */
  105796. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105797. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105798. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105799. return;
  105800. }
  105801. #endif
  105802. /* first do max_partition_order */
  105803. {
  105804. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105805. /* slightly pessimistic but still catches all common cases */
  105806. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105807. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105808. FLAC__uint32 abs_residual_partition_sum;
  105809. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105810. end += default_partition_samples;
  105811. abs_residual_partition_sum = 0;
  105812. for( ; residual_sample < end; residual_sample++)
  105813. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105814. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105815. }
  105816. }
  105817. else { /* have to pessimistically use 64 bits for accumulator */
  105818. FLAC__uint64 abs_residual_partition_sum;
  105819. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105820. end += default_partition_samples;
  105821. abs_residual_partition_sum = 0;
  105822. for( ; residual_sample < end; residual_sample++)
  105823. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105824. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105825. }
  105826. }
  105827. }
  105828. /* now merge partitions for lower orders */
  105829. {
  105830. unsigned from_partition = 0, to_partition = partitions;
  105831. int partition_order;
  105832. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105833. unsigned i;
  105834. partitions >>= 1;
  105835. for(i = 0; i < partitions; i++) {
  105836. abs_residual_partition_sums[to_partition++] =
  105837. abs_residual_partition_sums[from_partition ] +
  105838. abs_residual_partition_sums[from_partition+1];
  105839. from_partition += 2;
  105840. }
  105841. }
  105842. }
  105843. }
  105844. void precompute_partition_info_escapes_(
  105845. const FLAC__int32 residual[],
  105846. unsigned raw_bits_per_partition[],
  105847. unsigned residual_samples,
  105848. unsigned predictor_order,
  105849. unsigned min_partition_order,
  105850. unsigned max_partition_order
  105851. )
  105852. {
  105853. int partition_order;
  105854. unsigned from_partition, to_partition = 0;
  105855. const unsigned blocksize = residual_samples + predictor_order;
  105856. /* first do max_partition_order */
  105857. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105858. FLAC__int32 r;
  105859. FLAC__uint32 rmax;
  105860. unsigned partition, partition_sample, partition_samples, residual_sample;
  105861. const unsigned partitions = 1u << partition_order;
  105862. const unsigned default_partition_samples = blocksize >> partition_order;
  105863. FLAC__ASSERT(default_partition_samples > predictor_order);
  105864. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105865. partition_samples = default_partition_samples;
  105866. if(partition == 0)
  105867. partition_samples -= predictor_order;
  105868. rmax = 0;
  105869. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105870. r = residual[residual_sample++];
  105871. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105872. if(r < 0)
  105873. rmax |= ~r;
  105874. else
  105875. rmax |= r;
  105876. }
  105877. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105878. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105879. }
  105880. to_partition = partitions;
  105881. break; /*@@@ yuck, should remove the 'for' loop instead */
  105882. }
  105883. /* now merge partitions for lower orders */
  105884. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105885. unsigned m;
  105886. unsigned i;
  105887. const unsigned partitions = 1u << partition_order;
  105888. for(i = 0; i < partitions; i++) {
  105889. m = raw_bits_per_partition[from_partition];
  105890. from_partition++;
  105891. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105892. from_partition++;
  105893. to_partition++;
  105894. }
  105895. }
  105896. }
  105897. #ifdef EXACT_RICE_BITS_CALCULATION
  105898. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105899. const unsigned rice_parameter,
  105900. const unsigned partition_samples,
  105901. const FLAC__int32 *residual
  105902. )
  105903. {
  105904. unsigned i, partition_bits =
  105905. 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 */
  105906. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105907. ;
  105908. for(i = 0; i < partition_samples; i++)
  105909. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105910. return partition_bits;
  105911. }
  105912. #else
  105913. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105914. const unsigned rice_parameter,
  105915. const unsigned partition_samples,
  105916. const FLAC__uint64 abs_residual_partition_sum
  105917. )
  105918. {
  105919. return
  105920. 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 */
  105921. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105922. (
  105923. rice_parameter?
  105924. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105925. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105926. )
  105927. - (partition_samples >> 1)
  105928. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105929. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105930. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105931. * So the subtraction term tries to guess how many extra bits were contributed.
  105932. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105933. */
  105934. ;
  105935. }
  105936. #endif
  105937. FLAC__bool set_partitioned_rice_(
  105938. #ifdef EXACT_RICE_BITS_CALCULATION
  105939. const FLAC__int32 residual[],
  105940. #endif
  105941. const FLAC__uint64 abs_residual_partition_sums[],
  105942. const unsigned raw_bits_per_partition[],
  105943. const unsigned residual_samples,
  105944. const unsigned predictor_order,
  105945. const unsigned suggested_rice_parameter,
  105946. const unsigned rice_parameter_limit,
  105947. const unsigned rice_parameter_search_dist,
  105948. const unsigned partition_order,
  105949. const FLAC__bool search_for_escapes,
  105950. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105951. unsigned *bits
  105952. )
  105953. {
  105954. unsigned rice_parameter, partition_bits;
  105955. unsigned best_partition_bits, best_rice_parameter = 0;
  105956. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105957. unsigned *parameters, *raw_bits;
  105958. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105959. unsigned min_rice_parameter, max_rice_parameter;
  105960. #else
  105961. (void)rice_parameter_search_dist;
  105962. #endif
  105963. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105964. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105965. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105966. parameters = partitioned_rice_contents->parameters;
  105967. raw_bits = partitioned_rice_contents->raw_bits;
  105968. if(partition_order == 0) {
  105969. best_partition_bits = (unsigned)(-1);
  105970. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105971. if(rice_parameter_search_dist) {
  105972. if(suggested_rice_parameter < rice_parameter_search_dist)
  105973. min_rice_parameter = 0;
  105974. else
  105975. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105976. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105977. if(max_rice_parameter >= rice_parameter_limit) {
  105978. #ifdef DEBUG_VERBOSE
  105979. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105980. #endif
  105981. max_rice_parameter = rice_parameter_limit - 1;
  105982. }
  105983. }
  105984. else
  105985. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105986. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105987. #else
  105988. rice_parameter = suggested_rice_parameter;
  105989. #endif
  105990. #ifdef EXACT_RICE_BITS_CALCULATION
  105991. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105992. #else
  105993. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105994. #endif
  105995. if(partition_bits < best_partition_bits) {
  105996. best_rice_parameter = rice_parameter;
  105997. best_partition_bits = partition_bits;
  105998. }
  105999. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106000. }
  106001. #endif
  106002. if(search_for_escapes) {
  106003. 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;
  106004. if(partition_bits <= best_partition_bits) {
  106005. raw_bits[0] = raw_bits_per_partition[0];
  106006. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106007. best_partition_bits = partition_bits;
  106008. }
  106009. else
  106010. raw_bits[0] = 0;
  106011. }
  106012. parameters[0] = best_rice_parameter;
  106013. bits_ += best_partition_bits;
  106014. }
  106015. else {
  106016. unsigned partition, residual_sample;
  106017. unsigned partition_samples;
  106018. FLAC__uint64 mean, k;
  106019. const unsigned partitions = 1u << partition_order;
  106020. for(partition = residual_sample = 0; partition < partitions; partition++) {
  106021. partition_samples = (residual_samples+predictor_order) >> partition_order;
  106022. if(partition == 0) {
  106023. if(partition_samples <= predictor_order)
  106024. return false;
  106025. else
  106026. partition_samples -= predictor_order;
  106027. }
  106028. mean = abs_residual_partition_sums[partition];
  106029. /* we are basically calculating the size in bits of the
  106030. * average residual magnitude in the partition:
  106031. * rice_parameter = floor(log2(mean/partition_samples))
  106032. * 'mean' is not a good name for the variable, it is
  106033. * actually the sum of magnitudes of all residual values
  106034. * in the partition, so the actual mean is
  106035. * mean/partition_samples
  106036. */
  106037. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  106038. ;
  106039. if(rice_parameter >= rice_parameter_limit) {
  106040. #ifdef DEBUG_VERBOSE
  106041. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  106042. #endif
  106043. rice_parameter = rice_parameter_limit - 1;
  106044. }
  106045. best_partition_bits = (unsigned)(-1);
  106046. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106047. if(rice_parameter_search_dist) {
  106048. if(rice_parameter < rice_parameter_search_dist)
  106049. min_rice_parameter = 0;
  106050. else
  106051. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  106052. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  106053. if(max_rice_parameter >= rice_parameter_limit) {
  106054. #ifdef DEBUG_VERBOSE
  106055. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  106056. #endif
  106057. max_rice_parameter = rice_parameter_limit - 1;
  106058. }
  106059. }
  106060. else
  106061. min_rice_parameter = max_rice_parameter = rice_parameter;
  106062. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106063. #endif
  106064. #ifdef EXACT_RICE_BITS_CALCULATION
  106065. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  106066. #else
  106067. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  106068. #endif
  106069. if(partition_bits < best_partition_bits) {
  106070. best_rice_parameter = rice_parameter;
  106071. best_partition_bits = partition_bits;
  106072. }
  106073. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106074. }
  106075. #endif
  106076. if(search_for_escapes) {
  106077. 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;
  106078. if(partition_bits <= best_partition_bits) {
  106079. raw_bits[partition] = raw_bits_per_partition[partition];
  106080. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106081. best_partition_bits = partition_bits;
  106082. }
  106083. else
  106084. raw_bits[partition] = 0;
  106085. }
  106086. parameters[partition] = best_rice_parameter;
  106087. bits_ += best_partition_bits;
  106088. residual_sample += partition_samples;
  106089. }
  106090. }
  106091. *bits = bits_;
  106092. return true;
  106093. }
  106094. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  106095. {
  106096. unsigned i, shift;
  106097. FLAC__int32 x = 0;
  106098. for(i = 0; i < samples && !(x&1); i++)
  106099. x |= signal[i];
  106100. if(x == 0) {
  106101. shift = 0;
  106102. }
  106103. else {
  106104. for(shift = 0; !(x&1); shift++)
  106105. x >>= 1;
  106106. }
  106107. if(shift > 0) {
  106108. for(i = 0; i < samples; i++)
  106109. signal[i] >>= shift;
  106110. }
  106111. return shift;
  106112. }
  106113. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106114. {
  106115. unsigned channel;
  106116. for(channel = 0; channel < channels; channel++)
  106117. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  106118. fifo->tail += wide_samples;
  106119. FLAC__ASSERT(fifo->tail <= fifo->size);
  106120. }
  106121. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106122. {
  106123. unsigned channel;
  106124. unsigned sample, wide_sample;
  106125. unsigned tail = fifo->tail;
  106126. sample = input_offset * channels;
  106127. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  106128. for(channel = 0; channel < channels; channel++)
  106129. fifo->data[channel][tail] = input[sample++];
  106130. tail++;
  106131. }
  106132. fifo->tail = tail;
  106133. FLAC__ASSERT(fifo->tail <= fifo->size);
  106134. }
  106135. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106136. {
  106137. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106138. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  106139. (void)decoder;
  106140. if(encoder->private_->verify.needs_magic_hack) {
  106141. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  106142. *bytes = FLAC__STREAM_SYNC_LENGTH;
  106143. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  106144. encoder->private_->verify.needs_magic_hack = false;
  106145. }
  106146. else {
  106147. if(encoded_bytes == 0) {
  106148. /*
  106149. * If we get here, a FIFO underflow has occurred,
  106150. * which means there is a bug somewhere.
  106151. */
  106152. FLAC__ASSERT(0);
  106153. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  106154. }
  106155. else if(encoded_bytes < *bytes)
  106156. *bytes = encoded_bytes;
  106157. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  106158. encoder->private_->verify.output.data += *bytes;
  106159. encoder->private_->verify.output.bytes -= *bytes;
  106160. }
  106161. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106162. }
  106163. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106164. {
  106165. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106166. unsigned channel;
  106167. const unsigned channels = frame->header.channels;
  106168. const unsigned blocksize = frame->header.blocksize;
  106169. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106170. (void)decoder;
  106171. for(channel = 0; channel < channels; channel++) {
  106172. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106173. unsigned i, sample = 0;
  106174. FLAC__int32 expect = 0, got = 0;
  106175. for(i = 0; i < blocksize; i++) {
  106176. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106177. sample = i;
  106178. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106179. got = (FLAC__int32)buffer[channel][i];
  106180. break;
  106181. }
  106182. }
  106183. FLAC__ASSERT(i < blocksize);
  106184. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106185. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106186. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106187. encoder->private_->verify.error_stats.channel = channel;
  106188. encoder->private_->verify.error_stats.sample = sample;
  106189. encoder->private_->verify.error_stats.expected = expect;
  106190. encoder->private_->verify.error_stats.got = got;
  106191. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106192. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106193. }
  106194. }
  106195. /* dequeue the frame from the fifo */
  106196. encoder->private_->verify.input_fifo.tail -= blocksize;
  106197. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106198. for(channel = 0; channel < channels; channel++)
  106199. 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]));
  106200. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106201. }
  106202. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106203. {
  106204. (void)decoder, (void)metadata, (void)client_data;
  106205. }
  106206. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106207. {
  106208. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106209. (void)decoder, (void)status;
  106210. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106211. }
  106212. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106213. {
  106214. (void)client_data;
  106215. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106216. if (*bytes == 0) {
  106217. if (feof(encoder->private_->file))
  106218. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106219. else if (ferror(encoder->private_->file))
  106220. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106221. }
  106222. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106223. }
  106224. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106225. {
  106226. (void)client_data;
  106227. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106228. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106229. else
  106230. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106231. }
  106232. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106233. {
  106234. off_t offset;
  106235. (void)client_data;
  106236. offset = ftello(encoder->private_->file);
  106237. if(offset < 0) {
  106238. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106239. }
  106240. else {
  106241. *absolute_byte_offset = (FLAC__uint64)offset;
  106242. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106243. }
  106244. }
  106245. #ifdef FLAC__VALGRIND_TESTING
  106246. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106247. {
  106248. size_t ret = fwrite(ptr, size, nmemb, stream);
  106249. if(!ferror(stream))
  106250. fflush(stream);
  106251. return ret;
  106252. }
  106253. #else
  106254. #define local__fwrite fwrite
  106255. #endif
  106256. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106257. {
  106258. (void)client_data, (void)current_frame;
  106259. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106260. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106261. #if FLAC__HAS_OGG
  106262. /* We would like to be able to use 'samples > 0' in the
  106263. * clause here but currently because of the nature of our
  106264. * Ogg writing implementation, 'samples' is always 0 (see
  106265. * ogg_encoder_aspect.c). The downside is extra progress
  106266. * callbacks.
  106267. */
  106268. encoder->private_->is_ogg? true :
  106269. #endif
  106270. samples > 0
  106271. );
  106272. if(call_it) {
  106273. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106274. * because at this point in the callback chain, the stats
  106275. * have not been updated. Only after we return and control
  106276. * gets back to write_frame_() are the stats updated
  106277. */
  106278. 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);
  106279. }
  106280. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106281. }
  106282. else
  106283. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106284. }
  106285. /*
  106286. * This will forcibly set stdout to binary mode (for OSes that require it)
  106287. */
  106288. FILE *get_binary_stdout_(void)
  106289. {
  106290. /* if something breaks here it is probably due to the presence or
  106291. * absence of an underscore before the identifiers 'setmode',
  106292. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106293. */
  106294. #if defined _MSC_VER || defined __MINGW32__
  106295. _setmode(_fileno(stdout), _O_BINARY);
  106296. #elif defined __CYGWIN__
  106297. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106298. setmode(_fileno(stdout), _O_BINARY);
  106299. #elif defined __EMX__
  106300. setmode(fileno(stdout), O_BINARY);
  106301. #endif
  106302. return stdout;
  106303. }
  106304. #endif
  106305. /*** End of inlined file: stream_encoder.c ***/
  106306. /*** Start of inlined file: stream_encoder_framing.c ***/
  106307. /*** Start of inlined file: juce_FlacHeader.h ***/
  106308. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106309. // tasks..
  106310. #define VERSION "1.2.1"
  106311. #define FLAC__NO_DLL 1
  106312. #if JUCE_MSVC
  106313. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106314. #endif
  106315. #if JUCE_MAC
  106316. #define FLAC__SYS_DARWIN 1
  106317. #endif
  106318. /*** End of inlined file: juce_FlacHeader.h ***/
  106319. #if JUCE_USE_FLAC
  106320. #if HAVE_CONFIG_H
  106321. # include <config.h>
  106322. #endif
  106323. #include <stdio.h>
  106324. #include <string.h> /* for strlen() */
  106325. #ifdef max
  106326. #undef max
  106327. #endif
  106328. #define max(x,y) ((x)>(y)?(x):(y))
  106329. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106330. 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);
  106331. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106332. {
  106333. unsigned i, j;
  106334. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106335. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106336. return false;
  106337. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106338. return false;
  106339. /*
  106340. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106341. */
  106342. i = metadata->length;
  106343. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106344. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106345. i -= metadata->data.vorbis_comment.vendor_string.length;
  106346. i += vendor_string_length;
  106347. }
  106348. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106349. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106350. return false;
  106351. switch(metadata->type) {
  106352. case FLAC__METADATA_TYPE_STREAMINFO:
  106353. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106354. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106355. return false;
  106356. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106357. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106358. return false;
  106359. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106360. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106361. return false;
  106362. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106363. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106364. return false;
  106365. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106366. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106367. return false;
  106368. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106369. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106370. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106371. return false;
  106372. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106373. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106374. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106375. return false;
  106376. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106377. return false;
  106378. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106379. return false;
  106380. break;
  106381. case FLAC__METADATA_TYPE_PADDING:
  106382. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106383. return false;
  106384. break;
  106385. case FLAC__METADATA_TYPE_APPLICATION:
  106386. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106387. return false;
  106388. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106389. return false;
  106390. break;
  106391. case FLAC__METADATA_TYPE_SEEKTABLE:
  106392. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106393. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106394. return false;
  106395. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106396. return false;
  106397. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106398. return false;
  106399. }
  106400. break;
  106401. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106402. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106403. return false;
  106404. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106405. return false;
  106406. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106407. return false;
  106408. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106409. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106410. return false;
  106411. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106412. return false;
  106413. }
  106414. break;
  106415. case FLAC__METADATA_TYPE_CUESHEET:
  106416. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106417. 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))
  106418. return false;
  106419. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106420. return false;
  106421. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106422. return false;
  106423. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106424. return false;
  106425. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106426. return false;
  106427. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106428. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106429. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106430. return false;
  106431. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106432. return false;
  106433. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106434. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106435. return false;
  106436. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106437. return false;
  106438. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106439. return false;
  106440. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106441. return false;
  106442. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106443. return false;
  106444. for(j = 0; j < track->num_indices; j++) {
  106445. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106446. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106447. return false;
  106448. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106449. return false;
  106450. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106451. return false;
  106452. }
  106453. }
  106454. break;
  106455. case FLAC__METADATA_TYPE_PICTURE:
  106456. {
  106457. size_t len;
  106458. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106459. return false;
  106460. len = strlen(metadata->data.picture.mime_type);
  106461. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106462. return false;
  106463. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106464. return false;
  106465. len = strlen((const char *)metadata->data.picture.description);
  106466. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106467. return false;
  106468. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106469. return false;
  106470. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106471. return false;
  106472. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106473. return false;
  106474. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106475. return false;
  106476. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106477. return false;
  106478. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106479. return false;
  106480. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106481. return false;
  106482. }
  106483. break;
  106484. default:
  106485. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106486. return false;
  106487. break;
  106488. }
  106489. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106490. return true;
  106491. }
  106492. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106493. {
  106494. unsigned u, blocksize_hint, sample_rate_hint;
  106495. FLAC__byte crc;
  106496. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106497. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106498. return false;
  106499. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106500. return false;
  106501. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106502. return false;
  106503. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106504. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106505. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106506. blocksize_hint = 0;
  106507. switch(header->blocksize) {
  106508. case 192: u = 1; break;
  106509. case 576: u = 2; break;
  106510. case 1152: u = 3; break;
  106511. case 2304: u = 4; break;
  106512. case 4608: u = 5; break;
  106513. case 256: u = 8; break;
  106514. case 512: u = 9; break;
  106515. case 1024: u = 10; break;
  106516. case 2048: u = 11; break;
  106517. case 4096: u = 12; break;
  106518. case 8192: u = 13; break;
  106519. case 16384: u = 14; break;
  106520. case 32768: u = 15; break;
  106521. default:
  106522. if(header->blocksize <= 0x100)
  106523. blocksize_hint = u = 6;
  106524. else
  106525. blocksize_hint = u = 7;
  106526. break;
  106527. }
  106528. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106529. return false;
  106530. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106531. sample_rate_hint = 0;
  106532. switch(header->sample_rate) {
  106533. case 88200: u = 1; break;
  106534. case 176400: u = 2; break;
  106535. case 192000: u = 3; break;
  106536. case 8000: u = 4; break;
  106537. case 16000: u = 5; break;
  106538. case 22050: u = 6; break;
  106539. case 24000: u = 7; break;
  106540. case 32000: u = 8; break;
  106541. case 44100: u = 9; break;
  106542. case 48000: u = 10; break;
  106543. case 96000: u = 11; break;
  106544. default:
  106545. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106546. sample_rate_hint = u = 12;
  106547. else if(header->sample_rate % 10 == 0)
  106548. sample_rate_hint = u = 14;
  106549. else if(header->sample_rate <= 0xffff)
  106550. sample_rate_hint = u = 13;
  106551. else
  106552. u = 0;
  106553. break;
  106554. }
  106555. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106556. return false;
  106557. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106558. switch(header->channel_assignment) {
  106559. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106560. u = header->channels - 1;
  106561. break;
  106562. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106563. FLAC__ASSERT(header->channels == 2);
  106564. u = 8;
  106565. break;
  106566. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106567. FLAC__ASSERT(header->channels == 2);
  106568. u = 9;
  106569. break;
  106570. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106571. FLAC__ASSERT(header->channels == 2);
  106572. u = 10;
  106573. break;
  106574. default:
  106575. FLAC__ASSERT(0);
  106576. }
  106577. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106578. return false;
  106579. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106580. switch(header->bits_per_sample) {
  106581. case 8 : u = 1; break;
  106582. case 12: u = 2; break;
  106583. case 16: u = 4; break;
  106584. case 20: u = 5; break;
  106585. case 24: u = 6; break;
  106586. default: u = 0; break;
  106587. }
  106588. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106589. return false;
  106590. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106591. return false;
  106592. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106593. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106594. return false;
  106595. }
  106596. else {
  106597. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106598. return false;
  106599. }
  106600. if(blocksize_hint)
  106601. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106602. return false;
  106603. switch(sample_rate_hint) {
  106604. case 12:
  106605. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106606. return false;
  106607. break;
  106608. case 13:
  106609. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106610. return false;
  106611. break;
  106612. case 14:
  106613. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106614. return false;
  106615. break;
  106616. }
  106617. /* write the CRC */
  106618. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106619. return false;
  106620. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106621. return false;
  106622. return true;
  106623. }
  106624. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106625. {
  106626. FLAC__bool ok;
  106627. ok =
  106628. 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) &&
  106629. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106630. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106631. ;
  106632. return ok;
  106633. }
  106634. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106635. {
  106636. unsigned i;
  106637. 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))
  106638. return false;
  106639. if(wasted_bits)
  106640. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106641. return false;
  106642. for(i = 0; i < subframe->order; i++)
  106643. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106644. return false;
  106645. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106646. return false;
  106647. switch(subframe->entropy_coding_method.type) {
  106648. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106649. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106650. if(!add_residual_partitioned_rice_(
  106651. bw,
  106652. subframe->residual,
  106653. residual_samples,
  106654. subframe->order,
  106655. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106656. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106657. subframe->entropy_coding_method.data.partitioned_rice.order,
  106658. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106659. ))
  106660. return false;
  106661. break;
  106662. default:
  106663. FLAC__ASSERT(0);
  106664. }
  106665. return true;
  106666. }
  106667. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106668. {
  106669. unsigned i;
  106670. 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))
  106671. return false;
  106672. if(wasted_bits)
  106673. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106674. return false;
  106675. for(i = 0; i < subframe->order; i++)
  106676. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106677. return false;
  106678. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106679. return false;
  106680. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106681. return false;
  106682. for(i = 0; i < subframe->order; i++)
  106683. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106684. return false;
  106685. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106686. return false;
  106687. switch(subframe->entropy_coding_method.type) {
  106688. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106689. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106690. if(!add_residual_partitioned_rice_(
  106691. bw,
  106692. subframe->residual,
  106693. residual_samples,
  106694. subframe->order,
  106695. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106696. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106697. subframe->entropy_coding_method.data.partitioned_rice.order,
  106698. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106699. ))
  106700. return false;
  106701. break;
  106702. default:
  106703. FLAC__ASSERT(0);
  106704. }
  106705. return true;
  106706. }
  106707. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106708. {
  106709. unsigned i;
  106710. const FLAC__int32 *signal = subframe->data;
  106711. 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))
  106712. return false;
  106713. if(wasted_bits)
  106714. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106715. return false;
  106716. for(i = 0; i < samples; i++)
  106717. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106718. return false;
  106719. return true;
  106720. }
  106721. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106722. {
  106723. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106724. return false;
  106725. switch(method->type) {
  106726. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106727. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106728. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106729. return false;
  106730. break;
  106731. default:
  106732. FLAC__ASSERT(0);
  106733. }
  106734. return true;
  106735. }
  106736. 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)
  106737. {
  106738. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106739. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106740. if(partition_order == 0) {
  106741. unsigned i;
  106742. if(raw_bits[0] == 0) {
  106743. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106744. return false;
  106745. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106746. return false;
  106747. }
  106748. else {
  106749. FLAC__ASSERT(rice_parameters[0] == 0);
  106750. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106751. return false;
  106752. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106753. return false;
  106754. for(i = 0; i < residual_samples; i++) {
  106755. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106756. return false;
  106757. }
  106758. }
  106759. return true;
  106760. }
  106761. else {
  106762. unsigned i, j, k = 0, k_last = 0;
  106763. unsigned partition_samples;
  106764. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106765. for(i = 0; i < (1u<<partition_order); i++) {
  106766. partition_samples = default_partition_samples;
  106767. if(i == 0)
  106768. partition_samples -= predictor_order;
  106769. k += partition_samples;
  106770. if(raw_bits[i] == 0) {
  106771. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106772. return false;
  106773. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106774. return false;
  106775. }
  106776. else {
  106777. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106778. return false;
  106779. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106780. return false;
  106781. for(j = k_last; j < k; j++) {
  106782. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106783. return false;
  106784. }
  106785. }
  106786. k_last = k;
  106787. }
  106788. return true;
  106789. }
  106790. }
  106791. #endif
  106792. /*** End of inlined file: stream_encoder_framing.c ***/
  106793. /*** Start of inlined file: window_flac.c ***/
  106794. /*** Start of inlined file: juce_FlacHeader.h ***/
  106795. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106796. // tasks..
  106797. #define VERSION "1.2.1"
  106798. #define FLAC__NO_DLL 1
  106799. #if JUCE_MSVC
  106800. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106801. #endif
  106802. #if JUCE_MAC
  106803. #define FLAC__SYS_DARWIN 1
  106804. #endif
  106805. /*** End of inlined file: juce_FlacHeader.h ***/
  106806. #if JUCE_USE_FLAC
  106807. #if HAVE_CONFIG_H
  106808. # include <config.h>
  106809. #endif
  106810. #include <math.h>
  106811. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106812. #ifndef M_PI
  106813. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106814. #define M_PI 3.14159265358979323846
  106815. #endif
  106816. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106817. {
  106818. const FLAC__int32 N = L - 1;
  106819. FLAC__int32 n;
  106820. if (L & 1) {
  106821. for (n = 0; n <= N/2; n++)
  106822. window[n] = 2.0f * n / (float)N;
  106823. for (; n <= N; n++)
  106824. window[n] = 2.0f - 2.0f * n / (float)N;
  106825. }
  106826. else {
  106827. for (n = 0; n <= L/2-1; n++)
  106828. window[n] = 2.0f * n / (float)N;
  106829. for (; n <= N; n++)
  106830. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106831. }
  106832. }
  106833. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106834. {
  106835. const FLAC__int32 N = L - 1;
  106836. FLAC__int32 n;
  106837. for (n = 0; n < L; n++)
  106838. 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)));
  106839. }
  106840. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106841. {
  106842. const FLAC__int32 N = L - 1;
  106843. FLAC__int32 n;
  106844. for (n = 0; n < L; n++)
  106845. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106846. }
  106847. /* 4-term -92dB side-lobe */
  106848. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106849. {
  106850. const FLAC__int32 N = L - 1;
  106851. FLAC__int32 n;
  106852. for (n = 0; n <= N; n++)
  106853. 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));
  106854. }
  106855. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106856. {
  106857. const FLAC__int32 N = L - 1;
  106858. const double N2 = (double)N / 2.;
  106859. FLAC__int32 n;
  106860. for (n = 0; n <= N; n++) {
  106861. double k = ((double)n - N2) / N2;
  106862. k = 1.0f - k * k;
  106863. window[n] = (FLAC__real)(k * k);
  106864. }
  106865. }
  106866. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106867. {
  106868. const FLAC__int32 N = L - 1;
  106869. FLAC__int32 n;
  106870. for (n = 0; n < L; n++)
  106871. 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));
  106872. }
  106873. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106874. {
  106875. const FLAC__int32 N = L - 1;
  106876. const double N2 = (double)N / 2.;
  106877. FLAC__int32 n;
  106878. for (n = 0; n <= N; n++) {
  106879. const double k = ((double)n - N2) / (stddev * N2);
  106880. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106881. }
  106882. }
  106883. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106884. {
  106885. const FLAC__int32 N = L - 1;
  106886. FLAC__int32 n;
  106887. for (n = 0; n < L; n++)
  106888. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106889. }
  106890. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106891. {
  106892. const FLAC__int32 N = L - 1;
  106893. FLAC__int32 n;
  106894. for (n = 0; n < L; n++)
  106895. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106896. }
  106897. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106898. {
  106899. const FLAC__int32 N = L - 1;
  106900. FLAC__int32 n;
  106901. for (n = 0; n < L; n++)
  106902. 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));
  106903. }
  106904. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106905. {
  106906. const FLAC__int32 N = L - 1;
  106907. FLAC__int32 n;
  106908. for (n = 0; n < L; n++)
  106909. 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));
  106910. }
  106911. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106912. {
  106913. FLAC__int32 n;
  106914. for (n = 0; n < L; n++)
  106915. window[n] = 1.0f;
  106916. }
  106917. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106918. {
  106919. FLAC__int32 n;
  106920. if (L & 1) {
  106921. for (n = 1; n <= L+1/2; n++)
  106922. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106923. for (; n <= L; n++)
  106924. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106925. }
  106926. else {
  106927. for (n = 1; n <= L/2; n++)
  106928. window[n-1] = 2.0f * n / (float)L;
  106929. for (; n <= L; n++)
  106930. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106931. }
  106932. }
  106933. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106934. {
  106935. if (p <= 0.0)
  106936. FLAC__window_rectangle(window, L);
  106937. else if (p >= 1.0)
  106938. FLAC__window_hann(window, L);
  106939. else {
  106940. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106941. FLAC__int32 n;
  106942. /* start with rectangle... */
  106943. FLAC__window_rectangle(window, L);
  106944. /* ...replace ends with hann */
  106945. if (Np > 0) {
  106946. for (n = 0; n <= Np; n++) {
  106947. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106948. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106949. }
  106950. }
  106951. }
  106952. }
  106953. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106954. {
  106955. const FLAC__int32 N = L - 1;
  106956. const double N2 = (double)N / 2.;
  106957. FLAC__int32 n;
  106958. for (n = 0; n <= N; n++) {
  106959. const double k = ((double)n - N2) / N2;
  106960. window[n] = (FLAC__real)(1.0f - k * k);
  106961. }
  106962. }
  106963. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106964. #endif
  106965. /*** End of inlined file: window_flac.c ***/
  106966. #else
  106967. #include <FLAC/all.h>
  106968. #endif
  106969. }
  106970. #undef max
  106971. #undef min
  106972. BEGIN_JUCE_NAMESPACE
  106973. static const char* const flacFormatName = "FLAC file";
  106974. static const char* const flacExtensions[] = { ".flac", 0 };
  106975. class FlacReader : public AudioFormatReader
  106976. {
  106977. public:
  106978. FlacReader (InputStream* const in)
  106979. : AudioFormatReader (in, TRANS (flacFormatName)),
  106980. reservoir (2, 0),
  106981. reservoirStart (0),
  106982. samplesInReservoir (0),
  106983. scanningForLength (false)
  106984. {
  106985. using namespace FlacNamespace;
  106986. lengthInSamples = 0;
  106987. decoder = FLAC__stream_decoder_new();
  106988. ok = FLAC__stream_decoder_init_stream (decoder,
  106989. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106990. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106991. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106992. if (ok)
  106993. {
  106994. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106995. if (lengthInSamples == 0 && sampleRate > 0)
  106996. {
  106997. // the length hasn't been stored in the metadata, so we'll need to
  106998. // work it out the length the hard way, by scanning the whole file..
  106999. scanningForLength = true;
  107000. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  107001. scanningForLength = false;
  107002. const int64 tempLength = lengthInSamples;
  107003. FLAC__stream_decoder_reset (decoder);
  107004. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107005. lengthInSamples = tempLength;
  107006. }
  107007. }
  107008. }
  107009. ~FlacReader()
  107010. {
  107011. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  107012. }
  107013. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  107014. {
  107015. sampleRate = info.sample_rate;
  107016. bitsPerSample = info.bits_per_sample;
  107017. lengthInSamples = (unsigned int) info.total_samples;
  107018. numChannels = info.channels;
  107019. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  107020. }
  107021. // returns the number of samples read
  107022. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  107023. int64 startSampleInFile, int numSamples)
  107024. {
  107025. using namespace FlacNamespace;
  107026. if (! ok)
  107027. return false;
  107028. while (numSamples > 0)
  107029. {
  107030. if (startSampleInFile >= reservoirStart
  107031. && startSampleInFile < reservoirStart + samplesInReservoir)
  107032. {
  107033. const int num = (int) jmin ((int64) numSamples,
  107034. reservoirStart + samplesInReservoir - startSampleInFile);
  107035. jassert (num > 0);
  107036. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  107037. if (destSamples[i] != 0)
  107038. memcpy (destSamples[i] + startOffsetInDestBuffer,
  107039. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  107040. sizeof (int) * num);
  107041. startOffsetInDestBuffer += num;
  107042. startSampleInFile += num;
  107043. numSamples -= num;
  107044. }
  107045. else
  107046. {
  107047. if (startSampleInFile >= (int) lengthInSamples)
  107048. {
  107049. samplesInReservoir = 0;
  107050. }
  107051. else if (startSampleInFile < reservoirStart
  107052. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  107053. {
  107054. // had some problems with flac crashing if the read pos is aligned more
  107055. // accurately than this. Probably fixed in newer versions of the library, though.
  107056. reservoirStart = (int) (startSampleInFile & ~511);
  107057. samplesInReservoir = 0;
  107058. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  107059. }
  107060. else
  107061. {
  107062. reservoirStart += samplesInReservoir;
  107063. samplesInReservoir = 0;
  107064. FLAC__stream_decoder_process_single (decoder);
  107065. }
  107066. if (samplesInReservoir == 0)
  107067. break;
  107068. }
  107069. }
  107070. if (numSamples > 0)
  107071. {
  107072. for (int i = numDestChannels; --i >= 0;)
  107073. if (destSamples[i] != 0)
  107074. zeromem (destSamples[i] + startOffsetInDestBuffer,
  107075. sizeof (int) * numSamples);
  107076. }
  107077. return true;
  107078. }
  107079. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  107080. {
  107081. if (scanningForLength)
  107082. {
  107083. lengthInSamples += numSamples;
  107084. }
  107085. else
  107086. {
  107087. if (numSamples > reservoir.getNumSamples())
  107088. reservoir.setSize (numChannels, numSamples, false, false, true);
  107089. const int bitsToShift = 32 - bitsPerSample;
  107090. for (int i = 0; i < (int) numChannels; ++i)
  107091. {
  107092. const FlacNamespace::FLAC__int32* src = buffer[i];
  107093. int n = i;
  107094. while (src == 0 && n > 0)
  107095. src = buffer [--n];
  107096. if (src != 0)
  107097. {
  107098. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  107099. for (int j = 0; j < numSamples; ++j)
  107100. dest[j] = src[j] << bitsToShift;
  107101. }
  107102. }
  107103. samplesInReservoir = numSamples;
  107104. }
  107105. }
  107106. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  107107. {
  107108. using namespace FlacNamespace;
  107109. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  107110. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  107111. }
  107112. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  107113. {
  107114. using namespace FlacNamespace;
  107115. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  107116. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  107117. }
  107118. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107119. {
  107120. using namespace FlacNamespace;
  107121. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  107122. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  107123. }
  107124. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  107125. {
  107126. using namespace FlacNamespace;
  107127. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  107128. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  107129. }
  107130. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  107131. {
  107132. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  107133. }
  107134. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107135. const FlacNamespace::FLAC__Frame* frame,
  107136. const FlacNamespace::FLAC__int32* const buffer[],
  107137. void* client_data)
  107138. {
  107139. using namespace FlacNamespace;
  107140. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  107141. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  107142. }
  107143. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107144. const FlacNamespace::FLAC__StreamMetadata* metadata,
  107145. void* client_data)
  107146. {
  107147. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  107148. }
  107149. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  107150. {
  107151. }
  107152. private:
  107153. FlacNamespace::FLAC__StreamDecoder* decoder;
  107154. AudioSampleBuffer reservoir;
  107155. int reservoirStart, samplesInReservoir;
  107156. bool ok, scanningForLength;
  107157. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  107158. };
  107159. class FlacWriter : public AudioFormatWriter
  107160. {
  107161. public:
  107162. FlacWriter (OutputStream* const out, double sampleRate_,
  107163. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  107164. : AudioFormatWriter (out, TRANS (flacFormatName),
  107165. sampleRate_, numChannels_, bitsPerSample_)
  107166. {
  107167. using namespace FlacNamespace;
  107168. encoder = FLAC__stream_encoder_new();
  107169. if (qualityOptionIndex > 0)
  107170. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  107171. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107172. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107173. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107174. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107175. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107176. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107177. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107178. ok = FLAC__stream_encoder_init_stream (encoder,
  107179. encodeWriteCallback, encodeSeekCallback,
  107180. encodeTellCallback, encodeMetadataCallback,
  107181. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107182. }
  107183. ~FlacWriter()
  107184. {
  107185. if (ok)
  107186. {
  107187. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107188. output->flush();
  107189. }
  107190. else
  107191. {
  107192. output = 0; // to stop the base class deleting this, as it needs to be returned
  107193. // to the caller of createWriter()
  107194. }
  107195. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107196. }
  107197. bool write (const int** samplesToWrite, int numSamples)
  107198. {
  107199. using namespace FlacNamespace;
  107200. if (! ok)
  107201. return false;
  107202. int* buf[3];
  107203. HeapBlock<int> temp;
  107204. const int bitsToShift = 32 - bitsPerSample;
  107205. if (bitsToShift > 0)
  107206. {
  107207. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107208. temp.malloc (numSamples * numChannelsToWrite);
  107209. buf[0] = temp.getData();
  107210. buf[1] = temp.getData() + numSamples;
  107211. buf[2] = 0;
  107212. for (int i = numChannelsToWrite; --i >= 0;)
  107213. if (samplesToWrite[i] != 0)
  107214. for (int j = 0; j < numSamples; ++j)
  107215. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107216. samplesToWrite = const_cast<const int**> (buf);
  107217. }
  107218. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  107219. }
  107220. bool writeData (const void* const data, const int size) const
  107221. {
  107222. return output->write (data, size);
  107223. }
  107224. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107225. {
  107226. using namespace FlacNamespace;
  107227. b += bytes;
  107228. for (int i = 0; i < bytes; ++i)
  107229. {
  107230. *(--b) = (FLAC__byte) (val & 0xff);
  107231. val >>= 8;
  107232. }
  107233. }
  107234. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107235. {
  107236. using namespace FlacNamespace;
  107237. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107238. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107239. const unsigned int channelsMinus1 = info.channels - 1;
  107240. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107241. packUint32 (info.min_blocksize, buffer, 2);
  107242. packUint32 (info.max_blocksize, buffer + 2, 2);
  107243. packUint32 (info.min_framesize, buffer + 4, 3);
  107244. packUint32 (info.max_framesize, buffer + 7, 3);
  107245. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107246. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107247. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107248. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107249. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107250. memcpy (buffer + 18, info.md5sum, 16);
  107251. const bool seekOk = output->setPosition (4);
  107252. (void) seekOk;
  107253. // if this fails, you've given it an output stream that can't seek! It needs
  107254. // to be able to seek back to write the header
  107255. jassert (seekOk);
  107256. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107257. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107258. }
  107259. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107260. const FlacNamespace::FLAC__byte buffer[],
  107261. size_t bytes,
  107262. unsigned int /*samples*/,
  107263. unsigned int /*current_frame*/,
  107264. void* client_data)
  107265. {
  107266. using namespace FlacNamespace;
  107267. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107268. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107269. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107270. }
  107271. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107272. {
  107273. using namespace FlacNamespace;
  107274. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107275. }
  107276. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107277. {
  107278. using namespace FlacNamespace;
  107279. if (client_data == 0)
  107280. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107281. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107282. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107283. }
  107284. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107285. {
  107286. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107287. }
  107288. bool ok;
  107289. private:
  107290. FlacNamespace::FLAC__StreamEncoder* encoder;
  107291. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  107292. };
  107293. FlacAudioFormat::FlacAudioFormat()
  107294. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107295. {
  107296. }
  107297. FlacAudioFormat::~FlacAudioFormat()
  107298. {
  107299. }
  107300. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107301. {
  107302. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107303. return Array <int> (rates);
  107304. }
  107305. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107306. {
  107307. const int depths[] = { 16, 24, 0 };
  107308. return Array <int> (depths);
  107309. }
  107310. bool FlacAudioFormat::canDoStereo() { return true; }
  107311. bool FlacAudioFormat::canDoMono() { return true; }
  107312. bool FlacAudioFormat::isCompressed() { return true; }
  107313. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107314. const bool deleteStreamIfOpeningFails)
  107315. {
  107316. ScopedPointer<FlacReader> r (new FlacReader (in));
  107317. if (r->sampleRate > 0)
  107318. return r.release();
  107319. if (! deleteStreamIfOpeningFails)
  107320. r->input = 0;
  107321. return 0;
  107322. }
  107323. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107324. double sampleRate,
  107325. unsigned int numberOfChannels,
  107326. int bitsPerSample,
  107327. const StringPairArray& /*metadataValues*/,
  107328. int qualityOptionIndex)
  107329. {
  107330. if (getPossibleBitDepths().contains (bitsPerSample))
  107331. {
  107332. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107333. if (w->ok)
  107334. return w.release();
  107335. }
  107336. return 0;
  107337. }
  107338. END_JUCE_NAMESPACE
  107339. #endif
  107340. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107341. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107342. #if JUCE_USE_OGGVORBIS
  107343. #if JUCE_MAC
  107344. #define __MACOSX__ 1
  107345. #endif
  107346. namespace OggVorbisNamespace
  107347. {
  107348. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107349. /*** Start of inlined file: vorbisenc.h ***/
  107350. #ifndef _OV_ENC_H_
  107351. #define _OV_ENC_H_
  107352. #ifdef __cplusplus
  107353. extern "C"
  107354. {
  107355. #endif /* __cplusplus */
  107356. /*** Start of inlined file: codec.h ***/
  107357. #ifndef _vorbis_codec_h_
  107358. #define _vorbis_codec_h_
  107359. #ifdef __cplusplus
  107360. extern "C"
  107361. {
  107362. #endif /* __cplusplus */
  107363. /*** Start of inlined file: ogg.h ***/
  107364. #ifndef _OGG_H
  107365. #define _OGG_H
  107366. #ifdef __cplusplus
  107367. extern "C" {
  107368. #endif
  107369. /*** Start of inlined file: os_types.h ***/
  107370. #ifndef _OS_TYPES_H
  107371. #define _OS_TYPES_H
  107372. /* make it easy on the folks that want to compile the libs with a
  107373. different malloc than stdlib */
  107374. #define _ogg_malloc malloc
  107375. #define _ogg_calloc calloc
  107376. #define _ogg_realloc realloc
  107377. #define _ogg_free free
  107378. #if defined(_WIN32)
  107379. # if defined(__CYGWIN__)
  107380. # include <_G_config.h>
  107381. typedef _G_int64_t ogg_int64_t;
  107382. typedef _G_int32_t ogg_int32_t;
  107383. typedef _G_uint32_t ogg_uint32_t;
  107384. typedef _G_int16_t ogg_int16_t;
  107385. typedef _G_uint16_t ogg_uint16_t;
  107386. # elif defined(__MINGW32__)
  107387. typedef short ogg_int16_t;
  107388. typedef unsigned short ogg_uint16_t;
  107389. typedef int ogg_int32_t;
  107390. typedef unsigned int ogg_uint32_t;
  107391. typedef long long ogg_int64_t;
  107392. typedef unsigned long long ogg_uint64_t;
  107393. # elif defined(__MWERKS__)
  107394. typedef long long ogg_int64_t;
  107395. typedef int ogg_int32_t;
  107396. typedef unsigned int ogg_uint32_t;
  107397. typedef short ogg_int16_t;
  107398. typedef unsigned short ogg_uint16_t;
  107399. # else
  107400. /* MSVC/Borland */
  107401. typedef __int64 ogg_int64_t;
  107402. typedef __int32 ogg_int32_t;
  107403. typedef unsigned __int32 ogg_uint32_t;
  107404. typedef __int16 ogg_int16_t;
  107405. typedef unsigned __int16 ogg_uint16_t;
  107406. # endif
  107407. #elif defined(__MACOS__)
  107408. # include <sys/types.h>
  107409. typedef SInt16 ogg_int16_t;
  107410. typedef UInt16 ogg_uint16_t;
  107411. typedef SInt32 ogg_int32_t;
  107412. typedef UInt32 ogg_uint32_t;
  107413. typedef SInt64 ogg_int64_t;
  107414. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107415. # include <sys/types.h>
  107416. typedef int16_t ogg_int16_t;
  107417. typedef u_int16_t ogg_uint16_t;
  107418. typedef int32_t ogg_int32_t;
  107419. typedef u_int32_t ogg_uint32_t;
  107420. typedef int64_t ogg_int64_t;
  107421. #elif defined(__BEOS__)
  107422. /* Be */
  107423. # include <inttypes.h>
  107424. typedef int16_t ogg_int16_t;
  107425. typedef u_int16_t ogg_uint16_t;
  107426. typedef int32_t ogg_int32_t;
  107427. typedef u_int32_t ogg_uint32_t;
  107428. typedef int64_t ogg_int64_t;
  107429. #elif defined (__EMX__)
  107430. /* OS/2 GCC */
  107431. typedef short ogg_int16_t;
  107432. typedef unsigned short ogg_uint16_t;
  107433. typedef int ogg_int32_t;
  107434. typedef unsigned int ogg_uint32_t;
  107435. typedef long long ogg_int64_t;
  107436. #elif defined (DJGPP)
  107437. /* DJGPP */
  107438. typedef short ogg_int16_t;
  107439. typedef int ogg_int32_t;
  107440. typedef unsigned int ogg_uint32_t;
  107441. typedef long long ogg_int64_t;
  107442. #elif defined(R5900)
  107443. /* PS2 EE */
  107444. typedef long ogg_int64_t;
  107445. typedef int ogg_int32_t;
  107446. typedef unsigned ogg_uint32_t;
  107447. typedef short ogg_int16_t;
  107448. #elif defined(__SYMBIAN32__)
  107449. /* Symbian GCC */
  107450. typedef signed short ogg_int16_t;
  107451. typedef unsigned short ogg_uint16_t;
  107452. typedef signed int ogg_int32_t;
  107453. typedef unsigned int ogg_uint32_t;
  107454. typedef long long int ogg_int64_t;
  107455. #else
  107456. # include <sys/types.h>
  107457. /*** Start of inlined file: config_types.h ***/
  107458. #ifndef __CONFIG_TYPES_H__
  107459. #define __CONFIG_TYPES_H__
  107460. typedef int16_t ogg_int16_t;
  107461. typedef unsigned short ogg_uint16_t;
  107462. typedef int32_t ogg_int32_t;
  107463. typedef unsigned int ogg_uint32_t;
  107464. typedef int64_t ogg_int64_t;
  107465. #endif
  107466. /*** End of inlined file: config_types.h ***/
  107467. #endif
  107468. #endif /* _OS_TYPES_H */
  107469. /*** End of inlined file: os_types.h ***/
  107470. typedef struct {
  107471. long endbyte;
  107472. int endbit;
  107473. unsigned char *buffer;
  107474. unsigned char *ptr;
  107475. long storage;
  107476. } oggpack_buffer;
  107477. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107478. typedef struct {
  107479. unsigned char *header;
  107480. long header_len;
  107481. unsigned char *body;
  107482. long body_len;
  107483. } ogg_page;
  107484. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107485. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107486. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107487. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107488. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107489. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107490. }
  107491. /* ogg_stream_state contains the current encode/decode state of a logical
  107492. Ogg bitstream **********************************************************/
  107493. typedef struct {
  107494. unsigned char *body_data; /* bytes from packet bodies */
  107495. long body_storage; /* storage elements allocated */
  107496. long body_fill; /* elements stored; fill mark */
  107497. long body_returned; /* elements of fill returned */
  107498. int *lacing_vals; /* The values that will go to the segment table */
  107499. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107500. this way, but it is simple coupled to the
  107501. lacing fifo */
  107502. long lacing_storage;
  107503. long lacing_fill;
  107504. long lacing_packet;
  107505. long lacing_returned;
  107506. unsigned char header[282]; /* working space for header encode */
  107507. int header_fill;
  107508. int e_o_s; /* set when we have buffered the last packet in the
  107509. logical bitstream */
  107510. int b_o_s; /* set after we've written the initial page
  107511. of a logical bitstream */
  107512. long serialno;
  107513. long pageno;
  107514. ogg_int64_t packetno; /* sequence number for decode; the framing
  107515. knows where there's a hole in the data,
  107516. but we need coupling so that the codec
  107517. (which is in a seperate abstraction
  107518. layer) also knows about the gap */
  107519. ogg_int64_t granulepos;
  107520. } ogg_stream_state;
  107521. /* ogg_packet is used to encapsulate the data and metadata belonging
  107522. to a single raw Ogg/Vorbis packet *************************************/
  107523. typedef struct {
  107524. unsigned char *packet;
  107525. long bytes;
  107526. long b_o_s;
  107527. long e_o_s;
  107528. ogg_int64_t granulepos;
  107529. ogg_int64_t packetno; /* sequence number for decode; the framing
  107530. knows where there's a hole in the data,
  107531. but we need coupling so that the codec
  107532. (which is in a seperate abstraction
  107533. layer) also knows about the gap */
  107534. } ogg_packet;
  107535. typedef struct {
  107536. unsigned char *data;
  107537. int storage;
  107538. int fill;
  107539. int returned;
  107540. int unsynced;
  107541. int headerbytes;
  107542. int bodybytes;
  107543. } ogg_sync_state;
  107544. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107545. extern void oggpack_writeinit(oggpack_buffer *b);
  107546. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107547. extern void oggpack_writealign(oggpack_buffer *b);
  107548. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107549. extern void oggpack_reset(oggpack_buffer *b);
  107550. extern void oggpack_writeclear(oggpack_buffer *b);
  107551. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107552. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107553. extern long oggpack_look(oggpack_buffer *b,int bits);
  107554. extern long oggpack_look1(oggpack_buffer *b);
  107555. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107556. extern void oggpack_adv1(oggpack_buffer *b);
  107557. extern long oggpack_read(oggpack_buffer *b,int bits);
  107558. extern long oggpack_read1(oggpack_buffer *b);
  107559. extern long oggpack_bytes(oggpack_buffer *b);
  107560. extern long oggpack_bits(oggpack_buffer *b);
  107561. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107562. extern void oggpackB_writeinit(oggpack_buffer *b);
  107563. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107564. extern void oggpackB_writealign(oggpack_buffer *b);
  107565. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107566. extern void oggpackB_reset(oggpack_buffer *b);
  107567. extern void oggpackB_writeclear(oggpack_buffer *b);
  107568. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107569. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107570. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107571. extern long oggpackB_look1(oggpack_buffer *b);
  107572. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107573. extern void oggpackB_adv1(oggpack_buffer *b);
  107574. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107575. extern long oggpackB_read1(oggpack_buffer *b);
  107576. extern long oggpackB_bytes(oggpack_buffer *b);
  107577. extern long oggpackB_bits(oggpack_buffer *b);
  107578. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107579. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107580. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107581. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107582. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107583. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107584. extern int ogg_sync_init(ogg_sync_state *oy);
  107585. extern int ogg_sync_clear(ogg_sync_state *oy);
  107586. extern int ogg_sync_reset(ogg_sync_state *oy);
  107587. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107588. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107589. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107590. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107591. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107592. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107593. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107594. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107595. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107596. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107597. extern int ogg_stream_clear(ogg_stream_state *os);
  107598. extern int ogg_stream_reset(ogg_stream_state *os);
  107599. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107600. extern int ogg_stream_destroy(ogg_stream_state *os);
  107601. extern int ogg_stream_eos(ogg_stream_state *os);
  107602. extern void ogg_page_checksum_set(ogg_page *og);
  107603. extern int ogg_page_version(ogg_page *og);
  107604. extern int ogg_page_continued(ogg_page *og);
  107605. extern int ogg_page_bos(ogg_page *og);
  107606. extern int ogg_page_eos(ogg_page *og);
  107607. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107608. extern int ogg_page_serialno(ogg_page *og);
  107609. extern long ogg_page_pageno(ogg_page *og);
  107610. extern int ogg_page_packets(ogg_page *og);
  107611. extern void ogg_packet_clear(ogg_packet *op);
  107612. #ifdef __cplusplus
  107613. }
  107614. #endif
  107615. #endif /* _OGG_H */
  107616. /*** End of inlined file: ogg.h ***/
  107617. typedef struct vorbis_info{
  107618. int version;
  107619. int channels;
  107620. long rate;
  107621. /* The below bitrate declarations are *hints*.
  107622. Combinations of the three values carry the following implications:
  107623. all three set to the same value:
  107624. implies a fixed rate bitstream
  107625. only nominal set:
  107626. implies a VBR stream that averages the nominal bitrate. No hard
  107627. upper/lower limit
  107628. upper and or lower set:
  107629. implies a VBR bitstream that obeys the bitrate limits. nominal
  107630. may also be set to give a nominal rate.
  107631. none set:
  107632. the coder does not care to speculate.
  107633. */
  107634. long bitrate_upper;
  107635. long bitrate_nominal;
  107636. long bitrate_lower;
  107637. long bitrate_window;
  107638. void *codec_setup;
  107639. } vorbis_info;
  107640. /* vorbis_dsp_state buffers the current vorbis audio
  107641. analysis/synthesis state. The DSP state belongs to a specific
  107642. logical bitstream ****************************************************/
  107643. typedef struct vorbis_dsp_state{
  107644. int analysisp;
  107645. vorbis_info *vi;
  107646. float **pcm;
  107647. float **pcmret;
  107648. int pcm_storage;
  107649. int pcm_current;
  107650. int pcm_returned;
  107651. int preextrapolate;
  107652. int eofflag;
  107653. long lW;
  107654. long W;
  107655. long nW;
  107656. long centerW;
  107657. ogg_int64_t granulepos;
  107658. ogg_int64_t sequence;
  107659. ogg_int64_t glue_bits;
  107660. ogg_int64_t time_bits;
  107661. ogg_int64_t floor_bits;
  107662. ogg_int64_t res_bits;
  107663. void *backend_state;
  107664. } vorbis_dsp_state;
  107665. typedef struct vorbis_block{
  107666. /* necessary stream state for linking to the framing abstraction */
  107667. float **pcm; /* this is a pointer into local storage */
  107668. oggpack_buffer opb;
  107669. long lW;
  107670. long W;
  107671. long nW;
  107672. int pcmend;
  107673. int mode;
  107674. int eofflag;
  107675. ogg_int64_t granulepos;
  107676. ogg_int64_t sequence;
  107677. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107678. /* local storage to avoid remallocing; it's up to the mapping to
  107679. structure it */
  107680. void *localstore;
  107681. long localtop;
  107682. long localalloc;
  107683. long totaluse;
  107684. struct alloc_chain *reap;
  107685. /* bitmetrics for the frame */
  107686. long glue_bits;
  107687. long time_bits;
  107688. long floor_bits;
  107689. long res_bits;
  107690. void *internal;
  107691. } vorbis_block;
  107692. /* vorbis_block is a single block of data to be processed as part of
  107693. the analysis/synthesis stream; it belongs to a specific logical
  107694. bitstream, but is independant from other vorbis_blocks belonging to
  107695. that logical bitstream. *************************************************/
  107696. struct alloc_chain{
  107697. void *ptr;
  107698. struct alloc_chain *next;
  107699. };
  107700. /* vorbis_info contains all the setup information specific to the
  107701. specific compression/decompression mode in progress (eg,
  107702. psychoacoustic settings, channel setup, options, codebook
  107703. etc). vorbis_info and substructures are in backends.h.
  107704. *********************************************************************/
  107705. /* the comments are not part of vorbis_info so that vorbis_info can be
  107706. static storage */
  107707. typedef struct vorbis_comment{
  107708. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107709. whatever vendor is set to in encode */
  107710. char **user_comments;
  107711. int *comment_lengths;
  107712. int comments;
  107713. char *vendor;
  107714. } vorbis_comment;
  107715. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107716. and produce a packet (see docs/analysis.txt). The packet is then
  107717. coded into a framed OggSquish bitstream by the second layer (see
  107718. docs/framing.txt). Decode is the reverse process; we sync/frame
  107719. the bitstream and extract individual packets, then decode the
  107720. packet back into PCM audio.
  107721. The extra framing/packetizing is used in streaming formats, such as
  107722. files. Over the net (such as with UDP), the framing and
  107723. packetization aren't necessary as they're provided by the transport
  107724. and the streaming layer is not used */
  107725. /* Vorbis PRIMITIVES: general ***************************************/
  107726. extern void vorbis_info_init(vorbis_info *vi);
  107727. extern void vorbis_info_clear(vorbis_info *vi);
  107728. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107729. extern void vorbis_comment_init(vorbis_comment *vc);
  107730. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107731. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107732. const char *tag, char *contents);
  107733. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107734. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107735. extern void vorbis_comment_clear(vorbis_comment *vc);
  107736. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107737. extern int vorbis_block_clear(vorbis_block *vb);
  107738. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107739. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107740. ogg_int64_t granulepos);
  107741. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107742. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107743. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107744. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107745. vorbis_comment *vc,
  107746. ogg_packet *op,
  107747. ogg_packet *op_comm,
  107748. ogg_packet *op_code);
  107749. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107750. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107751. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107752. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107753. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107754. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107755. ogg_packet *op);
  107756. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107757. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107758. ogg_packet *op);
  107759. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107760. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107761. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107762. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107763. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107764. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107765. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107766. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107767. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107768. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107769. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107770. /* Vorbis ERRORS and return codes ***********************************/
  107771. #define OV_FALSE -1
  107772. #define OV_EOF -2
  107773. #define OV_HOLE -3
  107774. #define OV_EREAD -128
  107775. #define OV_EFAULT -129
  107776. #define OV_EIMPL -130
  107777. #define OV_EINVAL -131
  107778. #define OV_ENOTVORBIS -132
  107779. #define OV_EBADHEADER -133
  107780. #define OV_EVERSION -134
  107781. #define OV_ENOTAUDIO -135
  107782. #define OV_EBADPACKET -136
  107783. #define OV_EBADLINK -137
  107784. #define OV_ENOSEEK -138
  107785. #ifdef __cplusplus
  107786. }
  107787. #endif /* __cplusplus */
  107788. #endif
  107789. /*** End of inlined file: codec.h ***/
  107790. extern int vorbis_encode_init(vorbis_info *vi,
  107791. long channels,
  107792. long rate,
  107793. long max_bitrate,
  107794. long nominal_bitrate,
  107795. long min_bitrate);
  107796. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107797. long channels,
  107798. long rate,
  107799. long max_bitrate,
  107800. long nominal_bitrate,
  107801. long min_bitrate);
  107802. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107803. long channels,
  107804. long rate,
  107805. float quality /* quality level from 0. (lo) to 1. (hi) */
  107806. );
  107807. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107808. long channels,
  107809. long rate,
  107810. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107811. );
  107812. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107813. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107814. /* deprecated rate management supported only for compatability */
  107815. #define OV_ECTL_RATEMANAGE_GET 0x10
  107816. #define OV_ECTL_RATEMANAGE_SET 0x11
  107817. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107818. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107819. struct ovectl_ratemanage_arg {
  107820. int management_active;
  107821. long bitrate_hard_min;
  107822. long bitrate_hard_max;
  107823. double bitrate_hard_window;
  107824. long bitrate_av_lo;
  107825. long bitrate_av_hi;
  107826. double bitrate_av_window;
  107827. double bitrate_av_window_center;
  107828. };
  107829. /* new rate setup */
  107830. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107831. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107832. struct ovectl_ratemanage2_arg {
  107833. int management_active;
  107834. long bitrate_limit_min_kbps;
  107835. long bitrate_limit_max_kbps;
  107836. long bitrate_limit_reservoir_bits;
  107837. double bitrate_limit_reservoir_bias;
  107838. long bitrate_average_kbps;
  107839. double bitrate_average_damping;
  107840. };
  107841. #define OV_ECTL_LOWPASS_GET 0x20
  107842. #define OV_ECTL_LOWPASS_SET 0x21
  107843. #define OV_ECTL_IBLOCK_GET 0x30
  107844. #define OV_ECTL_IBLOCK_SET 0x31
  107845. #ifdef __cplusplus
  107846. }
  107847. #endif /* __cplusplus */
  107848. #endif
  107849. /*** End of inlined file: vorbisenc.h ***/
  107850. /*** Start of inlined file: vorbisfile.h ***/
  107851. #ifndef _OV_FILE_H_
  107852. #define _OV_FILE_H_
  107853. #ifdef __cplusplus
  107854. extern "C"
  107855. {
  107856. #endif /* __cplusplus */
  107857. #include <stdio.h>
  107858. /* The function prototypes for the callbacks are basically the same as for
  107859. * the stdio functions fread, fseek, fclose, ftell.
  107860. * The one difference is that the FILE * arguments have been replaced with
  107861. * a void * - this is to be used as a pointer to whatever internal data these
  107862. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107863. *
  107864. * If you use other functions, check the docs for these functions and return
  107865. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107866. * unseekable
  107867. */
  107868. typedef struct {
  107869. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107870. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107871. int (*close_func) (void *datasource);
  107872. long (*tell_func) (void *datasource);
  107873. } ov_callbacks;
  107874. #define NOTOPEN 0
  107875. #define PARTOPEN 1
  107876. #define OPENED 2
  107877. #define STREAMSET 3
  107878. #define INITSET 4
  107879. typedef struct OggVorbis_File {
  107880. void *datasource; /* Pointer to a FILE *, etc. */
  107881. int seekable;
  107882. ogg_int64_t offset;
  107883. ogg_int64_t end;
  107884. ogg_sync_state oy;
  107885. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107886. stream appears */
  107887. int links;
  107888. ogg_int64_t *offsets;
  107889. ogg_int64_t *dataoffsets;
  107890. long *serialnos;
  107891. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107892. compatability; x2 size, stores both
  107893. beginning and end values */
  107894. vorbis_info *vi;
  107895. vorbis_comment *vc;
  107896. /* Decoding working state local storage */
  107897. ogg_int64_t pcm_offset;
  107898. int ready_state;
  107899. long current_serialno;
  107900. int current_link;
  107901. double bittrack;
  107902. double samptrack;
  107903. ogg_stream_state os; /* take physical pages, weld into a logical
  107904. stream of packets */
  107905. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107906. vorbis_block vb; /* local working space for packet->PCM decode */
  107907. ov_callbacks callbacks;
  107908. } OggVorbis_File;
  107909. extern int ov_clear(OggVorbis_File *vf);
  107910. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107911. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107912. char *initial, long ibytes, ov_callbacks callbacks);
  107913. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107914. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107915. char *initial, long ibytes, ov_callbacks callbacks);
  107916. extern int ov_test_open(OggVorbis_File *vf);
  107917. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107918. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107919. extern long ov_streams(OggVorbis_File *vf);
  107920. extern long ov_seekable(OggVorbis_File *vf);
  107921. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107922. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107923. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107924. extern double ov_time_total(OggVorbis_File *vf,int i);
  107925. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107926. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107927. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107928. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107929. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107930. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107931. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107932. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107933. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107934. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107935. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107936. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107937. extern double ov_time_tell(OggVorbis_File *vf);
  107938. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107939. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107940. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107941. int *bitstream);
  107942. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107943. int bigendianp,int word,int sgned,int *bitstream);
  107944. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107945. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107946. extern int ov_halfrate_p(OggVorbis_File *vf);
  107947. #ifdef __cplusplus
  107948. }
  107949. #endif /* __cplusplus */
  107950. #endif
  107951. /*** End of inlined file: vorbisfile.h ***/
  107952. /*** Start of inlined file: bitwise.c ***/
  107953. /* We're 'LSb' endian; if we write a word but read individual bits,
  107954. then we'll read the lsb first */
  107955. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107956. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107957. // tasks..
  107958. #if JUCE_MSVC
  107959. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107960. #endif
  107961. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107962. #if JUCE_USE_OGGVORBIS
  107963. #include <string.h>
  107964. #include <stdlib.h>
  107965. #define BUFFER_INCREMENT 256
  107966. static const unsigned long mask[]=
  107967. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107968. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107969. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107970. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107971. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107972. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107973. 0x3fffffff,0x7fffffff,0xffffffff };
  107974. static const unsigned int mask8B[]=
  107975. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107976. void oggpack_writeinit(oggpack_buffer *b){
  107977. memset(b,0,sizeof(*b));
  107978. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107979. b->buffer[0]='\0';
  107980. b->storage=BUFFER_INCREMENT;
  107981. }
  107982. void oggpackB_writeinit(oggpack_buffer *b){
  107983. oggpack_writeinit(b);
  107984. }
  107985. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107986. long bytes=bits>>3;
  107987. bits-=bytes*8;
  107988. b->ptr=b->buffer+bytes;
  107989. b->endbit=bits;
  107990. b->endbyte=bytes;
  107991. *b->ptr&=mask[bits];
  107992. }
  107993. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107994. long bytes=bits>>3;
  107995. bits-=bytes*8;
  107996. b->ptr=b->buffer+bytes;
  107997. b->endbit=bits;
  107998. b->endbyte=bytes;
  107999. *b->ptr&=mask8B[bits];
  108000. }
  108001. /* Takes only up to 32 bits. */
  108002. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  108003. if(b->endbyte+4>=b->storage){
  108004. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108005. b->storage+=BUFFER_INCREMENT;
  108006. b->ptr=b->buffer+b->endbyte;
  108007. }
  108008. value&=mask[bits];
  108009. bits+=b->endbit;
  108010. b->ptr[0]|=value<<b->endbit;
  108011. if(bits>=8){
  108012. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  108013. if(bits>=16){
  108014. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  108015. if(bits>=24){
  108016. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  108017. if(bits>=32){
  108018. if(b->endbit)
  108019. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  108020. else
  108021. b->ptr[4]=0;
  108022. }
  108023. }
  108024. }
  108025. }
  108026. b->endbyte+=bits/8;
  108027. b->ptr+=bits/8;
  108028. b->endbit=bits&7;
  108029. }
  108030. /* Takes only up to 32 bits. */
  108031. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  108032. if(b->endbyte+4>=b->storage){
  108033. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108034. b->storage+=BUFFER_INCREMENT;
  108035. b->ptr=b->buffer+b->endbyte;
  108036. }
  108037. value=(value&mask[bits])<<(32-bits);
  108038. bits+=b->endbit;
  108039. b->ptr[0]|=value>>(24+b->endbit);
  108040. if(bits>=8){
  108041. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  108042. if(bits>=16){
  108043. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  108044. if(bits>=24){
  108045. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  108046. if(bits>=32){
  108047. if(b->endbit)
  108048. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  108049. else
  108050. b->ptr[4]=0;
  108051. }
  108052. }
  108053. }
  108054. }
  108055. b->endbyte+=bits/8;
  108056. b->ptr+=bits/8;
  108057. b->endbit=bits&7;
  108058. }
  108059. void oggpack_writealign(oggpack_buffer *b){
  108060. int bits=8-b->endbit;
  108061. if(bits<8)
  108062. oggpack_write(b,0,bits);
  108063. }
  108064. void oggpackB_writealign(oggpack_buffer *b){
  108065. int bits=8-b->endbit;
  108066. if(bits<8)
  108067. oggpackB_write(b,0,bits);
  108068. }
  108069. static void oggpack_writecopy_helper(oggpack_buffer *b,
  108070. void *source,
  108071. long bits,
  108072. void (*w)(oggpack_buffer *,
  108073. unsigned long,
  108074. int),
  108075. int msb){
  108076. unsigned char *ptr=(unsigned char *)source;
  108077. long bytes=bits/8;
  108078. bits-=bytes*8;
  108079. if(b->endbit){
  108080. int i;
  108081. /* unaligned copy. Do it the hard way. */
  108082. for(i=0;i<bytes;i++)
  108083. w(b,(unsigned long)(ptr[i]),8);
  108084. }else{
  108085. /* aligned block copy */
  108086. if(b->endbyte+bytes+1>=b->storage){
  108087. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  108088. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  108089. b->ptr=b->buffer+b->endbyte;
  108090. }
  108091. memmove(b->ptr,source,bytes);
  108092. b->ptr+=bytes;
  108093. b->endbyte+=bytes;
  108094. *b->ptr=0;
  108095. }
  108096. if(bits){
  108097. if(msb)
  108098. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  108099. else
  108100. w(b,(unsigned long)(ptr[bytes]),bits);
  108101. }
  108102. }
  108103. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  108104. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  108105. }
  108106. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  108107. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  108108. }
  108109. void oggpack_reset(oggpack_buffer *b){
  108110. b->ptr=b->buffer;
  108111. b->buffer[0]=0;
  108112. b->endbit=b->endbyte=0;
  108113. }
  108114. void oggpackB_reset(oggpack_buffer *b){
  108115. oggpack_reset(b);
  108116. }
  108117. void oggpack_writeclear(oggpack_buffer *b){
  108118. _ogg_free(b->buffer);
  108119. memset(b,0,sizeof(*b));
  108120. }
  108121. void oggpackB_writeclear(oggpack_buffer *b){
  108122. oggpack_writeclear(b);
  108123. }
  108124. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108125. memset(b,0,sizeof(*b));
  108126. b->buffer=b->ptr=buf;
  108127. b->storage=bytes;
  108128. }
  108129. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108130. oggpack_readinit(b,buf,bytes);
  108131. }
  108132. /* Read in bits without advancing the bitptr; bits <= 32 */
  108133. long oggpack_look(oggpack_buffer *b,int bits){
  108134. unsigned long ret;
  108135. unsigned long m=mask[bits];
  108136. bits+=b->endbit;
  108137. if(b->endbyte+4>=b->storage){
  108138. /* not the main path */
  108139. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108140. }
  108141. ret=b->ptr[0]>>b->endbit;
  108142. if(bits>8){
  108143. ret|=b->ptr[1]<<(8-b->endbit);
  108144. if(bits>16){
  108145. ret|=b->ptr[2]<<(16-b->endbit);
  108146. if(bits>24){
  108147. ret|=b->ptr[3]<<(24-b->endbit);
  108148. if(bits>32 && b->endbit)
  108149. ret|=b->ptr[4]<<(32-b->endbit);
  108150. }
  108151. }
  108152. }
  108153. return(m&ret);
  108154. }
  108155. /* Read in bits without advancing the bitptr; bits <= 32 */
  108156. long oggpackB_look(oggpack_buffer *b,int bits){
  108157. unsigned long ret;
  108158. int m=32-bits;
  108159. bits+=b->endbit;
  108160. if(b->endbyte+4>=b->storage){
  108161. /* not the main path */
  108162. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108163. }
  108164. ret=b->ptr[0]<<(24+b->endbit);
  108165. if(bits>8){
  108166. ret|=b->ptr[1]<<(16+b->endbit);
  108167. if(bits>16){
  108168. ret|=b->ptr[2]<<(8+b->endbit);
  108169. if(bits>24){
  108170. ret|=b->ptr[3]<<(b->endbit);
  108171. if(bits>32 && b->endbit)
  108172. ret|=b->ptr[4]>>(8-b->endbit);
  108173. }
  108174. }
  108175. }
  108176. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108177. }
  108178. long oggpack_look1(oggpack_buffer *b){
  108179. if(b->endbyte>=b->storage)return(-1);
  108180. return((b->ptr[0]>>b->endbit)&1);
  108181. }
  108182. long oggpackB_look1(oggpack_buffer *b){
  108183. if(b->endbyte>=b->storage)return(-1);
  108184. return((b->ptr[0]>>(7-b->endbit))&1);
  108185. }
  108186. void oggpack_adv(oggpack_buffer *b,int bits){
  108187. bits+=b->endbit;
  108188. b->ptr+=bits/8;
  108189. b->endbyte+=bits/8;
  108190. b->endbit=bits&7;
  108191. }
  108192. void oggpackB_adv(oggpack_buffer *b,int bits){
  108193. oggpack_adv(b,bits);
  108194. }
  108195. void oggpack_adv1(oggpack_buffer *b){
  108196. if(++(b->endbit)>7){
  108197. b->endbit=0;
  108198. b->ptr++;
  108199. b->endbyte++;
  108200. }
  108201. }
  108202. void oggpackB_adv1(oggpack_buffer *b){
  108203. oggpack_adv1(b);
  108204. }
  108205. /* bits <= 32 */
  108206. long oggpack_read(oggpack_buffer *b,int bits){
  108207. long ret;
  108208. unsigned long m=mask[bits];
  108209. bits+=b->endbit;
  108210. if(b->endbyte+4>=b->storage){
  108211. /* not the main path */
  108212. ret=-1L;
  108213. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108214. }
  108215. ret=b->ptr[0]>>b->endbit;
  108216. if(bits>8){
  108217. ret|=b->ptr[1]<<(8-b->endbit);
  108218. if(bits>16){
  108219. ret|=b->ptr[2]<<(16-b->endbit);
  108220. if(bits>24){
  108221. ret|=b->ptr[3]<<(24-b->endbit);
  108222. if(bits>32 && b->endbit){
  108223. ret|=b->ptr[4]<<(32-b->endbit);
  108224. }
  108225. }
  108226. }
  108227. }
  108228. ret&=m;
  108229. overflow:
  108230. b->ptr+=bits/8;
  108231. b->endbyte+=bits/8;
  108232. b->endbit=bits&7;
  108233. return(ret);
  108234. }
  108235. /* bits <= 32 */
  108236. long oggpackB_read(oggpack_buffer *b,int bits){
  108237. long ret;
  108238. long m=32-bits;
  108239. bits+=b->endbit;
  108240. if(b->endbyte+4>=b->storage){
  108241. /* not the main path */
  108242. ret=-1L;
  108243. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108244. }
  108245. ret=b->ptr[0]<<(24+b->endbit);
  108246. if(bits>8){
  108247. ret|=b->ptr[1]<<(16+b->endbit);
  108248. if(bits>16){
  108249. ret|=b->ptr[2]<<(8+b->endbit);
  108250. if(bits>24){
  108251. ret|=b->ptr[3]<<(b->endbit);
  108252. if(bits>32 && b->endbit)
  108253. ret|=b->ptr[4]>>(8-b->endbit);
  108254. }
  108255. }
  108256. }
  108257. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108258. overflow:
  108259. b->ptr+=bits/8;
  108260. b->endbyte+=bits/8;
  108261. b->endbit=bits&7;
  108262. return(ret);
  108263. }
  108264. long oggpack_read1(oggpack_buffer *b){
  108265. long ret;
  108266. if(b->endbyte>=b->storage){
  108267. /* not the main path */
  108268. ret=-1L;
  108269. goto overflow;
  108270. }
  108271. ret=(b->ptr[0]>>b->endbit)&1;
  108272. overflow:
  108273. b->endbit++;
  108274. if(b->endbit>7){
  108275. b->endbit=0;
  108276. b->ptr++;
  108277. b->endbyte++;
  108278. }
  108279. return(ret);
  108280. }
  108281. long oggpackB_read1(oggpack_buffer *b){
  108282. long ret;
  108283. if(b->endbyte>=b->storage){
  108284. /* not the main path */
  108285. ret=-1L;
  108286. goto overflow;
  108287. }
  108288. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108289. overflow:
  108290. b->endbit++;
  108291. if(b->endbit>7){
  108292. b->endbit=0;
  108293. b->ptr++;
  108294. b->endbyte++;
  108295. }
  108296. return(ret);
  108297. }
  108298. long oggpack_bytes(oggpack_buffer *b){
  108299. return(b->endbyte+(b->endbit+7)/8);
  108300. }
  108301. long oggpack_bits(oggpack_buffer *b){
  108302. return(b->endbyte*8+b->endbit);
  108303. }
  108304. long oggpackB_bytes(oggpack_buffer *b){
  108305. return oggpack_bytes(b);
  108306. }
  108307. long oggpackB_bits(oggpack_buffer *b){
  108308. return oggpack_bits(b);
  108309. }
  108310. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108311. return(b->buffer);
  108312. }
  108313. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108314. return oggpack_get_buffer(b);
  108315. }
  108316. /* Self test of the bitwise routines; everything else is based on
  108317. them, so they damned well better be solid. */
  108318. #ifdef _V_SELFTEST
  108319. #include <stdio.h>
  108320. static int ilog(unsigned int v){
  108321. int ret=0;
  108322. while(v){
  108323. ret++;
  108324. v>>=1;
  108325. }
  108326. return(ret);
  108327. }
  108328. oggpack_buffer o;
  108329. oggpack_buffer r;
  108330. void report(char *in){
  108331. fprintf(stderr,"%s",in);
  108332. exit(1);
  108333. }
  108334. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108335. long bytes,i;
  108336. unsigned char *buffer;
  108337. oggpack_reset(&o);
  108338. for(i=0;i<vals;i++)
  108339. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108340. buffer=oggpack_get_buffer(&o);
  108341. bytes=oggpack_bytes(&o);
  108342. if(bytes!=compsize)report("wrong number of bytes!\n");
  108343. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108344. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108345. report("wrote incorrect value!\n");
  108346. }
  108347. oggpack_readinit(&r,buffer,bytes);
  108348. for(i=0;i<vals;i++){
  108349. int tbit=bits?bits:ilog(b[i]);
  108350. if(oggpack_look(&r,tbit)==-1)
  108351. report("out of data!\n");
  108352. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108353. report("looked at incorrect value!\n");
  108354. if(tbit==1)
  108355. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108356. report("looked at single bit incorrect value!\n");
  108357. if(tbit==1){
  108358. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108359. report("read incorrect single bit value!\n");
  108360. }else{
  108361. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108362. report("read incorrect value!\n");
  108363. }
  108364. }
  108365. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108366. }
  108367. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108368. long bytes,i;
  108369. unsigned char *buffer;
  108370. oggpackB_reset(&o);
  108371. for(i=0;i<vals;i++)
  108372. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108373. buffer=oggpackB_get_buffer(&o);
  108374. bytes=oggpackB_bytes(&o);
  108375. if(bytes!=compsize)report("wrong number of bytes!\n");
  108376. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108377. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108378. report("wrote incorrect value!\n");
  108379. }
  108380. oggpackB_readinit(&r,buffer,bytes);
  108381. for(i=0;i<vals;i++){
  108382. int tbit=bits?bits:ilog(b[i]);
  108383. if(oggpackB_look(&r,tbit)==-1)
  108384. report("out of data!\n");
  108385. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108386. report("looked at incorrect value!\n");
  108387. if(tbit==1)
  108388. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108389. report("looked at single bit incorrect value!\n");
  108390. if(tbit==1){
  108391. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108392. report("read incorrect single bit value!\n");
  108393. }else{
  108394. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108395. report("read incorrect value!\n");
  108396. }
  108397. }
  108398. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108399. }
  108400. int main(void){
  108401. unsigned char *buffer;
  108402. long bytes,i;
  108403. static unsigned long testbuffer1[]=
  108404. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108405. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108406. int test1size=43;
  108407. static unsigned long testbuffer2[]=
  108408. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108409. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108410. 85525151,0,12321,1,349528352};
  108411. int test2size=21;
  108412. static unsigned long testbuffer3[]=
  108413. {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,
  108414. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108415. int test3size=56;
  108416. static unsigned long large[]=
  108417. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108418. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108419. 85525151,0,12321,1,2146528352};
  108420. int onesize=33;
  108421. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108422. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108423. 223,4};
  108424. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108425. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108426. 245,251,128};
  108427. int twosize=6;
  108428. static int two[6]={61,255,255,251,231,29};
  108429. static int twoB[6]={247,63,255,253,249,120};
  108430. int threesize=54;
  108431. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108432. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108433. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108434. 100,52,4,14,18,86,77,1};
  108435. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108436. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108437. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108438. 200,20,254,4,58,106,176,144,0};
  108439. int foursize=38;
  108440. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108441. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108442. 28,2,133,0,1};
  108443. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108444. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108445. 129,10,4,32};
  108446. int fivesize=45;
  108447. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108448. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108449. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108450. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108451. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108452. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108453. int sixsize=7;
  108454. static int six[7]={17,177,170,242,169,19,148};
  108455. static int sixB[7]={136,141,85,79,149,200,41};
  108456. /* Test read/write together */
  108457. /* Later we test against pregenerated bitstreams */
  108458. oggpack_writeinit(&o);
  108459. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108460. cliptest(testbuffer1,test1size,0,one,onesize);
  108461. fprintf(stderr,"ok.");
  108462. fprintf(stderr,"\nNull bit call (LSb): ");
  108463. cliptest(testbuffer3,test3size,0,two,twosize);
  108464. fprintf(stderr,"ok.");
  108465. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108466. cliptest(testbuffer2,test2size,0,three,threesize);
  108467. fprintf(stderr,"ok.");
  108468. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108469. oggpack_reset(&o);
  108470. for(i=0;i<test2size;i++)
  108471. oggpack_write(&o,large[i],32);
  108472. buffer=oggpack_get_buffer(&o);
  108473. bytes=oggpack_bytes(&o);
  108474. oggpack_readinit(&r,buffer,bytes);
  108475. for(i=0;i<test2size;i++){
  108476. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108477. if(oggpack_look(&r,32)!=large[i]){
  108478. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108479. oggpack_look(&r,32),large[i]);
  108480. report("read incorrect value!\n");
  108481. }
  108482. oggpack_adv(&r,32);
  108483. }
  108484. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108485. fprintf(stderr,"ok.");
  108486. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108487. cliptest(testbuffer1,test1size,7,four,foursize);
  108488. fprintf(stderr,"ok.");
  108489. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108490. cliptest(testbuffer2,test2size,17,five,fivesize);
  108491. fprintf(stderr,"ok.");
  108492. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108493. cliptest(testbuffer3,test3size,1,six,sixsize);
  108494. fprintf(stderr,"ok.");
  108495. fprintf(stderr,"\nTesting read past end (LSb): ");
  108496. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108497. for(i=0;i<64;i++){
  108498. if(oggpack_read(&r,1)!=0){
  108499. fprintf(stderr,"failed; got -1 prematurely.\n");
  108500. exit(1);
  108501. }
  108502. }
  108503. if(oggpack_look(&r,1)!=-1 ||
  108504. oggpack_read(&r,1)!=-1){
  108505. fprintf(stderr,"failed; read past end without -1.\n");
  108506. exit(1);
  108507. }
  108508. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108509. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108510. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108511. exit(1);
  108512. }
  108513. if(oggpack_look(&r,18)!=0 ||
  108514. oggpack_look(&r,18)!=0){
  108515. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108516. exit(1);
  108517. }
  108518. if(oggpack_look(&r,19)!=-1 ||
  108519. oggpack_look(&r,19)!=-1){
  108520. fprintf(stderr,"failed; read past end without -1.\n");
  108521. exit(1);
  108522. }
  108523. if(oggpack_look(&r,32)!=-1 ||
  108524. oggpack_look(&r,32)!=-1){
  108525. fprintf(stderr,"failed; read past end without -1.\n");
  108526. exit(1);
  108527. }
  108528. oggpack_writeclear(&o);
  108529. fprintf(stderr,"ok.\n");
  108530. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108531. /* Test read/write together */
  108532. /* Later we test against pregenerated bitstreams */
  108533. oggpackB_writeinit(&o);
  108534. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108535. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108536. fprintf(stderr,"ok.");
  108537. fprintf(stderr,"\nNull bit call (MSb): ");
  108538. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108539. fprintf(stderr,"ok.");
  108540. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108541. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108542. fprintf(stderr,"ok.");
  108543. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108544. oggpackB_reset(&o);
  108545. for(i=0;i<test2size;i++)
  108546. oggpackB_write(&o,large[i],32);
  108547. buffer=oggpackB_get_buffer(&o);
  108548. bytes=oggpackB_bytes(&o);
  108549. oggpackB_readinit(&r,buffer,bytes);
  108550. for(i=0;i<test2size;i++){
  108551. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108552. if(oggpackB_look(&r,32)!=large[i]){
  108553. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108554. oggpackB_look(&r,32),large[i]);
  108555. report("read incorrect value!\n");
  108556. }
  108557. oggpackB_adv(&r,32);
  108558. }
  108559. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108560. fprintf(stderr,"ok.");
  108561. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108562. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108563. fprintf(stderr,"ok.");
  108564. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108565. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108566. fprintf(stderr,"ok.");
  108567. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108568. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108569. fprintf(stderr,"ok.");
  108570. fprintf(stderr,"\nTesting read past end (MSb): ");
  108571. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108572. for(i=0;i<64;i++){
  108573. if(oggpackB_read(&r,1)!=0){
  108574. fprintf(stderr,"failed; got -1 prematurely.\n");
  108575. exit(1);
  108576. }
  108577. }
  108578. if(oggpackB_look(&r,1)!=-1 ||
  108579. oggpackB_read(&r,1)!=-1){
  108580. fprintf(stderr,"failed; read past end without -1.\n");
  108581. exit(1);
  108582. }
  108583. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108584. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108585. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108586. exit(1);
  108587. }
  108588. if(oggpackB_look(&r,18)!=0 ||
  108589. oggpackB_look(&r,18)!=0){
  108590. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108591. exit(1);
  108592. }
  108593. if(oggpackB_look(&r,19)!=-1 ||
  108594. oggpackB_look(&r,19)!=-1){
  108595. fprintf(stderr,"failed; read past end without -1.\n");
  108596. exit(1);
  108597. }
  108598. if(oggpackB_look(&r,32)!=-1 ||
  108599. oggpackB_look(&r,32)!=-1){
  108600. fprintf(stderr,"failed; read past end without -1.\n");
  108601. exit(1);
  108602. }
  108603. oggpackB_writeclear(&o);
  108604. fprintf(stderr,"ok.\n\n");
  108605. return(0);
  108606. }
  108607. #endif /* _V_SELFTEST */
  108608. #undef BUFFER_INCREMENT
  108609. #endif
  108610. /*** End of inlined file: bitwise.c ***/
  108611. /*** Start of inlined file: framing.c ***/
  108612. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108613. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108614. // tasks..
  108615. #if JUCE_MSVC
  108616. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108617. #endif
  108618. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108619. #if JUCE_USE_OGGVORBIS
  108620. #include <stdlib.h>
  108621. #include <string.h>
  108622. /* A complete description of Ogg framing exists in docs/framing.html */
  108623. int ogg_page_version(ogg_page *og){
  108624. return((int)(og->header[4]));
  108625. }
  108626. int ogg_page_continued(ogg_page *og){
  108627. return((int)(og->header[5]&0x01));
  108628. }
  108629. int ogg_page_bos(ogg_page *og){
  108630. return((int)(og->header[5]&0x02));
  108631. }
  108632. int ogg_page_eos(ogg_page *og){
  108633. return((int)(og->header[5]&0x04));
  108634. }
  108635. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108636. unsigned char *page=og->header;
  108637. ogg_int64_t granulepos=page[13]&(0xff);
  108638. granulepos= (granulepos<<8)|(page[12]&0xff);
  108639. granulepos= (granulepos<<8)|(page[11]&0xff);
  108640. granulepos= (granulepos<<8)|(page[10]&0xff);
  108641. granulepos= (granulepos<<8)|(page[9]&0xff);
  108642. granulepos= (granulepos<<8)|(page[8]&0xff);
  108643. granulepos= (granulepos<<8)|(page[7]&0xff);
  108644. granulepos= (granulepos<<8)|(page[6]&0xff);
  108645. return(granulepos);
  108646. }
  108647. int ogg_page_serialno(ogg_page *og){
  108648. return(og->header[14] |
  108649. (og->header[15]<<8) |
  108650. (og->header[16]<<16) |
  108651. (og->header[17]<<24));
  108652. }
  108653. long ogg_page_pageno(ogg_page *og){
  108654. return(og->header[18] |
  108655. (og->header[19]<<8) |
  108656. (og->header[20]<<16) |
  108657. (og->header[21]<<24));
  108658. }
  108659. /* returns the number of packets that are completed on this page (if
  108660. the leading packet is begun on a previous page, but ends on this
  108661. page, it's counted */
  108662. /* NOTE:
  108663. If a page consists of a packet begun on a previous page, and a new
  108664. packet begun (but not completed) on this page, the return will be:
  108665. ogg_page_packets(page) ==1,
  108666. ogg_page_continued(page) !=0
  108667. If a page happens to be a single packet that was begun on a
  108668. previous page, and spans to the next page (in the case of a three or
  108669. more page packet), the return will be:
  108670. ogg_page_packets(page) ==0,
  108671. ogg_page_continued(page) !=0
  108672. */
  108673. int ogg_page_packets(ogg_page *og){
  108674. int i,n=og->header[26],count=0;
  108675. for(i=0;i<n;i++)
  108676. if(og->header[27+i]<255)count++;
  108677. return(count);
  108678. }
  108679. #if 0
  108680. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108681. use the static init below) */
  108682. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108683. int i;
  108684. unsigned long r;
  108685. r = index << 24;
  108686. for (i=0; i<8; i++)
  108687. if (r & 0x80000000UL)
  108688. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108689. polynomial, although we use an
  108690. unreflected alg and an init/final
  108691. of 0, not 0xffffffff */
  108692. else
  108693. r<<=1;
  108694. return (r & 0xffffffffUL);
  108695. }
  108696. #endif
  108697. static const ogg_uint32_t crc_lookup[256]={
  108698. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108699. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108700. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108701. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108702. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108703. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108704. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108705. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108706. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108707. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108708. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108709. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108710. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108711. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108712. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108713. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108714. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108715. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108716. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108717. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108718. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108719. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108720. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108721. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108722. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108723. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108724. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108725. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108726. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108727. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108728. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108729. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108730. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108731. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108732. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108733. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108734. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108735. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108736. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108737. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108738. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108739. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108740. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108741. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108742. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108743. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108744. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108745. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108746. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108747. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108748. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108749. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108750. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108751. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108752. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108753. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108754. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108755. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108756. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108757. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108758. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108759. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108760. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108761. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108762. /* init the encode/decode logical stream state */
  108763. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108764. if(os){
  108765. memset(os,0,sizeof(*os));
  108766. os->body_storage=16*1024;
  108767. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108768. os->lacing_storage=1024;
  108769. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108770. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108771. os->serialno=serialno;
  108772. return(0);
  108773. }
  108774. return(-1);
  108775. }
  108776. /* _clear does not free os, only the non-flat storage within */
  108777. int ogg_stream_clear(ogg_stream_state *os){
  108778. if(os){
  108779. if(os->body_data)_ogg_free(os->body_data);
  108780. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108781. if(os->granule_vals)_ogg_free(os->granule_vals);
  108782. memset(os,0,sizeof(*os));
  108783. }
  108784. return(0);
  108785. }
  108786. int ogg_stream_destroy(ogg_stream_state *os){
  108787. if(os){
  108788. ogg_stream_clear(os);
  108789. _ogg_free(os);
  108790. }
  108791. return(0);
  108792. }
  108793. /* Helpers for ogg_stream_encode; this keeps the structure and
  108794. what's happening fairly clear */
  108795. static void _os_body_expand(ogg_stream_state *os,int needed){
  108796. if(os->body_storage<=os->body_fill+needed){
  108797. os->body_storage+=(needed+1024);
  108798. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108799. }
  108800. }
  108801. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108802. if(os->lacing_storage<=os->lacing_fill+needed){
  108803. os->lacing_storage+=(needed+32);
  108804. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108805. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108806. }
  108807. }
  108808. /* checksum the page */
  108809. /* Direct table CRC; note that this will be faster in the future if we
  108810. perform the checksum silmultaneously with other copies */
  108811. void ogg_page_checksum_set(ogg_page *og){
  108812. if(og){
  108813. ogg_uint32_t crc_reg=0;
  108814. int i;
  108815. /* safety; needed for API behavior, but not framing code */
  108816. og->header[22]=0;
  108817. og->header[23]=0;
  108818. og->header[24]=0;
  108819. og->header[25]=0;
  108820. for(i=0;i<og->header_len;i++)
  108821. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108822. for(i=0;i<og->body_len;i++)
  108823. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108824. og->header[22]=(unsigned char)(crc_reg&0xff);
  108825. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108826. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108827. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108828. }
  108829. }
  108830. /* submit data to the internal buffer of the framing engine */
  108831. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108832. int lacing_vals=op->bytes/255+1,i;
  108833. if(os->body_returned){
  108834. /* advance packet data according to the body_returned pointer. We
  108835. had to keep it around to return a pointer into the buffer last
  108836. call */
  108837. os->body_fill-=os->body_returned;
  108838. if(os->body_fill)
  108839. memmove(os->body_data,os->body_data+os->body_returned,
  108840. os->body_fill);
  108841. os->body_returned=0;
  108842. }
  108843. /* make sure we have the buffer storage */
  108844. _os_body_expand(os,op->bytes);
  108845. _os_lacing_expand(os,lacing_vals);
  108846. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108847. the liability of overly clean abstraction for the time being. It
  108848. will actually be fairly easy to eliminate the extra copy in the
  108849. future */
  108850. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108851. os->body_fill+=op->bytes;
  108852. /* Store lacing vals for this packet */
  108853. for(i=0;i<lacing_vals-1;i++){
  108854. os->lacing_vals[os->lacing_fill+i]=255;
  108855. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108856. }
  108857. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108858. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108859. /* flag the first segment as the beginning of the packet */
  108860. os->lacing_vals[os->lacing_fill]|= 0x100;
  108861. os->lacing_fill+=lacing_vals;
  108862. /* for the sake of completeness */
  108863. os->packetno++;
  108864. if(op->e_o_s)os->e_o_s=1;
  108865. return(0);
  108866. }
  108867. /* This will flush remaining packets into a page (returning nonzero),
  108868. even if there is not enough data to trigger a flush normally
  108869. (undersized page). If there are no packets or partial packets to
  108870. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108871. try to flush a normal sized page like ogg_stream_pageout; a call to
  108872. ogg_stream_flush does not guarantee that all packets have flushed.
  108873. Only a return value of 0 from ogg_stream_flush indicates all packet
  108874. data is flushed into pages.
  108875. since ogg_stream_flush will flush the last page in a stream even if
  108876. it's undersized, you almost certainly want to use ogg_stream_pageout
  108877. (and *not* ogg_stream_flush) unless you specifically need to flush
  108878. an page regardless of size in the middle of a stream. */
  108879. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108880. int i;
  108881. int vals=0;
  108882. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108883. int bytes=0;
  108884. long acc=0;
  108885. ogg_int64_t granule_pos=-1;
  108886. if(maxvals==0)return(0);
  108887. /* construct a page */
  108888. /* decide how many segments to include */
  108889. /* If this is the initial header case, the first page must only include
  108890. the initial header packet */
  108891. if(os->b_o_s==0){ /* 'initial header page' case */
  108892. granule_pos=0;
  108893. for(vals=0;vals<maxvals;vals++){
  108894. if((os->lacing_vals[vals]&0x0ff)<255){
  108895. vals++;
  108896. break;
  108897. }
  108898. }
  108899. }else{
  108900. for(vals=0;vals<maxvals;vals++){
  108901. if(acc>4096)break;
  108902. acc+=os->lacing_vals[vals]&0x0ff;
  108903. if((os->lacing_vals[vals]&0xff)<255)
  108904. granule_pos=os->granule_vals[vals];
  108905. }
  108906. }
  108907. /* construct the header in temp storage */
  108908. memcpy(os->header,"OggS",4);
  108909. /* stream structure version */
  108910. os->header[4]=0x00;
  108911. /* continued packet flag? */
  108912. os->header[5]=0x00;
  108913. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108914. /* first page flag? */
  108915. if(os->b_o_s==0)os->header[5]|=0x02;
  108916. /* last page flag? */
  108917. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108918. os->b_o_s=1;
  108919. /* 64 bits of PCM position */
  108920. for(i=6;i<14;i++){
  108921. os->header[i]=(unsigned char)(granule_pos&0xff);
  108922. granule_pos>>=8;
  108923. }
  108924. /* 32 bits of stream serial number */
  108925. {
  108926. long serialno=os->serialno;
  108927. for(i=14;i<18;i++){
  108928. os->header[i]=(unsigned char)(serialno&0xff);
  108929. serialno>>=8;
  108930. }
  108931. }
  108932. /* 32 bits of page counter (we have both counter and page header
  108933. because this val can roll over) */
  108934. if(os->pageno==-1)os->pageno=0; /* because someone called
  108935. stream_reset; this would be a
  108936. strange thing to do in an
  108937. encode stream, but it has
  108938. plausible uses */
  108939. {
  108940. long pageno=os->pageno++;
  108941. for(i=18;i<22;i++){
  108942. os->header[i]=(unsigned char)(pageno&0xff);
  108943. pageno>>=8;
  108944. }
  108945. }
  108946. /* zero for computation; filled in later */
  108947. os->header[22]=0;
  108948. os->header[23]=0;
  108949. os->header[24]=0;
  108950. os->header[25]=0;
  108951. /* segment table */
  108952. os->header[26]=(unsigned char)(vals&0xff);
  108953. for(i=0;i<vals;i++)
  108954. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108955. /* set pointers in the ogg_page struct */
  108956. og->header=os->header;
  108957. og->header_len=os->header_fill=vals+27;
  108958. og->body=os->body_data+os->body_returned;
  108959. og->body_len=bytes;
  108960. /* advance the lacing data and set the body_returned pointer */
  108961. os->lacing_fill-=vals;
  108962. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108963. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108964. os->body_returned+=bytes;
  108965. /* calculate the checksum */
  108966. ogg_page_checksum_set(og);
  108967. /* done */
  108968. return(1);
  108969. }
  108970. /* This constructs pages from buffered packet segments. The pointers
  108971. returned are to static buffers; do not free. The returned buffers are
  108972. good only until the next call (using the same ogg_stream_state) */
  108973. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108974. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108975. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108976. os->lacing_fill>=255 || /* 'segment table full' case */
  108977. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108978. return(ogg_stream_flush(os,og));
  108979. }
  108980. /* not enough data to construct a page and not end of stream */
  108981. return(0);
  108982. }
  108983. int ogg_stream_eos(ogg_stream_state *os){
  108984. return os->e_o_s;
  108985. }
  108986. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108987. /* This has two layers to place more of the multi-serialno and paging
  108988. control in the application's hands. First, we expose a data buffer
  108989. using ogg_sync_buffer(). The app either copies into the
  108990. buffer, or passes it directly to read(), etc. We then call
  108991. ogg_sync_wrote() to tell how many bytes we just added.
  108992. Pages are returned (pointers into the buffer in ogg_sync_state)
  108993. by ogg_sync_pageout(). The page is then submitted to
  108994. ogg_stream_pagein() along with the appropriate
  108995. ogg_stream_state* (ie, matching serialno). We then get raw
  108996. packets out calling ogg_stream_packetout() with a
  108997. ogg_stream_state. */
  108998. /* initialize the struct to a known state */
  108999. int ogg_sync_init(ogg_sync_state *oy){
  109000. if(oy){
  109001. memset(oy,0,sizeof(*oy));
  109002. }
  109003. return(0);
  109004. }
  109005. /* clear non-flat storage within */
  109006. int ogg_sync_clear(ogg_sync_state *oy){
  109007. if(oy){
  109008. if(oy->data)_ogg_free(oy->data);
  109009. ogg_sync_init(oy);
  109010. }
  109011. return(0);
  109012. }
  109013. int ogg_sync_destroy(ogg_sync_state *oy){
  109014. if(oy){
  109015. ogg_sync_clear(oy);
  109016. _ogg_free(oy);
  109017. }
  109018. return(0);
  109019. }
  109020. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  109021. /* first, clear out any space that has been previously returned */
  109022. if(oy->returned){
  109023. oy->fill-=oy->returned;
  109024. if(oy->fill>0)
  109025. memmove(oy->data,oy->data+oy->returned,oy->fill);
  109026. oy->returned=0;
  109027. }
  109028. if(size>oy->storage-oy->fill){
  109029. /* We need to extend the internal buffer */
  109030. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  109031. if(oy->data)
  109032. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  109033. else
  109034. oy->data=(unsigned char*) _ogg_malloc(newsize);
  109035. oy->storage=newsize;
  109036. }
  109037. /* expose a segment at least as large as requested at the fill mark */
  109038. return((char *)oy->data+oy->fill);
  109039. }
  109040. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  109041. if(oy->fill+bytes>oy->storage)return(-1);
  109042. oy->fill+=bytes;
  109043. return(0);
  109044. }
  109045. /* sync the stream. This is meant to be useful for finding page
  109046. boundaries.
  109047. return values for this:
  109048. -n) skipped n bytes
  109049. 0) page not ready; more data (no bytes skipped)
  109050. n) page synced at current location; page length n bytes
  109051. */
  109052. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  109053. unsigned char *page=oy->data+oy->returned;
  109054. unsigned char *next;
  109055. long bytes=oy->fill-oy->returned;
  109056. if(oy->headerbytes==0){
  109057. int headerbytes,i;
  109058. if(bytes<27)return(0); /* not enough for a header */
  109059. /* verify capture pattern */
  109060. if(memcmp(page,"OggS",4))goto sync_fail;
  109061. headerbytes=page[26]+27;
  109062. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  109063. /* count up body length in the segment table */
  109064. for(i=0;i<page[26];i++)
  109065. oy->bodybytes+=page[27+i];
  109066. oy->headerbytes=headerbytes;
  109067. }
  109068. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  109069. /* The whole test page is buffered. Verify the checksum */
  109070. {
  109071. /* Grab the checksum bytes, set the header field to zero */
  109072. char chksum[4];
  109073. ogg_page log;
  109074. memcpy(chksum,page+22,4);
  109075. memset(page+22,0,4);
  109076. /* set up a temp page struct and recompute the checksum */
  109077. log.header=page;
  109078. log.header_len=oy->headerbytes;
  109079. log.body=page+oy->headerbytes;
  109080. log.body_len=oy->bodybytes;
  109081. ogg_page_checksum_set(&log);
  109082. /* Compare */
  109083. if(memcmp(chksum,page+22,4)){
  109084. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  109085. at all) */
  109086. /* replace the computed checksum with the one actually read in */
  109087. memcpy(page+22,chksum,4);
  109088. /* Bad checksum. Lose sync */
  109089. goto sync_fail;
  109090. }
  109091. }
  109092. /* yes, have a whole page all ready to go */
  109093. {
  109094. unsigned char *page=oy->data+oy->returned;
  109095. long bytes;
  109096. if(og){
  109097. og->header=page;
  109098. og->header_len=oy->headerbytes;
  109099. og->body=page+oy->headerbytes;
  109100. og->body_len=oy->bodybytes;
  109101. }
  109102. oy->unsynced=0;
  109103. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  109104. oy->headerbytes=0;
  109105. oy->bodybytes=0;
  109106. return(bytes);
  109107. }
  109108. sync_fail:
  109109. oy->headerbytes=0;
  109110. oy->bodybytes=0;
  109111. /* search for possible capture */
  109112. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  109113. if(!next)
  109114. next=oy->data+oy->fill;
  109115. oy->returned=next-oy->data;
  109116. return(-(next-page));
  109117. }
  109118. /* sync the stream and get a page. Keep trying until we find a page.
  109119. Supress 'sync errors' after reporting the first.
  109120. return values:
  109121. -1) recapture (hole in data)
  109122. 0) need more data
  109123. 1) page returned
  109124. Returns pointers into buffered data; invalidated by next call to
  109125. _stream, _clear, _init, or _buffer */
  109126. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  109127. /* all we need to do is verify a page at the head of the stream
  109128. buffer. If it doesn't verify, we look for the next potential
  109129. frame */
  109130. for(;;){
  109131. long ret=ogg_sync_pageseek(oy,og);
  109132. if(ret>0){
  109133. /* have a page */
  109134. return(1);
  109135. }
  109136. if(ret==0){
  109137. /* need more data */
  109138. return(0);
  109139. }
  109140. /* head did not start a synced page... skipped some bytes */
  109141. if(!oy->unsynced){
  109142. oy->unsynced=1;
  109143. return(-1);
  109144. }
  109145. /* loop. keep looking */
  109146. }
  109147. }
  109148. /* add the incoming page to the stream state; we decompose the page
  109149. into packet segments here as well. */
  109150. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  109151. unsigned char *header=og->header;
  109152. unsigned char *body=og->body;
  109153. long bodysize=og->body_len;
  109154. int segptr=0;
  109155. int version=ogg_page_version(og);
  109156. int continued=ogg_page_continued(og);
  109157. int bos=ogg_page_bos(og);
  109158. int eos=ogg_page_eos(og);
  109159. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109160. int serialno=ogg_page_serialno(og);
  109161. long pageno=ogg_page_pageno(og);
  109162. int segments=header[26];
  109163. /* clean up 'returned data' */
  109164. {
  109165. long lr=os->lacing_returned;
  109166. long br=os->body_returned;
  109167. /* body data */
  109168. if(br){
  109169. os->body_fill-=br;
  109170. if(os->body_fill)
  109171. memmove(os->body_data,os->body_data+br,os->body_fill);
  109172. os->body_returned=0;
  109173. }
  109174. if(lr){
  109175. /* segment table */
  109176. if(os->lacing_fill-lr){
  109177. memmove(os->lacing_vals,os->lacing_vals+lr,
  109178. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109179. memmove(os->granule_vals,os->granule_vals+lr,
  109180. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109181. }
  109182. os->lacing_fill-=lr;
  109183. os->lacing_packet-=lr;
  109184. os->lacing_returned=0;
  109185. }
  109186. }
  109187. /* check the serial number */
  109188. if(serialno!=os->serialno)return(-1);
  109189. if(version>0)return(-1);
  109190. _os_lacing_expand(os,segments+1);
  109191. /* are we in sequence? */
  109192. if(pageno!=os->pageno){
  109193. int i;
  109194. /* unroll previous partial packet (if any) */
  109195. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109196. os->body_fill-=os->lacing_vals[i]&0xff;
  109197. os->lacing_fill=os->lacing_packet;
  109198. /* make a note of dropped data in segment table */
  109199. if(os->pageno!=-1){
  109200. os->lacing_vals[os->lacing_fill++]=0x400;
  109201. os->lacing_packet++;
  109202. }
  109203. }
  109204. /* are we a 'continued packet' page? If so, we may need to skip
  109205. some segments */
  109206. if(continued){
  109207. if(os->lacing_fill<1 ||
  109208. os->lacing_vals[os->lacing_fill-1]==0x400){
  109209. bos=0;
  109210. for(;segptr<segments;segptr++){
  109211. int val=header[27+segptr];
  109212. body+=val;
  109213. bodysize-=val;
  109214. if(val<255){
  109215. segptr++;
  109216. break;
  109217. }
  109218. }
  109219. }
  109220. }
  109221. if(bodysize){
  109222. _os_body_expand(os,bodysize);
  109223. memcpy(os->body_data+os->body_fill,body,bodysize);
  109224. os->body_fill+=bodysize;
  109225. }
  109226. {
  109227. int saved=-1;
  109228. while(segptr<segments){
  109229. int val=header[27+segptr];
  109230. os->lacing_vals[os->lacing_fill]=val;
  109231. os->granule_vals[os->lacing_fill]=-1;
  109232. if(bos){
  109233. os->lacing_vals[os->lacing_fill]|=0x100;
  109234. bos=0;
  109235. }
  109236. if(val<255)saved=os->lacing_fill;
  109237. os->lacing_fill++;
  109238. segptr++;
  109239. if(val<255)os->lacing_packet=os->lacing_fill;
  109240. }
  109241. /* set the granulepos on the last granuleval of the last full packet */
  109242. if(saved!=-1){
  109243. os->granule_vals[saved]=granulepos;
  109244. }
  109245. }
  109246. if(eos){
  109247. os->e_o_s=1;
  109248. if(os->lacing_fill>0)
  109249. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109250. }
  109251. os->pageno=pageno+1;
  109252. return(0);
  109253. }
  109254. /* clear things to an initial state. Good to call, eg, before seeking */
  109255. int ogg_sync_reset(ogg_sync_state *oy){
  109256. oy->fill=0;
  109257. oy->returned=0;
  109258. oy->unsynced=0;
  109259. oy->headerbytes=0;
  109260. oy->bodybytes=0;
  109261. return(0);
  109262. }
  109263. int ogg_stream_reset(ogg_stream_state *os){
  109264. os->body_fill=0;
  109265. os->body_returned=0;
  109266. os->lacing_fill=0;
  109267. os->lacing_packet=0;
  109268. os->lacing_returned=0;
  109269. os->header_fill=0;
  109270. os->e_o_s=0;
  109271. os->b_o_s=0;
  109272. os->pageno=-1;
  109273. os->packetno=0;
  109274. os->granulepos=0;
  109275. return(0);
  109276. }
  109277. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109278. ogg_stream_reset(os);
  109279. os->serialno=serialno;
  109280. return(0);
  109281. }
  109282. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109283. /* The last part of decode. We have the stream broken into packet
  109284. segments. Now we need to group them into packets (or return the
  109285. out of sync markers) */
  109286. int ptr=os->lacing_returned;
  109287. if(os->lacing_packet<=ptr)return(0);
  109288. if(os->lacing_vals[ptr]&0x400){
  109289. /* we need to tell the codec there's a gap; it might need to
  109290. handle previous packet dependencies. */
  109291. os->lacing_returned++;
  109292. os->packetno++;
  109293. return(-1);
  109294. }
  109295. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109296. to ask if there's a whole packet
  109297. waiting */
  109298. /* Gather the whole packet. We'll have no holes or a partial packet */
  109299. {
  109300. int size=os->lacing_vals[ptr]&0xff;
  109301. int bytes=size;
  109302. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109303. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109304. while(size==255){
  109305. int val=os->lacing_vals[++ptr];
  109306. size=val&0xff;
  109307. if(val&0x200)eos=0x200;
  109308. bytes+=size;
  109309. }
  109310. if(op){
  109311. op->e_o_s=eos;
  109312. op->b_o_s=bos;
  109313. op->packet=os->body_data+os->body_returned;
  109314. op->packetno=os->packetno;
  109315. op->granulepos=os->granule_vals[ptr];
  109316. op->bytes=bytes;
  109317. }
  109318. if(adv){
  109319. os->body_returned+=bytes;
  109320. os->lacing_returned=ptr+1;
  109321. os->packetno++;
  109322. }
  109323. }
  109324. return(1);
  109325. }
  109326. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109327. return _packetout(os,op,1);
  109328. }
  109329. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109330. return _packetout(os,op,0);
  109331. }
  109332. void ogg_packet_clear(ogg_packet *op) {
  109333. _ogg_free(op->packet);
  109334. memset(op, 0, sizeof(*op));
  109335. }
  109336. #ifdef _V_SELFTEST
  109337. #include <stdio.h>
  109338. ogg_stream_state os_en, os_de;
  109339. ogg_sync_state oy;
  109340. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109341. long j;
  109342. static int sequence=0;
  109343. static int lastno=0;
  109344. if(op->bytes!=len){
  109345. fprintf(stderr,"incorrect packet length!\n");
  109346. exit(1);
  109347. }
  109348. if(op->granulepos!=pos){
  109349. fprintf(stderr,"incorrect packet position!\n");
  109350. exit(1);
  109351. }
  109352. /* packet number just follows sequence/gap; adjust the input number
  109353. for that */
  109354. if(no==0){
  109355. sequence=0;
  109356. }else{
  109357. sequence++;
  109358. if(no>lastno+1)
  109359. sequence++;
  109360. }
  109361. lastno=no;
  109362. if(op->packetno!=sequence){
  109363. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109364. (long)(op->packetno),sequence);
  109365. exit(1);
  109366. }
  109367. /* Test data */
  109368. for(j=0;j<op->bytes;j++)
  109369. if(op->packet[j]!=((j+no)&0xff)){
  109370. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109371. j,op->packet[j],(j+no)&0xff);
  109372. exit(1);
  109373. }
  109374. }
  109375. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109376. long j;
  109377. /* Test data */
  109378. for(j=0;j<og->body_len;j++)
  109379. if(og->body[j]!=data[j]){
  109380. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109381. j,data[j],og->body[j]);
  109382. exit(1);
  109383. }
  109384. /* Test header */
  109385. for(j=0;j<og->header_len;j++){
  109386. if(og->header[j]!=header[j]){
  109387. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109388. for(j=0;j<header[26]+27;j++)
  109389. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109390. fprintf(stderr,"\n");
  109391. exit(1);
  109392. }
  109393. }
  109394. if(og->header_len!=header[26]+27){
  109395. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109396. og->header_len,header[26]+27);
  109397. exit(1);
  109398. }
  109399. }
  109400. void print_header(ogg_page *og){
  109401. int j;
  109402. fprintf(stderr,"\nHEADER:\n");
  109403. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109404. og->header[0],og->header[1],og->header[2],og->header[3],
  109405. (int)og->header[4],(int)og->header[5]);
  109406. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109407. (og->header[9]<<24)|(og->header[8]<<16)|
  109408. (og->header[7]<<8)|og->header[6],
  109409. (og->header[17]<<24)|(og->header[16]<<16)|
  109410. (og->header[15]<<8)|og->header[14],
  109411. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109412. (og->header[19]<<8)|og->header[18]);
  109413. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109414. (int)og->header[22],(int)og->header[23],
  109415. (int)og->header[24],(int)og->header[25],
  109416. (int)og->header[26]);
  109417. for(j=27;j<og->header_len;j++)
  109418. fprintf(stderr,"%d ",(int)og->header[j]);
  109419. fprintf(stderr,")\n\n");
  109420. }
  109421. void copy_page(ogg_page *og){
  109422. unsigned char *temp=_ogg_malloc(og->header_len);
  109423. memcpy(temp,og->header,og->header_len);
  109424. og->header=temp;
  109425. temp=_ogg_malloc(og->body_len);
  109426. memcpy(temp,og->body,og->body_len);
  109427. og->body=temp;
  109428. }
  109429. void free_page(ogg_page *og){
  109430. _ogg_free (og->header);
  109431. _ogg_free (og->body);
  109432. }
  109433. void error(void){
  109434. fprintf(stderr,"error!\n");
  109435. exit(1);
  109436. }
  109437. /* 17 only */
  109438. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109439. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109440. 0x01,0x02,0x03,0x04,0,0,0,0,
  109441. 0x15,0xed,0xec,0x91,
  109442. 1,
  109443. 17};
  109444. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109445. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109446. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109447. 0x01,0x02,0x03,0x04,0,0,0,0,
  109448. 0x59,0x10,0x6c,0x2c,
  109449. 1,
  109450. 17};
  109451. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109452. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109453. 0x01,0x02,0x03,0x04,1,0,0,0,
  109454. 0x89,0x33,0x85,0xce,
  109455. 13,
  109456. 254,255,0,255,1,255,245,255,255,0,
  109457. 255,255,90};
  109458. /* nil packets; beginning,middle,end */
  109459. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109460. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109461. 0x01,0x02,0x03,0x04,0,0,0,0,
  109462. 0xff,0x7b,0x23,0x17,
  109463. 1,
  109464. 0};
  109465. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109466. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109467. 0x01,0x02,0x03,0x04,1,0,0,0,
  109468. 0x5c,0x3f,0x66,0xcb,
  109469. 17,
  109470. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109471. 255,255,90,0};
  109472. /* large initial packet */
  109473. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109474. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109475. 0x01,0x02,0x03,0x04,0,0,0,0,
  109476. 0x01,0x27,0x31,0xaa,
  109477. 18,
  109478. 255,255,255,255,255,255,255,255,
  109479. 255,255,255,255,255,255,255,255,255,10};
  109480. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109481. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109482. 0x01,0x02,0x03,0x04,1,0,0,0,
  109483. 0x7f,0x4e,0x8a,0xd2,
  109484. 4,
  109485. 255,4,255,0};
  109486. /* continuing packet test */
  109487. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109488. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109489. 0x01,0x02,0x03,0x04,0,0,0,0,
  109490. 0xff,0x7b,0x23,0x17,
  109491. 1,
  109492. 0};
  109493. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109494. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109495. 0x01,0x02,0x03,0x04,1,0,0,0,
  109496. 0x54,0x05,0x51,0xc8,
  109497. 17,
  109498. 255,255,255,255,255,255,255,255,
  109499. 255,255,255,255,255,255,255,255,255};
  109500. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109501. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109502. 0x01,0x02,0x03,0x04,2,0,0,0,
  109503. 0xc8,0xc3,0xcb,0xed,
  109504. 5,
  109505. 10,255,4,255,0};
  109506. /* page with the 255 segment limit */
  109507. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109508. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109509. 0x01,0x02,0x03,0x04,0,0,0,0,
  109510. 0xff,0x7b,0x23,0x17,
  109511. 1,
  109512. 0};
  109513. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109514. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109515. 0x01,0x02,0x03,0x04,1,0,0,0,
  109516. 0xed,0x2a,0x2e,0xa7,
  109517. 255,
  109518. 10,10,10,10,10,10,10,10,
  109519. 10,10,10,10,10,10,10,10,
  109520. 10,10,10,10,10,10,10,10,
  109521. 10,10,10,10,10,10,10,10,
  109522. 10,10,10,10,10,10,10,10,
  109523. 10,10,10,10,10,10,10,10,
  109524. 10,10,10,10,10,10,10,10,
  109525. 10,10,10,10,10,10,10,10,
  109526. 10,10,10,10,10,10,10,10,
  109527. 10,10,10,10,10,10,10,10,
  109528. 10,10,10,10,10,10,10,10,
  109529. 10,10,10,10,10,10,10,10,
  109530. 10,10,10,10,10,10,10,10,
  109531. 10,10,10,10,10,10,10,10,
  109532. 10,10,10,10,10,10,10,10,
  109533. 10,10,10,10,10,10,10,10,
  109534. 10,10,10,10,10,10,10,10,
  109535. 10,10,10,10,10,10,10,10,
  109536. 10,10,10,10,10,10,10,10,
  109537. 10,10,10,10,10,10,10,10,
  109538. 10,10,10,10,10,10,10,10,
  109539. 10,10,10,10,10,10,10,10,
  109540. 10,10,10,10,10,10,10,10,
  109541. 10,10,10,10,10,10,10,10,
  109542. 10,10,10,10,10,10,10,10,
  109543. 10,10,10,10,10,10,10,10,
  109544. 10,10,10,10,10,10,10,10,
  109545. 10,10,10,10,10,10,10,10,
  109546. 10,10,10,10,10,10,10,10,
  109547. 10,10,10,10,10,10,10,10,
  109548. 10,10,10,10,10,10,10,10,
  109549. 10,10,10,10,10,10,10};
  109550. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109551. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109552. 0x01,0x02,0x03,0x04,2,0,0,0,
  109553. 0x6c,0x3b,0x82,0x3d,
  109554. 1,
  109555. 50};
  109556. /* packet that overspans over an entire page */
  109557. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109558. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109559. 0x01,0x02,0x03,0x04,0,0,0,0,
  109560. 0xff,0x7b,0x23,0x17,
  109561. 1,
  109562. 0};
  109563. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109564. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109565. 0x01,0x02,0x03,0x04,1,0,0,0,
  109566. 0x3c,0xd9,0x4d,0x3f,
  109567. 17,
  109568. 100,255,255,255,255,255,255,255,255,
  109569. 255,255,255,255,255,255,255,255};
  109570. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109571. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109572. 0x01,0x02,0x03,0x04,2,0,0,0,
  109573. 0x01,0xd2,0xe5,0xe5,
  109574. 17,
  109575. 255,255,255,255,255,255,255,255,
  109576. 255,255,255,255,255,255,255,255,255};
  109577. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109578. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109579. 0x01,0x02,0x03,0x04,3,0,0,0,
  109580. 0xef,0xdd,0x88,0xde,
  109581. 7,
  109582. 255,255,75,255,4,255,0};
  109583. /* packet that overspans over an entire page */
  109584. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109585. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109586. 0x01,0x02,0x03,0x04,0,0,0,0,
  109587. 0xff,0x7b,0x23,0x17,
  109588. 1,
  109589. 0};
  109590. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109591. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109592. 0x01,0x02,0x03,0x04,1,0,0,0,
  109593. 0x3c,0xd9,0x4d,0x3f,
  109594. 17,
  109595. 100,255,255,255,255,255,255,255,255,
  109596. 255,255,255,255,255,255,255,255};
  109597. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109598. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109599. 0x01,0x02,0x03,0x04,2,0,0,0,
  109600. 0xd4,0xe0,0x60,0xe5,
  109601. 1,0};
  109602. void test_pack(const int *pl, const int **headers, int byteskip,
  109603. int pageskip, int packetskip){
  109604. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109605. long inptr=0;
  109606. long outptr=0;
  109607. long deptr=0;
  109608. long depacket=0;
  109609. long granule_pos=7,pageno=0;
  109610. int i,j,packets,pageout=pageskip;
  109611. int eosflag=0;
  109612. int bosflag=0;
  109613. int byteskipcount=0;
  109614. ogg_stream_reset(&os_en);
  109615. ogg_stream_reset(&os_de);
  109616. ogg_sync_reset(&oy);
  109617. for(packets=0;packets<packetskip;packets++)
  109618. depacket+=pl[packets];
  109619. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109620. for(i=0;i<packets;i++){
  109621. /* construct a test packet */
  109622. ogg_packet op;
  109623. int len=pl[i];
  109624. op.packet=data+inptr;
  109625. op.bytes=len;
  109626. op.e_o_s=(pl[i+1]<0?1:0);
  109627. op.granulepos=granule_pos;
  109628. granule_pos+=1024;
  109629. for(j=0;j<len;j++)data[inptr++]=i+j;
  109630. /* submit the test packet */
  109631. ogg_stream_packetin(&os_en,&op);
  109632. /* retrieve any finished pages */
  109633. {
  109634. ogg_page og;
  109635. while(ogg_stream_pageout(&os_en,&og)){
  109636. /* We have a page. Check it carefully */
  109637. fprintf(stderr,"%ld, ",pageno);
  109638. if(headers[pageno]==NULL){
  109639. fprintf(stderr,"coded too many pages!\n");
  109640. exit(1);
  109641. }
  109642. check_page(data+outptr,headers[pageno],&og);
  109643. outptr+=og.body_len;
  109644. pageno++;
  109645. if(pageskip){
  109646. bosflag=1;
  109647. pageskip--;
  109648. deptr+=og.body_len;
  109649. }
  109650. /* have a complete page; submit it to sync/decode */
  109651. {
  109652. ogg_page og_de;
  109653. ogg_packet op_de,op_de2;
  109654. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109655. char *next=buf;
  109656. byteskipcount+=og.header_len;
  109657. if(byteskipcount>byteskip){
  109658. memcpy(next,og.header,byteskipcount-byteskip);
  109659. next+=byteskipcount-byteskip;
  109660. byteskipcount=byteskip;
  109661. }
  109662. byteskipcount+=og.body_len;
  109663. if(byteskipcount>byteskip){
  109664. memcpy(next,og.body,byteskipcount-byteskip);
  109665. next+=byteskipcount-byteskip;
  109666. byteskipcount=byteskip;
  109667. }
  109668. ogg_sync_wrote(&oy,next-buf);
  109669. while(1){
  109670. int ret=ogg_sync_pageout(&oy,&og_de);
  109671. if(ret==0)break;
  109672. if(ret<0)continue;
  109673. /* got a page. Happy happy. Verify that it's good. */
  109674. fprintf(stderr,"(%ld), ",pageout);
  109675. check_page(data+deptr,headers[pageout],&og_de);
  109676. deptr+=og_de.body_len;
  109677. pageout++;
  109678. /* submit it to deconstitution */
  109679. ogg_stream_pagein(&os_de,&og_de);
  109680. /* packets out? */
  109681. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109682. ogg_stream_packetpeek(&os_de,NULL);
  109683. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109684. /* verify peek and out match */
  109685. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109686. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109687. depacket);
  109688. exit(1);
  109689. }
  109690. /* verify the packet! */
  109691. /* check data */
  109692. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109693. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109694. depacket);
  109695. exit(1);
  109696. }
  109697. /* check bos flag */
  109698. if(bosflag==0 && op_de.b_o_s==0){
  109699. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109700. exit(1);
  109701. }
  109702. if(bosflag && op_de.b_o_s){
  109703. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109704. exit(1);
  109705. }
  109706. bosflag=1;
  109707. depacket+=op_de.bytes;
  109708. /* check eos flag */
  109709. if(eosflag){
  109710. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109711. exit(1);
  109712. }
  109713. if(op_de.e_o_s)eosflag=1;
  109714. /* check granulepos flag */
  109715. if(op_de.granulepos!=-1){
  109716. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109717. }
  109718. }
  109719. }
  109720. }
  109721. }
  109722. }
  109723. }
  109724. _ogg_free(data);
  109725. if(headers[pageno]!=NULL){
  109726. fprintf(stderr,"did not write last page!\n");
  109727. exit(1);
  109728. }
  109729. if(headers[pageout]!=NULL){
  109730. fprintf(stderr,"did not decode last page!\n");
  109731. exit(1);
  109732. }
  109733. if(inptr!=outptr){
  109734. fprintf(stderr,"encoded page data incomplete!\n");
  109735. exit(1);
  109736. }
  109737. if(inptr!=deptr){
  109738. fprintf(stderr,"decoded page data incomplete!\n");
  109739. exit(1);
  109740. }
  109741. if(inptr!=depacket){
  109742. fprintf(stderr,"decoded packet data incomplete!\n");
  109743. exit(1);
  109744. }
  109745. if(!eosflag){
  109746. fprintf(stderr,"Never got a packet with EOS set!\n");
  109747. exit(1);
  109748. }
  109749. fprintf(stderr,"ok.\n");
  109750. }
  109751. int main(void){
  109752. ogg_stream_init(&os_en,0x04030201);
  109753. ogg_stream_init(&os_de,0x04030201);
  109754. ogg_sync_init(&oy);
  109755. /* Exercise each code path in the framing code. Also verify that
  109756. the checksums are working. */
  109757. {
  109758. /* 17 only */
  109759. const int packets[]={17, -1};
  109760. const int *headret[]={head1_0,NULL};
  109761. fprintf(stderr,"testing single page encoding... ");
  109762. test_pack(packets,headret,0,0,0);
  109763. }
  109764. {
  109765. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109766. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109767. const int *headret[]={head1_1,head2_1,NULL};
  109768. fprintf(stderr,"testing basic page encoding... ");
  109769. test_pack(packets,headret,0,0,0);
  109770. }
  109771. {
  109772. /* nil packets; beginning,middle,end */
  109773. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109774. const int *headret[]={head1_2,head2_2,NULL};
  109775. fprintf(stderr,"testing basic nil packets... ");
  109776. test_pack(packets,headret,0,0,0);
  109777. }
  109778. {
  109779. /* large initial packet */
  109780. const int packets[]={4345,259,255,-1};
  109781. const int *headret[]={head1_3,head2_3,NULL};
  109782. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109783. test_pack(packets,headret,0,0,0);
  109784. }
  109785. {
  109786. /* continuing packet test */
  109787. const int packets[]={0,4345,259,255,-1};
  109788. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109789. fprintf(stderr,"testing single packet page span... ");
  109790. test_pack(packets,headret,0,0,0);
  109791. }
  109792. /* page with the 255 segment limit */
  109793. {
  109794. const int packets[]={0,10,10,10,10,10,10,10,10,
  109795. 10,10,10,10,10,10,10,10,
  109796. 10,10,10,10,10,10,10,10,
  109797. 10,10,10,10,10,10,10,10,
  109798. 10,10,10,10,10,10,10,10,
  109799. 10,10,10,10,10,10,10,10,
  109800. 10,10,10,10,10,10,10,10,
  109801. 10,10,10,10,10,10,10,10,
  109802. 10,10,10,10,10,10,10,10,
  109803. 10,10,10,10,10,10,10,10,
  109804. 10,10,10,10,10,10,10,10,
  109805. 10,10,10,10,10,10,10,10,
  109806. 10,10,10,10,10,10,10,10,
  109807. 10,10,10,10,10,10,10,10,
  109808. 10,10,10,10,10,10,10,10,
  109809. 10,10,10,10,10,10,10,10,
  109810. 10,10,10,10,10,10,10,10,
  109811. 10,10,10,10,10,10,10,10,
  109812. 10,10,10,10,10,10,10,10,
  109813. 10,10,10,10,10,10,10,10,
  109814. 10,10,10,10,10,10,10,10,
  109815. 10,10,10,10,10,10,10,10,
  109816. 10,10,10,10,10,10,10,10,
  109817. 10,10,10,10,10,10,10,10,
  109818. 10,10,10,10,10,10,10,10,
  109819. 10,10,10,10,10,10,10,10,
  109820. 10,10,10,10,10,10,10,10,
  109821. 10,10,10,10,10,10,10,10,
  109822. 10,10,10,10,10,10,10,10,
  109823. 10,10,10,10,10,10,10,10,
  109824. 10,10,10,10,10,10,10,10,
  109825. 10,10,10,10,10,10,10,50,-1};
  109826. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109827. fprintf(stderr,"testing max packet segments... ");
  109828. test_pack(packets,headret,0,0,0);
  109829. }
  109830. {
  109831. /* packet that overspans over an entire page */
  109832. const int packets[]={0,100,9000,259,255,-1};
  109833. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109834. fprintf(stderr,"testing very large packets... ");
  109835. test_pack(packets,headret,0,0,0);
  109836. }
  109837. {
  109838. /* test for the libogg 1.1.1 resync in large continuation bug
  109839. found by Josh Coalson) */
  109840. const int packets[]={0,100,9000,259,255,-1};
  109841. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109842. fprintf(stderr,"testing continuation resync in very large packets... ");
  109843. test_pack(packets,headret,100,2,3);
  109844. }
  109845. {
  109846. /* term only page. why not? */
  109847. const int packets[]={0,100,4080,-1};
  109848. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109849. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109850. test_pack(packets,headret,0,0,0);
  109851. }
  109852. {
  109853. /* build a bunch of pages for testing */
  109854. unsigned char *data=_ogg_malloc(1024*1024);
  109855. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109856. int inptr=0,i,j;
  109857. ogg_page og[5];
  109858. ogg_stream_reset(&os_en);
  109859. for(i=0;pl[i]!=-1;i++){
  109860. ogg_packet op;
  109861. int len=pl[i];
  109862. op.packet=data+inptr;
  109863. op.bytes=len;
  109864. op.e_o_s=(pl[i+1]<0?1:0);
  109865. op.granulepos=(i+1)*1000;
  109866. for(j=0;j<len;j++)data[inptr++]=i+j;
  109867. ogg_stream_packetin(&os_en,&op);
  109868. }
  109869. _ogg_free(data);
  109870. /* retrieve finished pages */
  109871. for(i=0;i<5;i++){
  109872. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109873. fprintf(stderr,"Too few pages output building sync tests!\n");
  109874. exit(1);
  109875. }
  109876. copy_page(&og[i]);
  109877. }
  109878. /* Test lost pages on pagein/packetout: no rollback */
  109879. {
  109880. ogg_page temp;
  109881. ogg_packet test;
  109882. fprintf(stderr,"Testing loss of pages... ");
  109883. ogg_sync_reset(&oy);
  109884. ogg_stream_reset(&os_de);
  109885. for(i=0;i<5;i++){
  109886. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109887. og[i].header_len);
  109888. ogg_sync_wrote(&oy,og[i].header_len);
  109889. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109890. ogg_sync_wrote(&oy,og[i].body_len);
  109891. }
  109892. ogg_sync_pageout(&oy,&temp);
  109893. ogg_stream_pagein(&os_de,&temp);
  109894. ogg_sync_pageout(&oy,&temp);
  109895. ogg_stream_pagein(&os_de,&temp);
  109896. ogg_sync_pageout(&oy,&temp);
  109897. /* skip */
  109898. ogg_sync_pageout(&oy,&temp);
  109899. ogg_stream_pagein(&os_de,&temp);
  109900. /* do we get the expected results/packets? */
  109901. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109902. checkpacket(&test,0,0,0);
  109903. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109904. checkpacket(&test,100,1,-1);
  109905. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109906. checkpacket(&test,4079,2,3000);
  109907. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109908. fprintf(stderr,"Error: loss of page did not return error\n");
  109909. exit(1);
  109910. }
  109911. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109912. checkpacket(&test,76,5,-1);
  109913. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109914. checkpacket(&test,34,6,-1);
  109915. fprintf(stderr,"ok.\n");
  109916. }
  109917. /* Test lost pages on pagein/packetout: rollback with continuation */
  109918. {
  109919. ogg_page temp;
  109920. ogg_packet test;
  109921. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109922. ogg_sync_reset(&oy);
  109923. ogg_stream_reset(&os_de);
  109924. for(i=0;i<5;i++){
  109925. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109926. og[i].header_len);
  109927. ogg_sync_wrote(&oy,og[i].header_len);
  109928. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109929. ogg_sync_wrote(&oy,og[i].body_len);
  109930. }
  109931. ogg_sync_pageout(&oy,&temp);
  109932. ogg_stream_pagein(&os_de,&temp);
  109933. ogg_sync_pageout(&oy,&temp);
  109934. ogg_stream_pagein(&os_de,&temp);
  109935. ogg_sync_pageout(&oy,&temp);
  109936. ogg_stream_pagein(&os_de,&temp);
  109937. ogg_sync_pageout(&oy,&temp);
  109938. /* skip */
  109939. ogg_sync_pageout(&oy,&temp);
  109940. ogg_stream_pagein(&os_de,&temp);
  109941. /* do we get the expected results/packets? */
  109942. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109943. checkpacket(&test,0,0,0);
  109944. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109945. checkpacket(&test,100,1,-1);
  109946. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109947. checkpacket(&test,4079,2,3000);
  109948. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109949. checkpacket(&test,2956,3,4000);
  109950. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109951. fprintf(stderr,"Error: loss of page did not return error\n");
  109952. exit(1);
  109953. }
  109954. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109955. checkpacket(&test,300,13,14000);
  109956. fprintf(stderr,"ok.\n");
  109957. }
  109958. /* the rest only test sync */
  109959. {
  109960. ogg_page og_de;
  109961. /* Test fractional page inputs: incomplete capture */
  109962. fprintf(stderr,"Testing sync on partial inputs... ");
  109963. ogg_sync_reset(&oy);
  109964. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109965. 3);
  109966. ogg_sync_wrote(&oy,3);
  109967. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109968. /* Test fractional page inputs: incomplete fixed header */
  109969. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109970. 20);
  109971. ogg_sync_wrote(&oy,20);
  109972. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109973. /* Test fractional page inputs: incomplete header */
  109974. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109975. 5);
  109976. ogg_sync_wrote(&oy,5);
  109977. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109978. /* Test fractional page inputs: incomplete body */
  109979. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109980. og[1].header_len-28);
  109981. ogg_sync_wrote(&oy,og[1].header_len-28);
  109982. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109983. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109984. ogg_sync_wrote(&oy,1000);
  109985. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109986. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109987. og[1].body_len-1000);
  109988. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109989. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109990. fprintf(stderr,"ok.\n");
  109991. }
  109992. /* Test fractional page inputs: page + incomplete capture */
  109993. {
  109994. ogg_page og_de;
  109995. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109996. ogg_sync_reset(&oy);
  109997. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109998. og[1].header_len);
  109999. ogg_sync_wrote(&oy,og[1].header_len);
  110000. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110001. og[1].body_len);
  110002. ogg_sync_wrote(&oy,og[1].body_len);
  110003. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110004. 20);
  110005. ogg_sync_wrote(&oy,20);
  110006. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110007. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110008. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  110009. og[1].header_len-20);
  110010. ogg_sync_wrote(&oy,og[1].header_len-20);
  110011. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110012. og[1].body_len);
  110013. ogg_sync_wrote(&oy,og[1].body_len);
  110014. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110015. fprintf(stderr,"ok.\n");
  110016. }
  110017. /* Test recapture: garbage + page */
  110018. {
  110019. ogg_page og_de;
  110020. fprintf(stderr,"Testing search for capture... ");
  110021. ogg_sync_reset(&oy);
  110022. /* 'garbage' */
  110023. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110024. og[1].body_len);
  110025. ogg_sync_wrote(&oy,og[1].body_len);
  110026. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110027. og[1].header_len);
  110028. ogg_sync_wrote(&oy,og[1].header_len);
  110029. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110030. og[1].body_len);
  110031. ogg_sync_wrote(&oy,og[1].body_len);
  110032. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110033. 20);
  110034. ogg_sync_wrote(&oy,20);
  110035. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110036. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110037. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110038. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  110039. og[2].header_len-20);
  110040. ogg_sync_wrote(&oy,og[2].header_len-20);
  110041. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110042. og[2].body_len);
  110043. ogg_sync_wrote(&oy,og[2].body_len);
  110044. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110045. fprintf(stderr,"ok.\n");
  110046. }
  110047. /* Test recapture: page + garbage + page */
  110048. {
  110049. ogg_page og_de;
  110050. fprintf(stderr,"Testing recapture... ");
  110051. ogg_sync_reset(&oy);
  110052. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110053. og[1].header_len);
  110054. ogg_sync_wrote(&oy,og[1].header_len);
  110055. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110056. og[1].body_len);
  110057. ogg_sync_wrote(&oy,og[1].body_len);
  110058. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110059. og[2].header_len);
  110060. ogg_sync_wrote(&oy,og[2].header_len);
  110061. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110062. og[2].header_len);
  110063. ogg_sync_wrote(&oy,og[2].header_len);
  110064. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110065. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110066. og[2].body_len-5);
  110067. ogg_sync_wrote(&oy,og[2].body_len-5);
  110068. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  110069. og[3].header_len);
  110070. ogg_sync_wrote(&oy,og[3].header_len);
  110071. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  110072. og[3].body_len);
  110073. ogg_sync_wrote(&oy,og[3].body_len);
  110074. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110075. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110076. fprintf(stderr,"ok.\n");
  110077. }
  110078. /* Free page data that was previously copied */
  110079. {
  110080. for(i=0;i<5;i++){
  110081. free_page(&og[i]);
  110082. }
  110083. }
  110084. }
  110085. return(0);
  110086. }
  110087. #endif
  110088. #endif
  110089. /*** End of inlined file: framing.c ***/
  110090. /*** Start of inlined file: analysis.c ***/
  110091. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110092. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110093. // tasks..
  110094. #if JUCE_MSVC
  110095. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110096. #endif
  110097. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110098. #if JUCE_USE_OGGVORBIS
  110099. #include <stdio.h>
  110100. #include <string.h>
  110101. #include <math.h>
  110102. /*** Start of inlined file: codec_internal.h ***/
  110103. #ifndef _V_CODECI_H_
  110104. #define _V_CODECI_H_
  110105. /*** Start of inlined file: envelope.h ***/
  110106. #ifndef _V_ENVELOPE_
  110107. #define _V_ENVELOPE_
  110108. /*** Start of inlined file: mdct.h ***/
  110109. #ifndef _OGG_mdct_H_
  110110. #define _OGG_mdct_H_
  110111. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  110112. #ifdef MDCT_INTEGERIZED
  110113. #define DATA_TYPE int
  110114. #define REG_TYPE register int
  110115. #define TRIGBITS 14
  110116. #define cPI3_8 6270
  110117. #define cPI2_8 11585
  110118. #define cPI1_8 15137
  110119. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  110120. #define MULT_NORM(x) ((x)>>TRIGBITS)
  110121. #define HALVE(x) ((x)>>1)
  110122. #else
  110123. #define DATA_TYPE float
  110124. #define REG_TYPE float
  110125. #define cPI3_8 .38268343236508977175F
  110126. #define cPI2_8 .70710678118654752441F
  110127. #define cPI1_8 .92387953251128675613F
  110128. #define FLOAT_CONV(x) (x)
  110129. #define MULT_NORM(x) (x)
  110130. #define HALVE(x) ((x)*.5f)
  110131. #endif
  110132. typedef struct {
  110133. int n;
  110134. int log2n;
  110135. DATA_TYPE *trig;
  110136. int *bitrev;
  110137. DATA_TYPE scale;
  110138. } mdct_lookup;
  110139. extern void mdct_init(mdct_lookup *lookup,int n);
  110140. extern void mdct_clear(mdct_lookup *l);
  110141. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110142. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110143. #endif
  110144. /*** End of inlined file: mdct.h ***/
  110145. #define VE_PRE 16
  110146. #define VE_WIN 4
  110147. #define VE_POST 2
  110148. #define VE_AMP (VE_PRE+VE_POST-1)
  110149. #define VE_BANDS 7
  110150. #define VE_NEARDC 15
  110151. #define VE_MINSTRETCH 2 /* a bit less than short block */
  110152. #define VE_MAXSTRETCH 12 /* one-third full block */
  110153. typedef struct {
  110154. float ampbuf[VE_AMP];
  110155. int ampptr;
  110156. float nearDC[VE_NEARDC];
  110157. float nearDC_acc;
  110158. float nearDC_partialacc;
  110159. int nearptr;
  110160. } envelope_filter_state;
  110161. typedef struct {
  110162. int begin;
  110163. int end;
  110164. float *window;
  110165. float total;
  110166. } envelope_band;
  110167. typedef struct {
  110168. int ch;
  110169. int winlength;
  110170. int searchstep;
  110171. float minenergy;
  110172. mdct_lookup mdct;
  110173. float *mdct_win;
  110174. envelope_band band[VE_BANDS];
  110175. envelope_filter_state *filter;
  110176. int stretch;
  110177. int *mark;
  110178. long storage;
  110179. long current;
  110180. long curmark;
  110181. long cursor;
  110182. } envelope_lookup;
  110183. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110184. extern void _ve_envelope_clear(envelope_lookup *e);
  110185. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110186. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110187. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110188. #endif
  110189. /*** End of inlined file: envelope.h ***/
  110190. /*** Start of inlined file: codebook.h ***/
  110191. #ifndef _V_CODEBOOK_H_
  110192. #define _V_CODEBOOK_H_
  110193. /* This structure encapsulates huffman and VQ style encoding books; it
  110194. doesn't do anything specific to either.
  110195. valuelist/quantlist are nonNULL (and q_* significant) only if
  110196. there's entry->value mapping to be done.
  110197. If encode-side mapping must be done (and thus the entry needs to be
  110198. hunted), the auxiliary encode pointer will point to a decision
  110199. tree. This is true of both VQ and huffman, but is mostly useful
  110200. with VQ.
  110201. */
  110202. typedef struct static_codebook{
  110203. long dim; /* codebook dimensions (elements per vector) */
  110204. long entries; /* codebook entries */
  110205. long *lengthlist; /* codeword lengths in bits */
  110206. /* mapping ***************************************************************/
  110207. int maptype; /* 0=none
  110208. 1=implicitly populated values from map column
  110209. 2=listed arbitrary values */
  110210. /* The below does a linear, single monotonic sequence mapping. */
  110211. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110212. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110213. int q_quant; /* bits: 0 < quant <= 16 */
  110214. int q_sequencep; /* bitflag */
  110215. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110216. map == 2: list of dim*entries quantized entry vals
  110217. */
  110218. /* encode helpers ********************************************************/
  110219. struct encode_aux_nearestmatch *nearest_tree;
  110220. struct encode_aux_threshmatch *thresh_tree;
  110221. struct encode_aux_pigeonhole *pigeon_tree;
  110222. int allocedp;
  110223. } static_codebook;
  110224. /* this structures an arbitrary trained book to quickly find the
  110225. nearest cell match */
  110226. typedef struct encode_aux_nearestmatch{
  110227. /* pre-calculated partitioning tree */
  110228. long *ptr0;
  110229. long *ptr1;
  110230. long *p; /* decision points (each is an entry) */
  110231. long *q; /* decision points (each is an entry) */
  110232. long aux; /* number of tree entries */
  110233. long alloc;
  110234. } encode_aux_nearestmatch;
  110235. /* assumes a maptype of 1; encode side only, so that's OK */
  110236. typedef struct encode_aux_threshmatch{
  110237. float *quantthresh;
  110238. long *quantmap;
  110239. int quantvals;
  110240. int threshvals;
  110241. } encode_aux_threshmatch;
  110242. typedef struct encode_aux_pigeonhole{
  110243. float min;
  110244. float del;
  110245. int mapentries;
  110246. int quantvals;
  110247. long *pigeonmap;
  110248. long fittotal;
  110249. long *fitlist;
  110250. long *fitmap;
  110251. long *fitlength;
  110252. } encode_aux_pigeonhole;
  110253. typedef struct codebook{
  110254. long dim; /* codebook dimensions (elements per vector) */
  110255. long entries; /* codebook entries */
  110256. long used_entries; /* populated codebook entries */
  110257. const static_codebook *c;
  110258. /* for encode, the below are entry-ordered, fully populated */
  110259. /* for decode, the below are ordered by bitreversed codeword and only
  110260. used entries are populated */
  110261. float *valuelist; /* list of dim*entries actual entry values */
  110262. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110263. int *dec_index; /* only used if sparseness collapsed */
  110264. char *dec_codelengths;
  110265. ogg_uint32_t *dec_firsttable;
  110266. int dec_firsttablen;
  110267. int dec_maxlength;
  110268. } codebook;
  110269. extern void vorbis_staticbook_clear(static_codebook *b);
  110270. extern void vorbis_staticbook_destroy(static_codebook *b);
  110271. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110272. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110273. extern void vorbis_book_clear(codebook *b);
  110274. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110275. extern float *_book_logdist(const static_codebook *b,float *vals);
  110276. extern float _float32_unpack(long val);
  110277. extern long _float32_pack(float val);
  110278. extern int _best(codebook *book, float *a, int step);
  110279. extern int _ilog(unsigned int v);
  110280. extern long _book_maptype1_quantvals(const static_codebook *b);
  110281. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110282. extern long vorbis_book_codeword(codebook *book,int entry);
  110283. extern long vorbis_book_codelen(codebook *book,int entry);
  110284. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110285. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110286. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110287. extern int vorbis_book_errorv(codebook *book, float *a);
  110288. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110289. oggpack_buffer *b);
  110290. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110291. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110292. oggpack_buffer *b,int n);
  110293. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110294. oggpack_buffer *b,int n);
  110295. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110296. oggpack_buffer *b,int n);
  110297. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110298. long off,int ch,
  110299. oggpack_buffer *b,int n);
  110300. #endif
  110301. /*** End of inlined file: codebook.h ***/
  110302. #define BLOCKTYPE_IMPULSE 0
  110303. #define BLOCKTYPE_PADDING 1
  110304. #define BLOCKTYPE_TRANSITION 0
  110305. #define BLOCKTYPE_LONG 1
  110306. #define PACKETBLOBS 15
  110307. typedef struct vorbis_block_internal{
  110308. float **pcmdelay; /* this is a pointer into local storage */
  110309. float ampmax;
  110310. int blocktype;
  110311. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110312. blob [PACKETBLOBS/2] points to
  110313. the oggpack_buffer in the
  110314. main vorbis_block */
  110315. } vorbis_block_internal;
  110316. typedef void vorbis_look_floor;
  110317. typedef void vorbis_look_residue;
  110318. typedef void vorbis_look_transform;
  110319. /* mode ************************************************************/
  110320. typedef struct {
  110321. int blockflag;
  110322. int windowtype;
  110323. int transformtype;
  110324. int mapping;
  110325. } vorbis_info_mode;
  110326. typedef void vorbis_info_floor;
  110327. typedef void vorbis_info_residue;
  110328. typedef void vorbis_info_mapping;
  110329. /*** Start of inlined file: psy.h ***/
  110330. #ifndef _V_PSY_H_
  110331. #define _V_PSY_H_
  110332. /*** Start of inlined file: smallft.h ***/
  110333. #ifndef _V_SMFT_H_
  110334. #define _V_SMFT_H_
  110335. typedef struct {
  110336. int n;
  110337. float *trigcache;
  110338. int *splitcache;
  110339. } drft_lookup;
  110340. extern void drft_forward(drft_lookup *l,float *data);
  110341. extern void drft_backward(drft_lookup *l,float *data);
  110342. extern void drft_init(drft_lookup *l,int n);
  110343. extern void drft_clear(drft_lookup *l);
  110344. #endif
  110345. /*** End of inlined file: smallft.h ***/
  110346. /*** Start of inlined file: backends.h ***/
  110347. /* this is exposed up here because we need it for static modes.
  110348. Lookups for each backend aren't exposed because there's no reason
  110349. to do so */
  110350. #ifndef _vorbis_backend_h_
  110351. #define _vorbis_backend_h_
  110352. /* this would all be simpler/shorter with templates, but.... */
  110353. /* Floor backend generic *****************************************/
  110354. typedef struct{
  110355. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110356. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110357. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110358. void (*free_info) (vorbis_info_floor *);
  110359. void (*free_look) (vorbis_look_floor *);
  110360. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110361. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110362. void *buffer,float *);
  110363. } vorbis_func_floor;
  110364. typedef struct{
  110365. int order;
  110366. long rate;
  110367. long barkmap;
  110368. int ampbits;
  110369. int ampdB;
  110370. int numbooks; /* <= 16 */
  110371. int books[16];
  110372. float lessthan; /* encode-only config setting hacks for libvorbis */
  110373. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110374. } vorbis_info_floor0;
  110375. #define VIF_POSIT 63
  110376. #define VIF_CLASS 16
  110377. #define VIF_PARTS 31
  110378. typedef struct{
  110379. int partitions; /* 0 to 31 */
  110380. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110381. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110382. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110383. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110384. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110385. int mult; /* 1 2 3 or 4 */
  110386. int postlist[VIF_POSIT+2]; /* first two implicit */
  110387. /* encode side analysis parameters */
  110388. float maxover;
  110389. float maxunder;
  110390. float maxerr;
  110391. float twofitweight;
  110392. float twofitatten;
  110393. int n;
  110394. } vorbis_info_floor1;
  110395. /* Residue backend generic *****************************************/
  110396. typedef struct{
  110397. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110398. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110399. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110400. vorbis_info_residue *);
  110401. void (*free_info) (vorbis_info_residue *);
  110402. void (*free_look) (vorbis_look_residue *);
  110403. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110404. float **,int *,int);
  110405. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110406. vorbis_look_residue *,
  110407. float **,float **,int *,int,long **);
  110408. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110409. float **,int *,int);
  110410. } vorbis_func_residue;
  110411. typedef struct vorbis_info_residue0{
  110412. /* block-partitioned VQ coded straight residue */
  110413. long begin;
  110414. long end;
  110415. /* first stage (lossless partitioning) */
  110416. int grouping; /* group n vectors per partition */
  110417. int partitions; /* possible codebooks for a partition */
  110418. int groupbook; /* huffbook for partitioning */
  110419. int secondstages[64]; /* expanded out to pointers in lookup */
  110420. int booklist[256]; /* list of second stage books */
  110421. float classmetric1[64];
  110422. float classmetric2[64];
  110423. } vorbis_info_residue0;
  110424. /* Mapping backend generic *****************************************/
  110425. typedef struct{
  110426. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110427. oggpack_buffer *);
  110428. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110429. void (*free_info) (vorbis_info_mapping *);
  110430. int (*forward) (struct vorbis_block *vb);
  110431. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110432. } vorbis_func_mapping;
  110433. typedef struct vorbis_info_mapping0{
  110434. int submaps; /* <= 16 */
  110435. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110436. int floorsubmap[16]; /* [mux] submap to floors */
  110437. int residuesubmap[16]; /* [mux] submap to residue */
  110438. int coupling_steps;
  110439. int coupling_mag[256];
  110440. int coupling_ang[256];
  110441. } vorbis_info_mapping0;
  110442. #endif
  110443. /*** End of inlined file: backends.h ***/
  110444. #ifndef EHMER_MAX
  110445. #define EHMER_MAX 56
  110446. #endif
  110447. /* psychoacoustic setup ********************************************/
  110448. #define P_BANDS 17 /* 62Hz to 16kHz */
  110449. #define P_LEVELS 8 /* 30dB to 100dB */
  110450. #define P_LEVEL_0 30. /* 30 dB */
  110451. #define P_NOISECURVES 3
  110452. #define NOISE_COMPAND_LEVELS 40
  110453. typedef struct vorbis_info_psy{
  110454. int blockflag;
  110455. float ath_adjatt;
  110456. float ath_maxatt;
  110457. float tone_masteratt[P_NOISECURVES];
  110458. float tone_centerboost;
  110459. float tone_decay;
  110460. float tone_abs_limit;
  110461. float toneatt[P_BANDS];
  110462. int noisemaskp;
  110463. float noisemaxsupp;
  110464. float noisewindowlo;
  110465. float noisewindowhi;
  110466. int noisewindowlomin;
  110467. int noisewindowhimin;
  110468. int noisewindowfixed;
  110469. float noiseoff[P_NOISECURVES][P_BANDS];
  110470. float noisecompand[NOISE_COMPAND_LEVELS];
  110471. float max_curve_dB;
  110472. int normal_channel_p;
  110473. int normal_point_p;
  110474. int normal_start;
  110475. int normal_partition;
  110476. double normal_thresh;
  110477. } vorbis_info_psy;
  110478. typedef struct{
  110479. int eighth_octave_lines;
  110480. /* for block long/short tuning; encode only */
  110481. float preecho_thresh[VE_BANDS];
  110482. float postecho_thresh[VE_BANDS];
  110483. float stretch_penalty;
  110484. float preecho_minenergy;
  110485. float ampmax_att_per_sec;
  110486. /* channel coupling config */
  110487. int coupling_pkHz[PACKETBLOBS];
  110488. int coupling_pointlimit[2][PACKETBLOBS];
  110489. int coupling_prepointamp[PACKETBLOBS];
  110490. int coupling_postpointamp[PACKETBLOBS];
  110491. int sliding_lowpass[2][PACKETBLOBS];
  110492. } vorbis_info_psy_global;
  110493. typedef struct {
  110494. float ampmax;
  110495. int channels;
  110496. vorbis_info_psy_global *gi;
  110497. int coupling_pointlimit[2][P_NOISECURVES];
  110498. } vorbis_look_psy_global;
  110499. typedef struct {
  110500. int n;
  110501. struct vorbis_info_psy *vi;
  110502. float ***tonecurves;
  110503. float **noiseoffset;
  110504. float *ath;
  110505. long *octave; /* in n.ocshift format */
  110506. long *bark;
  110507. long firstoc;
  110508. long shiftoc;
  110509. int eighth_octave_lines; /* power of two, please */
  110510. int total_octave_lines;
  110511. long rate; /* cache it */
  110512. float m_val; /* Masking compensation value */
  110513. } vorbis_look_psy;
  110514. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110515. vorbis_info_psy_global *gi,int n,long rate);
  110516. extern void _vp_psy_clear(vorbis_look_psy *p);
  110517. extern void *_vi_psy_dup(void *source);
  110518. extern void _vi_psy_free(vorbis_info_psy *i);
  110519. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110520. extern void _vp_remove_floor(vorbis_look_psy *p,
  110521. float *mdct,
  110522. int *icodedflr,
  110523. float *residue,
  110524. int sliding_lowpass);
  110525. extern void _vp_noisemask(vorbis_look_psy *p,
  110526. float *logmdct,
  110527. float *logmask);
  110528. extern void _vp_tonemask(vorbis_look_psy *p,
  110529. float *logfft,
  110530. float *logmask,
  110531. float global_specmax,
  110532. float local_specmax);
  110533. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110534. float *noise,
  110535. float *tone,
  110536. int offset_select,
  110537. float *logmask,
  110538. float *mdct,
  110539. float *logmdct);
  110540. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110541. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110542. vorbis_info_psy_global *g,
  110543. vorbis_look_psy *p,
  110544. vorbis_info_mapping0 *vi,
  110545. float **mdct);
  110546. extern void _vp_couple(int blobno,
  110547. vorbis_info_psy_global *g,
  110548. vorbis_look_psy *p,
  110549. vorbis_info_mapping0 *vi,
  110550. float **res,
  110551. float **mag_memo,
  110552. int **mag_sort,
  110553. int **ifloor,
  110554. int *nonzero,
  110555. int sliding_lowpass);
  110556. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110557. float *in,float *out,int *sortedindex);
  110558. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110559. float *magnitudes,int *sortedindex);
  110560. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110561. vorbis_look_psy *p,
  110562. vorbis_info_mapping0 *vi,
  110563. float **mags);
  110564. extern void hf_reduction(vorbis_info_psy_global *g,
  110565. vorbis_look_psy *p,
  110566. vorbis_info_mapping0 *vi,
  110567. float **mdct);
  110568. #endif
  110569. /*** End of inlined file: psy.h ***/
  110570. /*** Start of inlined file: bitrate.h ***/
  110571. #ifndef _V_BITRATE_H_
  110572. #define _V_BITRATE_H_
  110573. /*** Start of inlined file: os.h ***/
  110574. #ifndef _OS_H
  110575. #define _OS_H
  110576. /********************************************************************
  110577. * *
  110578. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110579. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110580. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110581. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110582. * *
  110583. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110584. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110585. * *
  110586. ********************************************************************
  110587. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110588. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110589. ********************************************************************/
  110590. #ifdef HAVE_CONFIG_H
  110591. #include "config.h"
  110592. #endif
  110593. #include <math.h>
  110594. /*** Start of inlined file: misc.h ***/
  110595. #ifndef _V_RANDOM_H_
  110596. #define _V_RANDOM_H_
  110597. extern int analysis_noisy;
  110598. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110599. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110600. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110601. ogg_int64_t off);
  110602. #ifdef DEBUG_MALLOC
  110603. #define _VDBG_GRAPHFILE "malloc.m"
  110604. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110605. extern void _VDBG_free(void *ptr,char *file,long line);
  110606. #ifndef MISC_C
  110607. #undef _ogg_malloc
  110608. #undef _ogg_calloc
  110609. #undef _ogg_realloc
  110610. #undef _ogg_free
  110611. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110612. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110613. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110614. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110615. #endif
  110616. #endif
  110617. #endif
  110618. /*** End of inlined file: misc.h ***/
  110619. #ifndef _V_IFDEFJAIL_H_
  110620. # define _V_IFDEFJAIL_H_
  110621. # ifdef __GNUC__
  110622. # define STIN static __inline__
  110623. # elif _WIN32
  110624. # define STIN static __inline
  110625. # else
  110626. # define STIN static
  110627. # endif
  110628. #ifdef DJGPP
  110629. # define rint(x) (floor((x)+0.5f))
  110630. #endif
  110631. #ifndef M_PI
  110632. # define M_PI (3.1415926536f)
  110633. #endif
  110634. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110635. # include <malloc.h>
  110636. # define rint(x) (floor((x)+0.5f))
  110637. # define NO_FLOAT_MATH_LIB
  110638. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110639. #endif
  110640. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110641. void *_alloca(size_t size);
  110642. # define alloca _alloca
  110643. #endif
  110644. #ifndef FAST_HYPOT
  110645. # define FAST_HYPOT hypot
  110646. #endif
  110647. #endif
  110648. #ifdef HAVE_ALLOCA_H
  110649. # include <alloca.h>
  110650. #endif
  110651. #ifdef USE_MEMORY_H
  110652. # include <memory.h>
  110653. #endif
  110654. #ifndef min
  110655. # define min(x,y) ((x)>(y)?(y):(x))
  110656. #endif
  110657. #ifndef max
  110658. # define max(x,y) ((x)<(y)?(y):(x))
  110659. #endif
  110660. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110661. # define VORBIS_FPU_CONTROL
  110662. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110663. Because of encapsulation constraints (GCC can't see inside the asm
  110664. block and so we end up doing stupid things like a store/load that
  110665. is collectively a noop), we do it this way */
  110666. /* we must set up the fpu before this works!! */
  110667. typedef ogg_int16_t vorbis_fpu_control;
  110668. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110669. ogg_int16_t ret;
  110670. ogg_int16_t temp;
  110671. __asm__ __volatile__("fnstcw %0\n\t"
  110672. "movw %0,%%dx\n\t"
  110673. "orw $62463,%%dx\n\t"
  110674. "movw %%dx,%1\n\t"
  110675. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110676. *fpu=ret;
  110677. }
  110678. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110679. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110680. }
  110681. /* assumes the FPU is in round mode! */
  110682. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110683. we get extra fst/fld to
  110684. truncate precision */
  110685. int i;
  110686. __asm__("fistl %0": "=m"(i) : "t"(f));
  110687. return(i);
  110688. }
  110689. #endif
  110690. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110691. # define VORBIS_FPU_CONTROL
  110692. typedef ogg_int16_t vorbis_fpu_control;
  110693. static __inline int vorbis_ftoi(double f){
  110694. int i;
  110695. __asm{
  110696. fld f
  110697. fistp i
  110698. }
  110699. return i;
  110700. }
  110701. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110702. }
  110703. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110704. }
  110705. #endif
  110706. #ifndef VORBIS_FPU_CONTROL
  110707. typedef int vorbis_fpu_control;
  110708. static int vorbis_ftoi(double f){
  110709. return (int)(f+.5);
  110710. }
  110711. /* We don't have special code for this compiler/arch, so do it the slow way */
  110712. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110713. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110714. #endif
  110715. #endif /* _OS_H */
  110716. /*** End of inlined file: os.h ***/
  110717. /* encode side bitrate tracking */
  110718. typedef struct bitrate_manager_state {
  110719. int managed;
  110720. long avg_reservoir;
  110721. long minmax_reservoir;
  110722. long avg_bitsper;
  110723. long min_bitsper;
  110724. long max_bitsper;
  110725. long short_per_long;
  110726. double avgfloat;
  110727. vorbis_block *vb;
  110728. int choice;
  110729. } bitrate_manager_state;
  110730. typedef struct bitrate_manager_info{
  110731. long avg_rate;
  110732. long min_rate;
  110733. long max_rate;
  110734. long reservoir_bits;
  110735. double reservoir_bias;
  110736. double slew_damp;
  110737. } bitrate_manager_info;
  110738. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110739. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110740. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110741. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110742. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110743. #endif
  110744. /*** End of inlined file: bitrate.h ***/
  110745. static int ilog(unsigned int v){
  110746. int ret=0;
  110747. while(v){
  110748. ret++;
  110749. v>>=1;
  110750. }
  110751. return(ret);
  110752. }
  110753. static int ilog2(unsigned int v){
  110754. int ret=0;
  110755. if(v)--v;
  110756. while(v){
  110757. ret++;
  110758. v>>=1;
  110759. }
  110760. return(ret);
  110761. }
  110762. typedef struct private_state {
  110763. /* local lookup storage */
  110764. envelope_lookup *ve; /* envelope lookup */
  110765. int window[2];
  110766. vorbis_look_transform **transform[2]; /* block, type */
  110767. drft_lookup fft_look[2];
  110768. int modebits;
  110769. vorbis_look_floor **flr;
  110770. vorbis_look_residue **residue;
  110771. vorbis_look_psy *psy;
  110772. vorbis_look_psy_global *psy_g_look;
  110773. /* local storage, only used on the encoding side. This way the
  110774. application does not need to worry about freeing some packets'
  110775. memory and not others'; packet storage is always tracked.
  110776. Cleared next call to a _dsp_ function */
  110777. unsigned char *header;
  110778. unsigned char *header1;
  110779. unsigned char *header2;
  110780. bitrate_manager_state bms;
  110781. ogg_int64_t sample_count;
  110782. } private_state;
  110783. /* codec_setup_info contains all the setup information specific to the
  110784. specific compression/decompression mode in progress (eg,
  110785. psychoacoustic settings, channel setup, options, codebook
  110786. etc).
  110787. *********************************************************************/
  110788. /*** Start of inlined file: highlevel.h ***/
  110789. typedef struct highlevel_byblocktype {
  110790. double tone_mask_setting;
  110791. double tone_peaklimit_setting;
  110792. double noise_bias_setting;
  110793. double noise_compand_setting;
  110794. } highlevel_byblocktype;
  110795. typedef struct highlevel_encode_setup {
  110796. void *setup;
  110797. int set_in_stone;
  110798. double base_setting;
  110799. double long_setting;
  110800. double short_setting;
  110801. double impulse_noisetune;
  110802. int managed;
  110803. long bitrate_min;
  110804. long bitrate_av;
  110805. double bitrate_av_damp;
  110806. long bitrate_max;
  110807. long bitrate_reservoir;
  110808. double bitrate_reservoir_bias;
  110809. int impulse_block_p;
  110810. int noise_normalize_p;
  110811. double stereo_point_setting;
  110812. double lowpass_kHz;
  110813. double ath_floating_dB;
  110814. double ath_absolute_dB;
  110815. double amplitude_track_dBpersec;
  110816. double trigger_setting;
  110817. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110818. } highlevel_encode_setup;
  110819. /*** End of inlined file: highlevel.h ***/
  110820. typedef struct codec_setup_info {
  110821. /* Vorbis supports only short and long blocks, but allows the
  110822. encoder to choose the sizes */
  110823. long blocksizes[2];
  110824. /* modes are the primary means of supporting on-the-fly different
  110825. blocksizes, different channel mappings (LR or M/A),
  110826. different residue backends, etc. Each mode consists of a
  110827. blocksize flag and a mapping (along with the mapping setup */
  110828. int modes;
  110829. int maps;
  110830. int floors;
  110831. int residues;
  110832. int books;
  110833. int psys; /* encode only */
  110834. vorbis_info_mode *mode_param[64];
  110835. int map_type[64];
  110836. vorbis_info_mapping *map_param[64];
  110837. int floor_type[64];
  110838. vorbis_info_floor *floor_param[64];
  110839. int residue_type[64];
  110840. vorbis_info_residue *residue_param[64];
  110841. static_codebook *book_param[256];
  110842. codebook *fullbooks;
  110843. vorbis_info_psy *psy_param[4]; /* encode only */
  110844. vorbis_info_psy_global psy_g_param;
  110845. bitrate_manager_info bi;
  110846. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110847. highly redundant structure, but
  110848. improves clarity of program flow. */
  110849. int halfrate_flag; /* painless downsample for decode */
  110850. } codec_setup_info;
  110851. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110852. extern void _vp_global_free(vorbis_look_psy_global *look);
  110853. #endif
  110854. /*** End of inlined file: codec_internal.h ***/
  110855. /*** Start of inlined file: registry.h ***/
  110856. #ifndef _V_REG_H_
  110857. #define _V_REG_H_
  110858. #define VI_TRANSFORMB 1
  110859. #define VI_WINDOWB 1
  110860. #define VI_TIMEB 1
  110861. #define VI_FLOORB 2
  110862. #define VI_RESB 3
  110863. #define VI_MAPB 1
  110864. extern vorbis_func_floor *_floor_P[];
  110865. extern vorbis_func_residue *_residue_P[];
  110866. extern vorbis_func_mapping *_mapping_P[];
  110867. #endif
  110868. /*** End of inlined file: registry.h ***/
  110869. /*** Start of inlined file: scales.h ***/
  110870. #ifndef _V_SCALES_H_
  110871. #define _V_SCALES_H_
  110872. #include <math.h>
  110873. /* 20log10(x) */
  110874. #define VORBIS_IEEE_FLOAT32 1
  110875. #ifdef VORBIS_IEEE_FLOAT32
  110876. static float unitnorm(float x){
  110877. union {
  110878. ogg_uint32_t i;
  110879. float f;
  110880. } ix;
  110881. ix.f = x;
  110882. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110883. return ix.f;
  110884. }
  110885. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110886. static float todB(const float *x){
  110887. union {
  110888. ogg_uint32_t i;
  110889. float f;
  110890. } ix;
  110891. ix.f = *x;
  110892. ix.i = ix.i&0x7fffffff;
  110893. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110894. }
  110895. #define todB_nn(x) todB(x)
  110896. #else
  110897. static float unitnorm(float x){
  110898. if(x<0)return(-1.f);
  110899. return(1.f);
  110900. }
  110901. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110902. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110903. #endif
  110904. #define fromdB(x) (exp((x)*.11512925f))
  110905. /* The bark scale equations are approximations, since the original
  110906. table was somewhat hand rolled. The below are chosen to have the
  110907. best possible fit to the rolled tables, thus their somewhat odd
  110908. appearance (these are more accurate and over a longer range than
  110909. the oft-quoted bark equations found in the texts I have). The
  110910. approximations are valid from 0 - 30kHz (nyquist) or so.
  110911. all f in Hz, z in Bark */
  110912. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110913. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110914. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110915. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110916. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110917. 0.0 */
  110918. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110919. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110920. #endif
  110921. /*** End of inlined file: scales.h ***/
  110922. int analysis_noisy=1;
  110923. /* decides between modes, dispatches to the appropriate mapping. */
  110924. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110925. int ret,i;
  110926. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110927. vb->glue_bits=0;
  110928. vb->time_bits=0;
  110929. vb->floor_bits=0;
  110930. vb->res_bits=0;
  110931. /* first things first. Make sure encode is ready */
  110932. for(i=0;i<PACKETBLOBS;i++)
  110933. oggpack_reset(vbi->packetblob[i]);
  110934. /* we only have one mapping type (0), and we let the mapping code
  110935. itself figure out what soft mode to use. This allows easier
  110936. bitrate management */
  110937. if((ret=_mapping_P[0]->forward(vb)))
  110938. return(ret);
  110939. if(op){
  110940. if(vorbis_bitrate_managed(vb))
  110941. /* The app is using a bitmanaged mode... but not using the
  110942. bitrate management interface. */
  110943. return(OV_EINVAL);
  110944. op->packet=oggpack_get_buffer(&vb->opb);
  110945. op->bytes=oggpack_bytes(&vb->opb);
  110946. op->b_o_s=0;
  110947. op->e_o_s=vb->eofflag;
  110948. op->granulepos=vb->granulepos;
  110949. op->packetno=vb->sequence; /* for sake of completeness */
  110950. }
  110951. return(0);
  110952. }
  110953. /* there was no great place to put this.... */
  110954. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110955. int j;
  110956. FILE *of;
  110957. char buffer[80];
  110958. /* if(i==5870){*/
  110959. sprintf(buffer,"%s_%d.m",base,i);
  110960. of=fopen(buffer,"w");
  110961. if(!of)perror("failed to open data dump file");
  110962. for(j=0;j<n;j++){
  110963. if(bark){
  110964. float b=toBARK((4000.f*j/n)+.25);
  110965. fprintf(of,"%f ",b);
  110966. }else
  110967. if(off!=0)
  110968. fprintf(of,"%f ",(double)(j+off)/8000.);
  110969. else
  110970. fprintf(of,"%f ",(double)j);
  110971. if(dB){
  110972. float val;
  110973. if(v[j]==0.)
  110974. val=-140.;
  110975. else
  110976. val=todB(v+j);
  110977. fprintf(of,"%f\n",val);
  110978. }else{
  110979. fprintf(of,"%f\n",v[j]);
  110980. }
  110981. }
  110982. fclose(of);
  110983. /* } */
  110984. }
  110985. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110986. ogg_int64_t off){
  110987. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110988. }
  110989. #endif
  110990. /*** End of inlined file: analysis.c ***/
  110991. /*** Start of inlined file: bitrate.c ***/
  110992. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110993. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110994. // tasks..
  110995. #if JUCE_MSVC
  110996. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110997. #endif
  110998. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110999. #if JUCE_USE_OGGVORBIS
  111000. #include <stdlib.h>
  111001. #include <string.h>
  111002. #include <math.h>
  111003. /* compute bitrate tracking setup */
  111004. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  111005. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111006. bitrate_manager_info *bi=&ci->bi;
  111007. memset(bm,0,sizeof(*bm));
  111008. if(bi && (bi->reservoir_bits>0)){
  111009. long ratesamples=vi->rate;
  111010. int halfsamples=ci->blocksizes[0]>>1;
  111011. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  111012. bm->managed=1;
  111013. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  111014. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  111015. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  111016. bm->avgfloat=PACKETBLOBS/2;
  111017. /* not a necessary fix, but one that leads to a more balanced
  111018. typical initialization */
  111019. {
  111020. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111021. bm->minmax_reservoir=desired_fill;
  111022. bm->avg_reservoir=desired_fill;
  111023. }
  111024. }
  111025. }
  111026. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  111027. memset(bm,0,sizeof(*bm));
  111028. return;
  111029. }
  111030. int vorbis_bitrate_managed(vorbis_block *vb){
  111031. vorbis_dsp_state *vd=vb->vd;
  111032. private_state *b=(private_state*)vd->backend_state;
  111033. bitrate_manager_state *bm=&b->bms;
  111034. if(bm && bm->managed)return(1);
  111035. return(0);
  111036. }
  111037. /* finish taking in the block we just processed */
  111038. int vorbis_bitrate_addblock(vorbis_block *vb){
  111039. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111040. vorbis_dsp_state *vd=vb->vd;
  111041. private_state *b=(private_state*)vd->backend_state;
  111042. bitrate_manager_state *bm=&b->bms;
  111043. vorbis_info *vi=vd->vi;
  111044. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111045. bitrate_manager_info *bi=&ci->bi;
  111046. int choice=rint(bm->avgfloat);
  111047. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111048. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  111049. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  111050. int samples=ci->blocksizes[vb->W]>>1;
  111051. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111052. if(!bm->managed){
  111053. /* not a bitrate managed stream, but for API simplicity, we'll
  111054. buffer the packet to keep the code path clean */
  111055. if(bm->vb)return(-1); /* one has been submitted without
  111056. being claimed */
  111057. bm->vb=vb;
  111058. return(0);
  111059. }
  111060. bm->vb=vb;
  111061. /* look ahead for avg floater */
  111062. if(bm->avg_bitsper>0){
  111063. double slew=0.;
  111064. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111065. double slewlimit= 15./bi->slew_damp;
  111066. /* choosing a new floater:
  111067. if we're over target, we slew down
  111068. if we're under target, we slew up
  111069. choose slew as follows: look through packetblobs of this frame
  111070. and set slew as the first in the appropriate direction that
  111071. gives us the slew we want. This may mean no slew if delta is
  111072. already favorable.
  111073. Then limit slew to slew max */
  111074. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111075. while(choice>0 && this_bits>avg_target_bits &&
  111076. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111077. choice--;
  111078. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111079. }
  111080. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111081. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  111082. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111083. choice++;
  111084. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111085. }
  111086. }
  111087. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  111088. if(slew<-slewlimit)slew=-slewlimit;
  111089. if(slew>slewlimit)slew=slewlimit;
  111090. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  111091. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111092. }
  111093. /* enforce min(if used) on the current floater (if used) */
  111094. if(bm->min_bitsper>0){
  111095. /* do we need to force the bitrate up? */
  111096. if(this_bits<min_target_bits){
  111097. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  111098. choice++;
  111099. if(choice>=PACKETBLOBS)break;
  111100. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111101. }
  111102. }
  111103. }
  111104. /* enforce max (if used) on the current floater (if used) */
  111105. if(bm->max_bitsper>0){
  111106. /* do we need to force the bitrate down? */
  111107. if(this_bits>max_target_bits){
  111108. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  111109. choice--;
  111110. if(choice<0)break;
  111111. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111112. }
  111113. }
  111114. }
  111115. /* Choice of packetblobs now made based on floater, and min/max
  111116. requirements. Now boundary check extreme choices */
  111117. if(choice<0){
  111118. /* choosing a smaller packetblob is insufficient to trim bitrate.
  111119. frame will need to be truncated */
  111120. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  111121. bm->choice=choice=0;
  111122. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  111123. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  111124. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111125. }
  111126. }else{
  111127. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  111128. if(choice>=PACKETBLOBS)
  111129. choice=PACKETBLOBS-1;
  111130. bm->choice=choice;
  111131. /* prop up bitrate according to demand. pad this frame out with zeroes */
  111132. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  111133. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  111134. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111135. }
  111136. /* now we have the final packet and the final packet size. Update statistics */
  111137. /* min and max reservoir */
  111138. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  111139. if(max_target_bits>0 && this_bits>max_target_bits){
  111140. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111141. }else if(min_target_bits>0 && this_bits<min_target_bits){
  111142. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111143. }else{
  111144. /* inbetween; we want to take reservoir toward but not past desired_fill */
  111145. if(bm->minmax_reservoir>desired_fill){
  111146. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  111147. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111148. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  111149. }else{
  111150. bm->minmax_reservoir=desired_fill;
  111151. }
  111152. }else{
  111153. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  111154. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111155. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111156. }else{
  111157. bm->minmax_reservoir=desired_fill;
  111158. }
  111159. }
  111160. }
  111161. }
  111162. /* avg reservoir */
  111163. if(bm->avg_bitsper>0){
  111164. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111165. bm->avg_reservoir+=this_bits-avg_target_bits;
  111166. }
  111167. return(0);
  111168. }
  111169. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111170. private_state *b=(private_state*)vd->backend_state;
  111171. bitrate_manager_state *bm=&b->bms;
  111172. vorbis_block *vb=bm->vb;
  111173. int choice=PACKETBLOBS/2;
  111174. if(!vb)return 0;
  111175. if(op){
  111176. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111177. if(vorbis_bitrate_managed(vb))
  111178. choice=bm->choice;
  111179. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111180. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111181. op->b_o_s=0;
  111182. op->e_o_s=vb->eofflag;
  111183. op->granulepos=vb->granulepos;
  111184. op->packetno=vb->sequence; /* for sake of completeness */
  111185. }
  111186. bm->vb=0;
  111187. return(1);
  111188. }
  111189. #endif
  111190. /*** End of inlined file: bitrate.c ***/
  111191. /*** Start of inlined file: block.c ***/
  111192. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111193. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111194. // tasks..
  111195. #if JUCE_MSVC
  111196. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111197. #endif
  111198. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111199. #if JUCE_USE_OGGVORBIS
  111200. #include <stdio.h>
  111201. #include <stdlib.h>
  111202. #include <string.h>
  111203. /*** Start of inlined file: window.h ***/
  111204. #ifndef _V_WINDOW_
  111205. #define _V_WINDOW_
  111206. extern float *_vorbis_window_get(int n);
  111207. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111208. int lW,int W,int nW);
  111209. #endif
  111210. /*** End of inlined file: window.h ***/
  111211. /*** Start of inlined file: lpc.h ***/
  111212. #ifndef _V_LPC_H_
  111213. #define _V_LPC_H_
  111214. /* simple linear scale LPC code */
  111215. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111216. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111217. float *data,long n);
  111218. #endif
  111219. /*** End of inlined file: lpc.h ***/
  111220. /* pcm accumulator examples (not exhaustive):
  111221. <-------------- lW ---------------->
  111222. <--------------- W ---------------->
  111223. : .....|..... _______________ |
  111224. : .''' | '''_--- | |\ |
  111225. :.....''' |_____--- '''......| | \_______|
  111226. :.................|__________________|_______|__|______|
  111227. |<------ Sl ------>| > Sr < |endW
  111228. |beginSl |endSl | |endSr
  111229. |beginW |endlW |beginSr
  111230. |< lW >|
  111231. <--------------- W ---------------->
  111232. | | .. ______________ |
  111233. | | ' `/ | ---_ |
  111234. |___.'___/`. | ---_____|
  111235. |_______|__|_______|_________________|
  111236. | >|Sl|< |<------ Sr ----->|endW
  111237. | | |endSl |beginSr |endSr
  111238. |beginW | |endlW
  111239. mult[0] |beginSl mult[n]
  111240. <-------------- lW ----------------->
  111241. |<--W-->|
  111242. : .............. ___ | |
  111243. : .''' |`/ \ | |
  111244. :.....''' |/`....\|...|
  111245. :.........................|___|___|___|
  111246. |Sl |Sr |endW
  111247. | | |endSr
  111248. | |beginSr
  111249. | |endSl
  111250. |beginSl
  111251. |beginW
  111252. */
  111253. /* block abstraction setup *********************************************/
  111254. #ifndef WORD_ALIGN
  111255. #define WORD_ALIGN 8
  111256. #endif
  111257. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111258. int i;
  111259. memset(vb,0,sizeof(*vb));
  111260. vb->vd=v;
  111261. vb->localalloc=0;
  111262. vb->localstore=NULL;
  111263. if(v->analysisp){
  111264. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111265. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111266. vbi->ampmax=-9999;
  111267. for(i=0;i<PACKETBLOBS;i++){
  111268. if(i==PACKETBLOBS/2){
  111269. vbi->packetblob[i]=&vb->opb;
  111270. }else{
  111271. vbi->packetblob[i]=
  111272. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111273. }
  111274. oggpack_writeinit(vbi->packetblob[i]);
  111275. }
  111276. }
  111277. return(0);
  111278. }
  111279. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111280. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111281. if(bytes+vb->localtop>vb->localalloc){
  111282. /* can't just _ogg_realloc... there are outstanding pointers */
  111283. if(vb->localstore){
  111284. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111285. vb->totaluse+=vb->localtop;
  111286. link->next=vb->reap;
  111287. link->ptr=vb->localstore;
  111288. vb->reap=link;
  111289. }
  111290. /* highly conservative */
  111291. vb->localalloc=bytes;
  111292. vb->localstore=_ogg_malloc(vb->localalloc);
  111293. vb->localtop=0;
  111294. }
  111295. {
  111296. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111297. vb->localtop+=bytes;
  111298. return ret;
  111299. }
  111300. }
  111301. /* reap the chain, pull the ripcord */
  111302. void _vorbis_block_ripcord(vorbis_block *vb){
  111303. /* reap the chain */
  111304. struct alloc_chain *reap=vb->reap;
  111305. while(reap){
  111306. struct alloc_chain *next=reap->next;
  111307. _ogg_free(reap->ptr);
  111308. memset(reap,0,sizeof(*reap));
  111309. _ogg_free(reap);
  111310. reap=next;
  111311. }
  111312. /* consolidate storage */
  111313. if(vb->totaluse){
  111314. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111315. vb->localalloc+=vb->totaluse;
  111316. vb->totaluse=0;
  111317. }
  111318. /* pull the ripcord */
  111319. vb->localtop=0;
  111320. vb->reap=NULL;
  111321. }
  111322. int vorbis_block_clear(vorbis_block *vb){
  111323. int i;
  111324. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111325. _vorbis_block_ripcord(vb);
  111326. if(vb->localstore)_ogg_free(vb->localstore);
  111327. if(vbi){
  111328. for(i=0;i<PACKETBLOBS;i++){
  111329. oggpack_writeclear(vbi->packetblob[i]);
  111330. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111331. }
  111332. _ogg_free(vbi);
  111333. }
  111334. memset(vb,0,sizeof(*vb));
  111335. return(0);
  111336. }
  111337. /* Analysis side code, but directly related to blocking. Thus it's
  111338. here and not in analysis.c (which is for analysis transforms only).
  111339. The init is here because some of it is shared */
  111340. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111341. int i;
  111342. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111343. private_state *b=NULL;
  111344. int hs;
  111345. if(ci==NULL) return 1;
  111346. hs=ci->halfrate_flag;
  111347. memset(v,0,sizeof(*v));
  111348. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111349. v->vi=vi;
  111350. b->modebits=ilog2(ci->modes);
  111351. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111352. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111353. /* MDCT is tranform 0 */
  111354. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111355. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111356. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111357. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111358. /* Vorbis I uses only window type 0 */
  111359. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111360. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111361. if(encp){ /* encode/decode differ here */
  111362. /* analysis always needs an fft */
  111363. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111364. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111365. /* finish the codebooks */
  111366. if(!ci->fullbooks){
  111367. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111368. for(i=0;i<ci->books;i++)
  111369. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111370. }
  111371. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111372. for(i=0;i<ci->psys;i++){
  111373. _vp_psy_init(b->psy+i,
  111374. ci->psy_param[i],
  111375. &ci->psy_g_param,
  111376. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111377. vi->rate);
  111378. }
  111379. v->analysisp=1;
  111380. }else{
  111381. /* finish the codebooks */
  111382. if(!ci->fullbooks){
  111383. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111384. for(i=0;i<ci->books;i++){
  111385. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111386. /* decode codebooks are now standalone after init */
  111387. vorbis_staticbook_destroy(ci->book_param[i]);
  111388. ci->book_param[i]=NULL;
  111389. }
  111390. }
  111391. }
  111392. /* initialize the storage vectors. blocksize[1] is small for encode,
  111393. but the correct size for decode */
  111394. v->pcm_storage=ci->blocksizes[1];
  111395. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111396. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111397. {
  111398. int i;
  111399. for(i=0;i<vi->channels;i++)
  111400. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111401. }
  111402. /* all 1 (large block) or 0 (small block) */
  111403. /* explicitly set for the sake of clarity */
  111404. v->lW=0; /* previous window size */
  111405. v->W=0; /* current window size */
  111406. /* all vector indexes */
  111407. v->centerW=ci->blocksizes[1]/2;
  111408. v->pcm_current=v->centerW;
  111409. /* initialize all the backend lookups */
  111410. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111411. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111412. for(i=0;i<ci->floors;i++)
  111413. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111414. look(v,ci->floor_param[i]);
  111415. for(i=0;i<ci->residues;i++)
  111416. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111417. look(v,ci->residue_param[i]);
  111418. return 0;
  111419. }
  111420. /* arbitrary settings and spec-mandated numbers get filled in here */
  111421. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111422. private_state *b=NULL;
  111423. if(_vds_shared_init(v,vi,1))return 1;
  111424. b=(private_state*)v->backend_state;
  111425. b->psy_g_look=_vp_global_look(vi);
  111426. /* Initialize the envelope state storage */
  111427. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111428. _ve_envelope_init(b->ve,vi);
  111429. vorbis_bitrate_init(vi,&b->bms);
  111430. /* compressed audio packets start after the headers
  111431. with sequence number 3 */
  111432. v->sequence=3;
  111433. return(0);
  111434. }
  111435. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111436. int i;
  111437. if(v){
  111438. vorbis_info *vi=v->vi;
  111439. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111440. private_state *b=(private_state*)v->backend_state;
  111441. if(b){
  111442. if(b->ve){
  111443. _ve_envelope_clear(b->ve);
  111444. _ogg_free(b->ve);
  111445. }
  111446. if(b->transform[0]){
  111447. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111448. _ogg_free(b->transform[0][0]);
  111449. _ogg_free(b->transform[0]);
  111450. }
  111451. if(b->transform[1]){
  111452. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111453. _ogg_free(b->transform[1][0]);
  111454. _ogg_free(b->transform[1]);
  111455. }
  111456. if(b->flr){
  111457. for(i=0;i<ci->floors;i++)
  111458. _floor_P[ci->floor_type[i]]->
  111459. free_look(b->flr[i]);
  111460. _ogg_free(b->flr);
  111461. }
  111462. if(b->residue){
  111463. for(i=0;i<ci->residues;i++)
  111464. _residue_P[ci->residue_type[i]]->
  111465. free_look(b->residue[i]);
  111466. _ogg_free(b->residue);
  111467. }
  111468. if(b->psy){
  111469. for(i=0;i<ci->psys;i++)
  111470. _vp_psy_clear(b->psy+i);
  111471. _ogg_free(b->psy);
  111472. }
  111473. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111474. vorbis_bitrate_clear(&b->bms);
  111475. drft_clear(&b->fft_look[0]);
  111476. drft_clear(&b->fft_look[1]);
  111477. }
  111478. if(v->pcm){
  111479. for(i=0;i<vi->channels;i++)
  111480. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111481. _ogg_free(v->pcm);
  111482. if(v->pcmret)_ogg_free(v->pcmret);
  111483. }
  111484. if(b){
  111485. /* free header, header1, header2 */
  111486. if(b->header)_ogg_free(b->header);
  111487. if(b->header1)_ogg_free(b->header1);
  111488. if(b->header2)_ogg_free(b->header2);
  111489. _ogg_free(b);
  111490. }
  111491. memset(v,0,sizeof(*v));
  111492. }
  111493. }
  111494. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111495. int i;
  111496. vorbis_info *vi=v->vi;
  111497. private_state *b=(private_state*)v->backend_state;
  111498. /* free header, header1, header2 */
  111499. if(b->header)_ogg_free(b->header);b->header=NULL;
  111500. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111501. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111502. /* Do we have enough storage space for the requested buffer? If not,
  111503. expand the PCM (and envelope) storage */
  111504. if(v->pcm_current+vals>=v->pcm_storage){
  111505. v->pcm_storage=v->pcm_current+vals*2;
  111506. for(i=0;i<vi->channels;i++){
  111507. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111508. }
  111509. }
  111510. for(i=0;i<vi->channels;i++)
  111511. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111512. return(v->pcmret);
  111513. }
  111514. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111515. int i;
  111516. int order=32;
  111517. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111518. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111519. long j;
  111520. v->preextrapolate=1;
  111521. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111522. for(i=0;i<v->vi->channels;i++){
  111523. /* need to run the extrapolation in reverse! */
  111524. for(j=0;j<v->pcm_current;j++)
  111525. work[j]=v->pcm[i][v->pcm_current-j-1];
  111526. /* prime as above */
  111527. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111528. /* run the predictor filter */
  111529. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111530. order,
  111531. work+v->pcm_current-v->centerW,
  111532. v->centerW);
  111533. for(j=0;j<v->pcm_current;j++)
  111534. v->pcm[i][v->pcm_current-j-1]=work[j];
  111535. }
  111536. }
  111537. }
  111538. /* call with val<=0 to set eof */
  111539. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111540. vorbis_info *vi=v->vi;
  111541. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111542. if(vals<=0){
  111543. int order=32;
  111544. int i;
  111545. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111546. /* if it wasn't done earlier (very short sample) */
  111547. if(!v->preextrapolate)
  111548. _preextrapolate_helper(v);
  111549. /* We're encoding the end of the stream. Just make sure we have
  111550. [at least] a few full blocks of zeroes at the end. */
  111551. /* actually, we don't want zeroes; that could drop a large
  111552. amplitude off a cliff, creating spread spectrum noise that will
  111553. suck to encode. Extrapolate for the sake of cleanliness. */
  111554. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111555. v->eofflag=v->pcm_current;
  111556. v->pcm_current+=ci->blocksizes[1]*3;
  111557. for(i=0;i<vi->channels;i++){
  111558. if(v->eofflag>order*2){
  111559. /* extrapolate with LPC to fill in */
  111560. long n;
  111561. /* make a predictor filter */
  111562. n=v->eofflag;
  111563. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111564. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111565. /* run the predictor filter */
  111566. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111567. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111568. }else{
  111569. /* not enough data to extrapolate (unlikely to happen due to
  111570. guarding the overlap, but bulletproof in case that
  111571. assumtion goes away). zeroes will do. */
  111572. memset(v->pcm[i]+v->eofflag,0,
  111573. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111574. }
  111575. }
  111576. }else{
  111577. if(v->pcm_current+vals>v->pcm_storage)
  111578. return(OV_EINVAL);
  111579. v->pcm_current+=vals;
  111580. /* we may want to reverse extrapolate the beginning of a stream
  111581. too... in case we're beginning on a cliff! */
  111582. /* clumsy, but simple. It only runs once, so simple is good. */
  111583. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111584. _preextrapolate_helper(v);
  111585. }
  111586. return(0);
  111587. }
  111588. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111589. the next block on which to continue analysis */
  111590. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111591. int i;
  111592. vorbis_info *vi=v->vi;
  111593. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111594. private_state *b=(private_state*)v->backend_state;
  111595. vorbis_look_psy_global *g=b->psy_g_look;
  111596. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111597. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111598. /* check to see if we're started... */
  111599. if(!v->preextrapolate)return(0);
  111600. /* check to see if we're done... */
  111601. if(v->eofflag==-1)return(0);
  111602. /* By our invariant, we have lW, W and centerW set. Search for
  111603. the next boundary so we can determine nW (the next window size)
  111604. which lets us compute the shape of the current block's window */
  111605. /* we do an envelope search even on a single blocksize; we may still
  111606. be throwing more bits at impulses, and envelope search handles
  111607. marking impulses too. */
  111608. {
  111609. long bp=_ve_envelope_search(v);
  111610. if(bp==-1){
  111611. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111612. full long block */
  111613. v->nW=0;
  111614. }else{
  111615. if(ci->blocksizes[0]==ci->blocksizes[1])
  111616. v->nW=0;
  111617. else
  111618. v->nW=bp;
  111619. }
  111620. }
  111621. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111622. {
  111623. /* center of next block + next block maximum right side. */
  111624. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111625. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111626. although this check is
  111627. less strict that the
  111628. _ve_envelope_search,
  111629. the search is not run
  111630. if we only use one
  111631. block size */
  111632. }
  111633. /* fill in the block. Note that for a short window, lW and nW are *short*
  111634. regardless of actual settings in the stream */
  111635. _vorbis_block_ripcord(vb);
  111636. vb->lW=v->lW;
  111637. vb->W=v->W;
  111638. vb->nW=v->nW;
  111639. if(v->W){
  111640. if(!v->lW || !v->nW){
  111641. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111642. /*fprintf(stderr,"-");*/
  111643. }else{
  111644. vbi->blocktype=BLOCKTYPE_LONG;
  111645. /*fprintf(stderr,"_");*/
  111646. }
  111647. }else{
  111648. if(_ve_envelope_mark(v)){
  111649. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111650. /*fprintf(stderr,"|");*/
  111651. }else{
  111652. vbi->blocktype=BLOCKTYPE_PADDING;
  111653. /*fprintf(stderr,".");*/
  111654. }
  111655. }
  111656. vb->vd=v;
  111657. vb->sequence=v->sequence++;
  111658. vb->granulepos=v->granulepos;
  111659. vb->pcmend=ci->blocksizes[v->W];
  111660. /* copy the vectors; this uses the local storage in vb */
  111661. /* this tracks 'strongest peak' for later psychoacoustics */
  111662. /* moved to the global psy state; clean this mess up */
  111663. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111664. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111665. vbi->ampmax=g->ampmax;
  111666. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111667. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111668. for(i=0;i<vi->channels;i++){
  111669. vbi->pcmdelay[i]=
  111670. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111671. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111672. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111673. /* before we added the delay
  111674. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111675. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111676. */
  111677. }
  111678. /* handle eof detection: eof==0 means that we've not yet received EOF
  111679. eof>0 marks the last 'real' sample in pcm[]
  111680. eof<0 'no more to do'; doesn't get here */
  111681. if(v->eofflag){
  111682. if(v->centerW>=v->eofflag){
  111683. v->eofflag=-1;
  111684. vb->eofflag=1;
  111685. return(1);
  111686. }
  111687. }
  111688. /* advance storage vectors and clean up */
  111689. {
  111690. int new_centerNext=ci->blocksizes[1]/2;
  111691. int movementW=centerNext-new_centerNext;
  111692. if(movementW>0){
  111693. _ve_envelope_shift(b->ve,movementW);
  111694. v->pcm_current-=movementW;
  111695. for(i=0;i<vi->channels;i++)
  111696. memmove(v->pcm[i],v->pcm[i]+movementW,
  111697. v->pcm_current*sizeof(*v->pcm[i]));
  111698. v->lW=v->W;
  111699. v->W=v->nW;
  111700. v->centerW=new_centerNext;
  111701. if(v->eofflag){
  111702. v->eofflag-=movementW;
  111703. if(v->eofflag<=0)v->eofflag=-1;
  111704. /* do not add padding to end of stream! */
  111705. if(v->centerW>=v->eofflag){
  111706. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111707. }else{
  111708. v->granulepos+=movementW;
  111709. }
  111710. }else{
  111711. v->granulepos+=movementW;
  111712. }
  111713. }
  111714. }
  111715. /* done */
  111716. return(1);
  111717. }
  111718. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111719. vorbis_info *vi=v->vi;
  111720. codec_setup_info *ci;
  111721. int hs;
  111722. if(!v->backend_state)return -1;
  111723. if(!vi)return -1;
  111724. ci=(codec_setup_info*) vi->codec_setup;
  111725. if(!ci)return -1;
  111726. hs=ci->halfrate_flag;
  111727. v->centerW=ci->blocksizes[1]>>(hs+1);
  111728. v->pcm_current=v->centerW>>hs;
  111729. v->pcm_returned=-1;
  111730. v->granulepos=-1;
  111731. v->sequence=-1;
  111732. v->eofflag=0;
  111733. ((private_state *)(v->backend_state))->sample_count=-1;
  111734. return(0);
  111735. }
  111736. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111737. if(_vds_shared_init(v,vi,0)) return 1;
  111738. vorbis_synthesis_restart(v);
  111739. return 0;
  111740. }
  111741. /* Unlike in analysis, the window is only partially applied for each
  111742. block. The time domain envelope is not yet handled at the point of
  111743. calling (as it relies on the previous block). */
  111744. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111745. vorbis_info *vi=v->vi;
  111746. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111747. private_state *b=(private_state*)v->backend_state;
  111748. int hs=ci->halfrate_flag;
  111749. int i,j;
  111750. if(!vb)return(OV_EINVAL);
  111751. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111752. v->lW=v->W;
  111753. v->W=vb->W;
  111754. v->nW=-1;
  111755. if((v->sequence==-1)||
  111756. (v->sequence+1 != vb->sequence)){
  111757. v->granulepos=-1; /* out of sequence; lose count */
  111758. b->sample_count=-1;
  111759. }
  111760. v->sequence=vb->sequence;
  111761. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111762. was called on block */
  111763. int n=ci->blocksizes[v->W]>>(hs+1);
  111764. int n0=ci->blocksizes[0]>>(hs+1);
  111765. int n1=ci->blocksizes[1]>>(hs+1);
  111766. int thisCenter;
  111767. int prevCenter;
  111768. v->glue_bits+=vb->glue_bits;
  111769. v->time_bits+=vb->time_bits;
  111770. v->floor_bits+=vb->floor_bits;
  111771. v->res_bits+=vb->res_bits;
  111772. if(v->centerW){
  111773. thisCenter=n1;
  111774. prevCenter=0;
  111775. }else{
  111776. thisCenter=0;
  111777. prevCenter=n1;
  111778. }
  111779. /* v->pcm is now used like a two-stage double buffer. We don't want
  111780. to have to constantly shift *or* adjust memory usage. Don't
  111781. accept a new block until the old is shifted out */
  111782. for(j=0;j<vi->channels;j++){
  111783. /* the overlap/add section */
  111784. if(v->lW){
  111785. if(v->W){
  111786. /* large/large */
  111787. float *w=_vorbis_window_get(b->window[1]-hs);
  111788. float *pcm=v->pcm[j]+prevCenter;
  111789. float *p=vb->pcm[j];
  111790. for(i=0;i<n1;i++)
  111791. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111792. }else{
  111793. /* large/small */
  111794. float *w=_vorbis_window_get(b->window[0]-hs);
  111795. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111796. float *p=vb->pcm[j];
  111797. for(i=0;i<n0;i++)
  111798. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111799. }
  111800. }else{
  111801. if(v->W){
  111802. /* small/large */
  111803. float *w=_vorbis_window_get(b->window[0]-hs);
  111804. float *pcm=v->pcm[j]+prevCenter;
  111805. float *p=vb->pcm[j]+n1/2-n0/2;
  111806. for(i=0;i<n0;i++)
  111807. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111808. for(;i<n1/2+n0/2;i++)
  111809. pcm[i]=p[i];
  111810. }else{
  111811. /* small/small */
  111812. float *w=_vorbis_window_get(b->window[0]-hs);
  111813. float *pcm=v->pcm[j]+prevCenter;
  111814. float *p=vb->pcm[j];
  111815. for(i=0;i<n0;i++)
  111816. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111817. }
  111818. }
  111819. /* the copy section */
  111820. {
  111821. float *pcm=v->pcm[j]+thisCenter;
  111822. float *p=vb->pcm[j]+n;
  111823. for(i=0;i<n;i++)
  111824. pcm[i]=p[i];
  111825. }
  111826. }
  111827. if(v->centerW)
  111828. v->centerW=0;
  111829. else
  111830. v->centerW=n1;
  111831. /* deal with initial packet state; we do this using the explicit
  111832. pcm_returned==-1 flag otherwise we're sensitive to first block
  111833. being short or long */
  111834. if(v->pcm_returned==-1){
  111835. v->pcm_returned=thisCenter;
  111836. v->pcm_current=thisCenter;
  111837. }else{
  111838. v->pcm_returned=prevCenter;
  111839. v->pcm_current=prevCenter+
  111840. ((ci->blocksizes[v->lW]/4+
  111841. ci->blocksizes[v->W]/4)>>hs);
  111842. }
  111843. }
  111844. /* track the frame number... This is for convenience, but also
  111845. making sure our last packet doesn't end with added padding. If
  111846. the last packet is partial, the number of samples we'll have to
  111847. return will be past the vb->granulepos.
  111848. This is not foolproof! It will be confused if we begin
  111849. decoding at the last page after a seek or hole. In that case,
  111850. we don't have a starting point to judge where the last frame
  111851. is. For this reason, vorbisfile will always try to make sure
  111852. it reads the last two marked pages in proper sequence */
  111853. if(b->sample_count==-1){
  111854. b->sample_count=0;
  111855. }else{
  111856. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111857. }
  111858. if(v->granulepos==-1){
  111859. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111860. v->granulepos=vb->granulepos;
  111861. /* is this a short page? */
  111862. if(b->sample_count>v->granulepos){
  111863. /* corner case; if this is both the first and last audio page,
  111864. then spec says the end is cut, not beginning */
  111865. if(vb->eofflag){
  111866. /* trim the end */
  111867. /* no preceeding granulepos; assume we started at zero (we'd
  111868. have to in a short single-page stream) */
  111869. /* granulepos could be -1 due to a seek, but that would result
  111870. in a long count, not short count */
  111871. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111872. }else{
  111873. /* trim the beginning */
  111874. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111875. if(v->pcm_returned>v->pcm_current)
  111876. v->pcm_returned=v->pcm_current;
  111877. }
  111878. }
  111879. }
  111880. }else{
  111881. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111882. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111883. if(v->granulepos>vb->granulepos){
  111884. long extra=v->granulepos-vb->granulepos;
  111885. if(extra)
  111886. if(vb->eofflag){
  111887. /* partial last frame. Strip the extra samples off */
  111888. v->pcm_current-=extra>>hs;
  111889. } /* else {Shouldn't happen *unless* the bitstream is out of
  111890. spec. Either way, believe the bitstream } */
  111891. } /* else {Shouldn't happen *unless* the bitstream is out of
  111892. spec. Either way, believe the bitstream } */
  111893. v->granulepos=vb->granulepos;
  111894. }
  111895. }
  111896. /* Update, cleanup */
  111897. if(vb->eofflag)v->eofflag=1;
  111898. return(0);
  111899. }
  111900. /* pcm==NULL indicates we just want the pending samples, no more */
  111901. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111902. vorbis_info *vi=v->vi;
  111903. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111904. if(pcm){
  111905. int i;
  111906. for(i=0;i<vi->channels;i++)
  111907. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111908. *pcm=v->pcmret;
  111909. }
  111910. return(v->pcm_current-v->pcm_returned);
  111911. }
  111912. return(0);
  111913. }
  111914. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111915. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111916. v->pcm_returned+=n;
  111917. return(0);
  111918. }
  111919. /* intended for use with a specific vorbisfile feature; we want access
  111920. to the [usually synthetic/postextrapolated] buffer and lapping at
  111921. the end of a decode cycle, specifically, a half-short-block worth.
  111922. This funtion works like pcmout above, except it will also expose
  111923. this implicit buffer data not normally decoded. */
  111924. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111925. vorbis_info *vi=v->vi;
  111926. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111927. int hs=ci->halfrate_flag;
  111928. int n=ci->blocksizes[v->W]>>(hs+1);
  111929. int n0=ci->blocksizes[0]>>(hs+1);
  111930. int n1=ci->blocksizes[1]>>(hs+1);
  111931. int i,j;
  111932. if(v->pcm_returned<0)return 0;
  111933. /* our returned data ends at pcm_returned; because the synthesis pcm
  111934. buffer is a two-fragment ring, that means our data block may be
  111935. fragmented by buffering, wrapping or a short block not filling
  111936. out a buffer. To simplify things, we unfragment if it's at all
  111937. possibly needed. Otherwise, we'd need to call lapout more than
  111938. once as well as hold additional dsp state. Opt for
  111939. simplicity. */
  111940. /* centerW was advanced by blockin; it would be the center of the
  111941. *next* block */
  111942. if(v->centerW==n1){
  111943. /* the data buffer wraps; swap the halves */
  111944. /* slow, sure, small */
  111945. for(j=0;j<vi->channels;j++){
  111946. float *p=v->pcm[j];
  111947. for(i=0;i<n1;i++){
  111948. float temp=p[i];
  111949. p[i]=p[i+n1];
  111950. p[i+n1]=temp;
  111951. }
  111952. }
  111953. v->pcm_current-=n1;
  111954. v->pcm_returned-=n1;
  111955. v->centerW=0;
  111956. }
  111957. /* solidify buffer into contiguous space */
  111958. if((v->lW^v->W)==1){
  111959. /* long/short or short/long */
  111960. for(j=0;j<vi->channels;j++){
  111961. float *s=v->pcm[j];
  111962. float *d=v->pcm[j]+(n1-n0)/2;
  111963. for(i=(n1+n0)/2-1;i>=0;--i)
  111964. d[i]=s[i];
  111965. }
  111966. v->pcm_returned+=(n1-n0)/2;
  111967. v->pcm_current+=(n1-n0)/2;
  111968. }else{
  111969. if(v->lW==0){
  111970. /* short/short */
  111971. for(j=0;j<vi->channels;j++){
  111972. float *s=v->pcm[j];
  111973. float *d=v->pcm[j]+n1-n0;
  111974. for(i=n0-1;i>=0;--i)
  111975. d[i]=s[i];
  111976. }
  111977. v->pcm_returned+=n1-n0;
  111978. v->pcm_current+=n1-n0;
  111979. }
  111980. }
  111981. if(pcm){
  111982. int i;
  111983. for(i=0;i<vi->channels;i++)
  111984. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111985. *pcm=v->pcmret;
  111986. }
  111987. return(n1+n-v->pcm_returned);
  111988. }
  111989. float *vorbis_window(vorbis_dsp_state *v,int W){
  111990. vorbis_info *vi=v->vi;
  111991. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111992. int hs=ci->halfrate_flag;
  111993. private_state *b=(private_state*)v->backend_state;
  111994. if(b->window[W]-1<0)return NULL;
  111995. return _vorbis_window_get(b->window[W]-hs);
  111996. }
  111997. #endif
  111998. /*** End of inlined file: block.c ***/
  111999. /*** Start of inlined file: codebook.c ***/
  112000. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112001. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112002. // tasks..
  112003. #if JUCE_MSVC
  112004. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112005. #endif
  112006. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112007. #if JUCE_USE_OGGVORBIS
  112008. #include <stdlib.h>
  112009. #include <string.h>
  112010. #include <math.h>
  112011. /* packs the given codebook into the bitstream **************************/
  112012. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  112013. long i,j;
  112014. int ordered=0;
  112015. /* first the basic parameters */
  112016. oggpack_write(opb,0x564342,24);
  112017. oggpack_write(opb,c->dim,16);
  112018. oggpack_write(opb,c->entries,24);
  112019. /* pack the codewords. There are two packings; length ordered and
  112020. length random. Decide between the two now. */
  112021. for(i=1;i<c->entries;i++)
  112022. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  112023. if(i==c->entries)ordered=1;
  112024. if(ordered){
  112025. /* length ordered. We only need to say how many codewords of
  112026. each length. The actual codewords are generated
  112027. deterministically */
  112028. long count=0;
  112029. oggpack_write(opb,1,1); /* ordered */
  112030. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  112031. for(i=1;i<c->entries;i++){
  112032. long thisx=c->lengthlist[i];
  112033. long last=c->lengthlist[i-1];
  112034. if(thisx>last){
  112035. for(j=last;j<thisx;j++){
  112036. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112037. count=i;
  112038. }
  112039. }
  112040. }
  112041. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112042. }else{
  112043. /* length random. Again, we don't code the codeword itself, just
  112044. the length. This time, though, we have to encode each length */
  112045. oggpack_write(opb,0,1); /* unordered */
  112046. /* algortihmic mapping has use for 'unused entries', which we tag
  112047. here. The algorithmic mapping happens as usual, but the unused
  112048. entry has no codeword. */
  112049. for(i=0;i<c->entries;i++)
  112050. if(c->lengthlist[i]==0)break;
  112051. if(i==c->entries){
  112052. oggpack_write(opb,0,1); /* no unused entries */
  112053. for(i=0;i<c->entries;i++)
  112054. oggpack_write(opb,c->lengthlist[i]-1,5);
  112055. }else{
  112056. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  112057. for(i=0;i<c->entries;i++){
  112058. if(c->lengthlist[i]==0){
  112059. oggpack_write(opb,0,1);
  112060. }else{
  112061. oggpack_write(opb,1,1);
  112062. oggpack_write(opb,c->lengthlist[i]-1,5);
  112063. }
  112064. }
  112065. }
  112066. }
  112067. /* is the entry number the desired return value, or do we have a
  112068. mapping? If we have a mapping, what type? */
  112069. oggpack_write(opb,c->maptype,4);
  112070. switch(c->maptype){
  112071. case 0:
  112072. /* no mapping */
  112073. break;
  112074. case 1:case 2:
  112075. /* implicitly populated value mapping */
  112076. /* explicitly populated value mapping */
  112077. if(!c->quantlist){
  112078. /* no quantlist? error */
  112079. return(-1);
  112080. }
  112081. /* values that define the dequantization */
  112082. oggpack_write(opb,c->q_min,32);
  112083. oggpack_write(opb,c->q_delta,32);
  112084. oggpack_write(opb,c->q_quant-1,4);
  112085. oggpack_write(opb,c->q_sequencep,1);
  112086. {
  112087. int quantvals;
  112088. switch(c->maptype){
  112089. case 1:
  112090. /* a single column of (c->entries/c->dim) quantized values for
  112091. building a full value list algorithmically (square lattice) */
  112092. quantvals=_book_maptype1_quantvals(c);
  112093. break;
  112094. case 2:
  112095. /* every value (c->entries*c->dim total) specified explicitly */
  112096. quantvals=c->entries*c->dim;
  112097. break;
  112098. default: /* NOT_REACHABLE */
  112099. quantvals=-1;
  112100. }
  112101. /* quantized values */
  112102. for(i=0;i<quantvals;i++)
  112103. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  112104. }
  112105. break;
  112106. default:
  112107. /* error case; we don't have any other map types now */
  112108. return(-1);
  112109. }
  112110. return(0);
  112111. }
  112112. /* unpacks a codebook from the packet buffer into the codebook struct,
  112113. readies the codebook auxiliary structures for decode *************/
  112114. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  112115. long i,j;
  112116. memset(s,0,sizeof(*s));
  112117. s->allocedp=1;
  112118. /* make sure alignment is correct */
  112119. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  112120. /* first the basic parameters */
  112121. s->dim=oggpack_read(opb,16);
  112122. s->entries=oggpack_read(opb,24);
  112123. if(s->entries==-1)goto _eofout;
  112124. /* codeword ordering.... length ordered or unordered? */
  112125. switch((int)oggpack_read(opb,1)){
  112126. case 0:
  112127. /* unordered */
  112128. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112129. /* allocated but unused entries? */
  112130. if(oggpack_read(opb,1)){
  112131. /* yes, unused entries */
  112132. for(i=0;i<s->entries;i++){
  112133. if(oggpack_read(opb,1)){
  112134. long num=oggpack_read(opb,5);
  112135. if(num==-1)goto _eofout;
  112136. s->lengthlist[i]=num+1;
  112137. }else
  112138. s->lengthlist[i]=0;
  112139. }
  112140. }else{
  112141. /* all entries used; no tagging */
  112142. for(i=0;i<s->entries;i++){
  112143. long num=oggpack_read(opb,5);
  112144. if(num==-1)goto _eofout;
  112145. s->lengthlist[i]=num+1;
  112146. }
  112147. }
  112148. break;
  112149. case 1:
  112150. /* ordered */
  112151. {
  112152. long length=oggpack_read(opb,5)+1;
  112153. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112154. for(i=0;i<s->entries;){
  112155. long num=oggpack_read(opb,_ilog(s->entries-i));
  112156. if(num==-1)goto _eofout;
  112157. for(j=0;j<num && i<s->entries;j++,i++)
  112158. s->lengthlist[i]=length;
  112159. length++;
  112160. }
  112161. }
  112162. break;
  112163. default:
  112164. /* EOF */
  112165. return(-1);
  112166. }
  112167. /* Do we have a mapping to unpack? */
  112168. switch((s->maptype=oggpack_read(opb,4))){
  112169. case 0:
  112170. /* no mapping */
  112171. break;
  112172. case 1: case 2:
  112173. /* implicitly populated value mapping */
  112174. /* explicitly populated value mapping */
  112175. s->q_min=oggpack_read(opb,32);
  112176. s->q_delta=oggpack_read(opb,32);
  112177. s->q_quant=oggpack_read(opb,4)+1;
  112178. s->q_sequencep=oggpack_read(opb,1);
  112179. {
  112180. int quantvals=0;
  112181. switch(s->maptype){
  112182. case 1:
  112183. quantvals=_book_maptype1_quantvals(s);
  112184. break;
  112185. case 2:
  112186. quantvals=s->entries*s->dim;
  112187. break;
  112188. }
  112189. /* quantized values */
  112190. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112191. for(i=0;i<quantvals;i++)
  112192. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112193. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112194. }
  112195. break;
  112196. default:
  112197. goto _errout;
  112198. }
  112199. /* all set */
  112200. return(0);
  112201. _errout:
  112202. _eofout:
  112203. vorbis_staticbook_clear(s);
  112204. return(-1);
  112205. }
  112206. /* returns the number of bits ************************************************/
  112207. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112208. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112209. return(book->c->lengthlist[a]);
  112210. }
  112211. /* One the encode side, our vector writers are each designed for a
  112212. specific purpose, and the encoder is not flexible without modification:
  112213. The LSP vector coder uses a single stage nearest-match with no
  112214. interleave, so no step and no error return. This is specced by floor0
  112215. and doesn't change.
  112216. Residue0 encoding interleaves, uses multiple stages, and each stage
  112217. peels of a specific amount of resolution from a lattice (thus we want
  112218. to match by threshold, not nearest match). Residue doesn't *have* to
  112219. be encoded that way, but to change it, one will need to add more
  112220. infrastructure on the encode side (decode side is specced and simpler) */
  112221. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112222. /* returns entry number and *modifies a* to the quantization value *****/
  112223. int vorbis_book_errorv(codebook *book,float *a){
  112224. int dim=book->dim,k;
  112225. int best=_best(book,a,1);
  112226. for(k=0;k<dim;k++)
  112227. a[k]=(book->valuelist+best*dim)[k];
  112228. return(best);
  112229. }
  112230. /* returns the number of bits and *modifies a* to the quantization value *****/
  112231. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112232. int k,dim=book->dim;
  112233. for(k=0;k<dim;k++)
  112234. a[k]=(book->valuelist+best*dim)[k];
  112235. return(vorbis_book_encode(book,best,b));
  112236. }
  112237. /* the 'eliminate the decode tree' optimization actually requires the
  112238. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112239. (and one of the first places where carefully thought out design
  112240. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112241. to an MSb bitpacker), but not actually the huge hit it appears to
  112242. be. The first-stage decode table catches most words so that
  112243. bitreverse is not in the main execution path. */
  112244. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112245. int read=book->dec_maxlength;
  112246. long lo,hi;
  112247. long lok = oggpack_look(b,book->dec_firsttablen);
  112248. if (lok >= 0) {
  112249. long entry = book->dec_firsttable[lok];
  112250. if(entry&0x80000000UL){
  112251. lo=(entry>>15)&0x7fff;
  112252. hi=book->used_entries-(entry&0x7fff);
  112253. }else{
  112254. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112255. return(entry-1);
  112256. }
  112257. }else{
  112258. lo=0;
  112259. hi=book->used_entries;
  112260. }
  112261. lok = oggpack_look(b, read);
  112262. while(lok<0 && read>1)
  112263. lok = oggpack_look(b, --read);
  112264. if(lok<0)return -1;
  112265. /* bisect search for the codeword in the ordered list */
  112266. {
  112267. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112268. while(hi-lo>1){
  112269. long p=(hi-lo)>>1;
  112270. long test=book->codelist[lo+p]>testword;
  112271. lo+=p&(test-1);
  112272. hi-=p&(-test);
  112273. }
  112274. if(book->dec_codelengths[lo]<=read){
  112275. oggpack_adv(b, book->dec_codelengths[lo]);
  112276. return(lo);
  112277. }
  112278. }
  112279. oggpack_adv(b, read);
  112280. return(-1);
  112281. }
  112282. /* Decode side is specced and easier, because we don't need to find
  112283. matches using different criteria; we simply read and map. There are
  112284. two things we need to do 'depending':
  112285. We may need to support interleave. We don't really, but it's
  112286. convenient to do it here rather than rebuild the vector later.
  112287. Cascades may be additive or multiplicitive; this is not inherent in
  112288. the codebook, but set in the code using the codebook. Like
  112289. interleaving, it's easiest to do it here.
  112290. addmul==0 -> declarative (set the value)
  112291. addmul==1 -> additive
  112292. addmul==2 -> multiplicitive */
  112293. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112294. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112295. long packed_entry=decode_packed_entry_number(book,b);
  112296. if(packed_entry>=0)
  112297. return(book->dec_index[packed_entry]);
  112298. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112299. return(packed_entry);
  112300. }
  112301. /* returns 0 on OK or -1 on eof *************************************/
  112302. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112303. int step=n/book->dim;
  112304. long *entry = (long*)alloca(sizeof(*entry)*step);
  112305. float **t = (float**)alloca(sizeof(*t)*step);
  112306. int i,j,o;
  112307. for (i = 0; i < step; i++) {
  112308. entry[i]=decode_packed_entry_number(book,b);
  112309. if(entry[i]==-1)return(-1);
  112310. t[i] = book->valuelist+entry[i]*book->dim;
  112311. }
  112312. for(i=0,o=0;i<book->dim;i++,o+=step)
  112313. for (j=0;j<step;j++)
  112314. a[o+j]+=t[j][i];
  112315. return(0);
  112316. }
  112317. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112318. int i,j,entry;
  112319. float *t;
  112320. if(book->dim>8){
  112321. for(i=0;i<n;){
  112322. entry = decode_packed_entry_number(book,b);
  112323. if(entry==-1)return(-1);
  112324. t = book->valuelist+entry*book->dim;
  112325. for (j=0;j<book->dim;)
  112326. a[i++]+=t[j++];
  112327. }
  112328. }else{
  112329. for(i=0;i<n;){
  112330. entry = decode_packed_entry_number(book,b);
  112331. if(entry==-1)return(-1);
  112332. t = book->valuelist+entry*book->dim;
  112333. j=0;
  112334. switch((int)book->dim){
  112335. case 8:
  112336. a[i++]+=t[j++];
  112337. case 7:
  112338. a[i++]+=t[j++];
  112339. case 6:
  112340. a[i++]+=t[j++];
  112341. case 5:
  112342. a[i++]+=t[j++];
  112343. case 4:
  112344. a[i++]+=t[j++];
  112345. case 3:
  112346. a[i++]+=t[j++];
  112347. case 2:
  112348. a[i++]+=t[j++];
  112349. case 1:
  112350. a[i++]+=t[j++];
  112351. case 0:
  112352. break;
  112353. }
  112354. }
  112355. }
  112356. return(0);
  112357. }
  112358. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112359. int i,j,entry;
  112360. float *t;
  112361. for(i=0;i<n;){
  112362. entry = decode_packed_entry_number(book,b);
  112363. if(entry==-1)return(-1);
  112364. t = book->valuelist+entry*book->dim;
  112365. for (j=0;j<book->dim;)
  112366. a[i++]=t[j++];
  112367. }
  112368. return(0);
  112369. }
  112370. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112371. oggpack_buffer *b,int n){
  112372. long i,j,entry;
  112373. int chptr=0;
  112374. for(i=offset/ch;i<(offset+n)/ch;){
  112375. entry = decode_packed_entry_number(book,b);
  112376. if(entry==-1)return(-1);
  112377. {
  112378. const float *t = book->valuelist+entry*book->dim;
  112379. for (j=0;j<book->dim;j++){
  112380. a[chptr++][i]+=t[j];
  112381. if(chptr==ch){
  112382. chptr=0;
  112383. i++;
  112384. }
  112385. }
  112386. }
  112387. }
  112388. return(0);
  112389. }
  112390. #ifdef _V_SELFTEST
  112391. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112392. number of vectors through (keeping track of the quantized values),
  112393. and decode using the unpacked book. quantized version of in should
  112394. exactly equal out */
  112395. #include <stdio.h>
  112396. #include "vorbis/book/lsp20_0.vqh"
  112397. #include "vorbis/book/res0a_13.vqh"
  112398. #define TESTSIZE 40
  112399. float test1[TESTSIZE]={
  112400. 0.105939f,
  112401. 0.215373f,
  112402. 0.429117f,
  112403. 0.587974f,
  112404. 0.181173f,
  112405. 0.296583f,
  112406. 0.515707f,
  112407. 0.715261f,
  112408. 0.162327f,
  112409. 0.263834f,
  112410. 0.342876f,
  112411. 0.406025f,
  112412. 0.103571f,
  112413. 0.223561f,
  112414. 0.368513f,
  112415. 0.540313f,
  112416. 0.136672f,
  112417. 0.395882f,
  112418. 0.587183f,
  112419. 0.652476f,
  112420. 0.114338f,
  112421. 0.417300f,
  112422. 0.525486f,
  112423. 0.698679f,
  112424. 0.147492f,
  112425. 0.324481f,
  112426. 0.643089f,
  112427. 0.757582f,
  112428. 0.139556f,
  112429. 0.215795f,
  112430. 0.324559f,
  112431. 0.399387f,
  112432. 0.120236f,
  112433. 0.267420f,
  112434. 0.446940f,
  112435. 0.608760f,
  112436. 0.115587f,
  112437. 0.287234f,
  112438. 0.571081f,
  112439. 0.708603f,
  112440. };
  112441. float test3[TESTSIZE]={
  112442. 0,1,-2,3,4,-5,6,7,8,9,
  112443. 8,-2,7,-1,4,6,8,3,1,-9,
  112444. 10,11,12,13,14,15,26,17,18,19,
  112445. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112446. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112447. &_vq_book_res0a_13,NULL};
  112448. float *testvec[]={test1,test3};
  112449. int main(){
  112450. oggpack_buffer write;
  112451. oggpack_buffer read;
  112452. long ptr=0,i;
  112453. oggpack_writeinit(&write);
  112454. fprintf(stderr,"Testing codebook abstraction...:\n");
  112455. while(testlist[ptr]){
  112456. codebook c;
  112457. static_codebook s;
  112458. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112459. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112460. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112461. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112462. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112463. /* pack the codebook, write the testvector */
  112464. oggpack_reset(&write);
  112465. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112466. we can write */
  112467. vorbis_staticbook_pack(testlist[ptr],&write);
  112468. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112469. for(i=0;i<TESTSIZE;i+=c.dim){
  112470. int best=_best(&c,qv+i,1);
  112471. vorbis_book_encodev(&c,best,qv+i,&write);
  112472. }
  112473. vorbis_book_clear(&c);
  112474. fprintf(stderr,"OK.\n");
  112475. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112476. /* transfer the write data to a read buffer and unpack/read */
  112477. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112478. if(vorbis_staticbook_unpack(&read,&s)){
  112479. fprintf(stderr,"Error unpacking codebook.\n");
  112480. exit(1);
  112481. }
  112482. if(vorbis_book_init_decode(&c,&s)){
  112483. fprintf(stderr,"Error initializing codebook.\n");
  112484. exit(1);
  112485. }
  112486. for(i=0;i<TESTSIZE;i+=c.dim)
  112487. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112488. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112489. exit(1);
  112490. }
  112491. for(i=0;i<TESTSIZE;i++)
  112492. if(fabs(qv[i]-iv[i])>.000001){
  112493. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112494. iv[i],qv[i],i);
  112495. exit(1);
  112496. }
  112497. fprintf(stderr,"OK\n");
  112498. ptr++;
  112499. }
  112500. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112501. exit(0);
  112502. }
  112503. #endif
  112504. #endif
  112505. /*** End of inlined file: codebook.c ***/
  112506. /*** Start of inlined file: envelope.c ***/
  112507. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112508. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112509. // tasks..
  112510. #if JUCE_MSVC
  112511. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112512. #endif
  112513. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112514. #if JUCE_USE_OGGVORBIS
  112515. #include <stdlib.h>
  112516. #include <string.h>
  112517. #include <stdio.h>
  112518. #include <math.h>
  112519. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112520. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112521. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112522. int ch=vi->channels;
  112523. int i,j;
  112524. int n=e->winlength=128;
  112525. e->searchstep=64; /* not random */
  112526. e->minenergy=gi->preecho_minenergy;
  112527. e->ch=ch;
  112528. e->storage=128;
  112529. e->cursor=ci->blocksizes[1]/2;
  112530. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112531. mdct_init(&e->mdct,n);
  112532. for(i=0;i<n;i++){
  112533. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112534. e->mdct_win[i]*=e->mdct_win[i];
  112535. }
  112536. /* magic follows */
  112537. e->band[0].begin=2; e->band[0].end=4;
  112538. e->band[1].begin=4; e->band[1].end=5;
  112539. e->band[2].begin=6; e->band[2].end=6;
  112540. e->band[3].begin=9; e->band[3].end=8;
  112541. e->band[4].begin=13; e->band[4].end=8;
  112542. e->band[5].begin=17; e->band[5].end=8;
  112543. e->band[6].begin=22; e->band[6].end=8;
  112544. for(j=0;j<VE_BANDS;j++){
  112545. n=e->band[j].end;
  112546. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112547. for(i=0;i<n;i++){
  112548. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112549. e->band[j].total+=e->band[j].window[i];
  112550. }
  112551. e->band[j].total=1./e->band[j].total;
  112552. }
  112553. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112554. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112555. }
  112556. void _ve_envelope_clear(envelope_lookup *e){
  112557. int i;
  112558. mdct_clear(&e->mdct);
  112559. for(i=0;i<VE_BANDS;i++)
  112560. _ogg_free(e->band[i].window);
  112561. _ogg_free(e->mdct_win);
  112562. _ogg_free(e->filter);
  112563. _ogg_free(e->mark);
  112564. memset(e,0,sizeof(*e));
  112565. }
  112566. /* fairly straight threshhold-by-band based until we find something
  112567. that works better and isn't patented. */
  112568. static int _ve_amp(envelope_lookup *ve,
  112569. vorbis_info_psy_global *gi,
  112570. float *data,
  112571. envelope_band *bands,
  112572. envelope_filter_state *filters,
  112573. long pos){
  112574. long n=ve->winlength;
  112575. int ret=0;
  112576. long i,j;
  112577. float decay;
  112578. /* we want to have a 'minimum bar' for energy, else we're just
  112579. basing blocks on quantization noise that outweighs the signal
  112580. itself (for low power signals) */
  112581. float minV=ve->minenergy;
  112582. float *vec=(float*) alloca(n*sizeof(*vec));
  112583. /* stretch is used to gradually lengthen the number of windows
  112584. considered prevoius-to-potential-trigger */
  112585. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112586. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112587. if(penalty<0.f)penalty=0.f;
  112588. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112589. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112590. totalshift+pos*ve->searchstep);*/
  112591. /* window and transform */
  112592. for(i=0;i<n;i++)
  112593. vec[i]=data[i]*ve->mdct_win[i];
  112594. mdct_forward(&ve->mdct,vec,vec);
  112595. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112596. /* near-DC spreading function; this has nothing to do with
  112597. psychoacoustics, just sidelobe leakage and window size */
  112598. {
  112599. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112600. int ptr=filters->nearptr;
  112601. /* the accumulation is regularly refreshed from scratch to avoid
  112602. floating point creep */
  112603. if(ptr==0){
  112604. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112605. filters->nearDC_partialacc=temp;
  112606. }else{
  112607. decay=filters->nearDC_acc+=temp;
  112608. filters->nearDC_partialacc+=temp;
  112609. }
  112610. filters->nearDC_acc-=filters->nearDC[ptr];
  112611. filters->nearDC[ptr]=temp;
  112612. decay*=(1./(VE_NEARDC+1));
  112613. filters->nearptr++;
  112614. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112615. decay=todB(&decay)*.5-15.f;
  112616. }
  112617. /* perform spreading and limiting, also smooth the spectrum. yes,
  112618. the MDCT results in all real coefficients, but it still *behaves*
  112619. like real/imaginary pairs */
  112620. for(i=0;i<n/2;i+=2){
  112621. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112622. val=todB(&val)*.5f;
  112623. if(val<decay)val=decay;
  112624. if(val<minV)val=minV;
  112625. vec[i>>1]=val;
  112626. decay-=8.;
  112627. }
  112628. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112629. /* perform preecho/postecho triggering by band */
  112630. for(j=0;j<VE_BANDS;j++){
  112631. float acc=0.;
  112632. float valmax,valmin;
  112633. /* accumulate amplitude */
  112634. for(i=0;i<bands[j].end;i++)
  112635. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112636. acc*=bands[j].total;
  112637. /* convert amplitude to delta */
  112638. {
  112639. int p,thisx=filters[j].ampptr;
  112640. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112641. p=thisx;
  112642. p--;
  112643. if(p<0)p+=VE_AMP;
  112644. postmax=max(acc,filters[j].ampbuf[p]);
  112645. postmin=min(acc,filters[j].ampbuf[p]);
  112646. for(i=0;i<stretch;i++){
  112647. p--;
  112648. if(p<0)p+=VE_AMP;
  112649. premax=max(premax,filters[j].ampbuf[p]);
  112650. premin=min(premin,filters[j].ampbuf[p]);
  112651. }
  112652. valmin=postmin-premin;
  112653. valmax=postmax-premax;
  112654. /*filters[j].markers[pos]=valmax;*/
  112655. filters[j].ampbuf[thisx]=acc;
  112656. filters[j].ampptr++;
  112657. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112658. }
  112659. /* look at min/max, decide trigger */
  112660. if(valmax>gi->preecho_thresh[j]+penalty){
  112661. ret|=1;
  112662. ret|=4;
  112663. }
  112664. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112665. }
  112666. return(ret);
  112667. }
  112668. #if 0
  112669. static int seq=0;
  112670. static ogg_int64_t totalshift=-1024;
  112671. #endif
  112672. long _ve_envelope_search(vorbis_dsp_state *v){
  112673. vorbis_info *vi=v->vi;
  112674. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112675. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112676. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112677. long i,j;
  112678. int first=ve->current/ve->searchstep;
  112679. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112680. if(first<0)first=0;
  112681. /* make sure we have enough storage to match the PCM */
  112682. if(last+VE_WIN+VE_POST>ve->storage){
  112683. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112684. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112685. }
  112686. for(j=first;j<last;j++){
  112687. int ret=0;
  112688. ve->stretch++;
  112689. if(ve->stretch>VE_MAXSTRETCH*2)
  112690. ve->stretch=VE_MAXSTRETCH*2;
  112691. for(i=0;i<ve->ch;i++){
  112692. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112693. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112694. }
  112695. ve->mark[j+VE_POST]=0;
  112696. if(ret&1){
  112697. ve->mark[j]=1;
  112698. ve->mark[j+1]=1;
  112699. }
  112700. if(ret&2){
  112701. ve->mark[j]=1;
  112702. if(j>0)ve->mark[j-1]=1;
  112703. }
  112704. if(ret&4)ve->stretch=-1;
  112705. }
  112706. ve->current=last*ve->searchstep;
  112707. {
  112708. long centerW=v->centerW;
  112709. long testW=
  112710. centerW+
  112711. ci->blocksizes[v->W]/4+
  112712. ci->blocksizes[1]/2+
  112713. ci->blocksizes[0]/4;
  112714. j=ve->cursor;
  112715. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112716. working back one window */
  112717. if(j>=testW)return(1);
  112718. ve->cursor=j;
  112719. if(ve->mark[j/ve->searchstep]){
  112720. if(j>centerW){
  112721. #if 0
  112722. if(j>ve->curmark){
  112723. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112724. int l,m;
  112725. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112726. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112727. seq,
  112728. (totalshift+ve->cursor)/44100.,
  112729. (totalshift+j)/44100.);
  112730. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112731. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112732. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112733. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112734. for(m=0;m<VE_BANDS;m++){
  112735. char buf[80];
  112736. sprintf(buf,"delL%d",m);
  112737. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112738. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112739. }
  112740. for(m=0;m<VE_BANDS;m++){
  112741. char buf[80];
  112742. sprintf(buf,"delR%d",m);
  112743. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112744. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112745. }
  112746. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112747. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112748. seq++;
  112749. }
  112750. #endif
  112751. ve->curmark=j;
  112752. if(j>=testW)return(1);
  112753. return(0);
  112754. }
  112755. }
  112756. j+=ve->searchstep;
  112757. }
  112758. }
  112759. return(-1);
  112760. }
  112761. int _ve_envelope_mark(vorbis_dsp_state *v){
  112762. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112763. vorbis_info *vi=v->vi;
  112764. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112765. long centerW=v->centerW;
  112766. long beginW=centerW-ci->blocksizes[v->W]/4;
  112767. long endW=centerW+ci->blocksizes[v->W]/4;
  112768. if(v->W){
  112769. beginW-=ci->blocksizes[v->lW]/4;
  112770. endW+=ci->blocksizes[v->nW]/4;
  112771. }else{
  112772. beginW-=ci->blocksizes[0]/4;
  112773. endW+=ci->blocksizes[0]/4;
  112774. }
  112775. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112776. {
  112777. long first=beginW/ve->searchstep;
  112778. long last=endW/ve->searchstep;
  112779. long i;
  112780. for(i=first;i<last;i++)
  112781. if(ve->mark[i])return(1);
  112782. }
  112783. return(0);
  112784. }
  112785. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112786. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112787. ahead of ve->current */
  112788. int smallshift=shift/e->searchstep;
  112789. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112790. #if 0
  112791. for(i=0;i<VE_BANDS*e->ch;i++)
  112792. memmove(e->filter[i].markers,
  112793. e->filter[i].markers+smallshift,
  112794. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112795. totalshift+=shift;
  112796. #endif
  112797. e->current-=shift;
  112798. if(e->curmark>=0)
  112799. e->curmark-=shift;
  112800. e->cursor-=shift;
  112801. }
  112802. #endif
  112803. /*** End of inlined file: envelope.c ***/
  112804. /*** Start of inlined file: floor0.c ***/
  112805. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112806. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112807. // tasks..
  112808. #if JUCE_MSVC
  112809. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112810. #endif
  112811. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112812. #if JUCE_USE_OGGVORBIS
  112813. #include <stdlib.h>
  112814. #include <string.h>
  112815. #include <math.h>
  112816. /*** Start of inlined file: lsp.h ***/
  112817. #ifndef _V_LSP_H_
  112818. #define _V_LSP_H_
  112819. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112820. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112821. float *lsp,int m,
  112822. float amp,float ampoffset);
  112823. #endif
  112824. /*** End of inlined file: lsp.h ***/
  112825. #include <stdio.h>
  112826. typedef struct {
  112827. int ln;
  112828. int m;
  112829. int **linearmap;
  112830. int n[2];
  112831. vorbis_info_floor0 *vi;
  112832. long bits;
  112833. long frames;
  112834. } vorbis_look_floor0;
  112835. /***********************************************/
  112836. static void floor0_free_info(vorbis_info_floor *i){
  112837. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112838. if(info){
  112839. memset(info,0,sizeof(*info));
  112840. _ogg_free(info);
  112841. }
  112842. }
  112843. static void floor0_free_look(vorbis_look_floor *i){
  112844. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112845. if(look){
  112846. if(look->linearmap){
  112847. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112848. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112849. _ogg_free(look->linearmap);
  112850. }
  112851. memset(look,0,sizeof(*look));
  112852. _ogg_free(look);
  112853. }
  112854. }
  112855. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112856. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112857. int j;
  112858. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112859. info->order=oggpack_read(opb,8);
  112860. info->rate=oggpack_read(opb,16);
  112861. info->barkmap=oggpack_read(opb,16);
  112862. info->ampbits=oggpack_read(opb,6);
  112863. info->ampdB=oggpack_read(opb,8);
  112864. info->numbooks=oggpack_read(opb,4)+1;
  112865. if(info->order<1)goto err_out;
  112866. if(info->rate<1)goto err_out;
  112867. if(info->barkmap<1)goto err_out;
  112868. if(info->numbooks<1)goto err_out;
  112869. for(j=0;j<info->numbooks;j++){
  112870. info->books[j]=oggpack_read(opb,8);
  112871. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112872. }
  112873. return(info);
  112874. err_out:
  112875. floor0_free_info(info);
  112876. return(NULL);
  112877. }
  112878. /* initialize Bark scale and normalization lookups. We could do this
  112879. with static tables, but Vorbis allows a number of possible
  112880. combinations, so it's best to do it computationally.
  112881. The below is authoritative in terms of defining scale mapping.
  112882. Note that the scale depends on the sampling rate as well as the
  112883. linear block and mapping sizes */
  112884. static void floor0_map_lazy_init(vorbis_block *vb,
  112885. vorbis_info_floor *infoX,
  112886. vorbis_look_floor0 *look){
  112887. if(!look->linearmap[vb->W]){
  112888. vorbis_dsp_state *vd=vb->vd;
  112889. vorbis_info *vi=vd->vi;
  112890. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112891. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112892. int W=vb->W;
  112893. int n=ci->blocksizes[W]/2,j;
  112894. /* we choose a scaling constant so that:
  112895. floor(bark(rate/2-1)*C)=mapped-1
  112896. floor(bark(rate/2)*C)=mapped */
  112897. float scale=look->ln/toBARK(info->rate/2.f);
  112898. /* the mapping from a linear scale to a smaller bark scale is
  112899. straightforward. We do *not* make sure that the linear mapping
  112900. does not skip bark-scale bins; the decoder simply skips them and
  112901. the encoder may do what it wishes in filling them. They're
  112902. necessary in some mapping combinations to keep the scale spacing
  112903. accurate */
  112904. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112905. for(j=0;j<n;j++){
  112906. int val=floor( toBARK((info->rate/2.f)/n*j)
  112907. *scale); /* bark numbers represent band edges */
  112908. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112909. look->linearmap[W][j]=val;
  112910. }
  112911. look->linearmap[W][j]=-1;
  112912. look->n[W]=n;
  112913. }
  112914. }
  112915. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112916. vorbis_info_floor *i){
  112917. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112918. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112919. look->m=info->order;
  112920. look->ln=info->barkmap;
  112921. look->vi=info;
  112922. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112923. return look;
  112924. }
  112925. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112926. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112927. vorbis_info_floor0 *info=look->vi;
  112928. int j,k;
  112929. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112930. if(ampraw>0){ /* also handles the -1 out of data case */
  112931. long maxval=(1<<info->ampbits)-1;
  112932. float amp=(float)ampraw/maxval*info->ampdB;
  112933. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112934. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112935. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112936. codebook *b=ci->fullbooks+info->books[booknum];
  112937. float last=0.f;
  112938. /* the additional b->dim is a guard against any possible stack
  112939. smash; b->dim is provably more than we can overflow the
  112940. vector */
  112941. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112942. for(j=0;j<look->m;j+=b->dim)
  112943. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112944. for(j=0;j<look->m;){
  112945. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112946. last=lsp[j-1];
  112947. }
  112948. lsp[look->m]=amp;
  112949. return(lsp);
  112950. }
  112951. }
  112952. eop:
  112953. return(NULL);
  112954. }
  112955. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112956. void *memo,float *out){
  112957. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112958. vorbis_info_floor0 *info=look->vi;
  112959. floor0_map_lazy_init(vb,info,look);
  112960. if(memo){
  112961. float *lsp=(float *)memo;
  112962. float amp=lsp[look->m];
  112963. /* take the coefficients back to a spectral envelope curve */
  112964. vorbis_lsp_to_curve(out,
  112965. look->linearmap[vb->W],
  112966. look->n[vb->W],
  112967. look->ln,
  112968. lsp,look->m,amp,(float)info->ampdB);
  112969. return(1);
  112970. }
  112971. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112972. return(0);
  112973. }
  112974. /* export hooks */
  112975. vorbis_func_floor floor0_exportbundle={
  112976. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112977. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112978. };
  112979. #endif
  112980. /*** End of inlined file: floor0.c ***/
  112981. /*** Start of inlined file: floor1.c ***/
  112982. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112983. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112984. // tasks..
  112985. #if JUCE_MSVC
  112986. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112987. #endif
  112988. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112989. #if JUCE_USE_OGGVORBIS
  112990. #include <stdlib.h>
  112991. #include <string.h>
  112992. #include <math.h>
  112993. #include <stdio.h>
  112994. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112995. typedef struct {
  112996. int sorted_index[VIF_POSIT+2];
  112997. int forward_index[VIF_POSIT+2];
  112998. int reverse_index[VIF_POSIT+2];
  112999. int hineighbor[VIF_POSIT];
  113000. int loneighbor[VIF_POSIT];
  113001. int posts;
  113002. int n;
  113003. int quant_q;
  113004. vorbis_info_floor1 *vi;
  113005. long phrasebits;
  113006. long postbits;
  113007. long frames;
  113008. } vorbis_look_floor1;
  113009. typedef struct lsfit_acc{
  113010. long x0;
  113011. long x1;
  113012. long xa;
  113013. long ya;
  113014. long x2a;
  113015. long y2a;
  113016. long xya;
  113017. long an;
  113018. } lsfit_acc;
  113019. /***********************************************/
  113020. static void floor1_free_info(vorbis_info_floor *i){
  113021. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113022. if(info){
  113023. memset(info,0,sizeof(*info));
  113024. _ogg_free(info);
  113025. }
  113026. }
  113027. static void floor1_free_look(vorbis_look_floor *i){
  113028. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  113029. if(look){
  113030. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  113031. (float)look->phrasebits/look->frames,
  113032. (float)look->postbits/look->frames,
  113033. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113034. memset(look,0,sizeof(*look));
  113035. _ogg_free(look);
  113036. }
  113037. }
  113038. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  113039. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113040. int j,k;
  113041. int count=0;
  113042. int rangebits;
  113043. int maxposit=info->postlist[1];
  113044. int maxclass=-1;
  113045. /* save out partitions */
  113046. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  113047. for(j=0;j<info->partitions;j++){
  113048. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  113049. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113050. }
  113051. /* save out partition classes */
  113052. for(j=0;j<maxclass+1;j++){
  113053. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  113054. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  113055. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  113056. for(k=0;k<(1<<info->class_subs[j]);k++)
  113057. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  113058. }
  113059. /* save out the post list */
  113060. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  113061. oggpack_write(opb,ilog2(maxposit),4);
  113062. rangebits=ilog2(maxposit);
  113063. for(j=0,k=0;j<info->partitions;j++){
  113064. count+=info->class_dim[info->partitionclass[j]];
  113065. for(;k<count;k++)
  113066. oggpack_write(opb,info->postlist[k+2],rangebits);
  113067. }
  113068. }
  113069. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  113070. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113071. int j,k,count=0,maxclass=-1,rangebits;
  113072. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  113073. /* read partitions */
  113074. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  113075. for(j=0;j<info->partitions;j++){
  113076. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  113077. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113078. }
  113079. /* read partition classes */
  113080. for(j=0;j<maxclass+1;j++){
  113081. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  113082. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  113083. if(info->class_subs[j]<0)
  113084. goto err_out;
  113085. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  113086. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  113087. goto err_out;
  113088. for(k=0;k<(1<<info->class_subs[j]);k++){
  113089. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  113090. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  113091. goto err_out;
  113092. }
  113093. }
  113094. /* read the post list */
  113095. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  113096. rangebits=oggpack_read(opb,4);
  113097. for(j=0,k=0;j<info->partitions;j++){
  113098. count+=info->class_dim[info->partitionclass[j]];
  113099. for(;k<count;k++){
  113100. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  113101. if(t<0 || t>=(1<<rangebits))
  113102. goto err_out;
  113103. }
  113104. }
  113105. info->postlist[0]=0;
  113106. info->postlist[1]=1<<rangebits;
  113107. return(info);
  113108. err_out:
  113109. floor1_free_info(info);
  113110. return(NULL);
  113111. }
  113112. static int JUCE_CDECL icomp(const void *a,const void *b){
  113113. return(**(int **)a-**(int **)b);
  113114. }
  113115. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  113116. vorbis_info_floor *in){
  113117. int *sortpointer[VIF_POSIT+2];
  113118. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  113119. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  113120. int i,j,n=0;
  113121. look->vi=info;
  113122. look->n=info->postlist[1];
  113123. /* we drop each position value in-between already decoded values,
  113124. and use linear interpolation to predict each new value past the
  113125. edges. The positions are read in the order of the position
  113126. list... we precompute the bounding positions in the lookup. Of
  113127. course, the neighbors can change (if a position is declined), but
  113128. this is an initial mapping */
  113129. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  113130. n+=2;
  113131. look->posts=n;
  113132. /* also store a sorted position index */
  113133. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  113134. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  113135. /* points from sort order back to range number */
  113136. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  113137. /* points from range order to sorted position */
  113138. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  113139. /* we actually need the post values too */
  113140. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  113141. /* quantize values to multiplier spec */
  113142. switch(info->mult){
  113143. case 1: /* 1024 -> 256 */
  113144. look->quant_q=256;
  113145. break;
  113146. case 2: /* 1024 -> 128 */
  113147. look->quant_q=128;
  113148. break;
  113149. case 3: /* 1024 -> 86 */
  113150. look->quant_q=86;
  113151. break;
  113152. case 4: /* 1024 -> 64 */
  113153. look->quant_q=64;
  113154. break;
  113155. }
  113156. /* discover our neighbors for decode where we don't use fit flags
  113157. (that would push the neighbors outward) */
  113158. for(i=0;i<n-2;i++){
  113159. int lo=0;
  113160. int hi=1;
  113161. int lx=0;
  113162. int hx=look->n;
  113163. int currentx=info->postlist[i+2];
  113164. for(j=0;j<i+2;j++){
  113165. int x=info->postlist[j];
  113166. if(x>lx && x<currentx){
  113167. lo=j;
  113168. lx=x;
  113169. }
  113170. if(x<hx && x>currentx){
  113171. hi=j;
  113172. hx=x;
  113173. }
  113174. }
  113175. look->loneighbor[i]=lo;
  113176. look->hineighbor[i]=hi;
  113177. }
  113178. return(look);
  113179. }
  113180. static int render_point(int x0,int x1,int y0,int y1,int x){
  113181. y0&=0x7fff; /* mask off flag */
  113182. y1&=0x7fff;
  113183. {
  113184. int dy=y1-y0;
  113185. int adx=x1-x0;
  113186. int ady=abs(dy);
  113187. int err=ady*(x-x0);
  113188. int off=err/adx;
  113189. if(dy<0)return(y0-off);
  113190. return(y0+off);
  113191. }
  113192. }
  113193. static int vorbis_dBquant(const float *x){
  113194. int i= *x*7.3142857f+1023.5f;
  113195. if(i>1023)return(1023);
  113196. if(i<0)return(0);
  113197. return i;
  113198. }
  113199. static float FLOOR1_fromdB_LOOKUP[256]={
  113200. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113201. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113202. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113203. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113204. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113205. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113206. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113207. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113208. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113209. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113210. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113211. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113212. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113213. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113214. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113215. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113216. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113217. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113218. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113219. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113220. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113221. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113222. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113223. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113224. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113225. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113226. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113227. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113228. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113229. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113230. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113231. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113232. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113233. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113234. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113235. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113236. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113237. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113238. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113239. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113240. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113241. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113242. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113243. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113244. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113245. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113246. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113247. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113248. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113249. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113250. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113251. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113252. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113253. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113254. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113255. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113256. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113257. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113258. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113259. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113260. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113261. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113262. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113263. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113264. };
  113265. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113266. int dy=y1-y0;
  113267. int adx=x1-x0;
  113268. int ady=abs(dy);
  113269. int base=dy/adx;
  113270. int sy=(dy<0?base-1:base+1);
  113271. int x=x0;
  113272. int y=y0;
  113273. int err=0;
  113274. ady-=abs(base*adx);
  113275. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113276. while(++x<x1){
  113277. err=err+ady;
  113278. if(err>=adx){
  113279. err-=adx;
  113280. y+=sy;
  113281. }else{
  113282. y+=base;
  113283. }
  113284. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113285. }
  113286. }
  113287. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113288. int dy=y1-y0;
  113289. int adx=x1-x0;
  113290. int ady=abs(dy);
  113291. int base=dy/adx;
  113292. int sy=(dy<0?base-1:base+1);
  113293. int x=x0;
  113294. int y=y0;
  113295. int err=0;
  113296. ady-=abs(base*adx);
  113297. d[x]=y;
  113298. while(++x<x1){
  113299. err=err+ady;
  113300. if(err>=adx){
  113301. err-=adx;
  113302. y+=sy;
  113303. }else{
  113304. y+=base;
  113305. }
  113306. d[x]=y;
  113307. }
  113308. }
  113309. /* the floor has already been filtered to only include relevant sections */
  113310. static int accumulate_fit(const float *flr,const float *mdct,
  113311. int x0, int x1,lsfit_acc *a,
  113312. int n,vorbis_info_floor1 *info){
  113313. long i;
  113314. 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;
  113315. memset(a,0,sizeof(*a));
  113316. a->x0=x0;
  113317. a->x1=x1;
  113318. if(x1>=n)x1=n-1;
  113319. for(i=x0;i<=x1;i++){
  113320. int quantized=vorbis_dBquant(flr+i);
  113321. if(quantized){
  113322. if(mdct[i]+info->twofitatten>=flr[i]){
  113323. xa += i;
  113324. ya += quantized;
  113325. x2a += i*i;
  113326. y2a += quantized*quantized;
  113327. xya += i*quantized;
  113328. na++;
  113329. }else{
  113330. xb += i;
  113331. yb += quantized;
  113332. x2b += i*i;
  113333. y2b += quantized*quantized;
  113334. xyb += i*quantized;
  113335. nb++;
  113336. }
  113337. }
  113338. }
  113339. xb+=xa;
  113340. yb+=ya;
  113341. x2b+=x2a;
  113342. y2b+=y2a;
  113343. xyb+=xya;
  113344. nb+=na;
  113345. /* weight toward the actually used frequencies if we meet the threshhold */
  113346. {
  113347. int weight=nb*info->twofitweight/(na+1);
  113348. a->xa=xa*weight+xb;
  113349. a->ya=ya*weight+yb;
  113350. a->x2a=x2a*weight+x2b;
  113351. a->y2a=y2a*weight+y2b;
  113352. a->xya=xya*weight+xyb;
  113353. a->an=na*weight+nb;
  113354. }
  113355. return(na);
  113356. }
  113357. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113358. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113359. long x0=a[0].x0;
  113360. long x1=a[fits-1].x1;
  113361. for(i=0;i<fits;i++){
  113362. x+=a[i].xa;
  113363. y+=a[i].ya;
  113364. x2+=a[i].x2a;
  113365. y2+=a[i].y2a;
  113366. xy+=a[i].xya;
  113367. an+=a[i].an;
  113368. }
  113369. if(*y0>=0){
  113370. x+= x0;
  113371. y+= *y0;
  113372. x2+= x0 * x0;
  113373. y2+= *y0 * *y0;
  113374. xy+= *y0 * x0;
  113375. an++;
  113376. }
  113377. if(*y1>=0){
  113378. x+= x1;
  113379. y+= *y1;
  113380. x2+= x1 * x1;
  113381. y2+= *y1 * *y1;
  113382. xy+= *y1 * x1;
  113383. an++;
  113384. }
  113385. if(an){
  113386. /* need 64 bit multiplies, which C doesn't give portably as int */
  113387. double fx=x;
  113388. double fy=y;
  113389. double fx2=x2;
  113390. double fxy=xy;
  113391. double denom=1./(an*fx2-fx*fx);
  113392. double a=(fy*fx2-fxy*fx)*denom;
  113393. double b=(an*fxy-fx*fy)*denom;
  113394. *y0=rint(a+b*x0);
  113395. *y1=rint(a+b*x1);
  113396. /* limit to our range! */
  113397. if(*y0>1023)*y0=1023;
  113398. if(*y1>1023)*y1=1023;
  113399. if(*y0<0)*y0=0;
  113400. if(*y1<0)*y1=0;
  113401. }else{
  113402. *y0=0;
  113403. *y1=0;
  113404. }
  113405. }
  113406. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113407. long y=0;
  113408. int i;
  113409. for(i=0;i<fits && y==0;i++)
  113410. y+=a[i].ya;
  113411. *y0=*y1=y;
  113412. }*/
  113413. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113414. const float *mdct,
  113415. vorbis_info_floor1 *info){
  113416. int dy=y1-y0;
  113417. int adx=x1-x0;
  113418. int ady=abs(dy);
  113419. int base=dy/adx;
  113420. int sy=(dy<0?base-1:base+1);
  113421. int x=x0;
  113422. int y=y0;
  113423. int err=0;
  113424. int val=vorbis_dBquant(mask+x);
  113425. int mse=0;
  113426. int n=0;
  113427. ady-=abs(base*adx);
  113428. mse=(y-val);
  113429. mse*=mse;
  113430. n++;
  113431. if(mdct[x]+info->twofitatten>=mask[x]){
  113432. if(y+info->maxover<val)return(1);
  113433. if(y-info->maxunder>val)return(1);
  113434. }
  113435. while(++x<x1){
  113436. err=err+ady;
  113437. if(err>=adx){
  113438. err-=adx;
  113439. y+=sy;
  113440. }else{
  113441. y+=base;
  113442. }
  113443. val=vorbis_dBquant(mask+x);
  113444. mse+=((y-val)*(y-val));
  113445. n++;
  113446. if(mdct[x]+info->twofitatten>=mask[x]){
  113447. if(val){
  113448. if(y+info->maxover<val)return(1);
  113449. if(y-info->maxunder>val)return(1);
  113450. }
  113451. }
  113452. }
  113453. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113454. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113455. if(mse/n>info->maxerr)return(1);
  113456. return(0);
  113457. }
  113458. static int post_Y(int *A,int *B,int pos){
  113459. if(A[pos]<0)
  113460. return B[pos];
  113461. if(B[pos]<0)
  113462. return A[pos];
  113463. return (A[pos]+B[pos])>>1;
  113464. }
  113465. int *floor1_fit(vorbis_block *vb,void *look_,
  113466. const float *logmdct, /* in */
  113467. const float *logmask){
  113468. long i,j;
  113469. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113470. vorbis_info_floor1 *info=look->vi;
  113471. long n=look->n;
  113472. long posts=look->posts;
  113473. long nonzero=0;
  113474. lsfit_acc fits[VIF_POSIT+1];
  113475. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113476. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113477. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113478. int hineighbor[VIF_POSIT+2];
  113479. int *output=NULL;
  113480. int memo[VIF_POSIT+2];
  113481. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113482. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113483. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113484. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113485. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113486. /* quantize the relevant floor points and collect them into line fit
  113487. structures (one per minimal division) at the same time */
  113488. if(posts==0){
  113489. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113490. }else{
  113491. for(i=0;i<posts-1;i++)
  113492. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113493. look->sorted_index[i+1],fits+i,
  113494. n,info);
  113495. }
  113496. if(nonzero){
  113497. /* start by fitting the implicit base case.... */
  113498. int y0=-200;
  113499. int y1=-200;
  113500. fit_line(fits,posts-1,&y0,&y1);
  113501. fit_valueA[0]=y0;
  113502. fit_valueB[0]=y0;
  113503. fit_valueB[1]=y1;
  113504. fit_valueA[1]=y1;
  113505. /* Non degenerate case */
  113506. /* start progressive splitting. This is a greedy, non-optimal
  113507. algorithm, but simple and close enough to the best
  113508. answer. */
  113509. for(i=2;i<posts;i++){
  113510. int sortpos=look->reverse_index[i];
  113511. int ln=loneighbor[sortpos];
  113512. int hn=hineighbor[sortpos];
  113513. /* eliminate repeat searches of a particular range with a memo */
  113514. if(memo[ln]!=hn){
  113515. /* haven't performed this error search yet */
  113516. int lsortpos=look->reverse_index[ln];
  113517. int hsortpos=look->reverse_index[hn];
  113518. memo[ln]=hn;
  113519. {
  113520. /* A note: we want to bound/minimize *local*, not global, error */
  113521. int lx=info->postlist[ln];
  113522. int hx=info->postlist[hn];
  113523. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113524. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113525. if(ly==-1 || hy==-1){
  113526. exit(1);
  113527. }
  113528. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113529. /* outside error bounds/begin search area. Split it. */
  113530. int ly0=-200;
  113531. int ly1=-200;
  113532. int hy0=-200;
  113533. int hy1=-200;
  113534. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113535. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113536. /* store new edge values */
  113537. fit_valueB[ln]=ly0;
  113538. if(ln==0)fit_valueA[ln]=ly0;
  113539. fit_valueA[i]=ly1;
  113540. fit_valueB[i]=hy0;
  113541. fit_valueA[hn]=hy1;
  113542. if(hn==1)fit_valueB[hn]=hy1;
  113543. if(ly1>=0 || hy0>=0){
  113544. /* store new neighbor values */
  113545. for(j=sortpos-1;j>=0;j--)
  113546. if(hineighbor[j]==hn)
  113547. hineighbor[j]=i;
  113548. else
  113549. break;
  113550. for(j=sortpos+1;j<posts;j++)
  113551. if(loneighbor[j]==ln)
  113552. loneighbor[j]=i;
  113553. else
  113554. break;
  113555. }
  113556. }else{
  113557. fit_valueA[i]=-200;
  113558. fit_valueB[i]=-200;
  113559. }
  113560. }
  113561. }
  113562. }
  113563. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113564. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113565. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113566. /* fill in posts marked as not using a fit; we will zero
  113567. back out to 'unused' when encoding them so long as curve
  113568. interpolation doesn't force them into use */
  113569. for(i=2;i<posts;i++){
  113570. int ln=look->loneighbor[i-2];
  113571. int hn=look->hineighbor[i-2];
  113572. int x0=info->postlist[ln];
  113573. int x1=info->postlist[hn];
  113574. int y0=output[ln];
  113575. int y1=output[hn];
  113576. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113577. int vx=post_Y(fit_valueA,fit_valueB,i);
  113578. if(vx>=0 && predicted!=vx){
  113579. output[i]=vx;
  113580. }else{
  113581. output[i]= predicted|0x8000;
  113582. }
  113583. }
  113584. }
  113585. return(output);
  113586. }
  113587. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113588. int *A,int *B,
  113589. int del){
  113590. long i;
  113591. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113592. long posts=look->posts;
  113593. int *output=NULL;
  113594. if(A && B){
  113595. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113596. for(i=0;i<posts;i++){
  113597. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113598. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113599. }
  113600. }
  113601. return(output);
  113602. }
  113603. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113604. void*look_,
  113605. int *post,int *ilogmask){
  113606. long i,j;
  113607. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113608. vorbis_info_floor1 *info=look->vi;
  113609. long posts=look->posts;
  113610. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113611. int out[VIF_POSIT+2];
  113612. static_codebook **sbooks=ci->book_param;
  113613. codebook *books=ci->fullbooks;
  113614. static long seq=0;
  113615. /* quantize values to multiplier spec */
  113616. if(post){
  113617. for(i=0;i<posts;i++){
  113618. int val=post[i]&0x7fff;
  113619. switch(info->mult){
  113620. case 1: /* 1024 -> 256 */
  113621. val>>=2;
  113622. break;
  113623. case 2: /* 1024 -> 128 */
  113624. val>>=3;
  113625. break;
  113626. case 3: /* 1024 -> 86 */
  113627. val/=12;
  113628. break;
  113629. case 4: /* 1024 -> 64 */
  113630. val>>=4;
  113631. break;
  113632. }
  113633. post[i]=val | (post[i]&0x8000);
  113634. }
  113635. out[0]=post[0];
  113636. out[1]=post[1];
  113637. /* find prediction values for each post and subtract them */
  113638. for(i=2;i<posts;i++){
  113639. int ln=look->loneighbor[i-2];
  113640. int hn=look->hineighbor[i-2];
  113641. int x0=info->postlist[ln];
  113642. int x1=info->postlist[hn];
  113643. int y0=post[ln];
  113644. int y1=post[hn];
  113645. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113646. if((post[i]&0x8000) || (predicted==post[i])){
  113647. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113648. in interpolation */
  113649. out[i]=0;
  113650. }else{
  113651. int headroom=(look->quant_q-predicted<predicted?
  113652. look->quant_q-predicted:predicted);
  113653. int val=post[i]-predicted;
  113654. /* at this point the 'deviation' value is in the range +/- max
  113655. range, but the real, unique range can always be mapped to
  113656. only [0-maxrange). So we want to wrap the deviation into
  113657. this limited range, but do it in the way that least screws
  113658. an essentially gaussian probability distribution. */
  113659. if(val<0)
  113660. if(val<-headroom)
  113661. val=headroom-val-1;
  113662. else
  113663. val=-1-(val<<1);
  113664. else
  113665. if(val>=headroom)
  113666. val= val+headroom;
  113667. else
  113668. val<<=1;
  113669. out[i]=val;
  113670. post[ln]&=0x7fff;
  113671. post[hn]&=0x7fff;
  113672. }
  113673. }
  113674. /* we have everything we need. pack it out */
  113675. /* mark nontrivial floor */
  113676. oggpack_write(opb,1,1);
  113677. /* beginning/end post */
  113678. look->frames++;
  113679. look->postbits+=ilog(look->quant_q-1)*2;
  113680. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113681. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113682. /* partition by partition */
  113683. for(i=0,j=2;i<info->partitions;i++){
  113684. int classx=info->partitionclass[i];
  113685. int cdim=info->class_dim[classx];
  113686. int csubbits=info->class_subs[classx];
  113687. int csub=1<<csubbits;
  113688. int bookas[8]={0,0,0,0,0,0,0,0};
  113689. int cval=0;
  113690. int cshift=0;
  113691. int k,l;
  113692. /* generate the partition's first stage cascade value */
  113693. if(csubbits){
  113694. int maxval[8];
  113695. for(k=0;k<csub;k++){
  113696. int booknum=info->class_subbook[classx][k];
  113697. if(booknum<0){
  113698. maxval[k]=1;
  113699. }else{
  113700. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113701. }
  113702. }
  113703. for(k=0;k<cdim;k++){
  113704. for(l=0;l<csub;l++){
  113705. int val=out[j+k];
  113706. if(val<maxval[l]){
  113707. bookas[k]=l;
  113708. break;
  113709. }
  113710. }
  113711. cval|= bookas[k]<<cshift;
  113712. cshift+=csubbits;
  113713. }
  113714. /* write it */
  113715. look->phrasebits+=
  113716. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113717. #ifdef TRAIN_FLOOR1
  113718. {
  113719. FILE *of;
  113720. char buffer[80];
  113721. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113722. vb->pcmend/2,posts-2,class);
  113723. of=fopen(buffer,"a");
  113724. fprintf(of,"%d\n",cval);
  113725. fclose(of);
  113726. }
  113727. #endif
  113728. }
  113729. /* write post values */
  113730. for(k=0;k<cdim;k++){
  113731. int book=info->class_subbook[classx][bookas[k]];
  113732. if(book>=0){
  113733. /* hack to allow training with 'bad' books */
  113734. if(out[j+k]<(books+book)->entries)
  113735. look->postbits+=vorbis_book_encode(books+book,
  113736. out[j+k],opb);
  113737. /*else
  113738. fprintf(stderr,"+!");*/
  113739. #ifdef TRAIN_FLOOR1
  113740. {
  113741. FILE *of;
  113742. char buffer[80];
  113743. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113744. vb->pcmend/2,posts-2,class,bookas[k]);
  113745. of=fopen(buffer,"a");
  113746. fprintf(of,"%d\n",out[j+k]);
  113747. fclose(of);
  113748. }
  113749. #endif
  113750. }
  113751. }
  113752. j+=cdim;
  113753. }
  113754. {
  113755. /* generate quantized floor equivalent to what we'd unpack in decode */
  113756. /* render the lines */
  113757. int hx=0;
  113758. int lx=0;
  113759. int ly=post[0]*info->mult;
  113760. for(j=1;j<look->posts;j++){
  113761. int current=look->forward_index[j];
  113762. int hy=post[current]&0x7fff;
  113763. if(hy==post[current]){
  113764. hy*=info->mult;
  113765. hx=info->postlist[current];
  113766. render_line0(lx,hx,ly,hy,ilogmask);
  113767. lx=hx;
  113768. ly=hy;
  113769. }
  113770. }
  113771. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113772. seq++;
  113773. return(1);
  113774. }
  113775. }else{
  113776. oggpack_write(opb,0,1);
  113777. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113778. seq++;
  113779. return(0);
  113780. }
  113781. }
  113782. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113783. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113784. vorbis_info_floor1 *info=look->vi;
  113785. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113786. int i,j,k;
  113787. codebook *books=ci->fullbooks;
  113788. /* unpack wrapped/predicted values from stream */
  113789. if(oggpack_read(&vb->opb,1)==1){
  113790. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113791. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113792. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113793. /* partition by partition */
  113794. for(i=0,j=2;i<info->partitions;i++){
  113795. int classx=info->partitionclass[i];
  113796. int cdim=info->class_dim[classx];
  113797. int csubbits=info->class_subs[classx];
  113798. int csub=1<<csubbits;
  113799. int cval=0;
  113800. /* decode the partition's first stage cascade value */
  113801. if(csubbits){
  113802. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113803. if(cval==-1)goto eop;
  113804. }
  113805. for(k=0;k<cdim;k++){
  113806. int book=info->class_subbook[classx][cval&(csub-1)];
  113807. cval>>=csubbits;
  113808. if(book>=0){
  113809. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113810. goto eop;
  113811. }else{
  113812. fit_value[j+k]=0;
  113813. }
  113814. }
  113815. j+=cdim;
  113816. }
  113817. /* unwrap positive values and reconsitute via linear interpolation */
  113818. for(i=2;i<look->posts;i++){
  113819. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113820. info->postlist[look->hineighbor[i-2]],
  113821. fit_value[look->loneighbor[i-2]],
  113822. fit_value[look->hineighbor[i-2]],
  113823. info->postlist[i]);
  113824. int hiroom=look->quant_q-predicted;
  113825. int loroom=predicted;
  113826. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113827. int val=fit_value[i];
  113828. if(val){
  113829. if(val>=room){
  113830. if(hiroom>loroom){
  113831. val = val-loroom;
  113832. }else{
  113833. val = -1-(val-hiroom);
  113834. }
  113835. }else{
  113836. if(val&1){
  113837. val= -((val+1)>>1);
  113838. }else{
  113839. val>>=1;
  113840. }
  113841. }
  113842. fit_value[i]=val+predicted;
  113843. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113844. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113845. }else{
  113846. fit_value[i]=predicted|0x8000;
  113847. }
  113848. }
  113849. return(fit_value);
  113850. }
  113851. eop:
  113852. return(NULL);
  113853. }
  113854. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113855. float *out){
  113856. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113857. vorbis_info_floor1 *info=look->vi;
  113858. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113859. int n=ci->blocksizes[vb->W]/2;
  113860. int j;
  113861. if(memo){
  113862. /* render the lines */
  113863. int *fit_value=(int *)memo;
  113864. int hx=0;
  113865. int lx=0;
  113866. int ly=fit_value[0]*info->mult;
  113867. for(j=1;j<look->posts;j++){
  113868. int current=look->forward_index[j];
  113869. int hy=fit_value[current]&0x7fff;
  113870. if(hy==fit_value[current]){
  113871. hy*=info->mult;
  113872. hx=info->postlist[current];
  113873. render_line(lx,hx,ly,hy,out);
  113874. lx=hx;
  113875. ly=hy;
  113876. }
  113877. }
  113878. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113879. return(1);
  113880. }
  113881. memset(out,0,sizeof(*out)*n);
  113882. return(0);
  113883. }
  113884. /* export hooks */
  113885. vorbis_func_floor floor1_exportbundle={
  113886. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113887. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113888. };
  113889. #endif
  113890. /*** End of inlined file: floor1.c ***/
  113891. /*** Start of inlined file: info.c ***/
  113892. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113893. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113894. // tasks..
  113895. #if JUCE_MSVC
  113896. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113897. #endif
  113898. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113899. #if JUCE_USE_OGGVORBIS
  113900. /* general handling of the header and the vorbis_info structure (and
  113901. substructures) */
  113902. #include <stdlib.h>
  113903. #include <string.h>
  113904. #include <ctype.h>
  113905. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113906. while(bytes--){
  113907. oggpack_write(o,*s++,8);
  113908. }
  113909. }
  113910. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113911. while(bytes--){
  113912. *buf++=oggpack_read(o,8);
  113913. }
  113914. }
  113915. void vorbis_comment_init(vorbis_comment *vc){
  113916. memset(vc,0,sizeof(*vc));
  113917. }
  113918. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113919. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113920. (vc->comments+2)*sizeof(*vc->user_comments));
  113921. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113922. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113923. vc->comment_lengths[vc->comments]=strlen(comment);
  113924. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113925. strcpy(vc->user_comments[vc->comments], comment);
  113926. vc->comments++;
  113927. vc->user_comments[vc->comments]=NULL;
  113928. }
  113929. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113930. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113931. strcpy(comment, tag);
  113932. strcat(comment, "=");
  113933. strcat(comment, contents);
  113934. vorbis_comment_add(vc, comment);
  113935. }
  113936. /* This is more or less the same as strncasecmp - but that doesn't exist
  113937. * everywhere, and this is a fairly trivial function, so we include it */
  113938. static int tagcompare(const char *s1, const char *s2, int n){
  113939. int c=0;
  113940. while(c < n){
  113941. if(toupper(s1[c]) != toupper(s2[c]))
  113942. return !0;
  113943. c++;
  113944. }
  113945. return 0;
  113946. }
  113947. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113948. long i;
  113949. int found = 0;
  113950. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113951. char *fulltag = (char*)alloca(taglen+ 1);
  113952. strcpy(fulltag, tag);
  113953. strcat(fulltag, "=");
  113954. for(i=0;i<vc->comments;i++){
  113955. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113956. if(count == found)
  113957. /* We return a pointer to the data, not a copy */
  113958. return vc->user_comments[i] + taglen;
  113959. else
  113960. found++;
  113961. }
  113962. }
  113963. return NULL; /* didn't find anything */
  113964. }
  113965. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113966. int i,count=0;
  113967. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113968. char *fulltag = (char*)alloca(taglen+1);
  113969. strcpy(fulltag,tag);
  113970. strcat(fulltag, "=");
  113971. for(i=0;i<vc->comments;i++){
  113972. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113973. count++;
  113974. }
  113975. return count;
  113976. }
  113977. void vorbis_comment_clear(vorbis_comment *vc){
  113978. if(vc){
  113979. long i;
  113980. for(i=0;i<vc->comments;i++)
  113981. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113982. if(vc->user_comments)_ogg_free(vc->user_comments);
  113983. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113984. if(vc->vendor)_ogg_free(vc->vendor);
  113985. }
  113986. memset(vc,0,sizeof(*vc));
  113987. }
  113988. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113989. They may be equal, but short will never ge greater than long */
  113990. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113991. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113992. return ci ? ci->blocksizes[zo] : -1;
  113993. }
  113994. /* used by synthesis, which has a full, alloced vi */
  113995. void vorbis_info_init(vorbis_info *vi){
  113996. memset(vi,0,sizeof(*vi));
  113997. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113998. }
  113999. void vorbis_info_clear(vorbis_info *vi){
  114000. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114001. int i;
  114002. if(ci){
  114003. for(i=0;i<ci->modes;i++)
  114004. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  114005. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  114006. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  114007. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  114008. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  114009. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  114010. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  114011. for(i=0;i<ci->books;i++){
  114012. if(ci->book_param[i]){
  114013. /* knows if the book was not alloced */
  114014. vorbis_staticbook_destroy(ci->book_param[i]);
  114015. }
  114016. if(ci->fullbooks)
  114017. vorbis_book_clear(ci->fullbooks+i);
  114018. }
  114019. if(ci->fullbooks)
  114020. _ogg_free(ci->fullbooks);
  114021. for(i=0;i<ci->psys;i++)
  114022. _vi_psy_free(ci->psy_param[i]);
  114023. _ogg_free(ci);
  114024. }
  114025. memset(vi,0,sizeof(*vi));
  114026. }
  114027. /* Header packing/unpacking ********************************************/
  114028. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  114029. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114030. if(!ci)return(OV_EFAULT);
  114031. vi->version=oggpack_read(opb,32);
  114032. if(vi->version!=0)return(OV_EVERSION);
  114033. vi->channels=oggpack_read(opb,8);
  114034. vi->rate=oggpack_read(opb,32);
  114035. vi->bitrate_upper=oggpack_read(opb,32);
  114036. vi->bitrate_nominal=oggpack_read(opb,32);
  114037. vi->bitrate_lower=oggpack_read(opb,32);
  114038. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  114039. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  114040. if(vi->rate<1)goto err_out;
  114041. if(vi->channels<1)goto err_out;
  114042. if(ci->blocksizes[0]<8)goto err_out;
  114043. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  114044. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114045. return(0);
  114046. err_out:
  114047. vorbis_info_clear(vi);
  114048. return(OV_EBADHEADER);
  114049. }
  114050. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  114051. int i;
  114052. int vendorlen=oggpack_read(opb,32);
  114053. if(vendorlen<0)goto err_out;
  114054. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  114055. _v_readstring(opb,vc->vendor,vendorlen);
  114056. vc->comments=oggpack_read(opb,32);
  114057. if(vc->comments<0)goto err_out;
  114058. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  114059. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  114060. for(i=0;i<vc->comments;i++){
  114061. int len=oggpack_read(opb,32);
  114062. if(len<0)goto err_out;
  114063. vc->comment_lengths[i]=len;
  114064. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  114065. _v_readstring(opb,vc->user_comments[i],len);
  114066. }
  114067. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114068. return(0);
  114069. err_out:
  114070. vorbis_comment_clear(vc);
  114071. return(OV_EBADHEADER);
  114072. }
  114073. /* all of the real encoding details are here. The modes, books,
  114074. everything */
  114075. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  114076. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114077. int i;
  114078. if(!ci)return(OV_EFAULT);
  114079. /* codebooks */
  114080. ci->books=oggpack_read(opb,8)+1;
  114081. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  114082. for(i=0;i<ci->books;i++){
  114083. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  114084. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  114085. }
  114086. /* time backend settings; hooks are unused */
  114087. {
  114088. int times=oggpack_read(opb,6)+1;
  114089. for(i=0;i<times;i++){
  114090. int test=oggpack_read(opb,16);
  114091. if(test<0 || test>=VI_TIMEB)goto err_out;
  114092. }
  114093. }
  114094. /* floor backend settings */
  114095. ci->floors=oggpack_read(opb,6)+1;
  114096. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  114097. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  114098. for(i=0;i<ci->floors;i++){
  114099. ci->floor_type[i]=oggpack_read(opb,16);
  114100. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  114101. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  114102. if(!ci->floor_param[i])goto err_out;
  114103. }
  114104. /* residue backend settings */
  114105. ci->residues=oggpack_read(opb,6)+1;
  114106. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  114107. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  114108. for(i=0;i<ci->residues;i++){
  114109. ci->residue_type[i]=oggpack_read(opb,16);
  114110. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  114111. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  114112. if(!ci->residue_param[i])goto err_out;
  114113. }
  114114. /* map backend settings */
  114115. ci->maps=oggpack_read(opb,6)+1;
  114116. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  114117. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  114118. for(i=0;i<ci->maps;i++){
  114119. ci->map_type[i]=oggpack_read(opb,16);
  114120. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  114121. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  114122. if(!ci->map_param[i])goto err_out;
  114123. }
  114124. /* mode settings */
  114125. ci->modes=oggpack_read(opb,6)+1;
  114126. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  114127. for(i=0;i<ci->modes;i++){
  114128. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  114129. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  114130. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  114131. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  114132. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  114133. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  114134. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  114135. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  114136. }
  114137. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  114138. return(0);
  114139. err_out:
  114140. vorbis_info_clear(vi);
  114141. return(OV_EBADHEADER);
  114142. }
  114143. /* The Vorbis header is in three packets; the initial small packet in
  114144. the first page that identifies basic parameters, a second packet
  114145. with bitstream comments and a third packet that holds the
  114146. codebook. */
  114147. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  114148. oggpack_buffer opb;
  114149. if(op){
  114150. oggpack_readinit(&opb,op->packet,op->bytes);
  114151. /* Which of the three types of header is this? */
  114152. /* Also verify header-ness, vorbis */
  114153. {
  114154. char buffer[6];
  114155. int packtype=oggpack_read(&opb,8);
  114156. memset(buffer,0,6);
  114157. _v_readstring(&opb,buffer,6);
  114158. if(memcmp(buffer,"vorbis",6)){
  114159. /* not a vorbis header */
  114160. return(OV_ENOTVORBIS);
  114161. }
  114162. switch(packtype){
  114163. case 0x01: /* least significant *bit* is read first */
  114164. if(!op->b_o_s){
  114165. /* Not the initial packet */
  114166. return(OV_EBADHEADER);
  114167. }
  114168. if(vi->rate!=0){
  114169. /* previously initialized info header */
  114170. return(OV_EBADHEADER);
  114171. }
  114172. return(_vorbis_unpack_info(vi,&opb));
  114173. case 0x03: /* least significant *bit* is read first */
  114174. if(vi->rate==0){
  114175. /* um... we didn't get the initial header */
  114176. return(OV_EBADHEADER);
  114177. }
  114178. return(_vorbis_unpack_comment(vc,&opb));
  114179. case 0x05: /* least significant *bit* is read first */
  114180. if(vi->rate==0 || vc->vendor==NULL){
  114181. /* um... we didn;t get the initial header or comments yet */
  114182. return(OV_EBADHEADER);
  114183. }
  114184. return(_vorbis_unpack_books(vi,&opb));
  114185. default:
  114186. /* Not a valid vorbis header type */
  114187. return(OV_EBADHEADER);
  114188. break;
  114189. }
  114190. }
  114191. }
  114192. return(OV_EBADHEADER);
  114193. }
  114194. /* pack side **********************************************************/
  114195. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114196. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114197. if(!ci)return(OV_EFAULT);
  114198. /* preamble */
  114199. oggpack_write(opb,0x01,8);
  114200. _v_writestring(opb,"vorbis", 6);
  114201. /* basic information about the stream */
  114202. oggpack_write(opb,0x00,32);
  114203. oggpack_write(opb,vi->channels,8);
  114204. oggpack_write(opb,vi->rate,32);
  114205. oggpack_write(opb,vi->bitrate_upper,32);
  114206. oggpack_write(opb,vi->bitrate_nominal,32);
  114207. oggpack_write(opb,vi->bitrate_lower,32);
  114208. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114209. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114210. oggpack_write(opb,1,1);
  114211. return(0);
  114212. }
  114213. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114214. char temp[]="Xiph.Org libVorbis I 20050304";
  114215. int bytes = strlen(temp);
  114216. /* preamble */
  114217. oggpack_write(opb,0x03,8);
  114218. _v_writestring(opb,"vorbis", 6);
  114219. /* vendor */
  114220. oggpack_write(opb,bytes,32);
  114221. _v_writestring(opb,temp, bytes);
  114222. /* comments */
  114223. oggpack_write(opb,vc->comments,32);
  114224. if(vc->comments){
  114225. int i;
  114226. for(i=0;i<vc->comments;i++){
  114227. if(vc->user_comments[i]){
  114228. oggpack_write(opb,vc->comment_lengths[i],32);
  114229. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114230. }else{
  114231. oggpack_write(opb,0,32);
  114232. }
  114233. }
  114234. }
  114235. oggpack_write(opb,1,1);
  114236. return(0);
  114237. }
  114238. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114239. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114240. int i;
  114241. if(!ci)return(OV_EFAULT);
  114242. oggpack_write(opb,0x05,8);
  114243. _v_writestring(opb,"vorbis", 6);
  114244. /* books */
  114245. oggpack_write(opb,ci->books-1,8);
  114246. for(i=0;i<ci->books;i++)
  114247. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114248. /* times; hook placeholders */
  114249. oggpack_write(opb,0,6);
  114250. oggpack_write(opb,0,16);
  114251. /* floors */
  114252. oggpack_write(opb,ci->floors-1,6);
  114253. for(i=0;i<ci->floors;i++){
  114254. oggpack_write(opb,ci->floor_type[i],16);
  114255. if(_floor_P[ci->floor_type[i]]->pack)
  114256. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114257. else
  114258. goto err_out;
  114259. }
  114260. /* residues */
  114261. oggpack_write(opb,ci->residues-1,6);
  114262. for(i=0;i<ci->residues;i++){
  114263. oggpack_write(opb,ci->residue_type[i],16);
  114264. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114265. }
  114266. /* maps */
  114267. oggpack_write(opb,ci->maps-1,6);
  114268. for(i=0;i<ci->maps;i++){
  114269. oggpack_write(opb,ci->map_type[i],16);
  114270. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114271. }
  114272. /* modes */
  114273. oggpack_write(opb,ci->modes-1,6);
  114274. for(i=0;i<ci->modes;i++){
  114275. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114276. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114277. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114278. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114279. }
  114280. oggpack_write(opb,1,1);
  114281. return(0);
  114282. err_out:
  114283. return(-1);
  114284. }
  114285. int vorbis_commentheader_out(vorbis_comment *vc,
  114286. ogg_packet *op){
  114287. oggpack_buffer opb;
  114288. oggpack_writeinit(&opb);
  114289. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114290. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114291. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114292. op->bytes=oggpack_bytes(&opb);
  114293. op->b_o_s=0;
  114294. op->e_o_s=0;
  114295. op->granulepos=0;
  114296. op->packetno=1;
  114297. return 0;
  114298. }
  114299. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114300. vorbis_comment *vc,
  114301. ogg_packet *op,
  114302. ogg_packet *op_comm,
  114303. ogg_packet *op_code){
  114304. int ret=OV_EIMPL;
  114305. vorbis_info *vi=v->vi;
  114306. oggpack_buffer opb;
  114307. private_state *b=(private_state*)v->backend_state;
  114308. if(!b){
  114309. ret=OV_EFAULT;
  114310. goto err_out;
  114311. }
  114312. /* first header packet **********************************************/
  114313. oggpack_writeinit(&opb);
  114314. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114315. /* build the packet */
  114316. if(b->header)_ogg_free(b->header);
  114317. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114318. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114319. op->packet=b->header;
  114320. op->bytes=oggpack_bytes(&opb);
  114321. op->b_o_s=1;
  114322. op->e_o_s=0;
  114323. op->granulepos=0;
  114324. op->packetno=0;
  114325. /* second header packet (comments) **********************************/
  114326. oggpack_reset(&opb);
  114327. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114328. if(b->header1)_ogg_free(b->header1);
  114329. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114330. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114331. op_comm->packet=b->header1;
  114332. op_comm->bytes=oggpack_bytes(&opb);
  114333. op_comm->b_o_s=0;
  114334. op_comm->e_o_s=0;
  114335. op_comm->granulepos=0;
  114336. op_comm->packetno=1;
  114337. /* third header packet (modes/codebooks) ****************************/
  114338. oggpack_reset(&opb);
  114339. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114340. if(b->header2)_ogg_free(b->header2);
  114341. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114342. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114343. op_code->packet=b->header2;
  114344. op_code->bytes=oggpack_bytes(&opb);
  114345. op_code->b_o_s=0;
  114346. op_code->e_o_s=0;
  114347. op_code->granulepos=0;
  114348. op_code->packetno=2;
  114349. oggpack_writeclear(&opb);
  114350. return(0);
  114351. err_out:
  114352. oggpack_writeclear(&opb);
  114353. memset(op,0,sizeof(*op));
  114354. memset(op_comm,0,sizeof(*op_comm));
  114355. memset(op_code,0,sizeof(*op_code));
  114356. if(b->header)_ogg_free(b->header);
  114357. if(b->header1)_ogg_free(b->header1);
  114358. if(b->header2)_ogg_free(b->header2);
  114359. b->header=NULL;
  114360. b->header1=NULL;
  114361. b->header2=NULL;
  114362. return(ret);
  114363. }
  114364. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114365. if(granulepos>=0)
  114366. return((double)granulepos/v->vi->rate);
  114367. return(-1);
  114368. }
  114369. #endif
  114370. /*** End of inlined file: info.c ***/
  114371. /*** Start of inlined file: lpc.c ***/
  114372. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114373. are derived from code written by Jutta Degener and Carsten Bormann;
  114374. thus we include their copyright below. The entirety of this file
  114375. is freely redistributable on the condition that both of these
  114376. copyright notices are preserved without modification. */
  114377. /* Preserved Copyright: *********************************************/
  114378. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114379. Technische Universita"t Berlin
  114380. Any use of this software is permitted provided that this notice is not
  114381. removed and that neither the authors nor the Technische Universita"t
  114382. Berlin are deemed to have made any representations as to the
  114383. suitability of this software for any purpose nor are held responsible
  114384. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114385. THIS SOFTWARE.
  114386. As a matter of courtesy, the authors request to be informed about uses
  114387. this software has found, about bugs in this software, and about any
  114388. improvements that may be of general interest.
  114389. Berlin, 28.11.1994
  114390. Jutta Degener
  114391. Carsten Bormann
  114392. *********************************************************************/
  114393. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114394. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114395. // tasks..
  114396. #if JUCE_MSVC
  114397. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114398. #endif
  114399. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114400. #if JUCE_USE_OGGVORBIS
  114401. #include <stdlib.h>
  114402. #include <string.h>
  114403. #include <math.h>
  114404. /* Autocorrelation LPC coeff generation algorithm invented by
  114405. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114406. /* Input : n elements of time doamin data
  114407. Output: m lpc coefficients, excitation energy */
  114408. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114409. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114410. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114411. double error;
  114412. int i,j;
  114413. /* autocorrelation, p+1 lag coefficients */
  114414. j=m+1;
  114415. while(j--){
  114416. double d=0; /* double needed for accumulator depth */
  114417. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114418. aut[j]=d;
  114419. }
  114420. /* Generate lpc coefficients from autocorr values */
  114421. error=aut[0];
  114422. for(i=0;i<m;i++){
  114423. double r= -aut[i+1];
  114424. if(error==0){
  114425. memset(lpci,0,m*sizeof(*lpci));
  114426. return 0;
  114427. }
  114428. /* Sum up this iteration's reflection coefficient; note that in
  114429. Vorbis we don't save it. If anyone wants to recycle this code
  114430. and needs reflection coefficients, save the results of 'r' from
  114431. each iteration. */
  114432. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114433. r/=error;
  114434. /* Update LPC coefficients and total error */
  114435. lpc[i]=r;
  114436. for(j=0;j<i/2;j++){
  114437. double tmp=lpc[j];
  114438. lpc[j]+=r*lpc[i-1-j];
  114439. lpc[i-1-j]+=r*tmp;
  114440. }
  114441. if(i%2)lpc[j]+=lpc[j]*r;
  114442. error*=1.f-r*r;
  114443. }
  114444. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114445. /* we need the error value to know how big an impulse to hit the
  114446. filter with later */
  114447. return error;
  114448. }
  114449. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114450. float *data,long n){
  114451. /* in: coeff[0...m-1] LPC coefficients
  114452. prime[0...m-1] initial values (allocated size of n+m-1)
  114453. out: data[0...n-1] data samples */
  114454. long i,j,o,p;
  114455. float y;
  114456. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114457. if(!prime)
  114458. for(i=0;i<m;i++)
  114459. work[i]=0.f;
  114460. else
  114461. for(i=0;i<m;i++)
  114462. work[i]=prime[i];
  114463. for(i=0;i<n;i++){
  114464. y=0;
  114465. o=i;
  114466. p=m;
  114467. for(j=0;j<m;j++)
  114468. y-=work[o++]*coeff[--p];
  114469. data[i]=work[o]=y;
  114470. }
  114471. }
  114472. #endif
  114473. /*** End of inlined file: lpc.c ***/
  114474. /*** Start of inlined file: lsp.c ***/
  114475. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114476. an iterative root polisher (CACM algorithm 283). It *is* possible
  114477. to confuse this algorithm into not converging; that should only
  114478. happen with absurdly closely spaced roots (very sharp peaks in the
  114479. LPC f response) which in turn should be impossible in our use of
  114480. the code. If this *does* happen anyway, it's a bug in the floor
  114481. finder; find the cause of the confusion (probably a single bin
  114482. spike or accidental near-float-limit resolution problems) and
  114483. correct it. */
  114484. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114485. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114486. // tasks..
  114487. #if JUCE_MSVC
  114488. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114489. #endif
  114490. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114491. #if JUCE_USE_OGGVORBIS
  114492. #include <math.h>
  114493. #include <string.h>
  114494. #include <stdlib.h>
  114495. /*** Start of inlined file: lookup.h ***/
  114496. #ifndef _V_LOOKUP_H_
  114497. #ifdef FLOAT_LOOKUP
  114498. extern float vorbis_coslook(float a);
  114499. extern float vorbis_invsqlook(float a);
  114500. extern float vorbis_invsq2explook(int a);
  114501. extern float vorbis_fromdBlook(float a);
  114502. #endif
  114503. #ifdef INT_LOOKUP
  114504. extern long vorbis_invsqlook_i(long a,long e);
  114505. extern long vorbis_coslook_i(long a);
  114506. extern float vorbis_fromdBlook_i(long a);
  114507. #endif
  114508. #endif
  114509. /*** End of inlined file: lookup.h ***/
  114510. /* three possible LSP to f curve functions; the exact computation
  114511. (float), a lookup based float implementation, and an integer
  114512. implementation. The float lookup is likely the optimal choice on
  114513. any machine with an FPU. The integer implementation is *not* fixed
  114514. point (due to the need for a large dynamic range and thus a
  114515. seperately tracked exponent) and thus much more complex than the
  114516. relatively simple float implementations. It's mostly for future
  114517. work on a fully fixed point implementation for processors like the
  114518. ARM family. */
  114519. /* undefine both for the 'old' but more precise implementation */
  114520. #define FLOAT_LOOKUP
  114521. #undef INT_LOOKUP
  114522. #ifdef FLOAT_LOOKUP
  114523. /*** Start of inlined file: lookup.c ***/
  114524. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114525. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114526. // tasks..
  114527. #if JUCE_MSVC
  114528. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114529. #endif
  114530. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114531. #if JUCE_USE_OGGVORBIS
  114532. #include <math.h>
  114533. /*** Start of inlined file: lookup.h ***/
  114534. #ifndef _V_LOOKUP_H_
  114535. #ifdef FLOAT_LOOKUP
  114536. extern float vorbis_coslook(float a);
  114537. extern float vorbis_invsqlook(float a);
  114538. extern float vorbis_invsq2explook(int a);
  114539. extern float vorbis_fromdBlook(float a);
  114540. #endif
  114541. #ifdef INT_LOOKUP
  114542. extern long vorbis_invsqlook_i(long a,long e);
  114543. extern long vorbis_coslook_i(long a);
  114544. extern float vorbis_fromdBlook_i(long a);
  114545. #endif
  114546. #endif
  114547. /*** End of inlined file: lookup.h ***/
  114548. /*** Start of inlined file: lookup_data.h ***/
  114549. #ifndef _V_LOOKUP_DATA_H_
  114550. #ifdef FLOAT_LOOKUP
  114551. #define COS_LOOKUP_SZ 128
  114552. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114553. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114554. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114555. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114556. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114557. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114558. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114559. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114560. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114561. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114562. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114563. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114564. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114565. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114566. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114567. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114568. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114569. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114570. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114571. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114572. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114573. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114574. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114575. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114576. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114577. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114578. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114579. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114580. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114581. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114582. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114583. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114584. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114585. -1.0000000000000f,
  114586. };
  114587. #define INVSQ_LOOKUP_SZ 32
  114588. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114589. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114590. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114591. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114592. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114593. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114594. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114595. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114596. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114597. 1.000000000000f,
  114598. };
  114599. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114600. #define INVSQ2EXP_LOOKUP_MAX 32
  114601. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114602. INVSQ2EXP_LOOKUP_MIN+1]={
  114603. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114604. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114605. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114606. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114607. 256.f, 181.019336f, 128.f, 90.50966799f,
  114608. 64.f, 45.254834f, 32.f, 22.627417f,
  114609. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114610. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114611. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114612. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114613. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114614. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114615. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114616. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114617. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114618. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114619. 1.525878906e-05f,
  114620. };
  114621. #endif
  114622. #define FROMdB_LOOKUP_SZ 35
  114623. #define FROMdB2_LOOKUP_SZ 32
  114624. #define FROMdB_SHIFT 5
  114625. #define FROMdB2_SHIFT 3
  114626. #define FROMdB2_MASK 31
  114627. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114628. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114629. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114630. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114631. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114632. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114633. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114634. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114635. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114636. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114637. };
  114638. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114639. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114640. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114641. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114642. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114643. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114644. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114645. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114646. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114647. };
  114648. #ifdef INT_LOOKUP
  114649. #define INVSQ_LOOKUP_I_SHIFT 10
  114650. #define INVSQ_LOOKUP_I_MASK 1023
  114651. static long INVSQ_LOOKUP_I[64+1]={
  114652. 92682l, 91966l, 91267l, 90583l,
  114653. 89915l, 89261l, 88621l, 87995l,
  114654. 87381l, 86781l, 86192l, 85616l,
  114655. 85051l, 84497l, 83953l, 83420l,
  114656. 82897l, 82384l, 81880l, 81385l,
  114657. 80899l, 80422l, 79953l, 79492l,
  114658. 79039l, 78594l, 78156l, 77726l,
  114659. 77302l, 76885l, 76475l, 76072l,
  114660. 75674l, 75283l, 74898l, 74519l,
  114661. 74146l, 73778l, 73415l, 73058l,
  114662. 72706l, 72359l, 72016l, 71679l,
  114663. 71347l, 71019l, 70695l, 70376l,
  114664. 70061l, 69750l, 69444l, 69141l,
  114665. 68842l, 68548l, 68256l, 67969l,
  114666. 67685l, 67405l, 67128l, 66855l,
  114667. 66585l, 66318l, 66054l, 65794l,
  114668. 65536l,
  114669. };
  114670. #define COS_LOOKUP_I_SHIFT 9
  114671. #define COS_LOOKUP_I_MASK 511
  114672. #define COS_LOOKUP_I_SZ 128
  114673. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114674. 16384l, 16379l, 16364l, 16340l,
  114675. 16305l, 16261l, 16207l, 16143l,
  114676. 16069l, 15986l, 15893l, 15791l,
  114677. 15679l, 15557l, 15426l, 15286l,
  114678. 15137l, 14978l, 14811l, 14635l,
  114679. 14449l, 14256l, 14053l, 13842l,
  114680. 13623l, 13395l, 13160l, 12916l,
  114681. 12665l, 12406l, 12140l, 11866l,
  114682. 11585l, 11297l, 11003l, 10702l,
  114683. 10394l, 10080l, 9760l, 9434l,
  114684. 9102l, 8765l, 8423l, 8076l,
  114685. 7723l, 7366l, 7005l, 6639l,
  114686. 6270l, 5897l, 5520l, 5139l,
  114687. 4756l, 4370l, 3981l, 3590l,
  114688. 3196l, 2801l, 2404l, 2006l,
  114689. 1606l, 1205l, 804l, 402l,
  114690. 0l, -401l, -803l, -1204l,
  114691. -1605l, -2005l, -2403l, -2800l,
  114692. -3195l, -3589l, -3980l, -4369l,
  114693. -4755l, -5138l, -5519l, -5896l,
  114694. -6269l, -6638l, -7004l, -7365l,
  114695. -7722l, -8075l, -8422l, -8764l,
  114696. -9101l, -9433l, -9759l, -10079l,
  114697. -10393l, -10701l, -11002l, -11296l,
  114698. -11584l, -11865l, -12139l, -12405l,
  114699. -12664l, -12915l, -13159l, -13394l,
  114700. -13622l, -13841l, -14052l, -14255l,
  114701. -14448l, -14634l, -14810l, -14977l,
  114702. -15136l, -15285l, -15425l, -15556l,
  114703. -15678l, -15790l, -15892l, -15985l,
  114704. -16068l, -16142l, -16206l, -16260l,
  114705. -16304l, -16339l, -16363l, -16378l,
  114706. -16383l,
  114707. };
  114708. #endif
  114709. #endif
  114710. /*** End of inlined file: lookup_data.h ***/
  114711. #ifdef FLOAT_LOOKUP
  114712. /* interpolated lookup based cos function, domain 0 to PI only */
  114713. float vorbis_coslook(float a){
  114714. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114715. int i=vorbis_ftoi(d-.5);
  114716. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114717. }
  114718. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114719. float vorbis_invsqlook(float a){
  114720. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114721. int i=vorbis_ftoi(d-.5f);
  114722. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114723. }
  114724. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114725. float vorbis_invsq2explook(int a){
  114726. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114727. }
  114728. #include <stdio.h>
  114729. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114730. float vorbis_fromdBlook(float a){
  114731. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114732. return (i<0)?1.f:
  114733. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114734. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114735. }
  114736. #endif
  114737. #ifdef INT_LOOKUP
  114738. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114739. 16.16 format
  114740. returns in m.8 format */
  114741. long vorbis_invsqlook_i(long a,long e){
  114742. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114743. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114744. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114745. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114746. d)>>16); /* result 1.16 */
  114747. e+=32;
  114748. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114749. e=(e>>1)-8;
  114750. return(val>>e);
  114751. }
  114752. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114753. /* a is in n.12 format */
  114754. float vorbis_fromdBlook_i(long a){
  114755. int i=(-a)>>(12-FROMdB2_SHIFT);
  114756. return (i<0)?1.f:
  114757. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114758. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114759. }
  114760. /* interpolated lookup based cos function, domain 0 to PI only */
  114761. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114762. long vorbis_coslook_i(long a){
  114763. int i=a>>COS_LOOKUP_I_SHIFT;
  114764. int d=a&COS_LOOKUP_I_MASK;
  114765. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114766. COS_LOOKUP_I_SHIFT);
  114767. }
  114768. #endif
  114769. #endif
  114770. /*** End of inlined file: lookup.c ***/
  114771. /* catch this in the build system; we #include for
  114772. compilers (like gcc) that can't inline across
  114773. modules */
  114774. /* side effect: changes *lsp to cosines of lsp */
  114775. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114776. float amp,float ampoffset){
  114777. int i;
  114778. float wdel=M_PI/ln;
  114779. vorbis_fpu_control fpu;
  114780. (void) fpu; // to avoid an unused variable warning
  114781. vorbis_fpu_setround(&fpu);
  114782. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114783. i=0;
  114784. while(i<n){
  114785. int k=map[i];
  114786. int qexp;
  114787. float p=.7071067812f;
  114788. float q=.7071067812f;
  114789. float w=vorbis_coslook(wdel*k);
  114790. float *ftmp=lsp;
  114791. int c=m>>1;
  114792. do{
  114793. q*=ftmp[0]-w;
  114794. p*=ftmp[1]-w;
  114795. ftmp+=2;
  114796. }while(--c);
  114797. if(m&1){
  114798. /* odd order filter; slightly assymetric */
  114799. /* the last coefficient */
  114800. q*=ftmp[0]-w;
  114801. q*=q;
  114802. p*=p*(1.f-w*w);
  114803. }else{
  114804. /* even order filter; still symmetric */
  114805. q*=q*(1.f+w);
  114806. p*=p*(1.f-w);
  114807. }
  114808. q=frexp(p+q,&qexp);
  114809. q=vorbis_fromdBlook(amp*
  114810. vorbis_invsqlook(q)*
  114811. vorbis_invsq2explook(qexp+m)-
  114812. ampoffset);
  114813. do{
  114814. curve[i++]*=q;
  114815. }while(map[i]==k);
  114816. }
  114817. vorbis_fpu_restore(fpu);
  114818. }
  114819. #else
  114820. #ifdef INT_LOOKUP
  114821. /*** Start of inlined file: lookup.c ***/
  114822. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114823. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114824. // tasks..
  114825. #if JUCE_MSVC
  114826. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114827. #endif
  114828. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114829. #if JUCE_USE_OGGVORBIS
  114830. #include <math.h>
  114831. /*** Start of inlined file: lookup.h ***/
  114832. #ifndef _V_LOOKUP_H_
  114833. #ifdef FLOAT_LOOKUP
  114834. extern float vorbis_coslook(float a);
  114835. extern float vorbis_invsqlook(float a);
  114836. extern float vorbis_invsq2explook(int a);
  114837. extern float vorbis_fromdBlook(float a);
  114838. #endif
  114839. #ifdef INT_LOOKUP
  114840. extern long vorbis_invsqlook_i(long a,long e);
  114841. extern long vorbis_coslook_i(long a);
  114842. extern float vorbis_fromdBlook_i(long a);
  114843. #endif
  114844. #endif
  114845. /*** End of inlined file: lookup.h ***/
  114846. /*** Start of inlined file: lookup_data.h ***/
  114847. #ifndef _V_LOOKUP_DATA_H_
  114848. #ifdef FLOAT_LOOKUP
  114849. #define COS_LOOKUP_SZ 128
  114850. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114851. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114852. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114853. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114854. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114855. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114856. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114857. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114858. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114859. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114860. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114861. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114862. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114863. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114864. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114865. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114866. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114867. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114868. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114869. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114870. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114871. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114872. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114873. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114874. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114875. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114876. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114877. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114878. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114879. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114880. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114881. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114882. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114883. -1.0000000000000f,
  114884. };
  114885. #define INVSQ_LOOKUP_SZ 32
  114886. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114887. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114888. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114889. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114890. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114891. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114892. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114893. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114894. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114895. 1.000000000000f,
  114896. };
  114897. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114898. #define INVSQ2EXP_LOOKUP_MAX 32
  114899. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114900. INVSQ2EXP_LOOKUP_MIN+1]={
  114901. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114902. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114903. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114904. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114905. 256.f, 181.019336f, 128.f, 90.50966799f,
  114906. 64.f, 45.254834f, 32.f, 22.627417f,
  114907. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114908. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114909. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114910. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114911. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114912. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114913. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114914. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114915. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114916. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114917. 1.525878906e-05f,
  114918. };
  114919. #endif
  114920. #define FROMdB_LOOKUP_SZ 35
  114921. #define FROMdB2_LOOKUP_SZ 32
  114922. #define FROMdB_SHIFT 5
  114923. #define FROMdB2_SHIFT 3
  114924. #define FROMdB2_MASK 31
  114925. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114926. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114927. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114928. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114929. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114930. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114931. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114932. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114933. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114934. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114935. };
  114936. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114937. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114938. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114939. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114940. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114941. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114942. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114943. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114944. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114945. };
  114946. #ifdef INT_LOOKUP
  114947. #define INVSQ_LOOKUP_I_SHIFT 10
  114948. #define INVSQ_LOOKUP_I_MASK 1023
  114949. static long INVSQ_LOOKUP_I[64+1]={
  114950. 92682l, 91966l, 91267l, 90583l,
  114951. 89915l, 89261l, 88621l, 87995l,
  114952. 87381l, 86781l, 86192l, 85616l,
  114953. 85051l, 84497l, 83953l, 83420l,
  114954. 82897l, 82384l, 81880l, 81385l,
  114955. 80899l, 80422l, 79953l, 79492l,
  114956. 79039l, 78594l, 78156l, 77726l,
  114957. 77302l, 76885l, 76475l, 76072l,
  114958. 75674l, 75283l, 74898l, 74519l,
  114959. 74146l, 73778l, 73415l, 73058l,
  114960. 72706l, 72359l, 72016l, 71679l,
  114961. 71347l, 71019l, 70695l, 70376l,
  114962. 70061l, 69750l, 69444l, 69141l,
  114963. 68842l, 68548l, 68256l, 67969l,
  114964. 67685l, 67405l, 67128l, 66855l,
  114965. 66585l, 66318l, 66054l, 65794l,
  114966. 65536l,
  114967. };
  114968. #define COS_LOOKUP_I_SHIFT 9
  114969. #define COS_LOOKUP_I_MASK 511
  114970. #define COS_LOOKUP_I_SZ 128
  114971. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114972. 16384l, 16379l, 16364l, 16340l,
  114973. 16305l, 16261l, 16207l, 16143l,
  114974. 16069l, 15986l, 15893l, 15791l,
  114975. 15679l, 15557l, 15426l, 15286l,
  114976. 15137l, 14978l, 14811l, 14635l,
  114977. 14449l, 14256l, 14053l, 13842l,
  114978. 13623l, 13395l, 13160l, 12916l,
  114979. 12665l, 12406l, 12140l, 11866l,
  114980. 11585l, 11297l, 11003l, 10702l,
  114981. 10394l, 10080l, 9760l, 9434l,
  114982. 9102l, 8765l, 8423l, 8076l,
  114983. 7723l, 7366l, 7005l, 6639l,
  114984. 6270l, 5897l, 5520l, 5139l,
  114985. 4756l, 4370l, 3981l, 3590l,
  114986. 3196l, 2801l, 2404l, 2006l,
  114987. 1606l, 1205l, 804l, 402l,
  114988. 0l, -401l, -803l, -1204l,
  114989. -1605l, -2005l, -2403l, -2800l,
  114990. -3195l, -3589l, -3980l, -4369l,
  114991. -4755l, -5138l, -5519l, -5896l,
  114992. -6269l, -6638l, -7004l, -7365l,
  114993. -7722l, -8075l, -8422l, -8764l,
  114994. -9101l, -9433l, -9759l, -10079l,
  114995. -10393l, -10701l, -11002l, -11296l,
  114996. -11584l, -11865l, -12139l, -12405l,
  114997. -12664l, -12915l, -13159l, -13394l,
  114998. -13622l, -13841l, -14052l, -14255l,
  114999. -14448l, -14634l, -14810l, -14977l,
  115000. -15136l, -15285l, -15425l, -15556l,
  115001. -15678l, -15790l, -15892l, -15985l,
  115002. -16068l, -16142l, -16206l, -16260l,
  115003. -16304l, -16339l, -16363l, -16378l,
  115004. -16383l,
  115005. };
  115006. #endif
  115007. #endif
  115008. /*** End of inlined file: lookup_data.h ***/
  115009. #ifdef FLOAT_LOOKUP
  115010. /* interpolated lookup based cos function, domain 0 to PI only */
  115011. float vorbis_coslook(float a){
  115012. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  115013. int i=vorbis_ftoi(d-.5);
  115014. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  115015. }
  115016. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115017. float vorbis_invsqlook(float a){
  115018. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  115019. int i=vorbis_ftoi(d-.5f);
  115020. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  115021. }
  115022. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115023. float vorbis_invsq2explook(int a){
  115024. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  115025. }
  115026. #include <stdio.h>
  115027. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115028. float vorbis_fromdBlook(float a){
  115029. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  115030. return (i<0)?1.f:
  115031. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115032. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115033. }
  115034. #endif
  115035. #ifdef INT_LOOKUP
  115036. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  115037. 16.16 format
  115038. returns in m.8 format */
  115039. long vorbis_invsqlook_i(long a,long e){
  115040. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  115041. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  115042. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  115043. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  115044. d)>>16); /* result 1.16 */
  115045. e+=32;
  115046. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  115047. e=(e>>1)-8;
  115048. return(val>>e);
  115049. }
  115050. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115051. /* a is in n.12 format */
  115052. float vorbis_fromdBlook_i(long a){
  115053. int i=(-a)>>(12-FROMdB2_SHIFT);
  115054. return (i<0)?1.f:
  115055. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115056. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115057. }
  115058. /* interpolated lookup based cos function, domain 0 to PI only */
  115059. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  115060. long vorbis_coslook_i(long a){
  115061. int i=a>>COS_LOOKUP_I_SHIFT;
  115062. int d=a&COS_LOOKUP_I_MASK;
  115063. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  115064. COS_LOOKUP_I_SHIFT);
  115065. }
  115066. #endif
  115067. #endif
  115068. /*** End of inlined file: lookup.c ***/
  115069. /* catch this in the build system; we #include for
  115070. compilers (like gcc) that can't inline across
  115071. modules */
  115072. static int MLOOP_1[64]={
  115073. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  115074. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  115075. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115076. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115077. };
  115078. static int MLOOP_2[64]={
  115079. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  115080. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  115081. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115082. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115083. };
  115084. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  115085. /* side effect: changes *lsp to cosines of lsp */
  115086. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115087. float amp,float ampoffset){
  115088. /* 0 <= m < 256 */
  115089. /* set up for using all int later */
  115090. int i;
  115091. int ampoffseti=rint(ampoffset*4096.f);
  115092. int ampi=rint(amp*16.f);
  115093. long *ilsp=alloca(m*sizeof(*ilsp));
  115094. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  115095. i=0;
  115096. while(i<n){
  115097. int j,k=map[i];
  115098. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  115099. unsigned long qi=46341;
  115100. int qexp=0,shift;
  115101. long wi=vorbis_coslook_i(k*65536/ln);
  115102. qi*=labs(ilsp[0]-wi);
  115103. pi*=labs(ilsp[1]-wi);
  115104. for(j=3;j<m;j+=2){
  115105. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115106. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115107. shift=MLOOP_3[(pi|qi)>>16];
  115108. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115109. pi=(pi>>shift)*labs(ilsp[j]-wi);
  115110. qexp+=shift;
  115111. }
  115112. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115113. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115114. shift=MLOOP_3[(pi|qi)>>16];
  115115. /* pi,qi normalized collectively, both tracked using qexp */
  115116. if(m&1){
  115117. /* odd order filter; slightly assymetric */
  115118. /* the last coefficient */
  115119. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115120. pi=(pi>>shift)<<14;
  115121. qexp+=shift;
  115122. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115123. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115124. shift=MLOOP_3[(pi|qi)>>16];
  115125. pi>>=shift;
  115126. qi>>=shift;
  115127. qexp+=shift-14*((m+1)>>1);
  115128. pi=((pi*pi)>>16);
  115129. qi=((qi*qi)>>16);
  115130. qexp=qexp*2+m;
  115131. pi*=(1<<14)-((wi*wi)>>14);
  115132. qi+=pi>>14;
  115133. }else{
  115134. /* even order filter; still symmetric */
  115135. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  115136. worth tracking step by step */
  115137. pi>>=shift;
  115138. qi>>=shift;
  115139. qexp+=shift-7*m;
  115140. pi=((pi*pi)>>16);
  115141. qi=((qi*qi)>>16);
  115142. qexp=qexp*2+m;
  115143. pi*=(1<<14)-wi;
  115144. qi*=(1<<14)+wi;
  115145. qi=(qi+pi)>>14;
  115146. }
  115147. /* we've let the normalization drift because it wasn't important;
  115148. however, for the lookup, things must be normalized again. We
  115149. need at most one right shift or a number of left shifts */
  115150. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  115151. qi>>=1; qexp++;
  115152. }else
  115153. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  115154. qi<<=1; qexp--;
  115155. }
  115156. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115157. vorbis_invsqlook_i(qi,qexp)-
  115158. /* m.8, m+n<=8 */
  115159. ampoffseti); /* 8.12[0] */
  115160. curve[i]*=amp;
  115161. while(map[++i]==k)curve[i]*=amp;
  115162. }
  115163. }
  115164. #else
  115165. /* old, nonoptimized but simple version for any poor sap who needs to
  115166. figure out what the hell this code does, or wants the other
  115167. fraction of a dB precision */
  115168. /* side effect: changes *lsp to cosines of lsp */
  115169. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115170. float amp,float ampoffset){
  115171. int i;
  115172. float wdel=M_PI/ln;
  115173. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115174. i=0;
  115175. while(i<n){
  115176. int j,k=map[i];
  115177. float p=.5f;
  115178. float q=.5f;
  115179. float w=2.f*cos(wdel*k);
  115180. for(j=1;j<m;j+=2){
  115181. q *= w-lsp[j-1];
  115182. p *= w-lsp[j];
  115183. }
  115184. if(j==m){
  115185. /* odd order filter; slightly assymetric */
  115186. /* the last coefficient */
  115187. q*=w-lsp[j-1];
  115188. p*=p*(4.f-w*w);
  115189. q*=q;
  115190. }else{
  115191. /* even order filter; still symmetric */
  115192. p*=p*(2.f-w);
  115193. q*=q*(2.f+w);
  115194. }
  115195. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115196. curve[i]*=q;
  115197. while(map[++i]==k)curve[i]*=q;
  115198. }
  115199. }
  115200. #endif
  115201. #endif
  115202. static void cheby(float *g, int ord) {
  115203. int i, j;
  115204. g[0] *= .5f;
  115205. for(i=2; i<= ord; i++) {
  115206. for(j=ord; j >= i; j--) {
  115207. g[j-2] -= g[j];
  115208. g[j] += g[j];
  115209. }
  115210. }
  115211. }
  115212. static int JUCE_CDECL comp(const void *a,const void *b){
  115213. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115214. }
  115215. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115216. but there are root sets for which it gets into limit cycles
  115217. (exacerbated by zero suppression) and fails. We can't afford to
  115218. fail, even if the failure is 1 in 100,000,000, so we now use
  115219. Laguerre and later polish with Newton-Raphson (which can then
  115220. afford to fail) */
  115221. #define EPSILON 10e-7
  115222. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115223. int i,m;
  115224. double lastdelta=0.f;
  115225. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115226. for(i=0;i<=ord;i++)defl[i]=a[i];
  115227. for(m=ord;m>0;m--){
  115228. double newx=0.f,delta;
  115229. /* iterate a root */
  115230. while(1){
  115231. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115232. /* eval the polynomial and its first two derivatives */
  115233. for(i=m;i>0;i--){
  115234. ppp = newx*ppp + pp;
  115235. pp = newx*pp + p;
  115236. p = newx*p + defl[i-1];
  115237. }
  115238. /* Laguerre's method */
  115239. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115240. if(denom<0)
  115241. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115242. if(pp>0){
  115243. denom = pp + sqrt(denom);
  115244. if(denom<EPSILON)denom=EPSILON;
  115245. }else{
  115246. denom = pp - sqrt(denom);
  115247. if(denom>-(EPSILON))denom=-(EPSILON);
  115248. }
  115249. delta = m*p/denom;
  115250. newx -= delta;
  115251. if(delta<0.f)delta*=-1;
  115252. if(fabs(delta/newx)<10e-12)break;
  115253. lastdelta=delta;
  115254. }
  115255. r[m-1]=newx;
  115256. /* forward deflation */
  115257. for(i=m;i>0;i--)
  115258. defl[i-1]+=newx*defl[i];
  115259. defl++;
  115260. }
  115261. return(0);
  115262. }
  115263. /* for spit-and-polish only */
  115264. static int Newton_Raphson(float *a,int ord,float *r){
  115265. int i, k, count=0;
  115266. double error=1.f;
  115267. double *root=(double*)alloca(ord*sizeof(*root));
  115268. for(i=0; i<ord;i++) root[i] = r[i];
  115269. while(error>1e-20){
  115270. error=0;
  115271. for(i=0; i<ord; i++) { /* Update each point. */
  115272. double pp=0.,delta;
  115273. double rooti=root[i];
  115274. double p=a[ord];
  115275. for(k=ord-1; k>= 0; k--) {
  115276. pp= pp* rooti + p;
  115277. p = p * rooti + a[k];
  115278. }
  115279. delta = p/pp;
  115280. root[i] -= delta;
  115281. error+= delta*delta;
  115282. }
  115283. if(count>40)return(-1);
  115284. count++;
  115285. }
  115286. /* Replaced the original bubble sort with a real sort. With your
  115287. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115288. for(i=0; i<ord;i++) r[i] = root[i];
  115289. return(0);
  115290. }
  115291. /* Convert lpc coefficients to lsp coefficients */
  115292. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115293. int order2=(m+1)>>1;
  115294. int g1_order,g2_order;
  115295. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115296. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115297. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115298. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115299. int i;
  115300. /* even and odd are slightly different base cases */
  115301. g1_order=(m+1)>>1;
  115302. g2_order=(m) >>1;
  115303. /* Compute the lengths of the x polynomials. */
  115304. /* Compute the first half of K & R F1 & F2 polynomials. */
  115305. /* Compute half of the symmetric and antisymmetric polynomials. */
  115306. /* Remove the roots at +1 and -1. */
  115307. g1[g1_order] = 1.f;
  115308. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115309. g2[g2_order] = 1.f;
  115310. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115311. if(g1_order>g2_order){
  115312. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115313. }else{
  115314. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115315. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115316. }
  115317. /* Convert into polynomials in cos(alpha) */
  115318. cheby(g1,g1_order);
  115319. cheby(g2,g2_order);
  115320. /* Find the roots of the 2 even polynomials.*/
  115321. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115322. Laguerre_With_Deflation(g2,g2_order,g2r))
  115323. return(-1);
  115324. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115325. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115326. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115327. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115328. for(i=0;i<g1_order;i++)
  115329. lsp[i*2] = acos(g1r[i]);
  115330. for(i=0;i<g2_order;i++)
  115331. lsp[i*2+1] = acos(g2r[i]);
  115332. return(0);
  115333. }
  115334. #endif
  115335. /*** End of inlined file: lsp.c ***/
  115336. /*** Start of inlined file: mapping0.c ***/
  115337. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115338. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115339. // tasks..
  115340. #if JUCE_MSVC
  115341. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115342. #endif
  115343. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115344. #if JUCE_USE_OGGVORBIS
  115345. #include <stdlib.h>
  115346. #include <stdio.h>
  115347. #include <string.h>
  115348. #include <math.h>
  115349. /* simplistic, wasteful way of doing this (unique lookup for each
  115350. mode/submapping); there should be a central repository for
  115351. identical lookups. That will require minor work, so I'm putting it
  115352. off as low priority.
  115353. Why a lookup for each backend in a given mode? Because the
  115354. blocksize is set by the mode, and low backend lookups may require
  115355. parameters from other areas of the mode/mapping */
  115356. static void mapping0_free_info(vorbis_info_mapping *i){
  115357. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115358. if(info){
  115359. memset(info,0,sizeof(*info));
  115360. _ogg_free(info);
  115361. }
  115362. }
  115363. static int ilog3(unsigned int v){
  115364. int ret=0;
  115365. if(v)--v;
  115366. while(v){
  115367. ret++;
  115368. v>>=1;
  115369. }
  115370. return(ret);
  115371. }
  115372. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115373. oggpack_buffer *opb){
  115374. int i;
  115375. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115376. /* another 'we meant to do it this way' hack... up to beta 4, we
  115377. packed 4 binary zeros here to signify one submapping in use. We
  115378. now redefine that to mean four bitflags that indicate use of
  115379. deeper features; bit0:submappings, bit1:coupling,
  115380. bit2,3:reserved. This is backward compatable with all actual uses
  115381. of the beta code. */
  115382. if(info->submaps>1){
  115383. oggpack_write(opb,1,1);
  115384. oggpack_write(opb,info->submaps-1,4);
  115385. }else
  115386. oggpack_write(opb,0,1);
  115387. if(info->coupling_steps>0){
  115388. oggpack_write(opb,1,1);
  115389. oggpack_write(opb,info->coupling_steps-1,8);
  115390. for(i=0;i<info->coupling_steps;i++){
  115391. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115392. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115393. }
  115394. }else
  115395. oggpack_write(opb,0,1);
  115396. oggpack_write(opb,0,2); /* 2,3:reserved */
  115397. /* we don't write the channel submappings if we only have one... */
  115398. if(info->submaps>1){
  115399. for(i=0;i<vi->channels;i++)
  115400. oggpack_write(opb,info->chmuxlist[i],4);
  115401. }
  115402. for(i=0;i<info->submaps;i++){
  115403. oggpack_write(opb,0,8); /* time submap unused */
  115404. oggpack_write(opb,info->floorsubmap[i],8);
  115405. oggpack_write(opb,info->residuesubmap[i],8);
  115406. }
  115407. }
  115408. /* also responsible for range checking */
  115409. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115410. int i;
  115411. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115412. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115413. memset(info,0,sizeof(*info));
  115414. if(oggpack_read(opb,1))
  115415. info->submaps=oggpack_read(opb,4)+1;
  115416. else
  115417. info->submaps=1;
  115418. if(oggpack_read(opb,1)){
  115419. info->coupling_steps=oggpack_read(opb,8)+1;
  115420. for(i=0;i<info->coupling_steps;i++){
  115421. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115422. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115423. if(testM<0 ||
  115424. testA<0 ||
  115425. testM==testA ||
  115426. testM>=vi->channels ||
  115427. testA>=vi->channels) goto err_out;
  115428. }
  115429. }
  115430. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115431. if(info->submaps>1){
  115432. for(i=0;i<vi->channels;i++){
  115433. info->chmuxlist[i]=oggpack_read(opb,4);
  115434. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115435. }
  115436. }
  115437. for(i=0;i<info->submaps;i++){
  115438. oggpack_read(opb,8); /* time submap unused */
  115439. info->floorsubmap[i]=oggpack_read(opb,8);
  115440. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115441. info->residuesubmap[i]=oggpack_read(opb,8);
  115442. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115443. }
  115444. return info;
  115445. err_out:
  115446. mapping0_free_info(info);
  115447. return(NULL);
  115448. }
  115449. #if 0
  115450. static long seq=0;
  115451. static ogg_int64_t total=0;
  115452. static float FLOOR1_fromdB_LOOKUP[256]={
  115453. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115454. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115455. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115456. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115457. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115458. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115459. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115460. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115461. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115462. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115463. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115464. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115465. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115466. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115467. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115468. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115469. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115470. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115471. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115472. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115473. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115474. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115475. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115476. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115477. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115478. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115479. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115480. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115481. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115482. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115483. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115484. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115485. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115486. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115487. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115488. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115489. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115490. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115491. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115492. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115493. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115494. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115495. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115496. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115497. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115498. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115499. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115500. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115501. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115502. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115503. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115504. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115505. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115506. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115507. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115508. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115509. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115510. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115511. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115512. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115513. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115514. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115515. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115516. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115517. };
  115518. #endif
  115519. extern int *floor1_fit(vorbis_block *vb,void *look,
  115520. const float *logmdct, /* in */
  115521. const float *logmask);
  115522. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115523. int *A,int *B,
  115524. int del);
  115525. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115526. void*look,
  115527. int *post,int *ilogmask);
  115528. static int mapping0_forward(vorbis_block *vb){
  115529. vorbis_dsp_state *vd=vb->vd;
  115530. vorbis_info *vi=vd->vi;
  115531. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115532. private_state *b=(private_state*)vb->vd->backend_state;
  115533. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115534. int n=vb->pcmend;
  115535. int i,j,k;
  115536. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115537. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115538. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115539. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115540. float global_ampmax=vbi->ampmax;
  115541. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115542. int blocktype=vbi->blocktype;
  115543. int modenumber=vb->W;
  115544. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115545. vorbis_look_psy *psy_look=
  115546. b->psy+blocktype+(vb->W?2:0);
  115547. vb->mode=modenumber;
  115548. for(i=0;i<vi->channels;i++){
  115549. float scale=4.f/n;
  115550. float scale_dB;
  115551. float *pcm =vb->pcm[i];
  115552. float *logfft =pcm;
  115553. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115554. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115555. todB estimation used on IEEE 754
  115556. compliant machines had a bug that
  115557. returned dB values about a third
  115558. of a decibel too high. The bug
  115559. was harmless because tunings
  115560. implicitly took that into
  115561. account. However, fixing the bug
  115562. in the estimator requires
  115563. changing all the tunings as well.
  115564. For now, it's easier to sync
  115565. things back up here, and
  115566. recalibrate the tunings in the
  115567. next major model upgrade. */
  115568. #if 0
  115569. if(vi->channels==2)
  115570. if(i==0)
  115571. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115572. else
  115573. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115574. #endif
  115575. /* window the PCM data */
  115576. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115577. #if 0
  115578. if(vi->channels==2)
  115579. if(i==0)
  115580. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115581. else
  115582. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115583. #endif
  115584. /* transform the PCM data */
  115585. /* only MDCT right now.... */
  115586. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115587. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115588. drft_forward(&b->fft_look[vb->W],pcm);
  115589. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115590. original todB estimation used on
  115591. IEEE 754 compliant machines had a
  115592. bug that returned dB values about
  115593. a third of a decibel too high.
  115594. The bug was harmless because
  115595. tunings implicitly took that into
  115596. account. However, fixing the bug
  115597. in the estimator requires
  115598. changing all the tunings as well.
  115599. For now, it's easier to sync
  115600. things back up here, and
  115601. recalibrate the tunings in the
  115602. next major model upgrade. */
  115603. local_ampmax[i]=logfft[0];
  115604. for(j=1;j<n-1;j+=2){
  115605. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115606. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115607. .345 is a hack; the original todB
  115608. estimation used on IEEE 754
  115609. compliant machines had a bug that
  115610. returned dB values about a third
  115611. of a decibel too high. The bug
  115612. was harmless because tunings
  115613. implicitly took that into
  115614. account. However, fixing the bug
  115615. in the estimator requires
  115616. changing all the tunings as well.
  115617. For now, it's easier to sync
  115618. things back up here, and
  115619. recalibrate the tunings in the
  115620. next major model upgrade. */
  115621. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115622. }
  115623. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115624. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115625. #if 0
  115626. if(vi->channels==2){
  115627. if(i==0){
  115628. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115629. }else{
  115630. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115631. }
  115632. }
  115633. #endif
  115634. }
  115635. {
  115636. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115637. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115638. for(i=0;i<vi->channels;i++){
  115639. /* the encoder setup assumes that all the modes used by any
  115640. specific bitrate tweaking use the same floor */
  115641. int submap=info->chmuxlist[i];
  115642. /* the following makes things clearer to *me* anyway */
  115643. float *mdct =gmdct[i];
  115644. float *logfft =vb->pcm[i];
  115645. float *logmdct =logfft+n/2;
  115646. float *logmask =logfft;
  115647. vb->mode=modenumber;
  115648. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115649. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115650. for(j=0;j<n/2;j++)
  115651. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115652. todB estimation used on IEEE 754
  115653. compliant machines had a bug that
  115654. returned dB values about a third
  115655. of a decibel too high. The bug
  115656. was harmless because tunings
  115657. implicitly took that into
  115658. account. However, fixing the bug
  115659. in the estimator requires
  115660. changing all the tunings as well.
  115661. For now, it's easier to sync
  115662. things back up here, and
  115663. recalibrate the tunings in the
  115664. next major model upgrade. */
  115665. #if 0
  115666. if(vi->channels==2){
  115667. if(i==0)
  115668. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115669. else
  115670. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115671. }else{
  115672. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115673. }
  115674. #endif
  115675. /* first step; noise masking. Not only does 'noise masking'
  115676. give us curves from which we can decide how much resolution
  115677. to give noise parts of the spectrum, it also implicitly hands
  115678. us a tonality estimate (the larger the value in the
  115679. 'noise_depth' vector, the more tonal that area is) */
  115680. _vp_noisemask(psy_look,
  115681. logmdct,
  115682. noise); /* noise does not have by-frequency offset
  115683. bias applied yet */
  115684. #if 0
  115685. if(vi->channels==2){
  115686. if(i==0)
  115687. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115688. else
  115689. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115690. }
  115691. #endif
  115692. /* second step: 'all the other crap'; all the stuff that isn't
  115693. computed/fit for bitrate management goes in the second psy
  115694. vector. This includes tone masking, peak limiting and ATH */
  115695. _vp_tonemask(psy_look,
  115696. logfft,
  115697. tone,
  115698. global_ampmax,
  115699. local_ampmax[i]);
  115700. #if 0
  115701. if(vi->channels==2){
  115702. if(i==0)
  115703. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115704. else
  115705. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115706. }
  115707. #endif
  115708. /* third step; we offset the noise vectors, overlay tone
  115709. masking. We then do a floor1-specific line fit. If we're
  115710. performing bitrate management, the line fit is performed
  115711. multiple times for up/down tweakage on demand. */
  115712. #if 0
  115713. {
  115714. float aotuv[psy_look->n];
  115715. #endif
  115716. _vp_offset_and_mix(psy_look,
  115717. noise,
  115718. tone,
  115719. 1,
  115720. logmask,
  115721. mdct,
  115722. logmdct);
  115723. #if 0
  115724. if(vi->channels==2){
  115725. if(i==0)
  115726. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115727. else
  115728. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115729. }
  115730. }
  115731. #endif
  115732. #if 0
  115733. if(vi->channels==2){
  115734. if(i==0)
  115735. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115736. else
  115737. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115738. }
  115739. #endif
  115740. /* this algorithm is hardwired to floor 1 for now; abort out if
  115741. we're *not* floor1. This won't happen unless someone has
  115742. broken the encode setup lib. Guard it anyway. */
  115743. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115744. floor_posts[i][PACKETBLOBS/2]=
  115745. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115746. logmdct,
  115747. logmask);
  115748. /* are we managing bitrate? If so, perform two more fits for
  115749. later rate tweaking (fits represent hi/lo) */
  115750. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115751. /* higher rate by way of lower noise curve */
  115752. _vp_offset_and_mix(psy_look,
  115753. noise,
  115754. tone,
  115755. 2,
  115756. logmask,
  115757. mdct,
  115758. logmdct);
  115759. #if 0
  115760. if(vi->channels==2){
  115761. if(i==0)
  115762. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115763. else
  115764. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115765. }
  115766. #endif
  115767. floor_posts[i][PACKETBLOBS-1]=
  115768. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115769. logmdct,
  115770. logmask);
  115771. /* lower rate by way of higher noise curve */
  115772. _vp_offset_and_mix(psy_look,
  115773. noise,
  115774. tone,
  115775. 0,
  115776. logmask,
  115777. mdct,
  115778. logmdct);
  115779. #if 0
  115780. if(vi->channels==2)
  115781. if(i==0)
  115782. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115783. else
  115784. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115785. #endif
  115786. floor_posts[i][0]=
  115787. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115788. logmdct,
  115789. logmask);
  115790. /* we also interpolate a range of intermediate curves for
  115791. intermediate rates */
  115792. for(k=1;k<PACKETBLOBS/2;k++)
  115793. floor_posts[i][k]=
  115794. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115795. floor_posts[i][0],
  115796. floor_posts[i][PACKETBLOBS/2],
  115797. k*65536/(PACKETBLOBS/2));
  115798. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115799. floor_posts[i][k]=
  115800. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115801. floor_posts[i][PACKETBLOBS/2],
  115802. floor_posts[i][PACKETBLOBS-1],
  115803. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115804. }
  115805. }
  115806. }
  115807. vbi->ampmax=global_ampmax;
  115808. /*
  115809. the next phases are performed once for vbr-only and PACKETBLOB
  115810. times for bitrate managed modes.
  115811. 1) encode actual mode being used
  115812. 2) encode the floor for each channel, compute coded mask curve/res
  115813. 3) normalize and couple.
  115814. 4) encode residue
  115815. 5) save packet bytes to the packetblob vector
  115816. */
  115817. /* iterate over the many masking curve fits we've created */
  115818. {
  115819. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115820. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115821. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115822. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115823. float **mag_memo;
  115824. int **mag_sort;
  115825. if(info->coupling_steps){
  115826. mag_memo=_vp_quantize_couple_memo(vb,
  115827. &ci->psy_g_param,
  115828. psy_look,
  115829. info,
  115830. gmdct);
  115831. mag_sort=_vp_quantize_couple_sort(vb,
  115832. psy_look,
  115833. info,
  115834. mag_memo);
  115835. hf_reduction(&ci->psy_g_param,
  115836. psy_look,
  115837. info,
  115838. mag_memo);
  115839. }
  115840. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115841. if(psy_look->vi->normal_channel_p){
  115842. for(i=0;i<vi->channels;i++){
  115843. float *mdct =gmdct[i];
  115844. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115845. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115846. }
  115847. }
  115848. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115849. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115850. k++){
  115851. oggpack_buffer *opb=vbi->packetblob[k];
  115852. /* start out our new packet blob with packet type and mode */
  115853. /* Encode the packet type */
  115854. oggpack_write(opb,0,1);
  115855. /* Encode the modenumber */
  115856. /* Encode frame mode, pre,post windowsize, then dispatch */
  115857. oggpack_write(opb,modenumber,b->modebits);
  115858. if(vb->W){
  115859. oggpack_write(opb,vb->lW,1);
  115860. oggpack_write(opb,vb->nW,1);
  115861. }
  115862. /* encode floor, compute masking curve, sep out residue */
  115863. for(i=0;i<vi->channels;i++){
  115864. int submap=info->chmuxlist[i];
  115865. float *mdct =gmdct[i];
  115866. float *res =vb->pcm[i];
  115867. int *ilogmask=ilogmaskch[i]=
  115868. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115869. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115870. floor_posts[i][k],
  115871. ilogmask);
  115872. #if 0
  115873. {
  115874. char buf[80];
  115875. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115876. float work[n/2];
  115877. for(j=0;j<n/2;j++)
  115878. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115879. _analysis_output(buf,seq,work,n/2,1,1,0);
  115880. }
  115881. #endif
  115882. _vp_remove_floor(psy_look,
  115883. mdct,
  115884. ilogmask,
  115885. res,
  115886. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115887. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115888. #if 0
  115889. {
  115890. char buf[80];
  115891. float work[n/2];
  115892. for(j=0;j<n/2;j++)
  115893. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115894. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115895. _analysis_output(buf,seq,work,n/2,1,1,0);
  115896. }
  115897. #endif
  115898. }
  115899. /* our iteration is now based on masking curve, not prequant and
  115900. coupling. Only one prequant/coupling step */
  115901. /* quantize/couple */
  115902. /* incomplete implementation that assumes the tree is all depth
  115903. one, or no tree at all */
  115904. if(info->coupling_steps){
  115905. _vp_couple(k,
  115906. &ci->psy_g_param,
  115907. psy_look,
  115908. info,
  115909. vb->pcm,
  115910. mag_memo,
  115911. mag_sort,
  115912. ilogmaskch,
  115913. nonzero,
  115914. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115915. }
  115916. /* classify and encode by submap */
  115917. for(i=0;i<info->submaps;i++){
  115918. int ch_in_bundle=0;
  115919. long **classifications;
  115920. int resnum=info->residuesubmap[i];
  115921. for(j=0;j<vi->channels;j++){
  115922. if(info->chmuxlist[j]==i){
  115923. zerobundle[ch_in_bundle]=0;
  115924. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115925. res_bundle[ch_in_bundle]=vb->pcm[j];
  115926. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115927. }
  115928. }
  115929. classifications=_residue_P[ci->residue_type[resnum]]->
  115930. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115931. _residue_P[ci->residue_type[resnum]]->
  115932. forward(opb,vb,b->residue[resnum],
  115933. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115934. }
  115935. /* ok, done encoding. Next protopacket. */
  115936. }
  115937. }
  115938. #if 0
  115939. seq++;
  115940. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115941. #endif
  115942. return(0);
  115943. }
  115944. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115945. vorbis_dsp_state *vd=vb->vd;
  115946. vorbis_info *vi=vd->vi;
  115947. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115948. private_state *b=(private_state*)vd->backend_state;
  115949. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115950. int i,j;
  115951. long n=vb->pcmend=ci->blocksizes[vb->W];
  115952. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115953. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115954. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115955. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115956. /* recover the spectral envelope; store it in the PCM vector for now */
  115957. for(i=0;i<vi->channels;i++){
  115958. int submap=info->chmuxlist[i];
  115959. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115960. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115961. if(floormemo[i])
  115962. nonzero[i]=1;
  115963. else
  115964. nonzero[i]=0;
  115965. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115966. }
  115967. /* channel coupling can 'dirty' the nonzero listing */
  115968. for(i=0;i<info->coupling_steps;i++){
  115969. if(nonzero[info->coupling_mag[i]] ||
  115970. nonzero[info->coupling_ang[i]]){
  115971. nonzero[info->coupling_mag[i]]=1;
  115972. nonzero[info->coupling_ang[i]]=1;
  115973. }
  115974. }
  115975. /* recover the residue into our working vectors */
  115976. for(i=0;i<info->submaps;i++){
  115977. int ch_in_bundle=0;
  115978. for(j=0;j<vi->channels;j++){
  115979. if(info->chmuxlist[j]==i){
  115980. if(nonzero[j])
  115981. zerobundle[ch_in_bundle]=1;
  115982. else
  115983. zerobundle[ch_in_bundle]=0;
  115984. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115985. }
  115986. }
  115987. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115988. inverse(vb,b->residue[info->residuesubmap[i]],
  115989. pcmbundle,zerobundle,ch_in_bundle);
  115990. }
  115991. /* channel coupling */
  115992. for(i=info->coupling_steps-1;i>=0;i--){
  115993. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115994. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115995. for(j=0;j<n/2;j++){
  115996. float mag=pcmM[j];
  115997. float ang=pcmA[j];
  115998. if(mag>0)
  115999. if(ang>0){
  116000. pcmM[j]=mag;
  116001. pcmA[j]=mag-ang;
  116002. }else{
  116003. pcmA[j]=mag;
  116004. pcmM[j]=mag+ang;
  116005. }
  116006. else
  116007. if(ang>0){
  116008. pcmM[j]=mag;
  116009. pcmA[j]=mag+ang;
  116010. }else{
  116011. pcmA[j]=mag;
  116012. pcmM[j]=mag-ang;
  116013. }
  116014. }
  116015. }
  116016. /* compute and apply spectral envelope */
  116017. for(i=0;i<vi->channels;i++){
  116018. float *pcm=vb->pcm[i];
  116019. int submap=info->chmuxlist[i];
  116020. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  116021. inverse2(vb,b->flr[info->floorsubmap[submap]],
  116022. floormemo[i],pcm);
  116023. }
  116024. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  116025. /* only MDCT right now.... */
  116026. for(i=0;i<vi->channels;i++){
  116027. float *pcm=vb->pcm[i];
  116028. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  116029. }
  116030. /* all done! */
  116031. return(0);
  116032. }
  116033. /* export hooks */
  116034. vorbis_func_mapping mapping0_exportbundle={
  116035. &mapping0_pack,
  116036. &mapping0_unpack,
  116037. &mapping0_free_info,
  116038. &mapping0_forward,
  116039. &mapping0_inverse
  116040. };
  116041. #endif
  116042. /*** End of inlined file: mapping0.c ***/
  116043. /*** Start of inlined file: mdct.c ***/
  116044. /* this can also be run as an integer transform by uncommenting a
  116045. define in mdct.h; the integerization is a first pass and although
  116046. it's likely stable for Vorbis, the dynamic range is constrained and
  116047. roundoff isn't done (so it's noisy). Consider it functional, but
  116048. only a starting point. There's no point on a machine with an FPU */
  116049. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116050. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116051. // tasks..
  116052. #if JUCE_MSVC
  116053. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116054. #endif
  116055. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116056. #if JUCE_USE_OGGVORBIS
  116057. #include <stdio.h>
  116058. #include <stdlib.h>
  116059. #include <string.h>
  116060. #include <math.h>
  116061. /* build lookups for trig functions; also pre-figure scaling and
  116062. some window function algebra. */
  116063. void mdct_init(mdct_lookup *lookup,int n){
  116064. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  116065. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  116066. int i;
  116067. int n2=n>>1;
  116068. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  116069. lookup->n=n;
  116070. lookup->trig=T;
  116071. lookup->bitrev=bitrev;
  116072. /* trig lookups... */
  116073. for(i=0;i<n/4;i++){
  116074. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  116075. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  116076. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  116077. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  116078. }
  116079. for(i=0;i<n/8;i++){
  116080. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  116081. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  116082. }
  116083. /* bitreverse lookup... */
  116084. {
  116085. int mask=(1<<(log2n-1))-1,i,j;
  116086. int msb=1<<(log2n-2);
  116087. for(i=0;i<n/8;i++){
  116088. int acc=0;
  116089. for(j=0;msb>>j;j++)
  116090. if((msb>>j)&i)acc|=1<<j;
  116091. bitrev[i*2]=((~acc)&mask)-1;
  116092. bitrev[i*2+1]=acc;
  116093. }
  116094. }
  116095. lookup->scale=FLOAT_CONV(4.f/n);
  116096. }
  116097. /* 8 point butterfly (in place, 4 register) */
  116098. STIN void mdct_butterfly_8(DATA_TYPE *x){
  116099. REG_TYPE r0 = x[6] + x[2];
  116100. REG_TYPE r1 = x[6] - x[2];
  116101. REG_TYPE r2 = x[4] + x[0];
  116102. REG_TYPE r3 = x[4] - x[0];
  116103. x[6] = r0 + r2;
  116104. x[4] = r0 - r2;
  116105. r0 = x[5] - x[1];
  116106. r2 = x[7] - x[3];
  116107. x[0] = r1 + r0;
  116108. x[2] = r1 - r0;
  116109. r0 = x[5] + x[1];
  116110. r1 = x[7] + x[3];
  116111. x[3] = r2 + r3;
  116112. x[1] = r2 - r3;
  116113. x[7] = r1 + r0;
  116114. x[5] = r1 - r0;
  116115. }
  116116. /* 16 point butterfly (in place, 4 register) */
  116117. STIN void mdct_butterfly_16(DATA_TYPE *x){
  116118. REG_TYPE r0 = x[1] - x[9];
  116119. REG_TYPE r1 = x[0] - x[8];
  116120. x[8] += x[0];
  116121. x[9] += x[1];
  116122. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  116123. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  116124. r0 = x[3] - x[11];
  116125. r1 = x[10] - x[2];
  116126. x[10] += x[2];
  116127. x[11] += x[3];
  116128. x[2] = r0;
  116129. x[3] = r1;
  116130. r0 = x[12] - x[4];
  116131. r1 = x[13] - x[5];
  116132. x[12] += x[4];
  116133. x[13] += x[5];
  116134. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  116135. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  116136. r0 = x[14] - x[6];
  116137. r1 = x[15] - x[7];
  116138. x[14] += x[6];
  116139. x[15] += x[7];
  116140. x[6] = r0;
  116141. x[7] = r1;
  116142. mdct_butterfly_8(x);
  116143. mdct_butterfly_8(x+8);
  116144. }
  116145. /* 32 point butterfly (in place, 4 register) */
  116146. STIN void mdct_butterfly_32(DATA_TYPE *x){
  116147. REG_TYPE r0 = x[30] - x[14];
  116148. REG_TYPE r1 = x[31] - x[15];
  116149. x[30] += x[14];
  116150. x[31] += x[15];
  116151. x[14] = r0;
  116152. x[15] = r1;
  116153. r0 = x[28] - x[12];
  116154. r1 = x[29] - x[13];
  116155. x[28] += x[12];
  116156. x[29] += x[13];
  116157. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116158. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116159. r0 = x[26] - x[10];
  116160. r1 = x[27] - x[11];
  116161. x[26] += x[10];
  116162. x[27] += x[11];
  116163. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116164. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116165. r0 = x[24] - x[8];
  116166. r1 = x[25] - x[9];
  116167. x[24] += x[8];
  116168. x[25] += x[9];
  116169. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116170. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116171. r0 = x[22] - x[6];
  116172. r1 = x[7] - x[23];
  116173. x[22] += x[6];
  116174. x[23] += x[7];
  116175. x[6] = r1;
  116176. x[7] = r0;
  116177. r0 = x[4] - x[20];
  116178. r1 = x[5] - x[21];
  116179. x[20] += x[4];
  116180. x[21] += x[5];
  116181. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116182. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116183. r0 = x[2] - x[18];
  116184. r1 = x[3] - x[19];
  116185. x[18] += x[2];
  116186. x[19] += x[3];
  116187. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116188. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116189. r0 = x[0] - x[16];
  116190. r1 = x[1] - x[17];
  116191. x[16] += x[0];
  116192. x[17] += x[1];
  116193. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116194. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116195. mdct_butterfly_16(x);
  116196. mdct_butterfly_16(x+16);
  116197. }
  116198. /* N point first stage butterfly (in place, 2 register) */
  116199. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116200. DATA_TYPE *x,
  116201. int points){
  116202. DATA_TYPE *x1 = x + points - 8;
  116203. DATA_TYPE *x2 = x + (points>>1) - 8;
  116204. REG_TYPE r0;
  116205. REG_TYPE r1;
  116206. do{
  116207. r0 = x1[6] - x2[6];
  116208. r1 = x1[7] - x2[7];
  116209. x1[6] += x2[6];
  116210. x1[7] += x2[7];
  116211. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116212. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116213. r0 = x1[4] - x2[4];
  116214. r1 = x1[5] - x2[5];
  116215. x1[4] += x2[4];
  116216. x1[5] += x2[5];
  116217. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116218. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116219. r0 = x1[2] - x2[2];
  116220. r1 = x1[3] - x2[3];
  116221. x1[2] += x2[2];
  116222. x1[3] += x2[3];
  116223. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116224. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116225. r0 = x1[0] - x2[0];
  116226. r1 = x1[1] - x2[1];
  116227. x1[0] += x2[0];
  116228. x1[1] += x2[1];
  116229. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116230. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116231. x1-=8;
  116232. x2-=8;
  116233. T+=16;
  116234. }while(x2>=x);
  116235. }
  116236. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116237. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116238. DATA_TYPE *x,
  116239. int points,
  116240. int trigint){
  116241. DATA_TYPE *x1 = x + points - 8;
  116242. DATA_TYPE *x2 = x + (points>>1) - 8;
  116243. REG_TYPE r0;
  116244. REG_TYPE r1;
  116245. do{
  116246. r0 = x1[6] - x2[6];
  116247. r1 = x1[7] - x2[7];
  116248. x1[6] += x2[6];
  116249. x1[7] += x2[7];
  116250. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116251. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116252. T+=trigint;
  116253. r0 = x1[4] - x2[4];
  116254. r1 = x1[5] - x2[5];
  116255. x1[4] += x2[4];
  116256. x1[5] += x2[5];
  116257. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116258. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116259. T+=trigint;
  116260. r0 = x1[2] - x2[2];
  116261. r1 = x1[3] - x2[3];
  116262. x1[2] += x2[2];
  116263. x1[3] += x2[3];
  116264. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116265. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116266. T+=trigint;
  116267. r0 = x1[0] - x2[0];
  116268. r1 = x1[1] - x2[1];
  116269. x1[0] += x2[0];
  116270. x1[1] += x2[1];
  116271. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116272. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116273. T+=trigint;
  116274. x1-=8;
  116275. x2-=8;
  116276. }while(x2>=x);
  116277. }
  116278. STIN void mdct_butterflies(mdct_lookup *init,
  116279. DATA_TYPE *x,
  116280. int points){
  116281. DATA_TYPE *T=init->trig;
  116282. int stages=init->log2n-5;
  116283. int i,j;
  116284. if(--stages>0){
  116285. mdct_butterfly_first(T,x,points);
  116286. }
  116287. for(i=1;--stages>0;i++){
  116288. for(j=0;j<(1<<i);j++)
  116289. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116290. }
  116291. for(j=0;j<points;j+=32)
  116292. mdct_butterfly_32(x+j);
  116293. }
  116294. void mdct_clear(mdct_lookup *l){
  116295. if(l){
  116296. if(l->trig)_ogg_free(l->trig);
  116297. if(l->bitrev)_ogg_free(l->bitrev);
  116298. memset(l,0,sizeof(*l));
  116299. }
  116300. }
  116301. STIN void mdct_bitreverse(mdct_lookup *init,
  116302. DATA_TYPE *x){
  116303. int n = init->n;
  116304. int *bit = init->bitrev;
  116305. DATA_TYPE *w0 = x;
  116306. DATA_TYPE *w1 = x = w0+(n>>1);
  116307. DATA_TYPE *T = init->trig+n;
  116308. do{
  116309. DATA_TYPE *x0 = x+bit[0];
  116310. DATA_TYPE *x1 = x+bit[1];
  116311. REG_TYPE r0 = x0[1] - x1[1];
  116312. REG_TYPE r1 = x0[0] + x1[0];
  116313. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116314. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116315. w1 -= 4;
  116316. r0 = HALVE(x0[1] + x1[1]);
  116317. r1 = HALVE(x0[0] - x1[0]);
  116318. w0[0] = r0 + r2;
  116319. w1[2] = r0 - r2;
  116320. w0[1] = r1 + r3;
  116321. w1[3] = r3 - r1;
  116322. x0 = x+bit[2];
  116323. x1 = x+bit[3];
  116324. r0 = x0[1] - x1[1];
  116325. r1 = x0[0] + x1[0];
  116326. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116327. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116328. r0 = HALVE(x0[1] + x1[1]);
  116329. r1 = HALVE(x0[0] - x1[0]);
  116330. w0[2] = r0 + r2;
  116331. w1[0] = r0 - r2;
  116332. w0[3] = r1 + r3;
  116333. w1[1] = r3 - r1;
  116334. T += 4;
  116335. bit += 4;
  116336. w0 += 4;
  116337. }while(w0<w1);
  116338. }
  116339. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116340. int n=init->n;
  116341. int n2=n>>1;
  116342. int n4=n>>2;
  116343. /* rotate */
  116344. DATA_TYPE *iX = in+n2-7;
  116345. DATA_TYPE *oX = out+n2+n4;
  116346. DATA_TYPE *T = init->trig+n4;
  116347. do{
  116348. oX -= 4;
  116349. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116350. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116351. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116352. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116353. iX -= 8;
  116354. T += 4;
  116355. }while(iX>=in);
  116356. iX = in+n2-8;
  116357. oX = out+n2+n4;
  116358. T = init->trig+n4;
  116359. do{
  116360. T -= 4;
  116361. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116362. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116363. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116364. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116365. iX -= 8;
  116366. oX += 4;
  116367. }while(iX>=in);
  116368. mdct_butterflies(init,out+n2,n2);
  116369. mdct_bitreverse(init,out);
  116370. /* roatate + window */
  116371. {
  116372. DATA_TYPE *oX1=out+n2+n4;
  116373. DATA_TYPE *oX2=out+n2+n4;
  116374. DATA_TYPE *iX =out;
  116375. T =init->trig+n2;
  116376. do{
  116377. oX1-=4;
  116378. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116379. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116380. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116381. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116382. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116383. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116384. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116385. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116386. oX2+=4;
  116387. iX += 8;
  116388. T += 8;
  116389. }while(iX<oX1);
  116390. iX=out+n2+n4;
  116391. oX1=out+n4;
  116392. oX2=oX1;
  116393. do{
  116394. oX1-=4;
  116395. iX-=4;
  116396. oX2[0] = -(oX1[3] = iX[3]);
  116397. oX2[1] = -(oX1[2] = iX[2]);
  116398. oX2[2] = -(oX1[1] = iX[1]);
  116399. oX2[3] = -(oX1[0] = iX[0]);
  116400. oX2+=4;
  116401. }while(oX2<iX);
  116402. iX=out+n2+n4;
  116403. oX1=out+n2+n4;
  116404. oX2=out+n2;
  116405. do{
  116406. oX1-=4;
  116407. oX1[0]= iX[3];
  116408. oX1[1]= iX[2];
  116409. oX1[2]= iX[1];
  116410. oX1[3]= iX[0];
  116411. iX+=4;
  116412. }while(oX1>oX2);
  116413. }
  116414. }
  116415. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116416. int n=init->n;
  116417. int n2=n>>1;
  116418. int n4=n>>2;
  116419. int n8=n>>3;
  116420. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116421. DATA_TYPE *w2=w+n2;
  116422. /* rotate */
  116423. /* window + rotate + step 1 */
  116424. REG_TYPE r0;
  116425. REG_TYPE r1;
  116426. DATA_TYPE *x0=in+n2+n4;
  116427. DATA_TYPE *x1=x0+1;
  116428. DATA_TYPE *T=init->trig+n2;
  116429. int i=0;
  116430. for(i=0;i<n8;i+=2){
  116431. x0 -=4;
  116432. T-=2;
  116433. r0= x0[2] + x1[0];
  116434. r1= x0[0] + x1[2];
  116435. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116436. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116437. x1 +=4;
  116438. }
  116439. x1=in+1;
  116440. for(;i<n2-n8;i+=2){
  116441. T-=2;
  116442. x0 -=4;
  116443. r0= x0[2] - x1[0];
  116444. r1= x0[0] - x1[2];
  116445. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116446. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116447. x1 +=4;
  116448. }
  116449. x0=in+n;
  116450. for(;i<n2;i+=2){
  116451. T-=2;
  116452. x0 -=4;
  116453. r0= -x0[2] - x1[0];
  116454. r1= -x0[0] - x1[2];
  116455. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116456. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116457. x1 +=4;
  116458. }
  116459. mdct_butterflies(init,w+n2,n2);
  116460. mdct_bitreverse(init,w);
  116461. /* roatate + window */
  116462. T=init->trig+n2;
  116463. x0=out+n2;
  116464. for(i=0;i<n4;i++){
  116465. x0--;
  116466. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116467. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116468. w+=2;
  116469. T+=2;
  116470. }
  116471. }
  116472. #endif
  116473. /*** End of inlined file: mdct.c ***/
  116474. /*** Start of inlined file: psy.c ***/
  116475. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116476. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116477. // tasks..
  116478. #if JUCE_MSVC
  116479. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116480. #endif
  116481. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116482. #if JUCE_USE_OGGVORBIS
  116483. #include <stdlib.h>
  116484. #include <math.h>
  116485. #include <string.h>
  116486. /*** Start of inlined file: masking.h ***/
  116487. #ifndef _V_MASKING_H_
  116488. #define _V_MASKING_H_
  116489. /* more detailed ATH; the bass if flat to save stressing the floor
  116490. overly for only a bin or two of savings. */
  116491. #define MAX_ATH 88
  116492. static float ATH[]={
  116493. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116494. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116495. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116496. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116497. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116498. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116499. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116500. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116501. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116502. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116503. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116504. };
  116505. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116506. replaced by an empirically collected data set. The previously
  116507. published values were, far too often, simply on crack. */
  116508. #define EHMER_OFFSET 16
  116509. #define EHMER_MAX 56
  116510. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116511. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116512. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116513. for collection of these curves) */
  116514. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116515. /* 62.5 Hz */
  116516. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116517. -60, -60, -60, -60, -62, -62, -65, -73,
  116518. -69, -68, -68, -67, -70, -70, -72, -74,
  116519. -75, -79, -79, -80, -83, -88, -93, -100,
  116520. -110, -999, -999, -999, -999, -999, -999, -999,
  116521. -999, -999, -999, -999, -999, -999, -999, -999,
  116522. -999, -999, -999, -999, -999, -999, -999, -999},
  116523. { -48, -48, -48, -48, -48, -48, -48, -48,
  116524. -48, -48, -48, -48, -48, -53, -61, -66,
  116525. -66, -68, -67, -70, -76, -76, -72, -73,
  116526. -75, -76, -78, -79, -83, -88, -93, -100,
  116527. -110, -999, -999, -999, -999, -999, -999, -999,
  116528. -999, -999, -999, -999, -999, -999, -999, -999,
  116529. -999, -999, -999, -999, -999, -999, -999, -999},
  116530. { -37, -37, -37, -37, -37, -37, -37, -37,
  116531. -38, -40, -42, -46, -48, -53, -55, -62,
  116532. -65, -58, -56, -56, -61, -60, -65, -67,
  116533. -69, -71, -77, -77, -78, -80, -82, -84,
  116534. -88, -93, -98, -106, -112, -999, -999, -999,
  116535. -999, -999, -999, -999, -999, -999, -999, -999,
  116536. -999, -999, -999, -999, -999, -999, -999, -999},
  116537. { -25, -25, -25, -25, -25, -25, -25, -25,
  116538. -25, -26, -27, -29, -32, -38, -48, -52,
  116539. -52, -50, -48, -48, -51, -52, -54, -60,
  116540. -67, -67, -66, -68, -69, -73, -73, -76,
  116541. -80, -81, -81, -85, -85, -86, -88, -93,
  116542. -100, -110, -999, -999, -999, -999, -999, -999,
  116543. -999, -999, -999, -999, -999, -999, -999, -999},
  116544. { -16, -16, -16, -16, -16, -16, -16, -16,
  116545. -17, -19, -20, -22, -26, -28, -31, -40,
  116546. -47, -39, -39, -40, -42, -43, -47, -51,
  116547. -57, -52, -55, -55, -60, -58, -62, -63,
  116548. -70, -67, -69, -72, -73, -77, -80, -82,
  116549. -83, -87, -90, -94, -98, -104, -115, -999,
  116550. -999, -999, -999, -999, -999, -999, -999, -999},
  116551. { -8, -8, -8, -8, -8, -8, -8, -8,
  116552. -8, -8, -10, -11, -15, -19, -25, -30,
  116553. -34, -31, -30, -31, -29, -32, -35, -42,
  116554. -48, -42, -44, -46, -50, -50, -51, -52,
  116555. -59, -54, -55, -55, -58, -62, -63, -66,
  116556. -72, -73, -76, -75, -78, -80, -80, -81,
  116557. -84, -88, -90, -94, -98, -101, -106, -110}},
  116558. /* 88Hz */
  116559. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116560. -66, -66, -66, -66, -66, -67, -67, -67,
  116561. -76, -72, -71, -74, -76, -76, -75, -78,
  116562. -79, -79, -81, -83, -86, -89, -93, -97,
  116563. -100, -105, -110, -999, -999, -999, -999, -999,
  116564. -999, -999, -999, -999, -999, -999, -999, -999,
  116565. -999, -999, -999, -999, -999, -999, -999, -999},
  116566. { -47, -47, -47, -47, -47, -47, -47, -47,
  116567. -47, -47, -47, -48, -51, -55, -59, -66,
  116568. -66, -66, -67, -66, -68, -69, -70, -74,
  116569. -79, -77, -77, -78, -80, -81, -82, -84,
  116570. -86, -88, -91, -95, -100, -108, -116, -999,
  116571. -999, -999, -999, -999, -999, -999, -999, -999,
  116572. -999, -999, -999, -999, -999, -999, -999, -999},
  116573. { -36, -36, -36, -36, -36, -36, -36, -36,
  116574. -36, -37, -37, -41, -44, -48, -51, -58,
  116575. -62, -60, -57, -59, -59, -60, -63, -65,
  116576. -72, -71, -70, -72, -74, -77, -76, -78,
  116577. -81, -81, -80, -83, -86, -91, -96, -100,
  116578. -105, -110, -999, -999, -999, -999, -999, -999,
  116579. -999, -999, -999, -999, -999, -999, -999, -999},
  116580. { -28, -28, -28, -28, -28, -28, -28, -28,
  116581. -28, -30, -32, -32, -33, -35, -41, -49,
  116582. -50, -49, -47, -48, -48, -52, -51, -57,
  116583. -65, -61, -59, -61, -64, -69, -70, -74,
  116584. -77, -77, -78, -81, -84, -85, -87, -90,
  116585. -92, -96, -100, -107, -112, -999, -999, -999,
  116586. -999, -999, -999, -999, -999, -999, -999, -999},
  116587. { -19, -19, -19, -19, -19, -19, -19, -19,
  116588. -20, -21, -23, -27, -30, -35, -36, -41,
  116589. -46, -44, -42, -40, -41, -41, -43, -48,
  116590. -55, -53, -52, -53, -56, -59, -58, -60,
  116591. -67, -66, -69, -71, -72, -75, -79, -81,
  116592. -84, -87, -90, -93, -97, -101, -107, -114,
  116593. -999, -999, -999, -999, -999, -999, -999, -999},
  116594. { -9, -9, -9, -9, -9, -9, -9, -9,
  116595. -11, -12, -12, -15, -16, -20, -23, -30,
  116596. -37, -34, -33, -34, -31, -32, -32, -38,
  116597. -47, -44, -41, -40, -47, -49, -46, -46,
  116598. -58, -50, -50, -54, -58, -62, -64, -67,
  116599. -67, -70, -72, -76, -79, -83, -87, -91,
  116600. -96, -100, -104, -110, -999, -999, -999, -999}},
  116601. /* 125 Hz */
  116602. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116603. -62, -62, -63, -64, -66, -67, -66, -68,
  116604. -75, -72, -76, -75, -76, -78, -79, -82,
  116605. -84, -85, -90, -94, -101, -110, -999, -999,
  116606. -999, -999, -999, -999, -999, -999, -999, -999,
  116607. -999, -999, -999, -999, -999, -999, -999, -999,
  116608. -999, -999, -999, -999, -999, -999, -999, -999},
  116609. { -59, -59, -59, -59, -59, -59, -59, -59,
  116610. -59, -59, -59, -60, -60, -61, -63, -66,
  116611. -71, -68, -70, -70, -71, -72, -72, -75,
  116612. -81, -78, -79, -82, -83, -86, -90, -97,
  116613. -103, -113, -999, -999, -999, -999, -999, -999,
  116614. -999, -999, -999, -999, -999, -999, -999, -999,
  116615. -999, -999, -999, -999, -999, -999, -999, -999},
  116616. { -53, -53, -53, -53, -53, -53, -53, -53,
  116617. -53, -54, -55, -57, -56, -57, -55, -61,
  116618. -65, -60, -60, -62, -63, -63, -66, -68,
  116619. -74, -73, -75, -75, -78, -80, -80, -82,
  116620. -85, -90, -96, -101, -108, -999, -999, -999,
  116621. -999, -999, -999, -999, -999, -999, -999, -999,
  116622. -999, -999, -999, -999, -999, -999, -999, -999},
  116623. { -46, -46, -46, -46, -46, -46, -46, -46,
  116624. -46, -46, -47, -47, -47, -47, -48, -51,
  116625. -57, -51, -49, -50, -51, -53, -54, -59,
  116626. -66, -60, -62, -67, -67, -70, -72, -75,
  116627. -76, -78, -81, -85, -88, -94, -97, -104,
  116628. -112, -999, -999, -999, -999, -999, -999, -999,
  116629. -999, -999, -999, -999, -999, -999, -999, -999},
  116630. { -36, -36, -36, -36, -36, -36, -36, -36,
  116631. -39, -41, -42, -42, -39, -38, -41, -43,
  116632. -52, -44, -40, -39, -37, -37, -40, -47,
  116633. -54, -50, -48, -50, -55, -61, -59, -62,
  116634. -66, -66, -66, -69, -69, -73, -74, -74,
  116635. -75, -77, -79, -82, -87, -91, -95, -100,
  116636. -108, -115, -999, -999, -999, -999, -999, -999},
  116637. { -28, -26, -24, -22, -20, -20, -23, -29,
  116638. -30, -31, -28, -27, -28, -28, -28, -35,
  116639. -40, -33, -32, -29, -30, -30, -30, -37,
  116640. -45, -41, -37, -38, -45, -47, -47, -48,
  116641. -53, -49, -48, -50, -49, -49, -51, -52,
  116642. -58, -56, -57, -56, -60, -61, -62, -70,
  116643. -72, -74, -78, -83, -88, -93, -100, -106}},
  116644. /* 177 Hz */
  116645. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116646. -999, -110, -105, -100, -95, -91, -87, -83,
  116647. -80, -78, -76, -78, -78, -81, -83, -85,
  116648. -86, -85, -86, -87, -90, -97, -107, -999,
  116649. -999, -999, -999, -999, -999, -999, -999, -999,
  116650. -999, -999, -999, -999, -999, -999, -999, -999,
  116651. -999, -999, -999, -999, -999, -999, -999, -999},
  116652. {-999, -999, -999, -110, -105, -100, -95, -90,
  116653. -85, -81, -77, -73, -70, -67, -67, -68,
  116654. -75, -73, -70, -69, -70, -72, -75, -79,
  116655. -84, -83, -84, -86, -88, -89, -89, -93,
  116656. -98, -105, -112, -999, -999, -999, -999, -999,
  116657. -999, -999, -999, -999, -999, -999, -999, -999,
  116658. -999, -999, -999, -999, -999, -999, -999, -999},
  116659. {-105, -100, -95, -90, -85, -80, -76, -71,
  116660. -68, -68, -65, -63, -63, -62, -62, -64,
  116661. -65, -64, -61, -62, -63, -64, -66, -68,
  116662. -73, -73, -74, -75, -76, -81, -83, -85,
  116663. -88, -89, -92, -95, -100, -108, -999, -999,
  116664. -999, -999, -999, -999, -999, -999, -999, -999,
  116665. -999, -999, -999, -999, -999, -999, -999, -999},
  116666. { -80, -75, -71, -68, -65, -63, -62, -61,
  116667. -61, -61, -61, -59, -56, -57, -53, -50,
  116668. -58, -52, -50, -50, -52, -53, -54, -58,
  116669. -67, -63, -67, -68, -72, -75, -78, -80,
  116670. -81, -81, -82, -85, -89, -90, -93, -97,
  116671. -101, -107, -114, -999, -999, -999, -999, -999,
  116672. -999, -999, -999, -999, -999, -999, -999, -999},
  116673. { -65, -61, -59, -57, -56, -55, -55, -56,
  116674. -56, -57, -55, -53, -52, -47, -44, -44,
  116675. -50, -44, -41, -39, -39, -42, -40, -46,
  116676. -51, -49, -50, -53, -54, -63, -60, -61,
  116677. -62, -66, -66, -66, -70, -73, -74, -75,
  116678. -76, -75, -79, -85, -89, -91, -96, -102,
  116679. -110, -999, -999, -999, -999, -999, -999, -999},
  116680. { -52, -50, -49, -49, -48, -48, -48, -49,
  116681. -50, -50, -49, -46, -43, -39, -35, -33,
  116682. -38, -36, -32, -29, -32, -32, -32, -35,
  116683. -44, -39, -38, -38, -46, -50, -45, -46,
  116684. -53, -50, -50, -50, -54, -54, -53, -53,
  116685. -56, -57, -59, -66, -70, -72, -74, -79,
  116686. -83, -85, -90, -97, -114, -999, -999, -999}},
  116687. /* 250 Hz */
  116688. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116689. -100, -95, -90, -86, -80, -75, -75, -79,
  116690. -80, -79, -80, -81, -82, -88, -95, -103,
  116691. -110, -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, -999, -999, -999, -999},
  116695. {-999, -999, -999, -999, -108, -103, -98, -93,
  116696. -88, -83, -79, -78, -75, -71, -67, -68,
  116697. -73, -73, -72, -73, -75, -77, -80, -82,
  116698. -88, -93, -100, -107, -114, -999, -999, -999,
  116699. -999, -999, -999, -999, -999, -999, -999, -999,
  116700. -999, -999, -999, -999, -999, -999, -999, -999,
  116701. -999, -999, -999, -999, -999, -999, -999, -999},
  116702. {-999, -999, -999, -110, -105, -101, -96, -90,
  116703. -86, -81, -77, -73, -69, -66, -61, -62,
  116704. -66, -64, -62, -65, -66, -70, -72, -76,
  116705. -81, -80, -84, -90, -95, -102, -110, -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, -107, -103, -97, -92, -88,
  116710. -83, -79, -74, -70, -66, -59, -53, -58,
  116711. -62, -55, -54, -54, -54, -58, -61, -62,
  116712. -72, -70, -72, -75, -78, -80, -81, -80,
  116713. -83, -83, -88, -93, -100, -107, -115, -999,
  116714. -999, -999, -999, -999, -999, -999, -999, -999,
  116715. -999, -999, -999, -999, -999, -999, -999, -999},
  116716. {-999, -999, -999, -105, -100, -95, -90, -85,
  116717. -80, -75, -70, -66, -62, -56, -48, -44,
  116718. -48, -46, -46, -43, -46, -48, -48, -51,
  116719. -58, -58, -59, -60, -62, -62, -61, -61,
  116720. -65, -64, -65, -68, -70, -74, -75, -78,
  116721. -81, -86, -95, -110, -999, -999, -999, -999,
  116722. -999, -999, -999, -999, -999, -999, -999, -999},
  116723. {-999, -999, -105, -100, -95, -90, -85, -80,
  116724. -75, -70, -65, -61, -55, -49, -39, -33,
  116725. -40, -35, -32, -38, -40, -33, -35, -37,
  116726. -46, -41, -45, -44, -46, -42, -45, -46,
  116727. -52, -50, -50, -50, -54, -54, -55, -57,
  116728. -62, -64, -66, -68, -70, -76, -81, -90,
  116729. -100, -110, -999, -999, -999, -999, -999, -999}},
  116730. /* 354 hz */
  116731. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116732. -105, -98, -90, -85, -82, -83, -80, -78,
  116733. -84, -79, -80, -83, -87, -89, -91, -93,
  116734. -99, -106, -117, -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, -999, -999, -999, -999, -999},
  116738. {-999, -999, -999, -999, -999, -999, -999, -999,
  116739. -105, -98, -90, -85, -80, -75, -70, -68,
  116740. -74, -72, -74, -77, -80, -82, -85, -87,
  116741. -92, -89, -91, -95, -100, -106, -112, -999,
  116742. -999, -999, -999, -999, -999, -999, -999, -999,
  116743. -999, -999, -999, -999, -999, -999, -999, -999,
  116744. -999, -999, -999, -999, -999, -999, -999, -999},
  116745. {-999, -999, -999, -999, -999, -999, -999, -999,
  116746. -105, -98, -90, -83, -75, -71, -63, -64,
  116747. -67, -62, -64, -67, -70, -73, -77, -81,
  116748. -84, -83, -85, -89, -90, -93, -98, -104,
  116749. -109, -114, -999, -999, -999, -999, -999, -999,
  116750. -999, -999, -999, -999, -999, -999, -999, -999,
  116751. -999, -999, -999, -999, -999, -999, -999, -999},
  116752. {-999, -999, -999, -999, -999, -999, -999, -999,
  116753. -103, -96, -88, -81, -75, -68, -58, -54,
  116754. -56, -54, -56, -56, -58, -60, -63, -66,
  116755. -74, -69, -72, -72, -75, -74, -77, -81,
  116756. -81, -82, -84, -87, -93, -96, -99, -104,
  116757. -110, -999, -999, -999, -999, -999, -999, -999,
  116758. -999, -999, -999, -999, -999, -999, -999, -999},
  116759. {-999, -999, -999, -999, -999, -108, -102, -96,
  116760. -91, -85, -80, -74, -68, -60, -51, -46,
  116761. -48, -46, -43, -45, -47, -47, -49, -48,
  116762. -56, -53, -55, -58, -57, -63, -58, -60,
  116763. -66, -64, -67, -70, -70, -74, -77, -84,
  116764. -86, -89, -91, -93, -94, -101, -109, -118,
  116765. -999, -999, -999, -999, -999, -999, -999, -999},
  116766. {-999, -999, -999, -108, -103, -98, -93, -88,
  116767. -83, -78, -73, -68, -60, -53, -44, -35,
  116768. -38, -38, -34, -34, -36, -40, -41, -44,
  116769. -51, -45, -46, -47, -46, -54, -50, -49,
  116770. -50, -50, -50, -51, -54, -57, -58, -60,
  116771. -66, -66, -66, -64, -65, -68, -77, -82,
  116772. -87, -95, -110, -999, -999, -999, -999, -999}},
  116773. /* 500 Hz */
  116774. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116775. -107, -102, -97, -92, -87, -83, -78, -75,
  116776. -82, -79, -83, -85, -89, -92, -95, -98,
  116777. -101, -105, -109, -113, -999, -999, -999, -999,
  116778. -999, -999, -999, -999, -999, -999, -999, -999,
  116779. -999, -999, -999, -999, -999, -999, -999, -999,
  116780. -999, -999, -999, -999, -999, -999, -999, -999},
  116781. {-999, -999, -999, -999, -999, -999, -999, -106,
  116782. -100, -95, -90, -86, -81, -78, -74, -69,
  116783. -74, -74, -76, -79, -83, -84, -86, -89,
  116784. -92, -97, -93, -100, -103, -107, -110, -999,
  116785. -999, -999, -999, -999, -999, -999, -999, -999,
  116786. -999, -999, -999, -999, -999, -999, -999, -999,
  116787. -999, -999, -999, -999, -999, -999, -999, -999},
  116788. {-999, -999, -999, -999, -999, -999, -106, -100,
  116789. -95, -90, -87, -83, -80, -75, -69, -60,
  116790. -66, -66, -68, -70, -74, -78, -79, -81,
  116791. -81, -83, -84, -87, -93, -96, -99, -103,
  116792. -107, -110, -999, -999, -999, -999, -999, -999,
  116793. -999, -999, -999, -999, -999, -999, -999, -999,
  116794. -999, -999, -999, -999, -999, -999, -999, -999},
  116795. {-999, -999, -999, -999, -999, -108, -103, -98,
  116796. -93, -89, -85, -82, -78, -71, -62, -55,
  116797. -58, -58, -54, -54, -55, -59, -61, -62,
  116798. -70, -66, -66, -67, -70, -72, -75, -78,
  116799. -84, -84, -84, -88, -91, -90, -95, -98,
  116800. -102, -103, -106, -110, -999, -999, -999, -999,
  116801. -999, -999, -999, -999, -999, -999, -999, -999},
  116802. {-999, -999, -999, -999, -108, -103, -98, -94,
  116803. -90, -87, -82, -79, -73, -67, -58, -47,
  116804. -50, -45, -41, -45, -48, -44, -44, -49,
  116805. -54, -51, -48, -47, -49, -50, -51, -57,
  116806. -58, -60, -63, -69, -70, -69, -71, -74,
  116807. -78, -82, -90, -95, -101, -105, -110, -999,
  116808. -999, -999, -999, -999, -999, -999, -999, -999},
  116809. {-999, -999, -999, -105, -101, -97, -93, -90,
  116810. -85, -80, -77, -72, -65, -56, -48, -37,
  116811. -40, -36, -34, -40, -50, -47, -38, -41,
  116812. -47, -38, -35, -39, -38, -43, -40, -45,
  116813. -50, -45, -44, -47, -50, -55, -48, -48,
  116814. -52, -66, -70, -76, -82, -90, -97, -105,
  116815. -110, -999, -999, -999, -999, -999, -999, -999}},
  116816. /* 707 Hz */
  116817. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116818. -999, -108, -103, -98, -93, -86, -79, -76,
  116819. -83, -81, -85, -87, -89, -93, -98, -102,
  116820. -107, -112, -999, -999, -999, -999, -999, -999,
  116821. -999, -999, -999, -999, -999, -999, -999, -999,
  116822. -999, -999, -999, -999, -999, -999, -999, -999,
  116823. -999, -999, -999, -999, -999, -999, -999, -999},
  116824. {-999, -999, -999, -999, -999, -999, -999, -999,
  116825. -999, -108, -103, -98, -93, -86, -79, -71,
  116826. -77, -74, -77, -79, -81, -84, -85, -90,
  116827. -92, -93, -92, -98, -101, -108, -112, -999,
  116828. -999, -999, -999, -999, -999, -999, -999, -999,
  116829. -999, -999, -999, -999, -999, -999, -999, -999,
  116830. -999, -999, -999, -999, -999, -999, -999, -999},
  116831. {-999, -999, -999, -999, -999, -999, -999, -999,
  116832. -108, -103, -98, -93, -87, -78, -68, -65,
  116833. -66, -62, -65, -67, -70, -73, -75, -78,
  116834. -82, -82, -83, -84, -91, -93, -98, -102,
  116835. -106, -110, -999, -999, -999, -999, -999, -999,
  116836. -999, -999, -999, -999, -999, -999, -999, -999,
  116837. -999, -999, -999, -999, -999, -999, -999, -999},
  116838. {-999, -999, -999, -999, -999, -999, -999, -999,
  116839. -105, -100, -95, -90, -82, -74, -62, -57,
  116840. -58, -56, -51, -52, -52, -54, -54, -58,
  116841. -66, -59, -60, -63, -66, -69, -73, -79,
  116842. -83, -84, -80, -81, -81, -82, -88, -92,
  116843. -98, -105, -113, -999, -999, -999, -999, -999,
  116844. -999, -999, -999, -999, -999, -999, -999, -999},
  116845. {-999, -999, -999, -999, -999, -999, -999, -107,
  116846. -102, -97, -92, -84, -79, -69, -57, -47,
  116847. -52, -47, -44, -45, -50, -52, -42, -42,
  116848. -53, -43, -43, -48, -51, -56, -55, -52,
  116849. -57, -59, -61, -62, -67, -71, -78, -83,
  116850. -86, -94, -98, -103, -110, -999, -999, -999,
  116851. -999, -999, -999, -999, -999, -999, -999, -999},
  116852. {-999, -999, -999, -999, -999, -999, -105, -100,
  116853. -95, -90, -84, -78, -70, -61, -51, -41,
  116854. -40, -38, -40, -46, -52, -51, -41, -40,
  116855. -46, -40, -38, -38, -41, -46, -41, -46,
  116856. -47, -43, -43, -45, -41, -45, -56, -67,
  116857. -68, -83, -87, -90, -95, -102, -107, -113,
  116858. -999, -999, -999, -999, -999, -999, -999, -999}},
  116859. /* 1000 Hz */
  116860. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116861. -999, -109, -105, -101, -96, -91, -84, -77,
  116862. -82, -82, -85, -89, -94, -100, -106, -110,
  116863. -999, -999, -999, -999, -999, -999, -999, -999,
  116864. -999, -999, -999, -999, -999, -999, -999, -999,
  116865. -999, -999, -999, -999, -999, -999, -999, -999,
  116866. -999, -999, -999, -999, -999, -999, -999, -999},
  116867. {-999, -999, -999, -999, -999, -999, -999, -999,
  116868. -999, -106, -103, -98, -92, -85, -80, -71,
  116869. -75, -72, -76, -80, -84, -86, -89, -93,
  116870. -100, -107, -113, -999, -999, -999, -999, -999,
  116871. -999, -999, -999, -999, -999, -999, -999, -999,
  116872. -999, -999, -999, -999, -999, -999, -999, -999,
  116873. -999, -999, -999, -999, -999, -999, -999, -999},
  116874. {-999, -999, -999, -999, -999, -999, -999, -107,
  116875. -104, -101, -97, -92, -88, -84, -80, -64,
  116876. -66, -63, -64, -66, -69, -73, -77, -83,
  116877. -83, -86, -91, -98, -104, -111, -999, -999,
  116878. -999, -999, -999, -999, -999, -999, -999, -999,
  116879. -999, -999, -999, -999, -999, -999, -999, -999,
  116880. -999, -999, -999, -999, -999, -999, -999, -999},
  116881. {-999, -999, -999, -999, -999, -999, -999, -107,
  116882. -104, -101, -97, -92, -90, -84, -74, -57,
  116883. -58, -52, -55, -54, -50, -52, -50, -52,
  116884. -63, -62, -69, -76, -77, -78, -78, -79,
  116885. -82, -88, -94, -100, -106, -111, -999, -999,
  116886. -999, -999, -999, -999, -999, -999, -999, -999,
  116887. -999, -999, -999, -999, -999, -999, -999, -999},
  116888. {-999, -999, -999, -999, -999, -999, -106, -102,
  116889. -98, -95, -90, -85, -83, -78, -70, -50,
  116890. -50, -41, -44, -49, -47, -50, -50, -44,
  116891. -55, -46, -47, -48, -48, -54, -49, -49,
  116892. -58, -62, -71, -81, -87, -92, -97, -102,
  116893. -108, -114, -999, -999, -999, -999, -999, -999,
  116894. -999, -999, -999, -999, -999, -999, -999, -999},
  116895. {-999, -999, -999, -999, -999, -999, -106, -102,
  116896. -98, -95, -90, -85, -83, -78, -70, -45,
  116897. -43, -41, -47, -50, -51, -50, -49, -45,
  116898. -47, -41, -44, -41, -39, -43, -38, -37,
  116899. -40, -41, -44, -50, -58, -65, -73, -79,
  116900. -85, -92, -97, -101, -105, -109, -113, -999,
  116901. -999, -999, -999, -999, -999, -999, -999, -999}},
  116902. /* 1414 Hz */
  116903. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116904. -999, -999, -999, -107, -100, -95, -87, -81,
  116905. -85, -83, -88, -93, -100, -107, -114, -999,
  116906. -999, -999, -999, -999, -999, -999, -999, -999,
  116907. -999, -999, -999, -999, -999, -999, -999, -999,
  116908. -999, -999, -999, -999, -999, -999, -999, -999,
  116909. -999, -999, -999, -999, -999, -999, -999, -999},
  116910. {-999, -999, -999, -999, -999, -999, -999, -999,
  116911. -999, -999, -107, -101, -95, -88, -83, -76,
  116912. -73, -72, -79, -84, -90, -95, -100, -105,
  116913. -110, -115, -999, -999, -999, -999, -999, -999,
  116914. -999, -999, -999, -999, -999, -999, -999, -999,
  116915. -999, -999, -999, -999, -999, -999, -999, -999,
  116916. -999, -999, -999, -999, -999, -999, -999, -999},
  116917. {-999, -999, -999, -999, -999, -999, -999, -999,
  116918. -999, -999, -104, -98, -92, -87, -81, -70,
  116919. -65, -62, -67, -71, -74, -80, -85, -91,
  116920. -95, -99, -103, -108, -111, -114, -999, -999,
  116921. -999, -999, -999, -999, -999, -999, -999, -999,
  116922. -999, -999, -999, -999, -999, -999, -999, -999,
  116923. -999, -999, -999, -999, -999, -999, -999, -999},
  116924. {-999, -999, -999, -999, -999, -999, -999, -999,
  116925. -999, -999, -103, -97, -90, -85, -76, -60,
  116926. -56, -54, -60, -62, -61, -56, -63, -65,
  116927. -73, -74, -77, -75, -78, -81, -86, -87,
  116928. -88, -91, -94, -98, -103, -110, -999, -999,
  116929. -999, -999, -999, -999, -999, -999, -999, -999,
  116930. -999, -999, -999, -999, -999, -999, -999, -999},
  116931. {-999, -999, -999, -999, -999, -999, -999, -105,
  116932. -100, -97, -92, -86, -81, -79, -70, -57,
  116933. -51, -47, -51, -58, -60, -56, -53, -50,
  116934. -58, -52, -50, -50, -53, -55, -64, -69,
  116935. -71, -85, -82, -78, -81, -85, -95, -102,
  116936. -112, -999, -999, -999, -999, -999, -999, -999,
  116937. -999, -999, -999, -999, -999, -999, -999, -999},
  116938. {-999, -999, -999, -999, -999, -999, -999, -105,
  116939. -100, -97, -92, -85, -83, -79, -72, -49,
  116940. -40, -43, -43, -54, -56, -51, -50, -40,
  116941. -43, -38, -36, -35, -37, -38, -37, -44,
  116942. -54, -60, -57, -60, -70, -75, -84, -92,
  116943. -103, -112, -999, -999, -999, -999, -999, -999,
  116944. -999, -999, -999, -999, -999, -999, -999, -999}},
  116945. /* 2000 Hz */
  116946. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116947. -999, -999, -999, -110, -102, -95, -89, -82,
  116948. -83, -84, -90, -92, -99, -107, -113, -999,
  116949. -999, -999, -999, -999, -999, -999, -999, -999,
  116950. -999, -999, -999, -999, -999, -999, -999, -999,
  116951. -999, -999, -999, -999, -999, -999, -999, -999,
  116952. -999, -999, -999, -999, -999, -999, -999, -999},
  116953. {-999, -999, -999, -999, -999, -999, -999, -999,
  116954. -999, -999, -107, -101, -95, -89, -83, -72,
  116955. -74, -78, -85, -88, -88, -90, -92, -98,
  116956. -105, -111, -999, -999, -999, -999, -999, -999,
  116957. -999, -999, -999, -999, -999, -999, -999, -999,
  116958. -999, -999, -999, -999, -999, -999, -999, -999,
  116959. -999, -999, -999, -999, -999, -999, -999, -999},
  116960. {-999, -999, -999, -999, -999, -999, -999, -999,
  116961. -999, -109, -103, -97, -93, -87, -81, -70,
  116962. -70, -67, -75, -73, -76, -79, -81, -83,
  116963. -88, -89, -97, -103, -110, -999, -999, -999,
  116964. -999, -999, -999, -999, -999, -999, -999, -999,
  116965. -999, -999, -999, -999, -999, -999, -999, -999,
  116966. -999, -999, -999, -999, -999, -999, -999, -999},
  116967. {-999, -999, -999, -999, -999, -999, -999, -999,
  116968. -999, -107, -100, -94, -88, -83, -75, -63,
  116969. -59, -59, -63, -66, -60, -62, -67, -67,
  116970. -77, -76, -81, -88, -86, -92, -96, -102,
  116971. -109, -116, -999, -999, -999, -999, -999, -999,
  116972. -999, -999, -999, -999, -999, -999, -999, -999,
  116973. -999, -999, -999, -999, -999, -999, -999, -999},
  116974. {-999, -999, -999, -999, -999, -999, -999, -999,
  116975. -999, -105, -98, -92, -86, -81, -73, -56,
  116976. -52, -47, -55, -60, -58, -52, -51, -45,
  116977. -49, -50, -53, -54, -61, -71, -70, -69,
  116978. -78, -79, -87, -90, -96, -104, -112, -999,
  116979. -999, -999, -999, -999, -999, -999, -999, -999,
  116980. -999, -999, -999, -999, -999, -999, -999, -999},
  116981. {-999, -999, -999, -999, -999, -999, -999, -999,
  116982. -999, -103, -96, -90, -86, -78, -70, -51,
  116983. -42, -47, -48, -55, -54, -54, -53, -42,
  116984. -35, -28, -33, -38, -37, -44, -47, -49,
  116985. -54, -63, -68, -78, -82, -89, -94, -99,
  116986. -104, -109, -114, -999, -999, -999, -999, -999,
  116987. -999, -999, -999, -999, -999, -999, -999, -999}},
  116988. /* 2828 Hz */
  116989. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116990. -999, -999, -999, -999, -110, -100, -90, -79,
  116991. -85, -81, -82, -82, -89, -94, -99, -103,
  116992. -109, -115, -999, -999, -999, -999, -999, -999,
  116993. -999, -999, -999, -999, -999, -999, -999, -999,
  116994. -999, -999, -999, -999, -999, -999, -999, -999,
  116995. -999, -999, -999, -999, -999, -999, -999, -999},
  116996. {-999, -999, -999, -999, -999, -999, -999, -999,
  116997. -999, -999, -999, -999, -105, -97, -85, -72,
  116998. -74, -70, -70, -70, -76, -85, -91, -93,
  116999. -97, -103, -109, -115, -999, -999, -999, -999,
  117000. -999, -999, -999, -999, -999, -999, -999, -999,
  117001. -999, -999, -999, -999, -999, -999, -999, -999,
  117002. -999, -999, -999, -999, -999, -999, -999, -999},
  117003. {-999, -999, -999, -999, -999, -999, -999, -999,
  117004. -999, -999, -999, -999, -112, -93, -81, -68,
  117005. -62, -60, -60, -57, -63, -70, -77, -82,
  117006. -90, -93, -98, -104, -109, -113, -999, -999,
  117007. -999, -999, -999, -999, -999, -999, -999, -999,
  117008. -999, -999, -999, -999, -999, -999, -999, -999,
  117009. -999, -999, -999, -999, -999, -999, -999, -999},
  117010. {-999, -999, -999, -999, -999, -999, -999, -999,
  117011. -999, -999, -999, -113, -100, -93, -84, -63,
  117012. -58, -48, -53, -54, -52, -52, -57, -64,
  117013. -66, -76, -83, -81, -85, -85, -90, -95,
  117014. -98, -101, -103, -106, -108, -111, -999, -999,
  117015. -999, -999, -999, -999, -999, -999, -999, -999,
  117016. -999, -999, -999, -999, -999, -999, -999, -999},
  117017. {-999, -999, -999, -999, -999, -999, -999, -999,
  117018. -999, -999, -999, -105, -95, -86, -74, -53,
  117019. -50, -38, -43, -49, -43, -42, -39, -39,
  117020. -46, -52, -57, -56, -72, -69, -74, -81,
  117021. -87, -92, -94, -97, -99, -102, -105, -108,
  117022. -999, -999, -999, -999, -999, -999, -999, -999,
  117023. -999, -999, -999, -999, -999, -999, -999, -999},
  117024. {-999, -999, -999, -999, -999, -999, -999, -999,
  117025. -999, -999, -108, -99, -90, -76, -66, -45,
  117026. -43, -41, -44, -47, -43, -47, -40, -30,
  117027. -31, -31, -39, -33, -40, -41, -43, -53,
  117028. -59, -70, -73, -77, -79, -82, -84, -87,
  117029. -999, -999, -999, -999, -999, -999, -999, -999,
  117030. -999, -999, -999, -999, -999, -999, -999, -999}},
  117031. /* 4000 Hz */
  117032. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117033. -999, -999, -999, -999, -999, -110, -91, -76,
  117034. -75, -85, -93, -98, -104, -110, -999, -999,
  117035. -999, -999, -999, -999, -999, -999, -999, -999,
  117036. -999, -999, -999, -999, -999, -999, -999, -999,
  117037. -999, -999, -999, -999, -999, -999, -999, -999,
  117038. -999, -999, -999, -999, -999, -999, -999, -999},
  117039. {-999, -999, -999, -999, -999, -999, -999, -999,
  117040. -999, -999, -999, -999, -999, -110, -91, -70,
  117041. -70, -75, -86, -89, -94, -98, -101, -106,
  117042. -110, -999, -999, -999, -999, -999, -999, -999,
  117043. -999, -999, -999, -999, -999, -999, -999, -999,
  117044. -999, -999, -999, -999, -999, -999, -999, -999,
  117045. -999, -999, -999, -999, -999, -999, -999, -999},
  117046. {-999, -999, -999, -999, -999, -999, -999, -999,
  117047. -999, -999, -999, -999, -110, -95, -80, -60,
  117048. -65, -64, -74, -83, -88, -91, -95, -99,
  117049. -103, -107, -110, -999, -999, -999, -999, -999,
  117050. -999, -999, -999, -999, -999, -999, -999, -999,
  117051. -999, -999, -999, -999, -999, -999, -999, -999,
  117052. -999, -999, -999, -999, -999, -999, -999, -999},
  117053. {-999, -999, -999, -999, -999, -999, -999, -999,
  117054. -999, -999, -999, -999, -110, -95, -80, -58,
  117055. -55, -49, -66, -68, -71, -78, -78, -80,
  117056. -88, -85, -89, -97, -100, -105, -110, -999,
  117057. -999, -999, -999, -999, -999, -999, -999, -999,
  117058. -999, -999, -999, -999, -999, -999, -999, -999,
  117059. -999, -999, -999, -999, -999, -999, -999, -999},
  117060. {-999, -999, -999, -999, -999, -999, -999, -999,
  117061. -999, -999, -999, -999, -110, -95, -80, -53,
  117062. -52, -41, -59, -59, -49, -58, -56, -63,
  117063. -86, -79, -90, -93, -98, -103, -107, -112,
  117064. -999, -999, -999, -999, -999, -999, -999, -999,
  117065. -999, -999, -999, -999, -999, -999, -999, -999,
  117066. -999, -999, -999, -999, -999, -999, -999, -999},
  117067. {-999, -999, -999, -999, -999, -999, -999, -999,
  117068. -999, -999, -999, -110, -97, -91, -73, -45,
  117069. -40, -33, -53, -61, -49, -54, -50, -50,
  117070. -60, -52, -67, -74, -81, -92, -96, -100,
  117071. -105, -110, -999, -999, -999, -999, -999, -999,
  117072. -999, -999, -999, -999, -999, -999, -999, -999,
  117073. -999, -999, -999, -999, -999, -999, -999, -999}},
  117074. /* 5657 Hz */
  117075. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117076. -999, -999, -999, -113, -106, -99, -92, -77,
  117077. -80, -88, -97, -106, -115, -999, -999, -999,
  117078. -999, -999, -999, -999, -999, -999, -999, -999,
  117079. -999, -999, -999, -999, -999, -999, -999, -999,
  117080. -999, -999, -999, -999, -999, -999, -999, -999,
  117081. -999, -999, -999, -999, -999, -999, -999, -999},
  117082. {-999, -999, -999, -999, -999, -999, -999, -999,
  117083. -999, -999, -116, -109, -102, -95, -89, -74,
  117084. -72, -88, -87, -95, -102, -109, -116, -999,
  117085. -999, -999, -999, -999, -999, -999, -999, -999,
  117086. -999, -999, -999, -999, -999, -999, -999, -999,
  117087. -999, -999, -999, -999, -999, -999, -999, -999,
  117088. -999, -999, -999, -999, -999, -999, -999, -999},
  117089. {-999, -999, -999, -999, -999, -999, -999, -999,
  117090. -999, -999, -116, -109, -102, -95, -89, -75,
  117091. -66, -74, -77, -78, -86, -87, -90, -96,
  117092. -105, -115, -999, -999, -999, -999, -999, -999,
  117093. -999, -999, -999, -999, -999, -999, -999, -999,
  117094. -999, -999, -999, -999, -999, -999, -999, -999,
  117095. -999, -999, -999, -999, -999, -999, -999, -999},
  117096. {-999, -999, -999, -999, -999, -999, -999, -999,
  117097. -999, -999, -115, -108, -101, -94, -88, -66,
  117098. -56, -61, -70, -65, -78, -72, -83, -84,
  117099. -93, -98, -105, -110, -999, -999, -999, -999,
  117100. -999, -999, -999, -999, -999, -999, -999, -999,
  117101. -999, -999, -999, -999, -999, -999, -999, -999,
  117102. -999, -999, -999, -999, -999, -999, -999, -999},
  117103. {-999, -999, -999, -999, -999, -999, -999, -999,
  117104. -999, -999, -110, -105, -95, -89, -82, -57,
  117105. -52, -52, -59, -56, -59, -58, -69, -67,
  117106. -88, -82, -82, -89, -94, -100, -108, -999,
  117107. -999, -999, -999, -999, -999, -999, -999, -999,
  117108. -999, -999, -999, -999, -999, -999, -999, -999,
  117109. -999, -999, -999, -999, -999, -999, -999, -999},
  117110. {-999, -999, -999, -999, -999, -999, -999, -999,
  117111. -999, -110, -101, -96, -90, -83, -77, -54,
  117112. -43, -38, -50, -48, -52, -48, -42, -42,
  117113. -51, -52, -53, -59, -65, -71, -78, -85,
  117114. -95, -999, -999, -999, -999, -999, -999, -999,
  117115. -999, -999, -999, -999, -999, -999, -999, -999,
  117116. -999, -999, -999, -999, -999, -999, -999, -999}},
  117117. /* 8000 Hz */
  117118. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117119. -999, -999, -999, -999, -120, -105, -86, -68,
  117120. -78, -79, -90, -100, -110, -999, -999, -999,
  117121. -999, -999, -999, -999, -999, -999, -999, -999,
  117122. -999, -999, -999, -999, -999, -999, -999, -999,
  117123. -999, -999, -999, -999, -999, -999, -999, -999,
  117124. -999, -999, -999, -999, -999, -999, -999, -999},
  117125. {-999, -999, -999, -999, -999, -999, -999, -999,
  117126. -999, -999, -999, -999, -120, -105, -86, -66,
  117127. -73, -77, -88, -96, -105, -115, -999, -999,
  117128. -999, -999, -999, -999, -999, -999, -999, -999,
  117129. -999, -999, -999, -999, -999, -999, -999, -999,
  117130. -999, -999, -999, -999, -999, -999, -999, -999,
  117131. -999, -999, -999, -999, -999, -999, -999, -999},
  117132. {-999, -999, -999, -999, -999, -999, -999, -999,
  117133. -999, -999, -999, -120, -105, -92, -80, -61,
  117134. -64, -68, -80, -87, -92, -100, -110, -999,
  117135. -999, -999, -999, -999, -999, -999, -999, -999,
  117136. -999, -999, -999, -999, -999, -999, -999, -999,
  117137. -999, -999, -999, -999, -999, -999, -999, -999,
  117138. -999, -999, -999, -999, -999, -999, -999, -999},
  117139. {-999, -999, -999, -999, -999, -999, -999, -999,
  117140. -999, -999, -999, -120, -104, -91, -79, -52,
  117141. -60, -54, -64, -69, -77, -80, -82, -84,
  117142. -85, -87, -88, -90, -999, -999, -999, -999,
  117143. -999, -999, -999, -999, -999, -999, -999, -999,
  117144. -999, -999, -999, -999, -999, -999, -999, -999,
  117145. -999, -999, -999, -999, -999, -999, -999, -999},
  117146. {-999, -999, -999, -999, -999, -999, -999, -999,
  117147. -999, -999, -999, -118, -100, -87, -77, -49,
  117148. -50, -44, -58, -61, -61, -67, -65, -62,
  117149. -62, -62, -65, -68, -999, -999, -999, -999,
  117150. -999, -999, -999, -999, -999, -999, -999, -999,
  117151. -999, -999, -999, -999, -999, -999, -999, -999,
  117152. -999, -999, -999, -999, -999, -999, -999, -999},
  117153. {-999, -999, -999, -999, -999, -999, -999, -999,
  117154. -999, -999, -999, -115, -98, -84, -62, -49,
  117155. -44, -38, -46, -49, -49, -46, -39, -37,
  117156. -39, -40, -42, -43, -999, -999, -999, -999,
  117157. -999, -999, -999, -999, -999, -999, -999, -999,
  117158. -999, -999, -999, -999, -999, -999, -999, -999,
  117159. -999, -999, -999, -999, -999, -999, -999, -999}},
  117160. /* 11314 Hz */
  117161. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117162. -999, -999, -999, -999, -999, -110, -88, -74,
  117163. -77, -82, -82, -85, -90, -94, -99, -104,
  117164. -999, -999, -999, -999, -999, -999, -999, -999,
  117165. -999, -999, -999, -999, -999, -999, -999, -999,
  117166. -999, -999, -999, -999, -999, -999, -999, -999,
  117167. -999, -999, -999, -999, -999, -999, -999, -999},
  117168. {-999, -999, -999, -999, -999, -999, -999, -999,
  117169. -999, -999, -999, -999, -999, -110, -88, -66,
  117170. -70, -81, -80, -81, -84, -88, -91, -93,
  117171. -999, -999, -999, -999, -999, -999, -999, -999,
  117172. -999, -999, -999, -999, -999, -999, -999, -999,
  117173. -999, -999, -999, -999, -999, -999, -999, -999,
  117174. -999, -999, -999, -999, -999, -999, -999, -999},
  117175. {-999, -999, -999, -999, -999, -999, -999, -999,
  117176. -999, -999, -999, -999, -999, -110, -88, -61,
  117177. -63, -70, -71, -74, -77, -80, -83, -85,
  117178. -999, -999, -999, -999, -999, -999, -999, -999,
  117179. -999, -999, -999, -999, -999, -999, -999, -999,
  117180. -999, -999, -999, -999, -999, -999, -999, -999,
  117181. -999, -999, -999, -999, -999, -999, -999, -999},
  117182. {-999, -999, -999, -999, -999, -999, -999, -999,
  117183. -999, -999, -999, -999, -999, -110, -86, -62,
  117184. -63, -62, -62, -58, -52, -50, -50, -52,
  117185. -54, -999, -999, -999, -999, -999, -999, -999,
  117186. -999, -999, -999, -999, -999, -999, -999, -999,
  117187. -999, -999, -999, -999, -999, -999, -999, -999,
  117188. -999, -999, -999, -999, -999, -999, -999, -999},
  117189. {-999, -999, -999, -999, -999, -999, -999, -999,
  117190. -999, -999, -999, -999, -118, -108, -84, -53,
  117191. -50, -50, -50, -55, -47, -45, -40, -40,
  117192. -40, -999, -999, -999, -999, -999, -999, -999,
  117193. -999, -999, -999, -999, -999, -999, -999, -999,
  117194. -999, -999, -999, -999, -999, -999, -999, -999,
  117195. -999, -999, -999, -999, -999, -999, -999, -999},
  117196. {-999, -999, -999, -999, -999, -999, -999, -999,
  117197. -999, -999, -999, -999, -118, -100, -73, -43,
  117198. -37, -42, -43, -53, -38, -37, -35, -35,
  117199. -38, -999, -999, -999, -999, -999, -999, -999,
  117200. -999, -999, -999, -999, -999, -999, -999, -999,
  117201. -999, -999, -999, -999, -999, -999, -999, -999,
  117202. -999, -999, -999, -999, -999, -999, -999, -999}},
  117203. /* 16000 Hz */
  117204. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117205. -999, -999, -999, -110, -100, -91, -84, -74,
  117206. -80, -80, -80, -80, -80, -999, -999, -999,
  117207. -999, -999, -999, -999, -999, -999, -999, -999,
  117208. -999, -999, -999, -999, -999, -999, -999, -999,
  117209. -999, -999, -999, -999, -999, -999, -999, -999,
  117210. -999, -999, -999, -999, -999, -999, -999, -999},
  117211. {-999, -999, -999, -999, -999, -999, -999, -999,
  117212. -999, -999, -999, -110, -100, -91, -84, -74,
  117213. -68, -68, -68, -68, -68, -999, -999, -999,
  117214. -999, -999, -999, -999, -999, -999, -999, -999,
  117215. -999, -999, -999, -999, -999, -999, -999, -999,
  117216. -999, -999, -999, -999, -999, -999, -999, -999,
  117217. -999, -999, -999, -999, -999, -999, -999, -999},
  117218. {-999, -999, -999, -999, -999, -999, -999, -999,
  117219. -999, -999, -999, -110, -100, -86, -78, -70,
  117220. -60, -45, -30, -21, -999, -999, -999, -999,
  117221. -999, -999, -999, -999, -999, -999, -999, -999,
  117222. -999, -999, -999, -999, -999, -999, -999, -999,
  117223. -999, -999, -999, -999, -999, -999, -999, -999,
  117224. -999, -999, -999, -999, -999, -999, -999, -999},
  117225. {-999, -999, -999, -999, -999, -999, -999, -999,
  117226. -999, -999, -999, -110, -100, -87, -78, -67,
  117227. -48, -38, -29, -21, -999, -999, -999, -999,
  117228. -999, -999, -999, -999, -999, -999, -999, -999,
  117229. -999, -999, -999, -999, -999, -999, -999, -999,
  117230. -999, -999, -999, -999, -999, -999, -999, -999,
  117231. -999, -999, -999, -999, -999, -999, -999, -999},
  117232. {-999, -999, -999, -999, -999, -999, -999, -999,
  117233. -999, -999, -999, -110, -100, -86, -69, -56,
  117234. -45, -35, -33, -29, -999, -999, -999, -999,
  117235. -999, -999, -999, -999, -999, -999, -999, -999,
  117236. -999, -999, -999, -999, -999, -999, -999, -999,
  117237. -999, -999, -999, -999, -999, -999, -999, -999,
  117238. -999, -999, -999, -999, -999, -999, -999, -999},
  117239. {-999, -999, -999, -999, -999, -999, -999, -999,
  117240. -999, -999, -999, -110, -100, -83, -71, -48,
  117241. -27, -38, -37, -34, -999, -999, -999, -999,
  117242. -999, -999, -999, -999, -999, -999, -999, -999,
  117243. -999, -999, -999, -999, -999, -999, -999, -999,
  117244. -999, -999, -999, -999, -999, -999, -999, -999,
  117245. -999, -999, -999, -999, -999, -999, -999, -999}}
  117246. };
  117247. #endif
  117248. /*** End of inlined file: masking.h ***/
  117249. #define NEGINF -9999.f
  117250. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117251. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117252. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117253. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117254. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117255. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117256. look->channels=vi->channels;
  117257. look->ampmax=-9999.;
  117258. look->gi=gi;
  117259. return(look);
  117260. }
  117261. void _vp_global_free(vorbis_look_psy_global *look){
  117262. if(look){
  117263. memset(look,0,sizeof(*look));
  117264. _ogg_free(look);
  117265. }
  117266. }
  117267. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117268. if(i){
  117269. memset(i,0,sizeof(*i));
  117270. _ogg_free(i);
  117271. }
  117272. }
  117273. void _vi_psy_free(vorbis_info_psy *i){
  117274. if(i){
  117275. memset(i,0,sizeof(*i));
  117276. _ogg_free(i);
  117277. }
  117278. }
  117279. static void min_curve(float *c,
  117280. float *c2){
  117281. int i;
  117282. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117283. }
  117284. static void max_curve(float *c,
  117285. float *c2){
  117286. int i;
  117287. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117288. }
  117289. static void attenuate_curve(float *c,float att){
  117290. int i;
  117291. for(i=0;i<EHMER_MAX;i++)
  117292. c[i]+=att;
  117293. }
  117294. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117295. float center_boost, float center_decay_rate){
  117296. int i,j,k,m;
  117297. float ath[EHMER_MAX];
  117298. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117299. float athc[P_LEVELS][EHMER_MAX];
  117300. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117301. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117302. memset(workc,0,sizeof(workc));
  117303. for(i=0;i<P_BANDS;i++){
  117304. /* we add back in the ATH to avoid low level curves falling off to
  117305. -infinity and unnecessarily cutting off high level curves in the
  117306. curve limiting (last step). */
  117307. /* A half-band's settings must be valid over the whole band, and
  117308. it's better to mask too little than too much */
  117309. int ath_offset=i*4;
  117310. for(j=0;j<EHMER_MAX;j++){
  117311. float min=999.;
  117312. for(k=0;k<4;k++)
  117313. if(j+k+ath_offset<MAX_ATH){
  117314. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117315. }else{
  117316. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117317. }
  117318. ath[j]=min;
  117319. }
  117320. /* copy curves into working space, replicate the 50dB curve to 30
  117321. and 40, replicate the 100dB curve to 110 */
  117322. for(j=0;j<6;j++)
  117323. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117324. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117325. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117326. /* apply centered curve boost/decay */
  117327. for(j=0;j<P_LEVELS;j++){
  117328. for(k=0;k<EHMER_MAX;k++){
  117329. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117330. if(adj<0. && center_boost>0)adj=0.;
  117331. if(adj>0. && center_boost<0)adj=0.;
  117332. workc[i][j][k]+=adj;
  117333. }
  117334. }
  117335. /* normalize curves so the driving amplitude is 0dB */
  117336. /* make temp curves with the ATH overlayed */
  117337. for(j=0;j<P_LEVELS;j++){
  117338. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117339. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117340. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117341. max_curve(athc[j],workc[i][j]);
  117342. }
  117343. /* Now limit the louder curves.
  117344. the idea is this: We don't know what the playback attenuation
  117345. will be; 0dB SL moves every time the user twiddles the volume
  117346. knob. So that means we have to use a single 'most pessimal' curve
  117347. for all masking amplitudes, right? Wrong. The *loudest* sound
  117348. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117349. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117350. etc... */
  117351. for(j=1;j<P_LEVELS;j++){
  117352. min_curve(athc[j],athc[j-1]);
  117353. min_curve(workc[i][j],athc[j]);
  117354. }
  117355. }
  117356. for(i=0;i<P_BANDS;i++){
  117357. int hi_curve,lo_curve,bin;
  117358. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117359. /* low frequency curves are measured with greater resolution than
  117360. the MDCT/FFT will actually give us; we want the curve applied
  117361. to the tone data to be pessimistic and thus apply the minimum
  117362. masking possible for a given bin. That means that a single bin
  117363. could span more than one octave and that the curve will be a
  117364. composite of multiple octaves. It also may mean that a single
  117365. bin may span > an eighth of an octave and that the eighth
  117366. octave values may also be composited. */
  117367. /* which octave curves will we be compositing? */
  117368. bin=floor(fromOC(i*.5)/binHz);
  117369. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117370. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117371. if(lo_curve>i)lo_curve=i;
  117372. if(lo_curve<0)lo_curve=0;
  117373. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117374. for(m=0;m<P_LEVELS;m++){
  117375. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117376. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117377. /* render the curve into bins, then pull values back into curve.
  117378. The point is that any inherent subsampling aliasing results in
  117379. a safe minimum */
  117380. for(k=lo_curve;k<=hi_curve;k++){
  117381. int l=0;
  117382. for(j=0;j<EHMER_MAX;j++){
  117383. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117384. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117385. if(lo_bin<0)lo_bin=0;
  117386. if(lo_bin>n)lo_bin=n;
  117387. if(lo_bin<l)l=lo_bin;
  117388. if(hi_bin<0)hi_bin=0;
  117389. if(hi_bin>n)hi_bin=n;
  117390. for(;l<hi_bin && l<n;l++)
  117391. if(brute_buffer[l]>workc[k][m][j])
  117392. brute_buffer[l]=workc[k][m][j];
  117393. }
  117394. for(;l<n;l++)
  117395. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117396. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117397. }
  117398. /* be equally paranoid about being valid up to next half ocatve */
  117399. if(i+1<P_BANDS){
  117400. int l=0;
  117401. k=i+1;
  117402. for(j=0;j<EHMER_MAX;j++){
  117403. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117404. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117405. if(lo_bin<0)lo_bin=0;
  117406. if(lo_bin>n)lo_bin=n;
  117407. if(lo_bin<l)l=lo_bin;
  117408. if(hi_bin<0)hi_bin=0;
  117409. if(hi_bin>n)hi_bin=n;
  117410. for(;l<hi_bin && l<n;l++)
  117411. if(brute_buffer[l]>workc[k][m][j])
  117412. brute_buffer[l]=workc[k][m][j];
  117413. }
  117414. for(;l<n;l++)
  117415. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117416. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117417. }
  117418. for(j=0;j<EHMER_MAX;j++){
  117419. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117420. if(bin<0){
  117421. ret[i][m][j+2]=-999.;
  117422. }else{
  117423. if(bin>=n){
  117424. ret[i][m][j+2]=-999.;
  117425. }else{
  117426. ret[i][m][j+2]=brute_buffer[bin];
  117427. }
  117428. }
  117429. }
  117430. /* add fenceposts */
  117431. for(j=0;j<EHMER_OFFSET;j++)
  117432. if(ret[i][m][j+2]>-200.f)break;
  117433. ret[i][m][0]=j;
  117434. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117435. if(ret[i][m][j+2]>-200.f)
  117436. break;
  117437. ret[i][m][1]=j;
  117438. }
  117439. }
  117440. return(ret);
  117441. }
  117442. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117443. vorbis_info_psy_global *gi,int n,long rate){
  117444. long i,j,lo=-99,hi=1;
  117445. long maxoc;
  117446. memset(p,0,sizeof(*p));
  117447. p->eighth_octave_lines=gi->eighth_octave_lines;
  117448. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117449. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117450. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117451. p->total_octave_lines=maxoc-p->firstoc+1;
  117452. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117453. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117454. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117455. p->vi=vi;
  117456. p->n=n;
  117457. p->rate=rate;
  117458. /* AoTuV HF weighting */
  117459. p->m_val = 1.;
  117460. if(rate < 26000) p->m_val = 0;
  117461. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117462. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117463. /* set up the lookups for a given blocksize and sample rate */
  117464. for(i=0,j=0;i<MAX_ATH-1;i++){
  117465. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117466. float base=ATH[i];
  117467. if(j<endpos){
  117468. float delta=(ATH[i+1]-base)/(endpos-j);
  117469. for(;j<endpos && j<n;j++){
  117470. p->ath[j]=base+100.;
  117471. base+=delta;
  117472. }
  117473. }
  117474. }
  117475. for(i=0;i<n;i++){
  117476. float bark=toBARK(rate/(2*n)*i);
  117477. for(;lo+vi->noisewindowlomin<i &&
  117478. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117479. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117480. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117481. p->bark[i]=((lo-1)<<16)+(hi-1);
  117482. }
  117483. for(i=0;i<n;i++)
  117484. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117485. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117486. vi->tone_centerboost,vi->tone_decay);
  117487. /* set up rolling noise median */
  117488. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117489. for(i=0;i<P_NOISECURVES;i++)
  117490. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117491. for(i=0;i<n;i++){
  117492. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117493. int inthalfoc;
  117494. float del;
  117495. if(halfoc<0)halfoc=0;
  117496. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117497. inthalfoc=(int)halfoc;
  117498. del=halfoc-inthalfoc;
  117499. for(j=0;j<P_NOISECURVES;j++)
  117500. p->noiseoffset[j][i]=
  117501. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117502. p->vi->noiseoff[j][inthalfoc+1]*del;
  117503. }
  117504. #if 0
  117505. {
  117506. static int ls=0;
  117507. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117508. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117509. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117510. }
  117511. #endif
  117512. }
  117513. void _vp_psy_clear(vorbis_look_psy *p){
  117514. int i,j;
  117515. if(p){
  117516. if(p->ath)_ogg_free(p->ath);
  117517. if(p->octave)_ogg_free(p->octave);
  117518. if(p->bark)_ogg_free(p->bark);
  117519. if(p->tonecurves){
  117520. for(i=0;i<P_BANDS;i++){
  117521. for(j=0;j<P_LEVELS;j++){
  117522. _ogg_free(p->tonecurves[i][j]);
  117523. }
  117524. _ogg_free(p->tonecurves[i]);
  117525. }
  117526. _ogg_free(p->tonecurves);
  117527. }
  117528. if(p->noiseoffset){
  117529. for(i=0;i<P_NOISECURVES;i++){
  117530. _ogg_free(p->noiseoffset[i]);
  117531. }
  117532. _ogg_free(p->noiseoffset);
  117533. }
  117534. memset(p,0,sizeof(*p));
  117535. }
  117536. }
  117537. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117538. static void seed_curve(float *seed,
  117539. const float **curves,
  117540. float amp,
  117541. int oc, int n,
  117542. int linesper,float dBoffset){
  117543. int i,post1;
  117544. int seedptr;
  117545. const float *posts,*curve;
  117546. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117547. choice=max(choice,0);
  117548. choice=min(choice,P_LEVELS-1);
  117549. posts=curves[choice];
  117550. curve=posts+2;
  117551. post1=(int)posts[1];
  117552. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117553. for(i=posts[0];i<post1;i++){
  117554. if(seedptr>0){
  117555. float lin=amp+curve[i];
  117556. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117557. }
  117558. seedptr+=linesper;
  117559. if(seedptr>=n)break;
  117560. }
  117561. }
  117562. static void seed_loop(vorbis_look_psy *p,
  117563. const float ***curves,
  117564. const float *f,
  117565. const float *flr,
  117566. float *seed,
  117567. float specmax){
  117568. vorbis_info_psy *vi=p->vi;
  117569. long n=p->n,i;
  117570. float dBoffset=vi->max_curve_dB-specmax;
  117571. /* prime the working vector with peak values */
  117572. for(i=0;i<n;i++){
  117573. float max=f[i];
  117574. long oc=p->octave[i];
  117575. while(i+1<n && p->octave[i+1]==oc){
  117576. i++;
  117577. if(f[i]>max)max=f[i];
  117578. }
  117579. if(max+6.f>flr[i]){
  117580. oc=oc>>p->shiftoc;
  117581. if(oc>=P_BANDS)oc=P_BANDS-1;
  117582. if(oc<0)oc=0;
  117583. seed_curve(seed,
  117584. curves[oc],
  117585. max,
  117586. p->octave[i]-p->firstoc,
  117587. p->total_octave_lines,
  117588. p->eighth_octave_lines,
  117589. dBoffset);
  117590. }
  117591. }
  117592. }
  117593. static void seed_chase(float *seeds, int linesper, long n){
  117594. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117595. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117596. long stack=0;
  117597. long pos=0;
  117598. long i;
  117599. for(i=0;i<n;i++){
  117600. if(stack<2){
  117601. posstack[stack]=i;
  117602. ampstack[stack++]=seeds[i];
  117603. }else{
  117604. while(1){
  117605. if(seeds[i]<ampstack[stack-1]){
  117606. posstack[stack]=i;
  117607. ampstack[stack++]=seeds[i];
  117608. break;
  117609. }else{
  117610. if(i<posstack[stack-1]+linesper){
  117611. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117612. i<posstack[stack-2]+linesper){
  117613. /* we completely overlap, making stack-1 irrelevant. pop it */
  117614. stack--;
  117615. continue;
  117616. }
  117617. }
  117618. posstack[stack]=i;
  117619. ampstack[stack++]=seeds[i];
  117620. break;
  117621. }
  117622. }
  117623. }
  117624. }
  117625. /* the stack now contains only the positions that are relevant. Scan
  117626. 'em straight through */
  117627. for(i=0;i<stack;i++){
  117628. long endpos;
  117629. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117630. endpos=posstack[i+1];
  117631. }else{
  117632. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117633. discarded in short frames */
  117634. }
  117635. if(endpos>n)endpos=n;
  117636. for(;pos<endpos;pos++)
  117637. seeds[pos]=ampstack[i];
  117638. }
  117639. /* there. Linear time. I now remember this was on a problem set I
  117640. had in Grad Skool... I didn't solve it at the time ;-) */
  117641. }
  117642. /* bleaugh, this is more complicated than it needs to be */
  117643. #include<stdio.h>
  117644. static void max_seeds(vorbis_look_psy *p,
  117645. float *seed,
  117646. float *flr){
  117647. long n=p->total_octave_lines;
  117648. int linesper=p->eighth_octave_lines;
  117649. long linpos=0;
  117650. long pos;
  117651. seed_chase(seed,linesper,n); /* for masking */
  117652. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117653. while(linpos+1<p->n){
  117654. float minV=seed[pos];
  117655. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117656. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117657. while(pos+1<=end){
  117658. pos++;
  117659. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117660. minV=seed[pos];
  117661. }
  117662. end=pos+p->firstoc;
  117663. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117664. if(flr[linpos]<minV)flr[linpos]=minV;
  117665. }
  117666. {
  117667. float minV=seed[p->total_octave_lines-1];
  117668. for(;linpos<p->n;linpos++)
  117669. if(flr[linpos]<minV)flr[linpos]=minV;
  117670. }
  117671. }
  117672. static void bark_noise_hybridmp(int n,const long *b,
  117673. const float *f,
  117674. float *noise,
  117675. const float offset,
  117676. const int fixed){
  117677. float *N=(float*) alloca(n*sizeof(*N));
  117678. float *X=(float*) alloca(n*sizeof(*N));
  117679. float *XX=(float*) alloca(n*sizeof(*N));
  117680. float *Y=(float*) alloca(n*sizeof(*N));
  117681. float *XY=(float*) alloca(n*sizeof(*N));
  117682. float tN, tX, tXX, tY, tXY;
  117683. int i;
  117684. int lo, hi;
  117685. float R, A, B, D;
  117686. float w, x, y;
  117687. tN = tX = tXX = tY = tXY = 0.f;
  117688. y = f[0] + offset;
  117689. if (y < 1.f) y = 1.f;
  117690. w = y * y * .5;
  117691. tN += w;
  117692. tX += w;
  117693. tY += w * y;
  117694. N[0] = tN;
  117695. X[0] = tX;
  117696. XX[0] = tXX;
  117697. Y[0] = tY;
  117698. XY[0] = tXY;
  117699. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117700. y = f[i] + offset;
  117701. if (y < 1.f) y = 1.f;
  117702. w = y * y;
  117703. tN += w;
  117704. tX += w * x;
  117705. tXX += w * x * x;
  117706. tY += w * y;
  117707. tXY += w * x * y;
  117708. N[i] = tN;
  117709. X[i] = tX;
  117710. XX[i] = tXX;
  117711. Y[i] = tY;
  117712. XY[i] = tXY;
  117713. }
  117714. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117715. lo = b[i] >> 16;
  117716. if( lo>=0 ) break;
  117717. hi = b[i] & 0xffff;
  117718. tN = N[hi] + N[-lo];
  117719. tX = X[hi] - X[-lo];
  117720. tXX = XX[hi] + XX[-lo];
  117721. tY = Y[hi] + Y[-lo];
  117722. tXY = XY[hi] - XY[-lo];
  117723. A = tY * tXX - tX * tXY;
  117724. B = tN * tXY - tX * tY;
  117725. D = tN * tXX - tX * tX;
  117726. R = (A + x * B) / D;
  117727. if (R < 0.f)
  117728. R = 0.f;
  117729. noise[i] = R - offset;
  117730. }
  117731. for ( ;; i++, x += 1.f) {
  117732. lo = b[i] >> 16;
  117733. hi = b[i] & 0xffff;
  117734. if(hi>=n)break;
  117735. tN = N[hi] - N[lo];
  117736. tX = X[hi] - X[lo];
  117737. tXX = XX[hi] - XX[lo];
  117738. tY = Y[hi] - Y[lo];
  117739. tXY = XY[hi] - XY[lo];
  117740. A = tY * tXX - tX * tXY;
  117741. B = tN * tXY - tX * tY;
  117742. D = tN * tXX - tX * tX;
  117743. R = (A + x * B) / D;
  117744. if (R < 0.f) R = 0.f;
  117745. noise[i] = R - offset;
  117746. }
  117747. for ( ; i < n; i++, x += 1.f) {
  117748. R = (A + x * B) / D;
  117749. if (R < 0.f) R = 0.f;
  117750. noise[i] = R - offset;
  117751. }
  117752. if (fixed <= 0) return;
  117753. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117754. hi = i + fixed / 2;
  117755. lo = hi - fixed;
  117756. if(lo>=0)break;
  117757. tN = N[hi] + N[-lo];
  117758. tX = X[hi] - X[-lo];
  117759. tXX = XX[hi] + XX[-lo];
  117760. tY = Y[hi] + Y[-lo];
  117761. tXY = XY[hi] - XY[-lo];
  117762. A = tY * tXX - tX * tXY;
  117763. B = tN * tXY - tX * tY;
  117764. D = tN * tXX - tX * tX;
  117765. R = (A + x * B) / D;
  117766. if (R - offset < noise[i]) noise[i] = R - offset;
  117767. }
  117768. for ( ;; i++, x += 1.f) {
  117769. hi = i + fixed / 2;
  117770. lo = hi - fixed;
  117771. if(hi>=n)break;
  117772. tN = N[hi] - N[lo];
  117773. tX = X[hi] - X[lo];
  117774. tXX = XX[hi] - XX[lo];
  117775. tY = Y[hi] - Y[lo];
  117776. tXY = XY[hi] - XY[lo];
  117777. A = tY * tXX - tX * tXY;
  117778. B = tN * tXY - tX * tY;
  117779. D = tN * tXX - tX * tX;
  117780. R = (A + x * B) / D;
  117781. if (R - offset < noise[i]) noise[i] = R - offset;
  117782. }
  117783. for ( ; i < n; i++, x += 1.f) {
  117784. R = (A + x * B) / D;
  117785. if (R - offset < noise[i]) noise[i] = R - offset;
  117786. }
  117787. }
  117788. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117789. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117790. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117791. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117792. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117793. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117794. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117795. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117796. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117797. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117798. 973377.F, 913981.F, 858210.F, 805842.F,
  117799. 756669.F, 710497.F, 667142.F, 626433.F,
  117800. 588208.F, 552316.F, 518613.F, 486967.F,
  117801. 457252.F, 429351.F, 403152.F, 378551.F,
  117802. 355452.F, 333762.F, 313396.F, 294273.F,
  117803. 276316.F, 259455.F, 243623.F, 228757.F,
  117804. 214798.F, 201691.F, 189384.F, 177828.F,
  117805. 166977.F, 156788.F, 147221.F, 138237.F,
  117806. 129802.F, 121881.F, 114444.F, 107461.F,
  117807. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117808. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117809. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117810. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117811. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117812. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117813. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117814. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117815. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117816. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117817. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117818. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117819. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117820. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117821. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117822. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117823. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117824. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117825. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117826. 842.910F, 791.475F, 743.179F, 697.830F,
  117827. 655.249F, 615.265F, 577.722F, 542.469F,
  117828. 509.367F, 478.286F, 449.101F, 421.696F,
  117829. 395.964F, 371.803F, 349.115F, 327.812F,
  117830. 307.809F, 289.026F, 271.390F, 254.830F,
  117831. 239.280F, 224.679F, 210.969F, 198.096F,
  117832. 186.008F, 174.658F, 164.000F, 153.993F,
  117833. 144.596F, 135.773F, 127.488F, 119.708F,
  117834. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117835. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117836. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117837. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117838. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117839. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117840. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117841. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117842. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117843. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117844. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117845. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117846. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117847. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117848. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117849. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117850. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117851. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117852. 1.20790F, 1.13419F, 1.06499F, 1.F
  117853. };
  117854. void _vp_remove_floor(vorbis_look_psy *p,
  117855. float *mdct,
  117856. int *codedflr,
  117857. float *residue,
  117858. int sliding_lowpass){
  117859. int i,n=p->n;
  117860. if(sliding_lowpass>n)sliding_lowpass=n;
  117861. for(i=0;i<sliding_lowpass;i++){
  117862. residue[i]=
  117863. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117864. }
  117865. for(;i<n;i++)
  117866. residue[i]=0.;
  117867. }
  117868. void _vp_noisemask(vorbis_look_psy *p,
  117869. float *logmdct,
  117870. float *logmask){
  117871. int i,n=p->n;
  117872. float *work=(float*) alloca(n*sizeof(*work));
  117873. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117874. 140.,-1);
  117875. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117876. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117877. p->vi->noisewindowfixed);
  117878. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117879. #if 0
  117880. {
  117881. static int seq=0;
  117882. float work2[n];
  117883. for(i=0;i<n;i++){
  117884. work2[i]=logmask[i]+work[i];
  117885. }
  117886. if(seq&1)
  117887. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117888. else
  117889. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117890. if(seq&1)
  117891. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117892. else
  117893. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117894. seq++;
  117895. }
  117896. #endif
  117897. for(i=0;i<n;i++){
  117898. int dB=logmask[i]+.5;
  117899. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117900. if(dB<0)dB=0;
  117901. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117902. }
  117903. }
  117904. void _vp_tonemask(vorbis_look_psy *p,
  117905. float *logfft,
  117906. float *logmask,
  117907. float global_specmax,
  117908. float local_specmax){
  117909. int i,n=p->n;
  117910. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117911. float att=local_specmax+p->vi->ath_adjatt;
  117912. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117913. /* set the ATH (floating below localmax, not global max by a
  117914. specified att) */
  117915. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117916. for(i=0;i<n;i++)
  117917. logmask[i]=p->ath[i]+att;
  117918. /* tone masking */
  117919. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117920. max_seeds(p,seed,logmask);
  117921. }
  117922. void _vp_offset_and_mix(vorbis_look_psy *p,
  117923. float *noise,
  117924. float *tone,
  117925. int offset_select,
  117926. float *logmask,
  117927. float *mdct,
  117928. float *logmdct){
  117929. int i,n=p->n;
  117930. float de, coeffi, cx;/* AoTuV */
  117931. float toneatt=p->vi->tone_masteratt[offset_select];
  117932. cx = p->m_val;
  117933. for(i=0;i<n;i++){
  117934. float val= noise[i]+p->noiseoffset[offset_select][i];
  117935. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117936. logmask[i]=max(val,tone[i]+toneatt);
  117937. /* AoTuV */
  117938. /** @ M1 **
  117939. The following codes improve a noise problem.
  117940. A fundamental idea uses the value of masking and carries out
  117941. the relative compensation of the MDCT.
  117942. However, this code is not perfect and all noise problems cannot be solved.
  117943. by Aoyumi @ 2004/04/18
  117944. */
  117945. if(offset_select == 1) {
  117946. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117947. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117948. if(val > coeffi){
  117949. /* mdct value is > -17.2 dB below floor */
  117950. de = 1.0-((val-coeffi)*0.005*cx);
  117951. /* pro-rated attenuation:
  117952. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117953. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117954. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117955. etc... */
  117956. if(de < 0) de = 0.0001;
  117957. }else
  117958. /* mdct value is <= -17.2 dB below floor */
  117959. de = 1.0-((val-coeffi)*0.0003*cx);
  117960. /* pro-rated attenuation:
  117961. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117962. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117963. etc... */
  117964. mdct[i] *= de;
  117965. }
  117966. }
  117967. }
  117968. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117969. vorbis_info *vi=vd->vi;
  117970. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117971. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117972. int n=ci->blocksizes[vd->W]/2;
  117973. float secs=(float)n/vi->rate;
  117974. amp+=secs*gi->ampmax_att_per_sec;
  117975. if(amp<-9999)amp=-9999;
  117976. return(amp);
  117977. }
  117978. static void couple_lossless(float A, float B,
  117979. float *qA, float *qB){
  117980. int test1=fabs(*qA)>fabs(*qB);
  117981. test1-= fabs(*qA)<fabs(*qB);
  117982. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117983. if(test1==1){
  117984. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117985. }else{
  117986. float temp=*qB;
  117987. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117988. *qA=temp;
  117989. }
  117990. if(*qB>fabs(*qA)*1.9999f){
  117991. *qB= -fabs(*qA)*2.f;
  117992. *qA= -*qA;
  117993. }
  117994. }
  117995. static float hypot_lookup[32]={
  117996. -0.009935, -0.011245, -0.012726, -0.014397,
  117997. -0.016282, -0.018407, -0.020800, -0.023494,
  117998. -0.026522, -0.029923, -0.033737, -0.038010,
  117999. -0.042787, -0.048121, -0.054064, -0.060671,
  118000. -0.068000, -0.076109, -0.085054, -0.094892,
  118001. -0.105675, -0.117451, -0.130260, -0.144134,
  118002. -0.159093, -0.175146, -0.192286, -0.210490,
  118003. -0.229718, -0.249913, -0.271001, -0.292893};
  118004. static void precomputed_couple_point(float premag,
  118005. int floorA,int floorB,
  118006. float *mag, float *ang){
  118007. int test=(floorA>floorB)-1;
  118008. int offset=31-abs(floorA-floorB);
  118009. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  118010. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  118011. *mag=premag*floormag;
  118012. *ang=0.f;
  118013. }
  118014. /* just like below, this is currently set up to only do
  118015. single-step-depth coupling. Otherwise, we'd have to do more
  118016. copying (which will be inevitable later) */
  118017. /* doing the real circular magnitude calculation is audibly superior
  118018. to (A+B)/sqrt(2) */
  118019. static float dipole_hypot(float a, float b){
  118020. if(a>0.){
  118021. if(b>0.)return sqrt(a*a+b*b);
  118022. if(a>-b)return sqrt(a*a-b*b);
  118023. return -sqrt(b*b-a*a);
  118024. }
  118025. if(b<0.)return -sqrt(a*a+b*b);
  118026. if(-a>b)return -sqrt(a*a-b*b);
  118027. return sqrt(b*b-a*a);
  118028. }
  118029. static float round_hypot(float a, float b){
  118030. if(a>0.){
  118031. if(b>0.)return sqrt(a*a+b*b);
  118032. if(a>-b)return sqrt(a*a+b*b);
  118033. return -sqrt(b*b+a*a);
  118034. }
  118035. if(b<0.)return -sqrt(a*a+b*b);
  118036. if(-a>b)return -sqrt(a*a+b*b);
  118037. return sqrt(b*b+a*a);
  118038. }
  118039. /* revert to round hypot for now */
  118040. float **_vp_quantize_couple_memo(vorbis_block *vb,
  118041. vorbis_info_psy_global *g,
  118042. vorbis_look_psy *p,
  118043. vorbis_info_mapping0 *vi,
  118044. float **mdct){
  118045. int i,j,n=p->n;
  118046. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118047. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118048. for(i=0;i<vi->coupling_steps;i++){
  118049. float *mdctM=mdct[vi->coupling_mag[i]];
  118050. float *mdctA=mdct[vi->coupling_ang[i]];
  118051. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118052. for(j=0;j<limit;j++)
  118053. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  118054. for(;j<n;j++)
  118055. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  118056. }
  118057. return(ret);
  118058. }
  118059. /* this is for per-channel noise normalization */
  118060. static int JUCE_CDECL apsort(const void *a, const void *b){
  118061. float f1=fabs(**(float**)a);
  118062. float f2=fabs(**(float**)b);
  118063. return (f1<f2)-(f1>f2);
  118064. }
  118065. int **_vp_quantize_couple_sort(vorbis_block *vb,
  118066. vorbis_look_psy *p,
  118067. vorbis_info_mapping0 *vi,
  118068. float **mags){
  118069. if(p->vi->normal_point_p){
  118070. int i,j,k,n=p->n;
  118071. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118072. int partition=p->vi->normal_partition;
  118073. float **work=(float**) alloca(sizeof(*work)*partition);
  118074. for(i=0;i<vi->coupling_steps;i++){
  118075. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118076. for(j=0;j<n;j+=partition){
  118077. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  118078. qsort(work,partition,sizeof(*work),apsort);
  118079. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  118080. }
  118081. }
  118082. return(ret);
  118083. }
  118084. return(NULL);
  118085. }
  118086. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  118087. float *magnitudes,int *sortedindex){
  118088. int i,j,n=p->n;
  118089. vorbis_info_psy *vi=p->vi;
  118090. int partition=vi->normal_partition;
  118091. float **work=(float**) alloca(sizeof(*work)*partition);
  118092. int start=vi->normal_start;
  118093. for(j=start;j<n;j+=partition){
  118094. if(j+partition>n)partition=n-j;
  118095. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  118096. qsort(work,partition,sizeof(*work),apsort);
  118097. for(i=0;i<partition;i++){
  118098. sortedindex[i+j-start]=work[i]-magnitudes;
  118099. }
  118100. }
  118101. }
  118102. void _vp_noise_normalize(vorbis_look_psy *p,
  118103. float *in,float *out,int *sortedindex){
  118104. int flag=0,i,j=0,n=p->n;
  118105. vorbis_info_psy *vi=p->vi;
  118106. int partition=vi->normal_partition;
  118107. int start=vi->normal_start;
  118108. if(start>n)start=n;
  118109. if(vi->normal_channel_p){
  118110. for(;j<start;j++)
  118111. out[j]=rint(in[j]);
  118112. for(;j+partition<=n;j+=partition){
  118113. float acc=0.;
  118114. int k;
  118115. for(i=j;i<j+partition;i++)
  118116. acc+=in[i]*in[i];
  118117. for(i=0;i<partition;i++){
  118118. k=sortedindex[i+j-start];
  118119. if(in[k]*in[k]>=.25f){
  118120. out[k]=rint(in[k]);
  118121. acc-=in[k]*in[k];
  118122. flag=1;
  118123. }else{
  118124. if(acc<vi->normal_thresh)break;
  118125. out[k]=unitnorm(in[k]);
  118126. acc-=1.;
  118127. }
  118128. }
  118129. for(;i<partition;i++){
  118130. k=sortedindex[i+j-start];
  118131. out[k]=0.;
  118132. }
  118133. }
  118134. }
  118135. for(;j<n;j++)
  118136. out[j]=rint(in[j]);
  118137. }
  118138. void _vp_couple(int blobno,
  118139. vorbis_info_psy_global *g,
  118140. vorbis_look_psy *p,
  118141. vorbis_info_mapping0 *vi,
  118142. float **res,
  118143. float **mag_memo,
  118144. int **mag_sort,
  118145. int **ifloor,
  118146. int *nonzero,
  118147. int sliding_lowpass){
  118148. int i,j,k,n=p->n;
  118149. /* perform any requested channel coupling */
  118150. /* point stereo can only be used in a first stage (in this encoder)
  118151. because of the dependency on floor lookups */
  118152. for(i=0;i<vi->coupling_steps;i++){
  118153. /* once we're doing multistage coupling in which a channel goes
  118154. through more than one coupling step, the floor vector
  118155. magnitudes will also have to be recalculated an propogated
  118156. along with PCM. Right now, we're not (that will wait until 5.1
  118157. most likely), so the code isn't here yet. The memory management
  118158. here is all assuming single depth couplings anyway. */
  118159. /* make sure coupling a zero and a nonzero channel results in two
  118160. nonzero channels. */
  118161. if(nonzero[vi->coupling_mag[i]] ||
  118162. nonzero[vi->coupling_ang[i]]){
  118163. float *rM=res[vi->coupling_mag[i]];
  118164. float *rA=res[vi->coupling_ang[i]];
  118165. float *qM=rM+n;
  118166. float *qA=rA+n;
  118167. int *floorM=ifloor[vi->coupling_mag[i]];
  118168. int *floorA=ifloor[vi->coupling_ang[i]];
  118169. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118170. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118171. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118172. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118173. int pointlimit=limit;
  118174. nonzero[vi->coupling_mag[i]]=1;
  118175. nonzero[vi->coupling_ang[i]]=1;
  118176. /* The threshold of a stereo is changed with the size of n */
  118177. if(n > 1000)
  118178. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118179. for(j=0;j<p->n;j+=partition){
  118180. float acc=0.f;
  118181. for(k=0;k<partition;k++){
  118182. int l=k+j;
  118183. if(l<sliding_lowpass){
  118184. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118185. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118186. precomputed_couple_point(mag_memo[i][l],
  118187. floorM[l],floorA[l],
  118188. qM+l,qA+l);
  118189. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118190. }else{
  118191. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118192. }
  118193. }else{
  118194. qM[l]=0.;
  118195. qA[l]=0.;
  118196. }
  118197. }
  118198. if(p->vi->normal_point_p){
  118199. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118200. int l=mag_sort[i][j+k];
  118201. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118202. qM[l]=unitnorm(qM[l]);
  118203. acc-=1.f;
  118204. }
  118205. }
  118206. }
  118207. }
  118208. }
  118209. }
  118210. }
  118211. /* AoTuV */
  118212. /** @ M2 **
  118213. The boost problem by the combination of noise normalization and point stereo is eased.
  118214. However, this is a temporary patch.
  118215. by Aoyumi @ 2004/04/18
  118216. */
  118217. void hf_reduction(vorbis_info_psy_global *g,
  118218. vorbis_look_psy *p,
  118219. vorbis_info_mapping0 *vi,
  118220. float **mdct){
  118221. int i,j,n=p->n, de=0.3*p->m_val;
  118222. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118223. for(i=0; i<vi->coupling_steps; i++){
  118224. /* for(j=start; j<limit; j++){} // ???*/
  118225. for(j=limit; j<n; j++)
  118226. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118227. }
  118228. }
  118229. #endif
  118230. /*** End of inlined file: psy.c ***/
  118231. /*** Start of inlined file: registry.c ***/
  118232. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118233. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118234. // tasks..
  118235. #if JUCE_MSVC
  118236. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118237. #endif
  118238. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118239. #if JUCE_USE_OGGVORBIS
  118240. /* seems like major overkill now; the backend numbers will grow into
  118241. the infrastructure soon enough */
  118242. extern vorbis_func_floor floor0_exportbundle;
  118243. extern vorbis_func_floor floor1_exportbundle;
  118244. extern vorbis_func_residue residue0_exportbundle;
  118245. extern vorbis_func_residue residue1_exportbundle;
  118246. extern vorbis_func_residue residue2_exportbundle;
  118247. extern vorbis_func_mapping mapping0_exportbundle;
  118248. vorbis_func_floor *_floor_P[]={
  118249. &floor0_exportbundle,
  118250. &floor1_exportbundle,
  118251. };
  118252. vorbis_func_residue *_residue_P[]={
  118253. &residue0_exportbundle,
  118254. &residue1_exportbundle,
  118255. &residue2_exportbundle,
  118256. };
  118257. vorbis_func_mapping *_mapping_P[]={
  118258. &mapping0_exportbundle,
  118259. };
  118260. #endif
  118261. /*** End of inlined file: registry.c ***/
  118262. /*** Start of inlined file: res0.c ***/
  118263. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118264. encode/decode loops are coded for clarity and performance is not
  118265. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118266. it's slow. */
  118267. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118268. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118269. // tasks..
  118270. #if JUCE_MSVC
  118271. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118272. #endif
  118273. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118274. #if JUCE_USE_OGGVORBIS
  118275. #include <stdlib.h>
  118276. #include <string.h>
  118277. #include <math.h>
  118278. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118279. #include <stdio.h>
  118280. #endif
  118281. typedef struct {
  118282. vorbis_info_residue0 *info;
  118283. int parts;
  118284. int stages;
  118285. codebook *fullbooks;
  118286. codebook *phrasebook;
  118287. codebook ***partbooks;
  118288. int partvals;
  118289. int **decodemap;
  118290. long postbits;
  118291. long phrasebits;
  118292. long frames;
  118293. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118294. int train_seq;
  118295. long *training_data[8][64];
  118296. float training_max[8][64];
  118297. float training_min[8][64];
  118298. float tmin;
  118299. float tmax;
  118300. #endif
  118301. } vorbis_look_residue0;
  118302. void res0_free_info(vorbis_info_residue *i){
  118303. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118304. if(info){
  118305. memset(info,0,sizeof(*info));
  118306. _ogg_free(info);
  118307. }
  118308. }
  118309. void res0_free_look(vorbis_look_residue *i){
  118310. int j;
  118311. if(i){
  118312. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118313. #ifdef TRAIN_RES
  118314. {
  118315. int j,k,l;
  118316. for(j=0;j<look->parts;j++){
  118317. /*fprintf(stderr,"partition %d: ",j);*/
  118318. for(k=0;k<8;k++)
  118319. if(look->training_data[k][j]){
  118320. char buffer[80];
  118321. FILE *of;
  118322. codebook *statebook=look->partbooks[j][k];
  118323. /* long and short into the same bucket by current convention */
  118324. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118325. of=fopen(buffer,"a");
  118326. for(l=0;l<statebook->entries;l++)
  118327. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118328. fclose(of);
  118329. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118330. look->training_min[k][j],look->training_max[k][j]);*/
  118331. _ogg_free(look->training_data[k][j]);
  118332. look->training_data[k][j]=NULL;
  118333. }
  118334. /*fprintf(stderr,"\n");*/
  118335. }
  118336. }
  118337. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118338. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118339. (float)look->phrasebits/look->frames,
  118340. (float)look->postbits/look->frames,
  118341. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118342. #endif
  118343. /*vorbis_info_residue0 *info=look->info;
  118344. fprintf(stderr,
  118345. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118346. "(%g/frame) \n",look->frames,look->phrasebits,
  118347. look->resbitsflat,
  118348. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118349. for(j=0;j<look->parts;j++){
  118350. long acc=0;
  118351. fprintf(stderr,"\t[%d] == ",j);
  118352. for(k=0;k<look->stages;k++)
  118353. if((info->secondstages[j]>>k)&1){
  118354. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118355. acc+=look->resbits[j][k];
  118356. }
  118357. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118358. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118359. }
  118360. fprintf(stderr,"\n");*/
  118361. for(j=0;j<look->parts;j++)
  118362. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118363. _ogg_free(look->partbooks);
  118364. for(j=0;j<look->partvals;j++)
  118365. _ogg_free(look->decodemap[j]);
  118366. _ogg_free(look->decodemap);
  118367. memset(look,0,sizeof(*look));
  118368. _ogg_free(look);
  118369. }
  118370. }
  118371. static int icount(unsigned int v){
  118372. int ret=0;
  118373. while(v){
  118374. ret+=v&1;
  118375. v>>=1;
  118376. }
  118377. return(ret);
  118378. }
  118379. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118380. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118381. int j,acc=0;
  118382. oggpack_write(opb,info->begin,24);
  118383. oggpack_write(opb,info->end,24);
  118384. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118385. code with a partitioned book */
  118386. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118387. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118388. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118389. bitmask of one indicates this partition class has bits to write
  118390. this pass */
  118391. for(j=0;j<info->partitions;j++){
  118392. if(ilog(info->secondstages[j])>3){
  118393. /* yes, this is a minor hack due to not thinking ahead */
  118394. oggpack_write(opb,info->secondstages[j],3);
  118395. oggpack_write(opb,1,1);
  118396. oggpack_write(opb,info->secondstages[j]>>3,5);
  118397. }else
  118398. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118399. acc+=icount(info->secondstages[j]);
  118400. }
  118401. for(j=0;j<acc;j++)
  118402. oggpack_write(opb,info->booklist[j],8);
  118403. }
  118404. /* vorbis_info is for range checking */
  118405. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118406. int j,acc=0;
  118407. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118408. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118409. info->begin=oggpack_read(opb,24);
  118410. info->end=oggpack_read(opb,24);
  118411. info->grouping=oggpack_read(opb,24)+1;
  118412. info->partitions=oggpack_read(opb,6)+1;
  118413. info->groupbook=oggpack_read(opb,8);
  118414. for(j=0;j<info->partitions;j++){
  118415. int cascade=oggpack_read(opb,3);
  118416. if(oggpack_read(opb,1))
  118417. cascade|=(oggpack_read(opb,5)<<3);
  118418. info->secondstages[j]=cascade;
  118419. acc+=icount(cascade);
  118420. }
  118421. for(j=0;j<acc;j++)
  118422. info->booklist[j]=oggpack_read(opb,8);
  118423. if(info->groupbook>=ci->books)goto errout;
  118424. for(j=0;j<acc;j++)
  118425. if(info->booklist[j]>=ci->books)goto errout;
  118426. return(info);
  118427. errout:
  118428. res0_free_info(info);
  118429. return(NULL);
  118430. }
  118431. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118432. vorbis_info_residue *vr){
  118433. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118434. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118435. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118436. int j,k,acc=0;
  118437. int dim;
  118438. int maxstage=0;
  118439. look->info=info;
  118440. look->parts=info->partitions;
  118441. look->fullbooks=ci->fullbooks;
  118442. look->phrasebook=ci->fullbooks+info->groupbook;
  118443. dim=look->phrasebook->dim;
  118444. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118445. for(j=0;j<look->parts;j++){
  118446. int stages=ilog(info->secondstages[j]);
  118447. if(stages){
  118448. if(stages>maxstage)maxstage=stages;
  118449. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118450. for(k=0;k<stages;k++)
  118451. if(info->secondstages[j]&(1<<k)){
  118452. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118453. #ifdef TRAIN_RES
  118454. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118455. sizeof(***look->training_data));
  118456. #endif
  118457. }
  118458. }
  118459. }
  118460. look->partvals=rint(pow((float)look->parts,(float)dim));
  118461. look->stages=maxstage;
  118462. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118463. for(j=0;j<look->partvals;j++){
  118464. long val=j;
  118465. long mult=look->partvals/look->parts;
  118466. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118467. for(k=0;k<dim;k++){
  118468. long deco=val/mult;
  118469. val-=deco*mult;
  118470. mult/=look->parts;
  118471. look->decodemap[j][k]=deco;
  118472. }
  118473. }
  118474. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118475. {
  118476. static int train_seq=0;
  118477. look->train_seq=train_seq++;
  118478. }
  118479. #endif
  118480. return(look);
  118481. }
  118482. /* break an abstraction and copy some code for performance purposes */
  118483. static int local_book_besterror(codebook *book,float *a){
  118484. int dim=book->dim,i,k,o;
  118485. int best=0;
  118486. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118487. /* find the quant val of each scalar */
  118488. for(k=0,o=dim;k<dim;++k){
  118489. float val=a[--o];
  118490. i=tt->threshvals>>1;
  118491. if(val<tt->quantthresh[i]){
  118492. if(val<tt->quantthresh[i-1]){
  118493. for(--i;i>0;--i)
  118494. if(val>=tt->quantthresh[i-1])
  118495. break;
  118496. }
  118497. }else{
  118498. for(++i;i<tt->threshvals-1;++i)
  118499. if(val<tt->quantthresh[i])break;
  118500. }
  118501. best=(best*tt->quantvals)+tt->quantmap[i];
  118502. }
  118503. /* regular lattices are easy :-) */
  118504. if(book->c->lengthlist[best]<=0){
  118505. const static_codebook *c=book->c;
  118506. int i,j;
  118507. float bestf=0.f;
  118508. float *e=book->valuelist;
  118509. best=-1;
  118510. for(i=0;i<book->entries;i++){
  118511. if(c->lengthlist[i]>0){
  118512. float thisx=0.f;
  118513. for(j=0;j<dim;j++){
  118514. float val=(e[j]-a[j]);
  118515. thisx+=val*val;
  118516. }
  118517. if(best==-1 || thisx<bestf){
  118518. bestf=thisx;
  118519. best=i;
  118520. }
  118521. }
  118522. e+=dim;
  118523. }
  118524. }
  118525. {
  118526. float *ptr=book->valuelist+best*dim;
  118527. for(i=0;i<dim;i++)
  118528. *a++ -= *ptr++;
  118529. }
  118530. return(best);
  118531. }
  118532. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118533. codebook *book,long *acc){
  118534. int i,bits=0;
  118535. int dim=book->dim;
  118536. int step=n/dim;
  118537. for(i=0;i<step;i++){
  118538. int entry=local_book_besterror(book,vec+i*dim);
  118539. #ifdef TRAIN_RES
  118540. acc[entry]++;
  118541. #endif
  118542. bits+=vorbis_book_encode(book,entry,opb);
  118543. }
  118544. return(bits);
  118545. }
  118546. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118547. float **in,int ch){
  118548. long i,j,k;
  118549. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118550. vorbis_info_residue0 *info=look->info;
  118551. /* move all this setup out later */
  118552. int samples_per_partition=info->grouping;
  118553. int possible_partitions=info->partitions;
  118554. int n=info->end-info->begin;
  118555. int partvals=n/samples_per_partition;
  118556. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118557. float scale=100./samples_per_partition;
  118558. /* we find the partition type for each partition of each
  118559. channel. We'll go back and do the interleaved encoding in a
  118560. bit. For now, clarity */
  118561. for(i=0;i<ch;i++){
  118562. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118563. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118564. }
  118565. for(i=0;i<partvals;i++){
  118566. int offset=i*samples_per_partition+info->begin;
  118567. for(j=0;j<ch;j++){
  118568. float max=0.;
  118569. float ent=0.;
  118570. for(k=0;k<samples_per_partition;k++){
  118571. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118572. ent+=fabs(rint(in[j][offset+k]));
  118573. }
  118574. ent*=scale;
  118575. for(k=0;k<possible_partitions-1;k++)
  118576. if(max<=info->classmetric1[k] &&
  118577. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118578. break;
  118579. partword[j][i]=k;
  118580. }
  118581. }
  118582. #ifdef TRAIN_RESAUX
  118583. {
  118584. FILE *of;
  118585. char buffer[80];
  118586. for(i=0;i<ch;i++){
  118587. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118588. of=fopen(buffer,"a");
  118589. for(j=0;j<partvals;j++)
  118590. fprintf(of,"%ld, ",partword[i][j]);
  118591. fprintf(of,"\n");
  118592. fclose(of);
  118593. }
  118594. }
  118595. #endif
  118596. look->frames++;
  118597. return(partword);
  118598. }
  118599. /* designed for stereo or other modes where the partition size is an
  118600. integer multiple of the number of channels encoded in the current
  118601. submap */
  118602. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118603. int ch){
  118604. long i,j,k,l;
  118605. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118606. vorbis_info_residue0 *info=look->info;
  118607. /* move all this setup out later */
  118608. int samples_per_partition=info->grouping;
  118609. int possible_partitions=info->partitions;
  118610. int n=info->end-info->begin;
  118611. int partvals=n/samples_per_partition;
  118612. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118613. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118614. FILE *of;
  118615. char buffer[80];
  118616. #endif
  118617. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118618. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118619. for(i=0,l=info->begin/ch;i<partvals;i++){
  118620. float magmax=0.f;
  118621. float angmax=0.f;
  118622. for(j=0;j<samples_per_partition;j+=ch){
  118623. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118624. for(k=1;k<ch;k++)
  118625. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118626. l++;
  118627. }
  118628. for(j=0;j<possible_partitions-1;j++)
  118629. if(magmax<=info->classmetric1[j] &&
  118630. angmax<=info->classmetric2[j])
  118631. break;
  118632. partword[0][i]=j;
  118633. }
  118634. #ifdef TRAIN_RESAUX
  118635. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118636. of=fopen(buffer,"a");
  118637. for(i=0;i<partvals;i++)
  118638. fprintf(of,"%ld, ",partword[0][i]);
  118639. fprintf(of,"\n");
  118640. fclose(of);
  118641. #endif
  118642. look->frames++;
  118643. return(partword);
  118644. }
  118645. static int _01forward(oggpack_buffer *opb,
  118646. vorbis_block *vb,vorbis_look_residue *vl,
  118647. float **in,int ch,
  118648. long **partword,
  118649. int (*encode)(oggpack_buffer *,float *,int,
  118650. codebook *,long *)){
  118651. long i,j,k,s;
  118652. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118653. vorbis_info_residue0 *info=look->info;
  118654. /* move all this setup out later */
  118655. int samples_per_partition=info->grouping;
  118656. int possible_partitions=info->partitions;
  118657. int partitions_per_word=look->phrasebook->dim;
  118658. int n=info->end-info->begin;
  118659. int partvals=n/samples_per_partition;
  118660. long resbits[128];
  118661. long resvals[128];
  118662. #ifdef TRAIN_RES
  118663. for(i=0;i<ch;i++)
  118664. for(j=info->begin;j<info->end;j++){
  118665. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118666. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118667. }
  118668. #endif
  118669. memset(resbits,0,sizeof(resbits));
  118670. memset(resvals,0,sizeof(resvals));
  118671. /* we code the partition words for each channel, then the residual
  118672. words for a partition per channel until we've written all the
  118673. residual words for that partition word. Then write the next
  118674. partition channel words... */
  118675. for(s=0;s<look->stages;s++){
  118676. for(i=0;i<partvals;){
  118677. /* first we encode a partition codeword for each channel */
  118678. if(s==0){
  118679. for(j=0;j<ch;j++){
  118680. long val=partword[j][i];
  118681. for(k=1;k<partitions_per_word;k++){
  118682. val*=possible_partitions;
  118683. if(i+k<partvals)
  118684. val+=partword[j][i+k];
  118685. }
  118686. /* training hack */
  118687. if(val<look->phrasebook->entries)
  118688. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118689. #if 0 /*def TRAIN_RES*/
  118690. else
  118691. fprintf(stderr,"!");
  118692. #endif
  118693. }
  118694. }
  118695. /* now we encode interleaved residual values for the partitions */
  118696. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118697. long offset=i*samples_per_partition+info->begin;
  118698. for(j=0;j<ch;j++){
  118699. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118700. if(info->secondstages[partword[j][i]]&(1<<s)){
  118701. codebook *statebook=look->partbooks[partword[j][i]][s];
  118702. if(statebook){
  118703. int ret;
  118704. long *accumulator=NULL;
  118705. #ifdef TRAIN_RES
  118706. accumulator=look->training_data[s][partword[j][i]];
  118707. {
  118708. int l;
  118709. float *samples=in[j]+offset;
  118710. for(l=0;l<samples_per_partition;l++){
  118711. if(samples[l]<look->training_min[s][partword[j][i]])
  118712. look->training_min[s][partword[j][i]]=samples[l];
  118713. if(samples[l]>look->training_max[s][partword[j][i]])
  118714. look->training_max[s][partword[j][i]]=samples[l];
  118715. }
  118716. }
  118717. #endif
  118718. ret=encode(opb,in[j]+offset,samples_per_partition,
  118719. statebook,accumulator);
  118720. look->postbits+=ret;
  118721. resbits[partword[j][i]]+=ret;
  118722. }
  118723. }
  118724. }
  118725. }
  118726. }
  118727. }
  118728. /*{
  118729. long total=0;
  118730. long totalbits=0;
  118731. fprintf(stderr,"%d :: ",vb->mode);
  118732. for(k=0;k<possible_partitions;k++){
  118733. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118734. total+=resvals[k];
  118735. totalbits+=resbits[k];
  118736. }
  118737. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118738. }*/
  118739. return(0);
  118740. }
  118741. /* a truncated packet here just means 'stop working'; it's not an error */
  118742. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118743. float **in,int ch,
  118744. long (*decodepart)(codebook *, float *,
  118745. oggpack_buffer *,int)){
  118746. long i,j,k,l,s;
  118747. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118748. vorbis_info_residue0 *info=look->info;
  118749. /* move all this setup out later */
  118750. int samples_per_partition=info->grouping;
  118751. int partitions_per_word=look->phrasebook->dim;
  118752. int n=info->end-info->begin;
  118753. int partvals=n/samples_per_partition;
  118754. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118755. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118756. for(j=0;j<ch;j++)
  118757. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118758. for(s=0;s<look->stages;s++){
  118759. /* each loop decodes on partition codeword containing
  118760. partitions_pre_word partitions */
  118761. for(i=0,l=0;i<partvals;l++){
  118762. if(s==0){
  118763. /* fetch the partition word for each channel */
  118764. for(j=0;j<ch;j++){
  118765. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118766. if(temp==-1)goto eopbreak;
  118767. partword[j][l]=look->decodemap[temp];
  118768. if(partword[j][l]==NULL)goto errout;
  118769. }
  118770. }
  118771. /* now we decode residual values for the partitions */
  118772. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118773. for(j=0;j<ch;j++){
  118774. long offset=info->begin+i*samples_per_partition;
  118775. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118776. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118777. if(stagebook){
  118778. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118779. samples_per_partition)==-1)goto eopbreak;
  118780. }
  118781. }
  118782. }
  118783. }
  118784. }
  118785. errout:
  118786. eopbreak:
  118787. return(0);
  118788. }
  118789. #if 0
  118790. /* residue 0 and 1 are just slight variants of one another. 0 is
  118791. interleaved, 1 is not */
  118792. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118793. float **in,int *nonzero,int ch){
  118794. /* we encode only the nonzero parts of a bundle */
  118795. int i,used=0;
  118796. for(i=0;i<ch;i++)
  118797. if(nonzero[i])
  118798. in[used++]=in[i];
  118799. if(used)
  118800. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118801. return(_01class(vb,vl,in,used));
  118802. else
  118803. return(0);
  118804. }
  118805. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118806. float **in,float **out,int *nonzero,int ch,
  118807. long **partword){
  118808. /* we encode only the nonzero parts of a bundle */
  118809. int i,j,used=0,n=vb->pcmend/2;
  118810. for(i=0;i<ch;i++)
  118811. if(nonzero[i]){
  118812. if(out)
  118813. for(j=0;j<n;j++)
  118814. out[i][j]+=in[i][j];
  118815. in[used++]=in[i];
  118816. }
  118817. if(used){
  118818. int ret=_01forward(vb,vl,in,used,partword,
  118819. _interleaved_encodepart);
  118820. if(out){
  118821. used=0;
  118822. for(i=0;i<ch;i++)
  118823. if(nonzero[i]){
  118824. for(j=0;j<n;j++)
  118825. out[i][j]-=in[used][j];
  118826. used++;
  118827. }
  118828. }
  118829. return(ret);
  118830. }else{
  118831. return(0);
  118832. }
  118833. }
  118834. #endif
  118835. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118836. float **in,int *nonzero,int ch){
  118837. int i,used=0;
  118838. for(i=0;i<ch;i++)
  118839. if(nonzero[i])
  118840. in[used++]=in[i];
  118841. if(used)
  118842. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118843. else
  118844. return(0);
  118845. }
  118846. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118847. float **in,float **out,int *nonzero,int ch,
  118848. long **partword){
  118849. int i,j,used=0,n=vb->pcmend/2;
  118850. for(i=0;i<ch;i++)
  118851. if(nonzero[i]){
  118852. if(out)
  118853. for(j=0;j<n;j++)
  118854. out[i][j]+=in[i][j];
  118855. in[used++]=in[i];
  118856. }
  118857. if(used){
  118858. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118859. if(out){
  118860. used=0;
  118861. for(i=0;i<ch;i++)
  118862. if(nonzero[i]){
  118863. for(j=0;j<n;j++)
  118864. out[i][j]-=in[used][j];
  118865. used++;
  118866. }
  118867. }
  118868. return(ret);
  118869. }else{
  118870. return(0);
  118871. }
  118872. }
  118873. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118874. float **in,int *nonzero,int ch){
  118875. int i,used=0;
  118876. for(i=0;i<ch;i++)
  118877. if(nonzero[i])
  118878. in[used++]=in[i];
  118879. if(used)
  118880. return(_01class(vb,vl,in,used));
  118881. else
  118882. return(0);
  118883. }
  118884. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118885. float **in,int *nonzero,int ch){
  118886. int i,used=0;
  118887. for(i=0;i<ch;i++)
  118888. if(nonzero[i])
  118889. in[used++]=in[i];
  118890. if(used)
  118891. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118892. else
  118893. return(0);
  118894. }
  118895. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118896. float **in,int *nonzero,int ch){
  118897. int i,used=0;
  118898. for(i=0;i<ch;i++)
  118899. if(nonzero[i])used++;
  118900. if(used)
  118901. return(_2class(vb,vl,in,ch));
  118902. else
  118903. return(0);
  118904. }
  118905. /* res2 is slightly more different; all the channels are interleaved
  118906. into a single vector and encoded. */
  118907. int res2_forward(oggpack_buffer *opb,
  118908. vorbis_block *vb,vorbis_look_residue *vl,
  118909. float **in,float **out,int *nonzero,int ch,
  118910. long **partword){
  118911. long i,j,k,n=vb->pcmend/2,used=0;
  118912. /* don't duplicate the code; use a working vector hack for now and
  118913. reshape ourselves into a single channel res1 */
  118914. /* ugly; reallocs for each coupling pass :-( */
  118915. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118916. for(i=0;i<ch;i++){
  118917. float *pcm=in[i];
  118918. if(nonzero[i])used++;
  118919. for(j=0,k=i;j<n;j++,k+=ch)
  118920. work[k]=pcm[j];
  118921. }
  118922. if(used){
  118923. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118924. /* update the sofar vector */
  118925. if(out){
  118926. for(i=0;i<ch;i++){
  118927. float *pcm=in[i];
  118928. float *sofar=out[i];
  118929. for(j=0,k=i;j<n;j++,k+=ch)
  118930. sofar[j]+=pcm[j]-work[k];
  118931. }
  118932. }
  118933. return(ret);
  118934. }else{
  118935. return(0);
  118936. }
  118937. }
  118938. /* duplicate code here as speed is somewhat more important */
  118939. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118940. float **in,int *nonzero,int ch){
  118941. long i,k,l,s;
  118942. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118943. vorbis_info_residue0 *info=look->info;
  118944. /* move all this setup out later */
  118945. int samples_per_partition=info->grouping;
  118946. int partitions_per_word=look->phrasebook->dim;
  118947. int n=info->end-info->begin;
  118948. int partvals=n/samples_per_partition;
  118949. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118950. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118951. for(i=0;i<ch;i++)if(nonzero[i])break;
  118952. if(i==ch)return(0); /* no nonzero vectors */
  118953. for(s=0;s<look->stages;s++){
  118954. for(i=0,l=0;i<partvals;l++){
  118955. if(s==0){
  118956. /* fetch the partition word */
  118957. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118958. if(temp==-1)goto eopbreak;
  118959. partword[l]=look->decodemap[temp];
  118960. if(partword[l]==NULL)goto errout;
  118961. }
  118962. /* now we decode residual values for the partitions */
  118963. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118964. if(info->secondstages[partword[l][k]]&(1<<s)){
  118965. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118966. if(stagebook){
  118967. if(vorbis_book_decodevv_add(stagebook,in,
  118968. i*samples_per_partition+info->begin,ch,
  118969. &vb->opb,samples_per_partition)==-1)
  118970. goto eopbreak;
  118971. }
  118972. }
  118973. }
  118974. }
  118975. errout:
  118976. eopbreak:
  118977. return(0);
  118978. }
  118979. vorbis_func_residue residue0_exportbundle={
  118980. NULL,
  118981. &res0_unpack,
  118982. &res0_look,
  118983. &res0_free_info,
  118984. &res0_free_look,
  118985. NULL,
  118986. NULL,
  118987. &res0_inverse
  118988. };
  118989. vorbis_func_residue residue1_exportbundle={
  118990. &res0_pack,
  118991. &res0_unpack,
  118992. &res0_look,
  118993. &res0_free_info,
  118994. &res0_free_look,
  118995. &res1_class,
  118996. &res1_forward,
  118997. &res1_inverse
  118998. };
  118999. vorbis_func_residue residue2_exportbundle={
  119000. &res0_pack,
  119001. &res0_unpack,
  119002. &res0_look,
  119003. &res0_free_info,
  119004. &res0_free_look,
  119005. &res2_class,
  119006. &res2_forward,
  119007. &res2_inverse
  119008. };
  119009. #endif
  119010. /*** End of inlined file: res0.c ***/
  119011. /*** Start of inlined file: sharedbook.c ***/
  119012. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119013. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119014. // tasks..
  119015. #if JUCE_MSVC
  119016. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119017. #endif
  119018. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119019. #if JUCE_USE_OGGVORBIS
  119020. #include <stdlib.h>
  119021. #include <math.h>
  119022. #include <string.h>
  119023. /**** pack/unpack helpers ******************************************/
  119024. int _ilog(unsigned int v){
  119025. int ret=0;
  119026. while(v){
  119027. ret++;
  119028. v>>=1;
  119029. }
  119030. return(ret);
  119031. }
  119032. /* 32 bit float (not IEEE; nonnormalized mantissa +
  119033. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  119034. Why not IEEE? It's just not that important here. */
  119035. #define VQ_FEXP 10
  119036. #define VQ_FMAN 21
  119037. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  119038. /* doesn't currently guard under/overflow */
  119039. long _float32_pack(float val){
  119040. int sign=0;
  119041. long exp;
  119042. long mant;
  119043. if(val<0){
  119044. sign=0x80000000;
  119045. val= -val;
  119046. }
  119047. exp= floor(log(val)/log(2.f));
  119048. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  119049. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  119050. return(sign|exp|mant);
  119051. }
  119052. float _float32_unpack(long val){
  119053. double mant=val&0x1fffff;
  119054. int sign=val&0x80000000;
  119055. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  119056. if(sign)mant= -mant;
  119057. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  119058. }
  119059. /* given a list of word lengths, generate a list of codewords. Works
  119060. for length ordered or unordered, always assigns the lowest valued
  119061. codewords first. Extended to handle unused entries (length 0) */
  119062. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  119063. long i,j,count=0;
  119064. ogg_uint32_t marker[33];
  119065. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  119066. memset(marker,0,sizeof(marker));
  119067. for(i=0;i<n;i++){
  119068. long length=l[i];
  119069. if(length>0){
  119070. ogg_uint32_t entry=marker[length];
  119071. /* when we claim a node for an entry, we also claim the nodes
  119072. below it (pruning off the imagined tree that may have dangled
  119073. from it) as well as blocking the use of any nodes directly
  119074. above for leaves */
  119075. /* update ourself */
  119076. if(length<32 && (entry>>length)){
  119077. /* error condition; the lengths must specify an overpopulated tree */
  119078. _ogg_free(r);
  119079. return(NULL);
  119080. }
  119081. r[count++]=entry;
  119082. /* Look to see if the next shorter marker points to the node
  119083. above. if so, update it and repeat. */
  119084. {
  119085. for(j=length;j>0;j--){
  119086. if(marker[j]&1){
  119087. /* have to jump branches */
  119088. if(j==1)
  119089. marker[1]++;
  119090. else
  119091. marker[j]=marker[j-1]<<1;
  119092. break; /* invariant says next upper marker would already
  119093. have been moved if it was on the same path */
  119094. }
  119095. marker[j]++;
  119096. }
  119097. }
  119098. /* prune the tree; the implicit invariant says all the longer
  119099. markers were dangling from our just-taken node. Dangle them
  119100. from our *new* node. */
  119101. for(j=length+1;j<33;j++)
  119102. if((marker[j]>>1) == entry){
  119103. entry=marker[j];
  119104. marker[j]=marker[j-1]<<1;
  119105. }else
  119106. break;
  119107. }else
  119108. if(sparsecount==0)count++;
  119109. }
  119110. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119111. endian */
  119112. for(i=0,count=0;i<n;i++){
  119113. ogg_uint32_t temp=0;
  119114. for(j=0;j<l[i];j++){
  119115. temp<<=1;
  119116. temp|=(r[count]>>j)&1;
  119117. }
  119118. if(sparsecount){
  119119. if(l[i])
  119120. r[count++]=temp;
  119121. }else
  119122. r[count++]=temp;
  119123. }
  119124. return(r);
  119125. }
  119126. /* there might be a straightforward one-line way to do the below
  119127. that's portable and totally safe against roundoff, but I haven't
  119128. thought of it. Therefore, we opt on the side of caution */
  119129. long _book_maptype1_quantvals(const static_codebook *b){
  119130. long vals=floor(pow((float)b->entries,1.f/b->dim));
  119131. /* the above *should* be reliable, but we'll not assume that FP is
  119132. ever reliable when bitstream sync is at stake; verify via integer
  119133. means that vals really is the greatest value of dim for which
  119134. vals^b->bim <= b->entries */
  119135. /* treat the above as an initial guess */
  119136. while(1){
  119137. long acc=1;
  119138. long acc1=1;
  119139. int i;
  119140. for(i=0;i<b->dim;i++){
  119141. acc*=vals;
  119142. acc1*=vals+1;
  119143. }
  119144. if(acc<=b->entries && acc1>b->entries){
  119145. return(vals);
  119146. }else{
  119147. if(acc>b->entries){
  119148. vals--;
  119149. }else{
  119150. vals++;
  119151. }
  119152. }
  119153. }
  119154. }
  119155. /* unpack the quantized list of values for encode/decode ***********/
  119156. /* we need to deal with two map types: in map type 1, the values are
  119157. generated algorithmically (each column of the vector counts through
  119158. the values in the quant vector). in map type 2, all the values came
  119159. in in an explicit list. Both value lists must be unpacked */
  119160. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119161. long j,k,count=0;
  119162. if(b->maptype==1 || b->maptype==2){
  119163. int quantvals;
  119164. float mindel=_float32_unpack(b->q_min);
  119165. float delta=_float32_unpack(b->q_delta);
  119166. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119167. /* maptype 1 and 2 both use a quantized value vector, but
  119168. different sizes */
  119169. switch(b->maptype){
  119170. case 1:
  119171. /* most of the time, entries%dimensions == 0, but we need to be
  119172. well defined. We define that the possible vales at each
  119173. scalar is values == entries/dim. If entries%dim != 0, we'll
  119174. have 'too few' values (values*dim<entries), which means that
  119175. we'll have 'left over' entries; left over entries use zeroed
  119176. values (and are wasted). So don't generate codebooks like
  119177. that */
  119178. quantvals=_book_maptype1_quantvals(b);
  119179. for(j=0;j<b->entries;j++){
  119180. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119181. float last=0.f;
  119182. int indexdiv=1;
  119183. for(k=0;k<b->dim;k++){
  119184. int index= (j/indexdiv)%quantvals;
  119185. float val=b->quantlist[index];
  119186. val=fabs(val)*delta+mindel+last;
  119187. if(b->q_sequencep)last=val;
  119188. if(sparsemap)
  119189. r[sparsemap[count]*b->dim+k]=val;
  119190. else
  119191. r[count*b->dim+k]=val;
  119192. indexdiv*=quantvals;
  119193. }
  119194. count++;
  119195. }
  119196. }
  119197. break;
  119198. case 2:
  119199. for(j=0;j<b->entries;j++){
  119200. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119201. float last=0.f;
  119202. for(k=0;k<b->dim;k++){
  119203. float val=b->quantlist[j*b->dim+k];
  119204. val=fabs(val)*delta+mindel+last;
  119205. if(b->q_sequencep)last=val;
  119206. if(sparsemap)
  119207. r[sparsemap[count]*b->dim+k]=val;
  119208. else
  119209. r[count*b->dim+k]=val;
  119210. }
  119211. count++;
  119212. }
  119213. }
  119214. break;
  119215. }
  119216. return(r);
  119217. }
  119218. return(NULL);
  119219. }
  119220. void vorbis_staticbook_clear(static_codebook *b){
  119221. if(b->allocedp){
  119222. if(b->quantlist)_ogg_free(b->quantlist);
  119223. if(b->lengthlist)_ogg_free(b->lengthlist);
  119224. if(b->nearest_tree){
  119225. _ogg_free(b->nearest_tree->ptr0);
  119226. _ogg_free(b->nearest_tree->ptr1);
  119227. _ogg_free(b->nearest_tree->p);
  119228. _ogg_free(b->nearest_tree->q);
  119229. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119230. _ogg_free(b->nearest_tree);
  119231. }
  119232. if(b->thresh_tree){
  119233. _ogg_free(b->thresh_tree->quantthresh);
  119234. _ogg_free(b->thresh_tree->quantmap);
  119235. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119236. _ogg_free(b->thresh_tree);
  119237. }
  119238. memset(b,0,sizeof(*b));
  119239. }
  119240. }
  119241. void vorbis_staticbook_destroy(static_codebook *b){
  119242. if(b->allocedp){
  119243. vorbis_staticbook_clear(b);
  119244. _ogg_free(b);
  119245. }
  119246. }
  119247. void vorbis_book_clear(codebook *b){
  119248. /* static book is not cleared; we're likely called on the lookup and
  119249. the static codebook belongs to the info struct */
  119250. if(b->valuelist)_ogg_free(b->valuelist);
  119251. if(b->codelist)_ogg_free(b->codelist);
  119252. if(b->dec_index)_ogg_free(b->dec_index);
  119253. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119254. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119255. memset(b,0,sizeof(*b));
  119256. }
  119257. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119258. memset(c,0,sizeof(*c));
  119259. c->c=s;
  119260. c->entries=s->entries;
  119261. c->used_entries=s->entries;
  119262. c->dim=s->dim;
  119263. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119264. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119265. return(0);
  119266. }
  119267. static int JUCE_CDECL sort32a(const void *a,const void *b){
  119268. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119269. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119270. }
  119271. /* decode codebook arrangement is more heavily optimized than encode */
  119272. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119273. int i,j,n=0,tabn;
  119274. int *sortindex;
  119275. memset(c,0,sizeof(*c));
  119276. /* count actually used entries */
  119277. for(i=0;i<s->entries;i++)
  119278. if(s->lengthlist[i]>0)
  119279. n++;
  119280. c->entries=s->entries;
  119281. c->used_entries=n;
  119282. c->dim=s->dim;
  119283. /* two different remappings go on here.
  119284. First, we collapse the likely sparse codebook down only to
  119285. actually represented values/words. This collapsing needs to be
  119286. indexed as map-valueless books are used to encode original entry
  119287. positions as integers.
  119288. Second, we reorder all vectors, including the entry index above,
  119289. by sorted bitreversed codeword to allow treeless decode. */
  119290. {
  119291. /* perform sort */
  119292. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119293. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119294. if(codes==NULL)goto err_out;
  119295. for(i=0;i<n;i++){
  119296. codes[i]=ogg_bitreverse(codes[i]);
  119297. codep[i]=codes+i;
  119298. }
  119299. qsort(codep,n,sizeof(*codep),sort32a);
  119300. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119301. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119302. /* the index is a reverse index */
  119303. for(i=0;i<n;i++){
  119304. int position=codep[i]-codes;
  119305. sortindex[position]=i;
  119306. }
  119307. for(i=0;i<n;i++)
  119308. c->codelist[sortindex[i]]=codes[i];
  119309. _ogg_free(codes);
  119310. }
  119311. c->valuelist=_book_unquantize(s,n,sortindex);
  119312. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119313. for(n=0,i=0;i<s->entries;i++)
  119314. if(s->lengthlist[i]>0)
  119315. c->dec_index[sortindex[n++]]=i;
  119316. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119317. for(n=0,i=0;i<s->entries;i++)
  119318. if(s->lengthlist[i]>0)
  119319. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119320. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119321. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119322. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119323. tabn=1<<c->dec_firsttablen;
  119324. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119325. c->dec_maxlength=0;
  119326. for(i=0;i<n;i++){
  119327. if(c->dec_maxlength<c->dec_codelengths[i])
  119328. c->dec_maxlength=c->dec_codelengths[i];
  119329. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119330. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119331. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119332. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119333. }
  119334. }
  119335. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119336. hints for the non-direct-hits */
  119337. {
  119338. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119339. long lo=0,hi=0;
  119340. for(i=0;i<tabn;i++){
  119341. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119342. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119343. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119344. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119345. /* we only actually have 15 bits per hint to play with here.
  119346. In order to overflow gracefully (nothing breaks, efficiency
  119347. just drops), encode as the difference from the extremes. */
  119348. {
  119349. unsigned long loval=lo;
  119350. unsigned long hival=n-hi;
  119351. if(loval>0x7fff)loval=0x7fff;
  119352. if(hival>0x7fff)hival=0x7fff;
  119353. c->dec_firsttable[ogg_bitreverse(word)]=
  119354. 0x80000000UL | (loval<<15) | hival;
  119355. }
  119356. }
  119357. }
  119358. }
  119359. return(0);
  119360. err_out:
  119361. vorbis_book_clear(c);
  119362. return(-1);
  119363. }
  119364. static float _dist(int el,float *ref, float *b,int step){
  119365. int i;
  119366. float acc=0.f;
  119367. for(i=0;i<el;i++){
  119368. float val=(ref[i]-b[i*step]);
  119369. acc+=val*val;
  119370. }
  119371. return(acc);
  119372. }
  119373. int _best(codebook *book, float *a, int step){
  119374. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119375. #if 0
  119376. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119377. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119378. #endif
  119379. int dim=book->dim;
  119380. int k,o;
  119381. /*int savebest=-1;
  119382. float saverr;*/
  119383. /* do we have a threshhold encode hint? */
  119384. if(tt){
  119385. int index=0,i;
  119386. /* find the quant val of each scalar */
  119387. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119388. i=tt->threshvals>>1;
  119389. if(a[o]<tt->quantthresh[i]){
  119390. for(;i>0;i--)
  119391. if(a[o]>=tt->quantthresh[i-1])
  119392. break;
  119393. }else{
  119394. for(i++;i<tt->threshvals-1;i++)
  119395. if(a[o]<tt->quantthresh[i])break;
  119396. }
  119397. index=(index*tt->quantvals)+tt->quantmap[i];
  119398. }
  119399. /* regular lattices are easy :-) */
  119400. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119401. use a decision tree after all
  119402. and fall through*/
  119403. return(index);
  119404. }
  119405. #if 0
  119406. /* do we have a pigeonhole encode hint? */
  119407. if(pt){
  119408. const static_codebook *c=book->c;
  119409. int i,besti=-1;
  119410. float best=0.f;
  119411. int entry=0;
  119412. /* dealing with sequentialness is a pain in the ass */
  119413. if(c->q_sequencep){
  119414. int pv;
  119415. long mul=1;
  119416. float qlast=0;
  119417. for(k=0,o=0;k<dim;k++,o+=step){
  119418. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119419. if(pv<0 || pv>=pt->mapentries)break;
  119420. entry+=pt->pigeonmap[pv]*mul;
  119421. mul*=pt->quantvals;
  119422. qlast+=pv*pt->del+pt->min;
  119423. }
  119424. }else{
  119425. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119426. int pv=(int)((a[o]-pt->min)/pt->del);
  119427. if(pv<0 || pv>=pt->mapentries)break;
  119428. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119429. }
  119430. }
  119431. /* must be within the pigeonholable range; if we quant outside (or
  119432. in an entry that we define no list for), brute force it */
  119433. if(k==dim && pt->fitlength[entry]){
  119434. /* search the abbreviated list */
  119435. long *list=pt->fitlist+pt->fitmap[entry];
  119436. for(i=0;i<pt->fitlength[entry];i++){
  119437. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119438. if(besti==-1 || this<best){
  119439. best=this;
  119440. besti=list[i];
  119441. }
  119442. }
  119443. return(besti);
  119444. }
  119445. }
  119446. if(nt){
  119447. /* optimized using the decision tree */
  119448. while(1){
  119449. float c=0.f;
  119450. float *p=book->valuelist+nt->p[ptr];
  119451. float *q=book->valuelist+nt->q[ptr];
  119452. for(k=0,o=0;k<dim;k++,o+=step)
  119453. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119454. if(c>0.f) /* in A */
  119455. ptr= -nt->ptr0[ptr];
  119456. else /* in B */
  119457. ptr= -nt->ptr1[ptr];
  119458. if(ptr<=0)break;
  119459. }
  119460. return(-ptr);
  119461. }
  119462. #endif
  119463. /* brute force it! */
  119464. {
  119465. const static_codebook *c=book->c;
  119466. int i,besti=-1;
  119467. float best=0.f;
  119468. float *e=book->valuelist;
  119469. for(i=0;i<book->entries;i++){
  119470. if(c->lengthlist[i]>0){
  119471. float thisx=_dist(dim,e,a,step);
  119472. if(besti==-1 || thisx<best){
  119473. best=thisx;
  119474. besti=i;
  119475. }
  119476. }
  119477. e+=dim;
  119478. }
  119479. /*if(savebest!=-1 && savebest!=besti){
  119480. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119481. "original:");
  119482. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119483. fprintf(stderr,"\n"
  119484. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119485. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119486. (book->valuelist+savebest*dim)[i]);
  119487. fprintf(stderr,"\n"
  119488. "bruteforce (entry %d, err %g):",besti,best);
  119489. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119490. (book->valuelist+besti*dim)[i]);
  119491. fprintf(stderr,"\n");
  119492. }*/
  119493. return(besti);
  119494. }
  119495. }
  119496. long vorbis_book_codeword(codebook *book,int entry){
  119497. if(book->c) /* only use with encode; decode optimizations are
  119498. allowed to break this */
  119499. return book->codelist[entry];
  119500. return -1;
  119501. }
  119502. long vorbis_book_codelen(codebook *book,int entry){
  119503. if(book->c) /* only use with encode; decode optimizations are
  119504. allowed to break this */
  119505. return book->c->lengthlist[entry];
  119506. return -1;
  119507. }
  119508. #ifdef _V_SELFTEST
  119509. /* Unit tests of the dequantizer; this stuff will be OK
  119510. cross-platform, I simply want to be sure that special mapping cases
  119511. actually work properly; a bug could go unnoticed for a while */
  119512. #include <stdio.h>
  119513. /* cases:
  119514. no mapping
  119515. full, explicit mapping
  119516. algorithmic mapping
  119517. nonsequential
  119518. sequential
  119519. */
  119520. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119521. static long partial_quantlist1[]={0,7,2};
  119522. /* no mapping */
  119523. static_codebook test1={
  119524. 4,16,
  119525. NULL,
  119526. 0,
  119527. 0,0,0,0,
  119528. NULL,
  119529. NULL,NULL
  119530. };
  119531. static float *test1_result=NULL;
  119532. /* linear, full mapping, nonsequential */
  119533. static_codebook test2={
  119534. 4,3,
  119535. NULL,
  119536. 2,
  119537. -533200896,1611661312,4,0,
  119538. full_quantlist1,
  119539. NULL,NULL
  119540. };
  119541. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119542. /* linear, full mapping, sequential */
  119543. static_codebook test3={
  119544. 4,3,
  119545. NULL,
  119546. 2,
  119547. -533200896,1611661312,4,1,
  119548. full_quantlist1,
  119549. NULL,NULL
  119550. };
  119551. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119552. /* linear, algorithmic mapping, nonsequential */
  119553. static_codebook test4={
  119554. 3,27,
  119555. NULL,
  119556. 1,
  119557. -533200896,1611661312,4,0,
  119558. partial_quantlist1,
  119559. NULL,NULL
  119560. };
  119561. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119562. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119563. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119564. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119565. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119566. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119567. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119568. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119569. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119570. /* linear, algorithmic mapping, sequential */
  119571. static_codebook test5={
  119572. 3,27,
  119573. NULL,
  119574. 1,
  119575. -533200896,1611661312,4,1,
  119576. partial_quantlist1,
  119577. NULL,NULL
  119578. };
  119579. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119580. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119581. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119582. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119583. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119584. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119585. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119586. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119587. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119588. void run_test(static_codebook *b,float *comp){
  119589. float *out=_book_unquantize(b,b->entries,NULL);
  119590. int i;
  119591. if(comp){
  119592. if(!out){
  119593. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119594. exit(1);
  119595. }
  119596. for(i=0;i<b->entries*b->dim;i++)
  119597. if(fabs(out[i]-comp[i])>.0001){
  119598. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119599. "position %d, %g != %g\n",i,out[i],comp[i]);
  119600. exit(1);
  119601. }
  119602. }else{
  119603. if(out){
  119604. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119605. " correct result should have been NULL\n");
  119606. exit(1);
  119607. }
  119608. }
  119609. }
  119610. int main(){
  119611. /* run the nine dequant tests, and compare to the hand-rolled results */
  119612. fprintf(stderr,"Dequant test 1... ");
  119613. run_test(&test1,test1_result);
  119614. fprintf(stderr,"OK\nDequant test 2... ");
  119615. run_test(&test2,test2_result);
  119616. fprintf(stderr,"OK\nDequant test 3... ");
  119617. run_test(&test3,test3_result);
  119618. fprintf(stderr,"OK\nDequant test 4... ");
  119619. run_test(&test4,test4_result);
  119620. fprintf(stderr,"OK\nDequant test 5... ");
  119621. run_test(&test5,test5_result);
  119622. fprintf(stderr,"OK\n\n");
  119623. return(0);
  119624. }
  119625. #endif
  119626. #endif
  119627. /*** End of inlined file: sharedbook.c ***/
  119628. /*** Start of inlined file: smallft.c ***/
  119629. /* FFT implementation from OggSquish, minus cosine transforms,
  119630. * minus all but radix 2/4 case. In Vorbis we only need this
  119631. * cut-down version.
  119632. *
  119633. * To do more than just power-of-two sized vectors, see the full
  119634. * version I wrote for NetLib.
  119635. *
  119636. * Note that the packing is a little strange; rather than the FFT r/i
  119637. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119638. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119639. * FORTRAN version
  119640. */
  119641. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119642. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119643. // tasks..
  119644. #if JUCE_MSVC
  119645. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119646. #endif
  119647. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119648. #if JUCE_USE_OGGVORBIS
  119649. #include <stdlib.h>
  119650. #include <string.h>
  119651. #include <math.h>
  119652. static void drfti1(int n, float *wa, int *ifac){
  119653. static int ntryh[4] = { 4,2,3,5 };
  119654. static float tpi = 6.28318530717958648f;
  119655. float arg,argh,argld,fi;
  119656. int ntry=0,i,j=-1;
  119657. int k1, l1, l2, ib;
  119658. int ld, ii, ip, is, nq, nr;
  119659. int ido, ipm, nfm1;
  119660. int nl=n;
  119661. int nf=0;
  119662. L101:
  119663. j++;
  119664. if (j < 4)
  119665. ntry=ntryh[j];
  119666. else
  119667. ntry+=2;
  119668. L104:
  119669. nq=nl/ntry;
  119670. nr=nl-ntry*nq;
  119671. if (nr!=0) goto L101;
  119672. nf++;
  119673. ifac[nf+1]=ntry;
  119674. nl=nq;
  119675. if(ntry!=2)goto L107;
  119676. if(nf==1)goto L107;
  119677. for (i=1;i<nf;i++){
  119678. ib=nf-i+1;
  119679. ifac[ib+1]=ifac[ib];
  119680. }
  119681. ifac[2] = 2;
  119682. L107:
  119683. if(nl!=1)goto L104;
  119684. ifac[0]=n;
  119685. ifac[1]=nf;
  119686. argh=tpi/n;
  119687. is=0;
  119688. nfm1=nf-1;
  119689. l1=1;
  119690. if(nfm1==0)return;
  119691. for (k1=0;k1<nfm1;k1++){
  119692. ip=ifac[k1+2];
  119693. ld=0;
  119694. l2=l1*ip;
  119695. ido=n/l2;
  119696. ipm=ip-1;
  119697. for (j=0;j<ipm;j++){
  119698. ld+=l1;
  119699. i=is;
  119700. argld=(float)ld*argh;
  119701. fi=0.f;
  119702. for (ii=2;ii<ido;ii+=2){
  119703. fi+=1.f;
  119704. arg=fi*argld;
  119705. wa[i++]=cos(arg);
  119706. wa[i++]=sin(arg);
  119707. }
  119708. is+=ido;
  119709. }
  119710. l1=l2;
  119711. }
  119712. }
  119713. static void fdrffti(int n, float *wsave, int *ifac){
  119714. if (n == 1) return;
  119715. drfti1(n, wsave+n, ifac);
  119716. }
  119717. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119718. int i,k;
  119719. float ti2,tr2;
  119720. int t0,t1,t2,t3,t4,t5,t6;
  119721. t1=0;
  119722. t0=(t2=l1*ido);
  119723. t3=ido<<1;
  119724. for(k=0;k<l1;k++){
  119725. ch[t1<<1]=cc[t1]+cc[t2];
  119726. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119727. t1+=ido;
  119728. t2+=ido;
  119729. }
  119730. if(ido<2)return;
  119731. if(ido==2)goto L105;
  119732. t1=0;
  119733. t2=t0;
  119734. for(k=0;k<l1;k++){
  119735. t3=t2;
  119736. t4=(t1<<1)+(ido<<1);
  119737. t5=t1;
  119738. t6=t1+t1;
  119739. for(i=2;i<ido;i+=2){
  119740. t3+=2;
  119741. t4-=2;
  119742. t5+=2;
  119743. t6+=2;
  119744. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119745. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119746. ch[t6]=cc[t5]+ti2;
  119747. ch[t4]=ti2-cc[t5];
  119748. ch[t6-1]=cc[t5-1]+tr2;
  119749. ch[t4-1]=cc[t5-1]-tr2;
  119750. }
  119751. t1+=ido;
  119752. t2+=ido;
  119753. }
  119754. if(ido%2==1)return;
  119755. L105:
  119756. t3=(t2=(t1=ido)-1);
  119757. t2+=t0;
  119758. for(k=0;k<l1;k++){
  119759. ch[t1]=-cc[t2];
  119760. ch[t1-1]=cc[t3];
  119761. t1+=ido<<1;
  119762. t2+=ido;
  119763. t3+=ido;
  119764. }
  119765. }
  119766. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119767. float *wa2,float *wa3){
  119768. static float hsqt2 = .70710678118654752f;
  119769. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119770. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119771. t0=l1*ido;
  119772. t1=t0;
  119773. t4=t1<<1;
  119774. t2=t1+(t1<<1);
  119775. t3=0;
  119776. for(k=0;k<l1;k++){
  119777. tr1=cc[t1]+cc[t2];
  119778. tr2=cc[t3]+cc[t4];
  119779. ch[t5=t3<<2]=tr1+tr2;
  119780. ch[(ido<<2)+t5-1]=tr2-tr1;
  119781. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119782. ch[t5]=cc[t2]-cc[t1];
  119783. t1+=ido;
  119784. t2+=ido;
  119785. t3+=ido;
  119786. t4+=ido;
  119787. }
  119788. if(ido<2)return;
  119789. if(ido==2)goto L105;
  119790. t1=0;
  119791. for(k=0;k<l1;k++){
  119792. t2=t1;
  119793. t4=t1<<2;
  119794. t5=(t6=ido<<1)+t4;
  119795. for(i=2;i<ido;i+=2){
  119796. t3=(t2+=2);
  119797. t4+=2;
  119798. t5-=2;
  119799. t3+=t0;
  119800. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119801. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119802. t3+=t0;
  119803. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119804. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119805. t3+=t0;
  119806. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119807. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119808. tr1=cr2+cr4;
  119809. tr4=cr4-cr2;
  119810. ti1=ci2+ci4;
  119811. ti4=ci2-ci4;
  119812. ti2=cc[t2]+ci3;
  119813. ti3=cc[t2]-ci3;
  119814. tr2=cc[t2-1]+cr3;
  119815. tr3=cc[t2-1]-cr3;
  119816. ch[t4-1]=tr1+tr2;
  119817. ch[t4]=ti1+ti2;
  119818. ch[t5-1]=tr3-ti4;
  119819. ch[t5]=tr4-ti3;
  119820. ch[t4+t6-1]=ti4+tr3;
  119821. ch[t4+t6]=tr4+ti3;
  119822. ch[t5+t6-1]=tr2-tr1;
  119823. ch[t5+t6]=ti1-ti2;
  119824. }
  119825. t1+=ido;
  119826. }
  119827. if(ido&1)return;
  119828. L105:
  119829. t2=(t1=t0+ido-1)+(t0<<1);
  119830. t3=ido<<2;
  119831. t4=ido;
  119832. t5=ido<<1;
  119833. t6=ido;
  119834. for(k=0;k<l1;k++){
  119835. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119836. tr1=hsqt2*(cc[t1]-cc[t2]);
  119837. ch[t4-1]=tr1+cc[t6-1];
  119838. ch[t4+t5-1]=cc[t6-1]-tr1;
  119839. ch[t4]=ti1-cc[t1+t0];
  119840. ch[t4+t5]=ti1+cc[t1+t0];
  119841. t1+=ido;
  119842. t2+=ido;
  119843. t4+=t3;
  119844. t6+=ido;
  119845. }
  119846. }
  119847. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119848. float *c2,float *ch,float *ch2,float *wa){
  119849. static float tpi=6.283185307179586f;
  119850. int idij,ipph,i,j,k,l,ic,ik,is;
  119851. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119852. float dc2,ai1,ai2,ar1,ar2,ds2;
  119853. int nbd;
  119854. float dcp,arg,dsp,ar1h,ar2h;
  119855. int idp2,ipp2;
  119856. arg=tpi/(float)ip;
  119857. dcp=cos(arg);
  119858. dsp=sin(arg);
  119859. ipph=(ip+1)>>1;
  119860. ipp2=ip;
  119861. idp2=ido;
  119862. nbd=(ido-1)>>1;
  119863. t0=l1*ido;
  119864. t10=ip*ido;
  119865. if(ido==1)goto L119;
  119866. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119867. t1=0;
  119868. for(j=1;j<ip;j++){
  119869. t1+=t0;
  119870. t2=t1;
  119871. for(k=0;k<l1;k++){
  119872. ch[t2]=c1[t2];
  119873. t2+=ido;
  119874. }
  119875. }
  119876. is=-ido;
  119877. t1=0;
  119878. if(nbd>l1){
  119879. for(j=1;j<ip;j++){
  119880. t1+=t0;
  119881. is+=ido;
  119882. t2= -ido+t1;
  119883. for(k=0;k<l1;k++){
  119884. idij=is-1;
  119885. t2+=ido;
  119886. t3=t2;
  119887. for(i=2;i<ido;i+=2){
  119888. idij+=2;
  119889. t3+=2;
  119890. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119891. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119892. }
  119893. }
  119894. }
  119895. }else{
  119896. for(j=1;j<ip;j++){
  119897. is+=ido;
  119898. idij=is-1;
  119899. t1+=t0;
  119900. t2=t1;
  119901. for(i=2;i<ido;i+=2){
  119902. idij+=2;
  119903. t2+=2;
  119904. t3=t2;
  119905. for(k=0;k<l1;k++){
  119906. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119907. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119908. t3+=ido;
  119909. }
  119910. }
  119911. }
  119912. }
  119913. t1=0;
  119914. t2=ipp2*t0;
  119915. if(nbd<l1){
  119916. for(j=1;j<ipph;j++){
  119917. t1+=t0;
  119918. t2-=t0;
  119919. t3=t1;
  119920. t4=t2;
  119921. for(i=2;i<ido;i+=2){
  119922. t3+=2;
  119923. t4+=2;
  119924. t5=t3-ido;
  119925. t6=t4-ido;
  119926. for(k=0;k<l1;k++){
  119927. t5+=ido;
  119928. t6+=ido;
  119929. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119930. c1[t6-1]=ch[t5]-ch[t6];
  119931. c1[t5]=ch[t5]+ch[t6];
  119932. c1[t6]=ch[t6-1]-ch[t5-1];
  119933. }
  119934. }
  119935. }
  119936. }else{
  119937. for(j=1;j<ipph;j++){
  119938. t1+=t0;
  119939. t2-=t0;
  119940. t3=t1;
  119941. t4=t2;
  119942. for(k=0;k<l1;k++){
  119943. t5=t3;
  119944. t6=t4;
  119945. for(i=2;i<ido;i+=2){
  119946. t5+=2;
  119947. t6+=2;
  119948. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119949. c1[t6-1]=ch[t5]-ch[t6];
  119950. c1[t5]=ch[t5]+ch[t6];
  119951. c1[t6]=ch[t6-1]-ch[t5-1];
  119952. }
  119953. t3+=ido;
  119954. t4+=ido;
  119955. }
  119956. }
  119957. }
  119958. L119:
  119959. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119960. t1=0;
  119961. t2=ipp2*idl1;
  119962. for(j=1;j<ipph;j++){
  119963. t1+=t0;
  119964. t2-=t0;
  119965. t3=t1-ido;
  119966. t4=t2-ido;
  119967. for(k=0;k<l1;k++){
  119968. t3+=ido;
  119969. t4+=ido;
  119970. c1[t3]=ch[t3]+ch[t4];
  119971. c1[t4]=ch[t4]-ch[t3];
  119972. }
  119973. }
  119974. ar1=1.f;
  119975. ai1=0.f;
  119976. t1=0;
  119977. t2=ipp2*idl1;
  119978. t3=(ip-1)*idl1;
  119979. for(l=1;l<ipph;l++){
  119980. t1+=idl1;
  119981. t2-=idl1;
  119982. ar1h=dcp*ar1-dsp*ai1;
  119983. ai1=dcp*ai1+dsp*ar1;
  119984. ar1=ar1h;
  119985. t4=t1;
  119986. t5=t2;
  119987. t6=t3;
  119988. t7=idl1;
  119989. for(ik=0;ik<idl1;ik++){
  119990. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119991. ch2[t5++]=ai1*c2[t6++];
  119992. }
  119993. dc2=ar1;
  119994. ds2=ai1;
  119995. ar2=ar1;
  119996. ai2=ai1;
  119997. t4=idl1;
  119998. t5=(ipp2-1)*idl1;
  119999. for(j=2;j<ipph;j++){
  120000. t4+=idl1;
  120001. t5-=idl1;
  120002. ar2h=dc2*ar2-ds2*ai2;
  120003. ai2=dc2*ai2+ds2*ar2;
  120004. ar2=ar2h;
  120005. t6=t1;
  120006. t7=t2;
  120007. t8=t4;
  120008. t9=t5;
  120009. for(ik=0;ik<idl1;ik++){
  120010. ch2[t6++]+=ar2*c2[t8++];
  120011. ch2[t7++]+=ai2*c2[t9++];
  120012. }
  120013. }
  120014. }
  120015. t1=0;
  120016. for(j=1;j<ipph;j++){
  120017. t1+=idl1;
  120018. t2=t1;
  120019. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  120020. }
  120021. if(ido<l1)goto L132;
  120022. t1=0;
  120023. t2=0;
  120024. for(k=0;k<l1;k++){
  120025. t3=t1;
  120026. t4=t2;
  120027. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  120028. t1+=ido;
  120029. t2+=t10;
  120030. }
  120031. goto L135;
  120032. L132:
  120033. for(i=0;i<ido;i++){
  120034. t1=i;
  120035. t2=i;
  120036. for(k=0;k<l1;k++){
  120037. cc[t2]=ch[t1];
  120038. t1+=ido;
  120039. t2+=t10;
  120040. }
  120041. }
  120042. L135:
  120043. t1=0;
  120044. t2=ido<<1;
  120045. t3=0;
  120046. t4=ipp2*t0;
  120047. for(j=1;j<ipph;j++){
  120048. t1+=t2;
  120049. t3+=t0;
  120050. t4-=t0;
  120051. t5=t1;
  120052. t6=t3;
  120053. t7=t4;
  120054. for(k=0;k<l1;k++){
  120055. cc[t5-1]=ch[t6];
  120056. cc[t5]=ch[t7];
  120057. t5+=t10;
  120058. t6+=ido;
  120059. t7+=ido;
  120060. }
  120061. }
  120062. if(ido==1)return;
  120063. if(nbd<l1)goto L141;
  120064. t1=-ido;
  120065. t3=0;
  120066. t4=0;
  120067. t5=ipp2*t0;
  120068. for(j=1;j<ipph;j++){
  120069. t1+=t2;
  120070. t3+=t2;
  120071. t4+=t0;
  120072. t5-=t0;
  120073. t6=t1;
  120074. t7=t3;
  120075. t8=t4;
  120076. t9=t5;
  120077. for(k=0;k<l1;k++){
  120078. for(i=2;i<ido;i+=2){
  120079. ic=idp2-i;
  120080. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  120081. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  120082. cc[i+t7]=ch[i+t8]+ch[i+t9];
  120083. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  120084. }
  120085. t6+=t10;
  120086. t7+=t10;
  120087. t8+=ido;
  120088. t9+=ido;
  120089. }
  120090. }
  120091. return;
  120092. L141:
  120093. t1=-ido;
  120094. t3=0;
  120095. t4=0;
  120096. t5=ipp2*t0;
  120097. for(j=1;j<ipph;j++){
  120098. t1+=t2;
  120099. t3+=t2;
  120100. t4+=t0;
  120101. t5-=t0;
  120102. for(i=2;i<ido;i+=2){
  120103. t6=idp2+t1-i;
  120104. t7=i+t3;
  120105. t8=i+t4;
  120106. t9=i+t5;
  120107. for(k=0;k<l1;k++){
  120108. cc[t7-1]=ch[t8-1]+ch[t9-1];
  120109. cc[t6-1]=ch[t8-1]-ch[t9-1];
  120110. cc[t7]=ch[t8]+ch[t9];
  120111. cc[t6]=ch[t9]-ch[t8];
  120112. t6+=t10;
  120113. t7+=t10;
  120114. t8+=ido;
  120115. t9+=ido;
  120116. }
  120117. }
  120118. }
  120119. }
  120120. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  120121. int i,k1,l1,l2;
  120122. int na,kh,nf;
  120123. int ip,iw,ido,idl1,ix2,ix3;
  120124. nf=ifac[1];
  120125. na=1;
  120126. l2=n;
  120127. iw=n;
  120128. for(k1=0;k1<nf;k1++){
  120129. kh=nf-k1;
  120130. ip=ifac[kh+1];
  120131. l1=l2/ip;
  120132. ido=n/l2;
  120133. idl1=ido*l1;
  120134. iw-=(ip-1)*ido;
  120135. na=1-na;
  120136. if(ip!=4)goto L102;
  120137. ix2=iw+ido;
  120138. ix3=ix2+ido;
  120139. if(na!=0)
  120140. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120141. else
  120142. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120143. goto L110;
  120144. L102:
  120145. if(ip!=2)goto L104;
  120146. if(na!=0)goto L103;
  120147. dradf2(ido,l1,c,ch,wa+iw-1);
  120148. goto L110;
  120149. L103:
  120150. dradf2(ido,l1,ch,c,wa+iw-1);
  120151. goto L110;
  120152. L104:
  120153. if(ido==1)na=1-na;
  120154. if(na!=0)goto L109;
  120155. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120156. na=1;
  120157. goto L110;
  120158. L109:
  120159. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120160. na=0;
  120161. L110:
  120162. l2=l1;
  120163. }
  120164. if(na==1)return;
  120165. for(i=0;i<n;i++)c[i]=ch[i];
  120166. }
  120167. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120168. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120169. float ti2,tr2;
  120170. t0=l1*ido;
  120171. t1=0;
  120172. t2=0;
  120173. t3=(ido<<1)-1;
  120174. for(k=0;k<l1;k++){
  120175. ch[t1]=cc[t2]+cc[t3+t2];
  120176. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120177. t2=(t1+=ido)<<1;
  120178. }
  120179. if(ido<2)return;
  120180. if(ido==2)goto L105;
  120181. t1=0;
  120182. t2=0;
  120183. for(k=0;k<l1;k++){
  120184. t3=t1;
  120185. t5=(t4=t2)+(ido<<1);
  120186. t6=t0+t1;
  120187. for(i=2;i<ido;i+=2){
  120188. t3+=2;
  120189. t4+=2;
  120190. t5-=2;
  120191. t6+=2;
  120192. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120193. tr2=cc[t4-1]-cc[t5-1];
  120194. ch[t3]=cc[t4]-cc[t5];
  120195. ti2=cc[t4]+cc[t5];
  120196. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120197. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120198. }
  120199. t2=(t1+=ido)<<1;
  120200. }
  120201. if(ido%2==1)return;
  120202. L105:
  120203. t1=ido-1;
  120204. t2=ido-1;
  120205. for(k=0;k<l1;k++){
  120206. ch[t1]=cc[t2]+cc[t2];
  120207. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120208. t1+=ido;
  120209. t2+=ido<<1;
  120210. }
  120211. }
  120212. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120213. float *wa2){
  120214. static float taur = -.5f;
  120215. static float taui = .8660254037844386f;
  120216. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120217. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120218. t0=l1*ido;
  120219. t1=0;
  120220. t2=t0<<1;
  120221. t3=ido<<1;
  120222. t4=ido+(ido<<1);
  120223. t5=0;
  120224. for(k=0;k<l1;k++){
  120225. tr2=cc[t3-1]+cc[t3-1];
  120226. cr2=cc[t5]+(taur*tr2);
  120227. ch[t1]=cc[t5]+tr2;
  120228. ci3=taui*(cc[t3]+cc[t3]);
  120229. ch[t1+t0]=cr2-ci3;
  120230. ch[t1+t2]=cr2+ci3;
  120231. t1+=ido;
  120232. t3+=t4;
  120233. t5+=t4;
  120234. }
  120235. if(ido==1)return;
  120236. t1=0;
  120237. t3=ido<<1;
  120238. for(k=0;k<l1;k++){
  120239. t7=t1+(t1<<1);
  120240. t6=(t5=t7+t3);
  120241. t8=t1;
  120242. t10=(t9=t1+t0)+t0;
  120243. for(i=2;i<ido;i+=2){
  120244. t5+=2;
  120245. t6-=2;
  120246. t7+=2;
  120247. t8+=2;
  120248. t9+=2;
  120249. t10+=2;
  120250. tr2=cc[t5-1]+cc[t6-1];
  120251. cr2=cc[t7-1]+(taur*tr2);
  120252. ch[t8-1]=cc[t7-1]+tr2;
  120253. ti2=cc[t5]-cc[t6];
  120254. ci2=cc[t7]+(taur*ti2);
  120255. ch[t8]=cc[t7]+ti2;
  120256. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120257. ci3=taui*(cc[t5]+cc[t6]);
  120258. dr2=cr2-ci3;
  120259. dr3=cr2+ci3;
  120260. di2=ci2+cr3;
  120261. di3=ci2-cr3;
  120262. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120263. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120264. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120265. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120266. }
  120267. t1+=ido;
  120268. }
  120269. }
  120270. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120271. float *wa2,float *wa3){
  120272. static float sqrt2=1.414213562373095f;
  120273. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120274. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120275. t0=l1*ido;
  120276. t1=0;
  120277. t2=ido<<2;
  120278. t3=0;
  120279. t6=ido<<1;
  120280. for(k=0;k<l1;k++){
  120281. t4=t3+t6;
  120282. t5=t1;
  120283. tr3=cc[t4-1]+cc[t4-1];
  120284. tr4=cc[t4]+cc[t4];
  120285. tr1=cc[t3]-cc[(t4+=t6)-1];
  120286. tr2=cc[t3]+cc[t4-1];
  120287. ch[t5]=tr2+tr3;
  120288. ch[t5+=t0]=tr1-tr4;
  120289. ch[t5+=t0]=tr2-tr3;
  120290. ch[t5+=t0]=tr1+tr4;
  120291. t1+=ido;
  120292. t3+=t2;
  120293. }
  120294. if(ido<2)return;
  120295. if(ido==2)goto L105;
  120296. t1=0;
  120297. for(k=0;k<l1;k++){
  120298. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120299. t7=t1;
  120300. for(i=2;i<ido;i+=2){
  120301. t2+=2;
  120302. t3+=2;
  120303. t4-=2;
  120304. t5-=2;
  120305. t7+=2;
  120306. ti1=cc[t2]+cc[t5];
  120307. ti2=cc[t2]-cc[t5];
  120308. ti3=cc[t3]-cc[t4];
  120309. tr4=cc[t3]+cc[t4];
  120310. tr1=cc[t2-1]-cc[t5-1];
  120311. tr2=cc[t2-1]+cc[t5-1];
  120312. ti4=cc[t3-1]-cc[t4-1];
  120313. tr3=cc[t3-1]+cc[t4-1];
  120314. ch[t7-1]=tr2+tr3;
  120315. cr3=tr2-tr3;
  120316. ch[t7]=ti2+ti3;
  120317. ci3=ti2-ti3;
  120318. cr2=tr1-tr4;
  120319. cr4=tr1+tr4;
  120320. ci2=ti1+ti4;
  120321. ci4=ti1-ti4;
  120322. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120323. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120324. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120325. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120326. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120327. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120328. }
  120329. t1+=ido;
  120330. }
  120331. if(ido%2 == 1)return;
  120332. L105:
  120333. t1=ido;
  120334. t2=ido<<2;
  120335. t3=ido-1;
  120336. t4=ido+(ido<<1);
  120337. for(k=0;k<l1;k++){
  120338. t5=t3;
  120339. ti1=cc[t1]+cc[t4];
  120340. ti2=cc[t4]-cc[t1];
  120341. tr1=cc[t1-1]-cc[t4-1];
  120342. tr2=cc[t1-1]+cc[t4-1];
  120343. ch[t5]=tr2+tr2;
  120344. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120345. ch[t5+=t0]=ti2+ti2;
  120346. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120347. t3+=ido;
  120348. t1+=t2;
  120349. t4+=t2;
  120350. }
  120351. }
  120352. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120353. float *c2,float *ch,float *ch2,float *wa){
  120354. static float tpi=6.283185307179586f;
  120355. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120356. t11,t12;
  120357. float dc2,ai1,ai2,ar1,ar2,ds2;
  120358. int nbd;
  120359. float dcp,arg,dsp,ar1h,ar2h;
  120360. int ipp2;
  120361. t10=ip*ido;
  120362. t0=l1*ido;
  120363. arg=tpi/(float)ip;
  120364. dcp=cos(arg);
  120365. dsp=sin(arg);
  120366. nbd=(ido-1)>>1;
  120367. ipp2=ip;
  120368. ipph=(ip+1)>>1;
  120369. if(ido<l1)goto L103;
  120370. t1=0;
  120371. t2=0;
  120372. for(k=0;k<l1;k++){
  120373. t3=t1;
  120374. t4=t2;
  120375. for(i=0;i<ido;i++){
  120376. ch[t3]=cc[t4];
  120377. t3++;
  120378. t4++;
  120379. }
  120380. t1+=ido;
  120381. t2+=t10;
  120382. }
  120383. goto L106;
  120384. L103:
  120385. t1=0;
  120386. for(i=0;i<ido;i++){
  120387. t2=t1;
  120388. t3=t1;
  120389. for(k=0;k<l1;k++){
  120390. ch[t2]=cc[t3];
  120391. t2+=ido;
  120392. t3+=t10;
  120393. }
  120394. t1++;
  120395. }
  120396. L106:
  120397. t1=0;
  120398. t2=ipp2*t0;
  120399. t7=(t5=ido<<1);
  120400. for(j=1;j<ipph;j++){
  120401. t1+=t0;
  120402. t2-=t0;
  120403. t3=t1;
  120404. t4=t2;
  120405. t6=t5;
  120406. for(k=0;k<l1;k++){
  120407. ch[t3]=cc[t6-1]+cc[t6-1];
  120408. ch[t4]=cc[t6]+cc[t6];
  120409. t3+=ido;
  120410. t4+=ido;
  120411. t6+=t10;
  120412. }
  120413. t5+=t7;
  120414. }
  120415. if (ido == 1)goto L116;
  120416. if(nbd<l1)goto L112;
  120417. t1=0;
  120418. t2=ipp2*t0;
  120419. t7=0;
  120420. for(j=1;j<ipph;j++){
  120421. t1+=t0;
  120422. t2-=t0;
  120423. t3=t1;
  120424. t4=t2;
  120425. t7+=(ido<<1);
  120426. t8=t7;
  120427. for(k=0;k<l1;k++){
  120428. t5=t3;
  120429. t6=t4;
  120430. t9=t8;
  120431. t11=t8;
  120432. for(i=2;i<ido;i+=2){
  120433. t5+=2;
  120434. t6+=2;
  120435. t9+=2;
  120436. t11-=2;
  120437. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120438. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120439. ch[t5]=cc[t9]-cc[t11];
  120440. ch[t6]=cc[t9]+cc[t11];
  120441. }
  120442. t3+=ido;
  120443. t4+=ido;
  120444. t8+=t10;
  120445. }
  120446. }
  120447. goto L116;
  120448. L112:
  120449. t1=0;
  120450. t2=ipp2*t0;
  120451. t7=0;
  120452. for(j=1;j<ipph;j++){
  120453. t1+=t0;
  120454. t2-=t0;
  120455. t3=t1;
  120456. t4=t2;
  120457. t7+=(ido<<1);
  120458. t8=t7;
  120459. t9=t7;
  120460. for(i=2;i<ido;i+=2){
  120461. t3+=2;
  120462. t4+=2;
  120463. t8+=2;
  120464. t9-=2;
  120465. t5=t3;
  120466. t6=t4;
  120467. t11=t8;
  120468. t12=t9;
  120469. for(k=0;k<l1;k++){
  120470. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120471. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120472. ch[t5]=cc[t11]-cc[t12];
  120473. ch[t6]=cc[t11]+cc[t12];
  120474. t5+=ido;
  120475. t6+=ido;
  120476. t11+=t10;
  120477. t12+=t10;
  120478. }
  120479. }
  120480. }
  120481. L116:
  120482. ar1=1.f;
  120483. ai1=0.f;
  120484. t1=0;
  120485. t9=(t2=ipp2*idl1);
  120486. t3=(ip-1)*idl1;
  120487. for(l=1;l<ipph;l++){
  120488. t1+=idl1;
  120489. t2-=idl1;
  120490. ar1h=dcp*ar1-dsp*ai1;
  120491. ai1=dcp*ai1+dsp*ar1;
  120492. ar1=ar1h;
  120493. t4=t1;
  120494. t5=t2;
  120495. t6=0;
  120496. t7=idl1;
  120497. t8=t3;
  120498. for(ik=0;ik<idl1;ik++){
  120499. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120500. c2[t5++]=ai1*ch2[t8++];
  120501. }
  120502. dc2=ar1;
  120503. ds2=ai1;
  120504. ar2=ar1;
  120505. ai2=ai1;
  120506. t6=idl1;
  120507. t7=t9-idl1;
  120508. for(j=2;j<ipph;j++){
  120509. t6+=idl1;
  120510. t7-=idl1;
  120511. ar2h=dc2*ar2-ds2*ai2;
  120512. ai2=dc2*ai2+ds2*ar2;
  120513. ar2=ar2h;
  120514. t4=t1;
  120515. t5=t2;
  120516. t11=t6;
  120517. t12=t7;
  120518. for(ik=0;ik<idl1;ik++){
  120519. c2[t4++]+=ar2*ch2[t11++];
  120520. c2[t5++]+=ai2*ch2[t12++];
  120521. }
  120522. }
  120523. }
  120524. t1=0;
  120525. for(j=1;j<ipph;j++){
  120526. t1+=idl1;
  120527. t2=t1;
  120528. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120529. }
  120530. t1=0;
  120531. t2=ipp2*t0;
  120532. for(j=1;j<ipph;j++){
  120533. t1+=t0;
  120534. t2-=t0;
  120535. t3=t1;
  120536. t4=t2;
  120537. for(k=0;k<l1;k++){
  120538. ch[t3]=c1[t3]-c1[t4];
  120539. ch[t4]=c1[t3]+c1[t4];
  120540. t3+=ido;
  120541. t4+=ido;
  120542. }
  120543. }
  120544. if(ido==1)goto L132;
  120545. if(nbd<l1)goto L128;
  120546. t1=0;
  120547. t2=ipp2*t0;
  120548. for(j=1;j<ipph;j++){
  120549. t1+=t0;
  120550. t2-=t0;
  120551. t3=t1;
  120552. t4=t2;
  120553. for(k=0;k<l1;k++){
  120554. t5=t3;
  120555. t6=t4;
  120556. for(i=2;i<ido;i+=2){
  120557. t5+=2;
  120558. t6+=2;
  120559. ch[t5-1]=c1[t5-1]-c1[t6];
  120560. ch[t6-1]=c1[t5-1]+c1[t6];
  120561. ch[t5]=c1[t5]+c1[t6-1];
  120562. ch[t6]=c1[t5]-c1[t6-1];
  120563. }
  120564. t3+=ido;
  120565. t4+=ido;
  120566. }
  120567. }
  120568. goto L132;
  120569. L128:
  120570. t1=0;
  120571. t2=ipp2*t0;
  120572. for(j=1;j<ipph;j++){
  120573. t1+=t0;
  120574. t2-=t0;
  120575. t3=t1;
  120576. t4=t2;
  120577. for(i=2;i<ido;i+=2){
  120578. t3+=2;
  120579. t4+=2;
  120580. t5=t3;
  120581. t6=t4;
  120582. for(k=0;k<l1;k++){
  120583. ch[t5-1]=c1[t5-1]-c1[t6];
  120584. ch[t6-1]=c1[t5-1]+c1[t6];
  120585. ch[t5]=c1[t5]+c1[t6-1];
  120586. ch[t6]=c1[t5]-c1[t6-1];
  120587. t5+=ido;
  120588. t6+=ido;
  120589. }
  120590. }
  120591. }
  120592. L132:
  120593. if(ido==1)return;
  120594. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120595. t1=0;
  120596. for(j=1;j<ip;j++){
  120597. t2=(t1+=t0);
  120598. for(k=0;k<l1;k++){
  120599. c1[t2]=ch[t2];
  120600. t2+=ido;
  120601. }
  120602. }
  120603. if(nbd>l1)goto L139;
  120604. is= -ido-1;
  120605. t1=0;
  120606. for(j=1;j<ip;j++){
  120607. is+=ido;
  120608. t1+=t0;
  120609. idij=is;
  120610. t2=t1;
  120611. for(i=2;i<ido;i+=2){
  120612. t2+=2;
  120613. idij+=2;
  120614. t3=t2;
  120615. for(k=0;k<l1;k++){
  120616. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120617. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120618. t3+=ido;
  120619. }
  120620. }
  120621. }
  120622. return;
  120623. L139:
  120624. is= -ido-1;
  120625. t1=0;
  120626. for(j=1;j<ip;j++){
  120627. is+=ido;
  120628. t1+=t0;
  120629. t2=t1;
  120630. for(k=0;k<l1;k++){
  120631. idij=is;
  120632. t3=t2;
  120633. for(i=2;i<ido;i+=2){
  120634. idij+=2;
  120635. t3+=2;
  120636. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120637. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120638. }
  120639. t2+=ido;
  120640. }
  120641. }
  120642. }
  120643. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120644. int i,k1,l1,l2;
  120645. int na;
  120646. int nf,ip,iw,ix2,ix3,ido,idl1;
  120647. nf=ifac[1];
  120648. na=0;
  120649. l1=1;
  120650. iw=1;
  120651. for(k1=0;k1<nf;k1++){
  120652. ip=ifac[k1 + 2];
  120653. l2=ip*l1;
  120654. ido=n/l2;
  120655. idl1=ido*l1;
  120656. if(ip!=4)goto L103;
  120657. ix2=iw+ido;
  120658. ix3=ix2+ido;
  120659. if(na!=0)
  120660. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120661. else
  120662. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120663. na=1-na;
  120664. goto L115;
  120665. L103:
  120666. if(ip!=2)goto L106;
  120667. if(na!=0)
  120668. dradb2(ido,l1,ch,c,wa+iw-1);
  120669. else
  120670. dradb2(ido,l1,c,ch,wa+iw-1);
  120671. na=1-na;
  120672. goto L115;
  120673. L106:
  120674. if(ip!=3)goto L109;
  120675. ix2=iw+ido;
  120676. if(na!=0)
  120677. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120678. else
  120679. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120680. na=1-na;
  120681. goto L115;
  120682. L109:
  120683. /* The radix five case can be translated later..... */
  120684. /* if(ip!=5)goto L112;
  120685. ix2=iw+ido;
  120686. ix3=ix2+ido;
  120687. ix4=ix3+ido;
  120688. if(na!=0)
  120689. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120690. else
  120691. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120692. na=1-na;
  120693. goto L115;
  120694. L112:*/
  120695. if(na!=0)
  120696. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120697. else
  120698. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120699. if(ido==1)na=1-na;
  120700. L115:
  120701. l1=l2;
  120702. iw+=(ip-1)*ido;
  120703. }
  120704. if(na==0)return;
  120705. for(i=0;i<n;i++)c[i]=ch[i];
  120706. }
  120707. void drft_forward(drft_lookup *l,float *data){
  120708. if(l->n==1)return;
  120709. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120710. }
  120711. void drft_backward(drft_lookup *l,float *data){
  120712. if (l->n==1)return;
  120713. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120714. }
  120715. void drft_init(drft_lookup *l,int n){
  120716. l->n=n;
  120717. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120718. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120719. fdrffti(n, l->trigcache, l->splitcache);
  120720. }
  120721. void drft_clear(drft_lookup *l){
  120722. if(l){
  120723. if(l->trigcache)_ogg_free(l->trigcache);
  120724. if(l->splitcache)_ogg_free(l->splitcache);
  120725. memset(l,0,sizeof(*l));
  120726. }
  120727. }
  120728. #endif
  120729. /*** End of inlined file: smallft.c ***/
  120730. /*** Start of inlined file: synthesis.c ***/
  120731. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120732. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120733. // tasks..
  120734. #if JUCE_MSVC
  120735. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120736. #endif
  120737. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120738. #if JUCE_USE_OGGVORBIS
  120739. #include <stdio.h>
  120740. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120741. vorbis_dsp_state *vd=vb->vd;
  120742. private_state *b=(private_state*)vd->backend_state;
  120743. vorbis_info *vi=vd->vi;
  120744. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120745. oggpack_buffer *opb=&vb->opb;
  120746. int type,mode,i;
  120747. /* first things first. Make sure decode is ready */
  120748. _vorbis_block_ripcord(vb);
  120749. oggpack_readinit(opb,op->packet,op->bytes);
  120750. /* Check the packet type */
  120751. if(oggpack_read(opb,1)!=0){
  120752. /* Oops. This is not an audio data packet */
  120753. return(OV_ENOTAUDIO);
  120754. }
  120755. /* read our mode and pre/post windowsize */
  120756. mode=oggpack_read(opb,b->modebits);
  120757. if(mode==-1)return(OV_EBADPACKET);
  120758. vb->mode=mode;
  120759. vb->W=ci->mode_param[mode]->blockflag;
  120760. if(vb->W){
  120761. /* this doesn;t get mapped through mode selection as it's used
  120762. only for window selection */
  120763. vb->lW=oggpack_read(opb,1);
  120764. vb->nW=oggpack_read(opb,1);
  120765. if(vb->nW==-1) return(OV_EBADPACKET);
  120766. }else{
  120767. vb->lW=0;
  120768. vb->nW=0;
  120769. }
  120770. /* more setup */
  120771. vb->granulepos=op->granulepos;
  120772. vb->sequence=op->packetno;
  120773. vb->eofflag=op->e_o_s;
  120774. /* alloc pcm passback storage */
  120775. vb->pcmend=ci->blocksizes[vb->W];
  120776. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120777. for(i=0;i<vi->channels;i++)
  120778. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120779. /* unpack_header enforces range checking */
  120780. type=ci->map_type[ci->mode_param[mode]->mapping];
  120781. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120782. mapping]));
  120783. }
  120784. /* used to track pcm position without actually performing decode.
  120785. Useful for sequential 'fast forward' */
  120786. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120787. vorbis_dsp_state *vd=vb->vd;
  120788. private_state *b=(private_state*)vd->backend_state;
  120789. vorbis_info *vi=vd->vi;
  120790. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120791. oggpack_buffer *opb=&vb->opb;
  120792. int mode;
  120793. /* first things first. Make sure decode is ready */
  120794. _vorbis_block_ripcord(vb);
  120795. oggpack_readinit(opb,op->packet,op->bytes);
  120796. /* Check the packet type */
  120797. if(oggpack_read(opb,1)!=0){
  120798. /* Oops. This is not an audio data packet */
  120799. return(OV_ENOTAUDIO);
  120800. }
  120801. /* read our mode and pre/post windowsize */
  120802. mode=oggpack_read(opb,b->modebits);
  120803. if(mode==-1)return(OV_EBADPACKET);
  120804. vb->mode=mode;
  120805. vb->W=ci->mode_param[mode]->blockflag;
  120806. if(vb->W){
  120807. vb->lW=oggpack_read(opb,1);
  120808. vb->nW=oggpack_read(opb,1);
  120809. if(vb->nW==-1) return(OV_EBADPACKET);
  120810. }else{
  120811. vb->lW=0;
  120812. vb->nW=0;
  120813. }
  120814. /* more setup */
  120815. vb->granulepos=op->granulepos;
  120816. vb->sequence=op->packetno;
  120817. vb->eofflag=op->e_o_s;
  120818. /* no pcm */
  120819. vb->pcmend=0;
  120820. vb->pcm=NULL;
  120821. return(0);
  120822. }
  120823. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120824. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120825. oggpack_buffer opb;
  120826. int mode;
  120827. oggpack_readinit(&opb,op->packet,op->bytes);
  120828. /* Check the packet type */
  120829. if(oggpack_read(&opb,1)!=0){
  120830. /* Oops. This is not an audio data packet */
  120831. return(OV_ENOTAUDIO);
  120832. }
  120833. {
  120834. int modebits=0;
  120835. int v=ci->modes;
  120836. while(v>1){
  120837. modebits++;
  120838. v>>=1;
  120839. }
  120840. /* read our mode and pre/post windowsize */
  120841. mode=oggpack_read(&opb,modebits);
  120842. }
  120843. if(mode==-1)return(OV_EBADPACKET);
  120844. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120845. }
  120846. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120847. /* set / clear half-sample-rate mode */
  120848. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120849. /* right now, our MDCT can't handle < 64 sample windows. */
  120850. if(ci->blocksizes[0]<=64 && flag)return -1;
  120851. ci->halfrate_flag=(flag?1:0);
  120852. return 0;
  120853. }
  120854. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120855. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120856. return ci->halfrate_flag;
  120857. }
  120858. #endif
  120859. /*** End of inlined file: synthesis.c ***/
  120860. /*** Start of inlined file: vorbisenc.c ***/
  120861. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120862. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120863. // tasks..
  120864. #if JUCE_MSVC
  120865. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120866. #endif
  120867. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120868. #if JUCE_USE_OGGVORBIS
  120869. #include <stdlib.h>
  120870. #include <string.h>
  120871. #include <math.h>
  120872. /* careful with this; it's using static array sizing to make managing
  120873. all the modes a little less annoying. If we use a residue backend
  120874. with > 12 partition types, or a different division of iteration,
  120875. this needs to be updated. */
  120876. typedef struct {
  120877. static_codebook *books[12][3];
  120878. } static_bookblock;
  120879. typedef struct {
  120880. int res_type;
  120881. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120882. vorbis_info_residue0 *res;
  120883. static_codebook *book_aux;
  120884. static_codebook *book_aux_managed;
  120885. static_bookblock *books_base;
  120886. static_bookblock *books_base_managed;
  120887. } vorbis_residue_template;
  120888. typedef struct {
  120889. vorbis_info_mapping0 *map;
  120890. vorbis_residue_template *res;
  120891. } vorbis_mapping_template;
  120892. typedef struct vp_adjblock{
  120893. int block[P_BANDS];
  120894. } vp_adjblock;
  120895. typedef struct {
  120896. int data[NOISE_COMPAND_LEVELS];
  120897. } compandblock;
  120898. /* high level configuration information for setting things up
  120899. step-by-step with the detailed vorbis_encode_ctl interface.
  120900. There's a fair amount of redundancy such that interactive setup
  120901. does not directly deal with any vorbis_info or codec_setup_info
  120902. initialization; it's all stored (until full init) in this highlevel
  120903. setup, then flushed out to the real codec setup structs later. */
  120904. typedef struct {
  120905. int att[P_NOISECURVES];
  120906. float boost;
  120907. float decay;
  120908. } att3;
  120909. typedef struct { int data[P_NOISECURVES]; } adj3;
  120910. typedef struct {
  120911. int pre[PACKETBLOBS];
  120912. int post[PACKETBLOBS];
  120913. float kHz[PACKETBLOBS];
  120914. float lowpasskHz[PACKETBLOBS];
  120915. } adj_stereo;
  120916. typedef struct {
  120917. int lo;
  120918. int hi;
  120919. int fixed;
  120920. } noiseguard;
  120921. typedef struct {
  120922. int data[P_NOISECURVES][17];
  120923. } noise3;
  120924. typedef struct {
  120925. int mappings;
  120926. double *rate_mapping;
  120927. double *quality_mapping;
  120928. int coupling_restriction;
  120929. long samplerate_min_restriction;
  120930. long samplerate_max_restriction;
  120931. int *blocksize_short;
  120932. int *blocksize_long;
  120933. att3 *psy_tone_masteratt;
  120934. int *psy_tone_0dB;
  120935. int *psy_tone_dBsuppress;
  120936. vp_adjblock *psy_tone_adj_impulse;
  120937. vp_adjblock *psy_tone_adj_long;
  120938. vp_adjblock *psy_tone_adj_other;
  120939. noiseguard *psy_noiseguards;
  120940. noise3 *psy_noise_bias_impulse;
  120941. noise3 *psy_noise_bias_padding;
  120942. noise3 *psy_noise_bias_trans;
  120943. noise3 *psy_noise_bias_long;
  120944. int *psy_noise_dBsuppress;
  120945. compandblock *psy_noise_compand;
  120946. double *psy_noise_compand_short_mapping;
  120947. double *psy_noise_compand_long_mapping;
  120948. int *psy_noise_normal_start[2];
  120949. int *psy_noise_normal_partition[2];
  120950. double *psy_noise_normal_thresh;
  120951. int *psy_ath_float;
  120952. int *psy_ath_abs;
  120953. double *psy_lowpass;
  120954. vorbis_info_psy_global *global_params;
  120955. double *global_mapping;
  120956. adj_stereo *stereo_modes;
  120957. static_codebook ***floor_books;
  120958. vorbis_info_floor1 *floor_params;
  120959. int *floor_short_mapping;
  120960. int *floor_long_mapping;
  120961. vorbis_mapping_template *maps;
  120962. } ve_setup_data_template;
  120963. /* a few static coder conventions */
  120964. static vorbis_info_mode _mode_template[2]={
  120965. {0,0,0,0},
  120966. {1,0,0,1}
  120967. };
  120968. static vorbis_info_mapping0 _map_nominal[2]={
  120969. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120970. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120971. };
  120972. /*** Start of inlined file: setup_44.h ***/
  120973. /*** Start of inlined file: floor_all.h ***/
  120974. /*** Start of inlined file: floor_books.h ***/
  120975. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120976. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120977. };
  120978. static static_codebook _huff_book_line_256x7_0sub1 = {
  120979. 1, 9,
  120980. _huff_lengthlist_line_256x7_0sub1,
  120981. 0, 0, 0, 0, 0,
  120982. NULL,
  120983. NULL,
  120984. NULL,
  120985. NULL,
  120986. 0
  120987. };
  120988. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120990. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120991. };
  120992. static static_codebook _huff_book_line_256x7_0sub2 = {
  120993. 1, 25,
  120994. _huff_lengthlist_line_256x7_0sub2,
  120995. 0, 0, 0, 0, 0,
  120996. NULL,
  120997. NULL,
  120998. NULL,
  120999. NULL,
  121000. 0
  121001. };
  121002. static long _huff_lengthlist_line_256x7_0sub3[] = {
  121003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  121005. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  121006. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  121007. };
  121008. static static_codebook _huff_book_line_256x7_0sub3 = {
  121009. 1, 64,
  121010. _huff_lengthlist_line_256x7_0sub3,
  121011. 0, 0, 0, 0, 0,
  121012. NULL,
  121013. NULL,
  121014. NULL,
  121015. NULL,
  121016. 0
  121017. };
  121018. static long _huff_lengthlist_line_256x7_1sub1[] = {
  121019. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  121020. };
  121021. static static_codebook _huff_book_line_256x7_1sub1 = {
  121022. 1, 9,
  121023. _huff_lengthlist_line_256x7_1sub1,
  121024. 0, 0, 0, 0, 0,
  121025. NULL,
  121026. NULL,
  121027. NULL,
  121028. NULL,
  121029. 0
  121030. };
  121031. static long _huff_lengthlist_line_256x7_1sub2[] = {
  121032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  121033. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  121034. };
  121035. static static_codebook _huff_book_line_256x7_1sub2 = {
  121036. 1, 25,
  121037. _huff_lengthlist_line_256x7_1sub2,
  121038. 0, 0, 0, 0, 0,
  121039. NULL,
  121040. NULL,
  121041. NULL,
  121042. NULL,
  121043. 0
  121044. };
  121045. static long _huff_lengthlist_line_256x7_1sub3[] = {
  121046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  121048. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121049. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  121050. };
  121051. static static_codebook _huff_book_line_256x7_1sub3 = {
  121052. 1, 64,
  121053. _huff_lengthlist_line_256x7_1sub3,
  121054. 0, 0, 0, 0, 0,
  121055. NULL,
  121056. NULL,
  121057. NULL,
  121058. NULL,
  121059. 0
  121060. };
  121061. static long _huff_lengthlist_line_256x7_class0[] = {
  121062. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  121063. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  121064. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  121065. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  121066. };
  121067. static static_codebook _huff_book_line_256x7_class0 = {
  121068. 1, 64,
  121069. _huff_lengthlist_line_256x7_class0,
  121070. 0, 0, 0, 0, 0,
  121071. NULL,
  121072. NULL,
  121073. NULL,
  121074. NULL,
  121075. 0
  121076. };
  121077. static long _huff_lengthlist_line_256x7_class1[] = {
  121078. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  121079. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  121080. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  121081. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  121082. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  121083. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  121084. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  121085. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  121086. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  121087. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  121088. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  121089. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  121090. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121091. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121092. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  121093. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  121094. };
  121095. static static_codebook _huff_book_line_256x7_class1 = {
  121096. 1, 256,
  121097. _huff_lengthlist_line_256x7_class1,
  121098. 0, 0, 0, 0, 0,
  121099. NULL,
  121100. NULL,
  121101. NULL,
  121102. NULL,
  121103. 0
  121104. };
  121105. static long _huff_lengthlist_line_512x17_0sub0[] = {
  121106. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  121107. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  121108. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  121109. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  121110. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  121111. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  121112. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  121113. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121114. };
  121115. static static_codebook _huff_book_line_512x17_0sub0 = {
  121116. 1, 128,
  121117. _huff_lengthlist_line_512x17_0sub0,
  121118. 0, 0, 0, 0, 0,
  121119. NULL,
  121120. NULL,
  121121. NULL,
  121122. NULL,
  121123. 0
  121124. };
  121125. static long _huff_lengthlist_line_512x17_1sub0[] = {
  121126. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121127. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  121128. };
  121129. static static_codebook _huff_book_line_512x17_1sub0 = {
  121130. 1, 32,
  121131. _huff_lengthlist_line_512x17_1sub0,
  121132. 0, 0, 0, 0, 0,
  121133. NULL,
  121134. NULL,
  121135. NULL,
  121136. NULL,
  121137. 0
  121138. };
  121139. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121142. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121143. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121144. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121145. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121146. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121147. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121148. };
  121149. static static_codebook _huff_book_line_512x17_1sub1 = {
  121150. 1, 128,
  121151. _huff_lengthlist_line_512x17_1sub1,
  121152. 0, 0, 0, 0, 0,
  121153. NULL,
  121154. NULL,
  121155. NULL,
  121156. NULL,
  121157. 0
  121158. };
  121159. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121160. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121161. 5, 3,
  121162. };
  121163. static static_codebook _huff_book_line_512x17_2sub1 = {
  121164. 1, 18,
  121165. _huff_lengthlist_line_512x17_2sub1,
  121166. 0, 0, 0, 0, 0,
  121167. NULL,
  121168. NULL,
  121169. NULL,
  121170. NULL,
  121171. 0
  121172. };
  121173. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121175. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121176. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121177. 9, 8,
  121178. };
  121179. static static_codebook _huff_book_line_512x17_2sub2 = {
  121180. 1, 50,
  121181. _huff_lengthlist_line_512x17_2sub2,
  121182. 0, 0, 0, 0, 0,
  121183. NULL,
  121184. NULL,
  121185. NULL,
  121186. NULL,
  121187. 0
  121188. };
  121189. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121193. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121194. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121195. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121196. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121197. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121198. };
  121199. static static_codebook _huff_book_line_512x17_2sub3 = {
  121200. 1, 128,
  121201. _huff_lengthlist_line_512x17_2sub3,
  121202. 0, 0, 0, 0, 0,
  121203. NULL,
  121204. NULL,
  121205. NULL,
  121206. NULL,
  121207. 0
  121208. };
  121209. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121210. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121211. 5, 5,
  121212. };
  121213. static static_codebook _huff_book_line_512x17_3sub1 = {
  121214. 1, 18,
  121215. _huff_lengthlist_line_512x17_3sub1,
  121216. 0, 0, 0, 0, 0,
  121217. NULL,
  121218. NULL,
  121219. NULL,
  121220. NULL,
  121221. 0
  121222. };
  121223. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121225. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121226. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121227. 11,14,
  121228. };
  121229. static static_codebook _huff_book_line_512x17_3sub2 = {
  121230. 1, 50,
  121231. _huff_lengthlist_line_512x17_3sub2,
  121232. 0, 0, 0, 0, 0,
  121233. NULL,
  121234. NULL,
  121235. NULL,
  121236. NULL,
  121237. 0
  121238. };
  121239. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121243. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121244. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121245. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121246. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121247. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121248. };
  121249. static static_codebook _huff_book_line_512x17_3sub3 = {
  121250. 1, 128,
  121251. _huff_lengthlist_line_512x17_3sub3,
  121252. 0, 0, 0, 0, 0,
  121253. NULL,
  121254. NULL,
  121255. NULL,
  121256. NULL,
  121257. 0
  121258. };
  121259. static long _huff_lengthlist_line_512x17_class1[] = {
  121260. 1, 2, 3, 6, 5, 4, 7, 7,
  121261. };
  121262. static static_codebook _huff_book_line_512x17_class1 = {
  121263. 1, 8,
  121264. _huff_lengthlist_line_512x17_class1,
  121265. 0, 0, 0, 0, 0,
  121266. NULL,
  121267. NULL,
  121268. NULL,
  121269. NULL,
  121270. 0
  121271. };
  121272. static long _huff_lengthlist_line_512x17_class2[] = {
  121273. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121274. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121275. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121276. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121277. };
  121278. static static_codebook _huff_book_line_512x17_class2 = {
  121279. 1, 64,
  121280. _huff_lengthlist_line_512x17_class2,
  121281. 0, 0, 0, 0, 0,
  121282. NULL,
  121283. NULL,
  121284. NULL,
  121285. NULL,
  121286. 0
  121287. };
  121288. static long _huff_lengthlist_line_512x17_class3[] = {
  121289. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121290. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121291. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121292. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121293. };
  121294. static static_codebook _huff_book_line_512x17_class3 = {
  121295. 1, 64,
  121296. _huff_lengthlist_line_512x17_class3,
  121297. 0, 0, 0, 0, 0,
  121298. NULL,
  121299. NULL,
  121300. NULL,
  121301. NULL,
  121302. 0
  121303. };
  121304. static long _huff_lengthlist_line_128x4_class0[] = {
  121305. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121306. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121307. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121308. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121309. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121310. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121311. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121312. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121313. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121314. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121315. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121316. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121317. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121318. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121319. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121320. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121321. };
  121322. static static_codebook _huff_book_line_128x4_class0 = {
  121323. 1, 256,
  121324. _huff_lengthlist_line_128x4_class0,
  121325. 0, 0, 0, 0, 0,
  121326. NULL,
  121327. NULL,
  121328. NULL,
  121329. NULL,
  121330. 0
  121331. };
  121332. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121333. 2, 2, 2, 2,
  121334. };
  121335. static static_codebook _huff_book_line_128x4_0sub0 = {
  121336. 1, 4,
  121337. _huff_lengthlist_line_128x4_0sub0,
  121338. 0, 0, 0, 0, 0,
  121339. NULL,
  121340. NULL,
  121341. NULL,
  121342. NULL,
  121343. 0
  121344. };
  121345. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121346. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121347. };
  121348. static static_codebook _huff_book_line_128x4_0sub1 = {
  121349. 1, 10,
  121350. _huff_lengthlist_line_128x4_0sub1,
  121351. 0, 0, 0, 0, 0,
  121352. NULL,
  121353. NULL,
  121354. NULL,
  121355. NULL,
  121356. 0
  121357. };
  121358. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121360. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121361. };
  121362. static static_codebook _huff_book_line_128x4_0sub2 = {
  121363. 1, 25,
  121364. _huff_lengthlist_line_128x4_0sub2,
  121365. 0, 0, 0, 0, 0,
  121366. NULL,
  121367. NULL,
  121368. NULL,
  121369. NULL,
  121370. 0
  121371. };
  121372. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121375. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121376. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121377. };
  121378. static static_codebook _huff_book_line_128x4_0sub3 = {
  121379. 1, 64,
  121380. _huff_lengthlist_line_128x4_0sub3,
  121381. 0, 0, 0, 0, 0,
  121382. NULL,
  121383. NULL,
  121384. NULL,
  121385. NULL,
  121386. 0
  121387. };
  121388. static long _huff_lengthlist_line_256x4_class0[] = {
  121389. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121390. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121391. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121392. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121393. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121394. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121395. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121396. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121397. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121398. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121399. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121400. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121401. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121402. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121403. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121404. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121405. };
  121406. static static_codebook _huff_book_line_256x4_class0 = {
  121407. 1, 256,
  121408. _huff_lengthlist_line_256x4_class0,
  121409. 0, 0, 0, 0, 0,
  121410. NULL,
  121411. NULL,
  121412. NULL,
  121413. NULL,
  121414. 0
  121415. };
  121416. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121417. 2, 2, 2, 2,
  121418. };
  121419. static static_codebook _huff_book_line_256x4_0sub0 = {
  121420. 1, 4,
  121421. _huff_lengthlist_line_256x4_0sub0,
  121422. 0, 0, 0, 0, 0,
  121423. NULL,
  121424. NULL,
  121425. NULL,
  121426. NULL,
  121427. 0
  121428. };
  121429. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121430. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121431. };
  121432. static static_codebook _huff_book_line_256x4_0sub1 = {
  121433. 1, 10,
  121434. _huff_lengthlist_line_256x4_0sub1,
  121435. 0, 0, 0, 0, 0,
  121436. NULL,
  121437. NULL,
  121438. NULL,
  121439. NULL,
  121440. 0
  121441. };
  121442. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121444. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121445. };
  121446. static static_codebook _huff_book_line_256x4_0sub2 = {
  121447. 1, 25,
  121448. _huff_lengthlist_line_256x4_0sub2,
  121449. 0, 0, 0, 0, 0,
  121450. NULL,
  121451. NULL,
  121452. NULL,
  121453. NULL,
  121454. 0
  121455. };
  121456. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121459. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121460. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121461. };
  121462. static static_codebook _huff_book_line_256x4_0sub3 = {
  121463. 1, 64,
  121464. _huff_lengthlist_line_256x4_0sub3,
  121465. 0, 0, 0, 0, 0,
  121466. NULL,
  121467. NULL,
  121468. NULL,
  121469. NULL,
  121470. 0
  121471. };
  121472. static long _huff_lengthlist_line_128x7_class0[] = {
  121473. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121474. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121475. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121476. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121477. };
  121478. static static_codebook _huff_book_line_128x7_class0 = {
  121479. 1, 64,
  121480. _huff_lengthlist_line_128x7_class0,
  121481. 0, 0, 0, 0, 0,
  121482. NULL,
  121483. NULL,
  121484. NULL,
  121485. NULL,
  121486. 0
  121487. };
  121488. static long _huff_lengthlist_line_128x7_class1[] = {
  121489. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121490. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121491. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121492. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121493. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121494. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121495. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121496. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121497. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121498. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121499. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121500. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121501. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121502. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121503. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121504. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121505. };
  121506. static static_codebook _huff_book_line_128x7_class1 = {
  121507. 1, 256,
  121508. _huff_lengthlist_line_128x7_class1,
  121509. 0, 0, 0, 0, 0,
  121510. NULL,
  121511. NULL,
  121512. NULL,
  121513. NULL,
  121514. 0
  121515. };
  121516. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121517. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121518. };
  121519. static static_codebook _huff_book_line_128x7_0sub1 = {
  121520. 1, 9,
  121521. _huff_lengthlist_line_128x7_0sub1,
  121522. 0, 0, 0, 0, 0,
  121523. NULL,
  121524. NULL,
  121525. NULL,
  121526. NULL,
  121527. 0
  121528. };
  121529. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121531. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121532. };
  121533. static static_codebook _huff_book_line_128x7_0sub2 = {
  121534. 1, 25,
  121535. _huff_lengthlist_line_128x7_0sub2,
  121536. 0, 0, 0, 0, 0,
  121537. NULL,
  121538. NULL,
  121539. NULL,
  121540. NULL,
  121541. 0
  121542. };
  121543. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121546. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121547. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121548. };
  121549. static static_codebook _huff_book_line_128x7_0sub3 = {
  121550. 1, 64,
  121551. _huff_lengthlist_line_128x7_0sub3,
  121552. 0, 0, 0, 0, 0,
  121553. NULL,
  121554. NULL,
  121555. NULL,
  121556. NULL,
  121557. 0
  121558. };
  121559. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121560. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121561. };
  121562. static static_codebook _huff_book_line_128x7_1sub1 = {
  121563. 1, 9,
  121564. _huff_lengthlist_line_128x7_1sub1,
  121565. 0, 0, 0, 0, 0,
  121566. NULL,
  121567. NULL,
  121568. NULL,
  121569. NULL,
  121570. 0
  121571. };
  121572. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121574. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121575. };
  121576. static static_codebook _huff_book_line_128x7_1sub2 = {
  121577. 1, 25,
  121578. _huff_lengthlist_line_128x7_1sub2,
  121579. 0, 0, 0, 0, 0,
  121580. NULL,
  121581. NULL,
  121582. NULL,
  121583. NULL,
  121584. 0
  121585. };
  121586. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121589. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121590. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121591. };
  121592. static static_codebook _huff_book_line_128x7_1sub3 = {
  121593. 1, 64,
  121594. _huff_lengthlist_line_128x7_1sub3,
  121595. 0, 0, 0, 0, 0,
  121596. NULL,
  121597. NULL,
  121598. NULL,
  121599. NULL,
  121600. 0
  121601. };
  121602. static long _huff_lengthlist_line_128x11_class1[] = {
  121603. 1, 6, 3, 7, 2, 4, 5, 7,
  121604. };
  121605. static static_codebook _huff_book_line_128x11_class1 = {
  121606. 1, 8,
  121607. _huff_lengthlist_line_128x11_class1,
  121608. 0, 0, 0, 0, 0,
  121609. NULL,
  121610. NULL,
  121611. NULL,
  121612. NULL,
  121613. 0
  121614. };
  121615. static long _huff_lengthlist_line_128x11_class2[] = {
  121616. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121617. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121618. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121619. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121620. };
  121621. static static_codebook _huff_book_line_128x11_class2 = {
  121622. 1, 64,
  121623. _huff_lengthlist_line_128x11_class2,
  121624. 0, 0, 0, 0, 0,
  121625. NULL,
  121626. NULL,
  121627. NULL,
  121628. NULL,
  121629. 0
  121630. };
  121631. static long _huff_lengthlist_line_128x11_class3[] = {
  121632. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121633. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121634. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121635. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121636. };
  121637. static static_codebook _huff_book_line_128x11_class3 = {
  121638. 1, 64,
  121639. _huff_lengthlist_line_128x11_class3,
  121640. 0, 0, 0, 0, 0,
  121641. NULL,
  121642. NULL,
  121643. NULL,
  121644. NULL,
  121645. 0
  121646. };
  121647. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121648. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121649. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121650. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121651. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121652. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121653. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121654. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121655. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121656. };
  121657. static static_codebook _huff_book_line_128x11_0sub0 = {
  121658. 1, 128,
  121659. _huff_lengthlist_line_128x11_0sub0,
  121660. 0, 0, 0, 0, 0,
  121661. NULL,
  121662. NULL,
  121663. NULL,
  121664. NULL,
  121665. 0
  121666. };
  121667. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121668. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121669. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121670. };
  121671. static static_codebook _huff_book_line_128x11_1sub0 = {
  121672. 1, 32,
  121673. _huff_lengthlist_line_128x11_1sub0,
  121674. 0, 0, 0, 0, 0,
  121675. NULL,
  121676. NULL,
  121677. NULL,
  121678. NULL,
  121679. 0
  121680. };
  121681. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121684. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121685. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121686. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121687. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121688. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121689. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121690. };
  121691. static static_codebook _huff_book_line_128x11_1sub1 = {
  121692. 1, 128,
  121693. _huff_lengthlist_line_128x11_1sub1,
  121694. 0, 0, 0, 0, 0,
  121695. NULL,
  121696. NULL,
  121697. NULL,
  121698. NULL,
  121699. 0
  121700. };
  121701. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121702. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121703. 5, 5,
  121704. };
  121705. static static_codebook _huff_book_line_128x11_2sub1 = {
  121706. 1, 18,
  121707. _huff_lengthlist_line_128x11_2sub1,
  121708. 0, 0, 0, 0, 0,
  121709. NULL,
  121710. NULL,
  121711. NULL,
  121712. NULL,
  121713. 0
  121714. };
  121715. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121717. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121718. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121719. 8,11,
  121720. };
  121721. static static_codebook _huff_book_line_128x11_2sub2 = {
  121722. 1, 50,
  121723. _huff_lengthlist_line_128x11_2sub2,
  121724. 0, 0, 0, 0, 0,
  121725. NULL,
  121726. NULL,
  121727. NULL,
  121728. NULL,
  121729. 0
  121730. };
  121731. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121735. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121736. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121737. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121738. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121739. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121740. };
  121741. static static_codebook _huff_book_line_128x11_2sub3 = {
  121742. 1, 128,
  121743. _huff_lengthlist_line_128x11_2sub3,
  121744. 0, 0, 0, 0, 0,
  121745. NULL,
  121746. NULL,
  121747. NULL,
  121748. NULL,
  121749. 0
  121750. };
  121751. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121752. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121753. 5, 4,
  121754. };
  121755. static static_codebook _huff_book_line_128x11_3sub1 = {
  121756. 1, 18,
  121757. _huff_lengthlist_line_128x11_3sub1,
  121758. 0, 0, 0, 0, 0,
  121759. NULL,
  121760. NULL,
  121761. NULL,
  121762. NULL,
  121763. 0
  121764. };
  121765. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121767. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121768. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121769. 12, 6,
  121770. };
  121771. static static_codebook _huff_book_line_128x11_3sub2 = {
  121772. 1, 50,
  121773. _huff_lengthlist_line_128x11_3sub2,
  121774. 0, 0, 0, 0, 0,
  121775. NULL,
  121776. NULL,
  121777. NULL,
  121778. NULL,
  121779. 0
  121780. };
  121781. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121785. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121786. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121787. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121788. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121789. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121790. };
  121791. static static_codebook _huff_book_line_128x11_3sub3 = {
  121792. 1, 128,
  121793. _huff_lengthlist_line_128x11_3sub3,
  121794. 0, 0, 0, 0, 0,
  121795. NULL,
  121796. NULL,
  121797. NULL,
  121798. NULL,
  121799. 0
  121800. };
  121801. static long _huff_lengthlist_line_128x17_class1[] = {
  121802. 1, 3, 4, 7, 2, 5, 6, 7,
  121803. };
  121804. static static_codebook _huff_book_line_128x17_class1 = {
  121805. 1, 8,
  121806. _huff_lengthlist_line_128x17_class1,
  121807. 0, 0, 0, 0, 0,
  121808. NULL,
  121809. NULL,
  121810. NULL,
  121811. NULL,
  121812. 0
  121813. };
  121814. static long _huff_lengthlist_line_128x17_class2[] = {
  121815. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121816. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121817. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121818. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121819. };
  121820. static static_codebook _huff_book_line_128x17_class2 = {
  121821. 1, 64,
  121822. _huff_lengthlist_line_128x17_class2,
  121823. 0, 0, 0, 0, 0,
  121824. NULL,
  121825. NULL,
  121826. NULL,
  121827. NULL,
  121828. 0
  121829. };
  121830. static long _huff_lengthlist_line_128x17_class3[] = {
  121831. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121832. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121833. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121834. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121835. };
  121836. static static_codebook _huff_book_line_128x17_class3 = {
  121837. 1, 64,
  121838. _huff_lengthlist_line_128x17_class3,
  121839. 0, 0, 0, 0, 0,
  121840. NULL,
  121841. NULL,
  121842. NULL,
  121843. NULL,
  121844. 0
  121845. };
  121846. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121847. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121848. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121849. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121850. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121851. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121852. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121853. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121854. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121855. };
  121856. static static_codebook _huff_book_line_128x17_0sub0 = {
  121857. 1, 128,
  121858. _huff_lengthlist_line_128x17_0sub0,
  121859. 0, 0, 0, 0, 0,
  121860. NULL,
  121861. NULL,
  121862. NULL,
  121863. NULL,
  121864. 0
  121865. };
  121866. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121867. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121868. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121869. };
  121870. static static_codebook _huff_book_line_128x17_1sub0 = {
  121871. 1, 32,
  121872. _huff_lengthlist_line_128x17_1sub0,
  121873. 0, 0, 0, 0, 0,
  121874. NULL,
  121875. NULL,
  121876. NULL,
  121877. NULL,
  121878. 0
  121879. };
  121880. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121883. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121884. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121885. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121886. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121887. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121888. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121889. };
  121890. static static_codebook _huff_book_line_128x17_1sub1 = {
  121891. 1, 128,
  121892. _huff_lengthlist_line_128x17_1sub1,
  121893. 0, 0, 0, 0, 0,
  121894. NULL,
  121895. NULL,
  121896. NULL,
  121897. NULL,
  121898. 0
  121899. };
  121900. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121901. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121902. 9, 4,
  121903. };
  121904. static static_codebook _huff_book_line_128x17_2sub1 = {
  121905. 1, 18,
  121906. _huff_lengthlist_line_128x17_2sub1,
  121907. 0, 0, 0, 0, 0,
  121908. NULL,
  121909. NULL,
  121910. NULL,
  121911. NULL,
  121912. 0
  121913. };
  121914. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121916. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121917. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121918. 13,13,
  121919. };
  121920. static static_codebook _huff_book_line_128x17_2sub2 = {
  121921. 1, 50,
  121922. _huff_lengthlist_line_128x17_2sub2,
  121923. 0, 0, 0, 0, 0,
  121924. NULL,
  121925. NULL,
  121926. NULL,
  121927. NULL,
  121928. 0
  121929. };
  121930. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121934. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121935. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121936. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121937. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121938. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121939. };
  121940. static static_codebook _huff_book_line_128x17_2sub3 = {
  121941. 1, 128,
  121942. _huff_lengthlist_line_128x17_2sub3,
  121943. 0, 0, 0, 0, 0,
  121944. NULL,
  121945. NULL,
  121946. NULL,
  121947. NULL,
  121948. 0
  121949. };
  121950. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121951. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121952. 6, 4,
  121953. };
  121954. static static_codebook _huff_book_line_128x17_3sub1 = {
  121955. 1, 18,
  121956. _huff_lengthlist_line_128x17_3sub1,
  121957. 0, 0, 0, 0, 0,
  121958. NULL,
  121959. NULL,
  121960. NULL,
  121961. NULL,
  121962. 0
  121963. };
  121964. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121966. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121967. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121968. 10, 8,
  121969. };
  121970. static static_codebook _huff_book_line_128x17_3sub2 = {
  121971. 1, 50,
  121972. _huff_lengthlist_line_128x17_3sub2,
  121973. 0, 0, 0, 0, 0,
  121974. NULL,
  121975. NULL,
  121976. NULL,
  121977. NULL,
  121978. 0
  121979. };
  121980. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121984. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121985. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121986. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121987. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121988. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121989. };
  121990. static static_codebook _huff_book_line_128x17_3sub3 = {
  121991. 1, 128,
  121992. _huff_lengthlist_line_128x17_3sub3,
  121993. 0, 0, 0, 0, 0,
  121994. NULL,
  121995. NULL,
  121996. NULL,
  121997. NULL,
  121998. 0
  121999. };
  122000. static long _huff_lengthlist_line_1024x27_class1[] = {
  122001. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  122002. };
  122003. static static_codebook _huff_book_line_1024x27_class1 = {
  122004. 1, 16,
  122005. _huff_lengthlist_line_1024x27_class1,
  122006. 0, 0, 0, 0, 0,
  122007. NULL,
  122008. NULL,
  122009. NULL,
  122010. NULL,
  122011. 0
  122012. };
  122013. static long _huff_lengthlist_line_1024x27_class2[] = {
  122014. 1, 4, 2, 6, 3, 7, 5, 7,
  122015. };
  122016. static static_codebook _huff_book_line_1024x27_class2 = {
  122017. 1, 8,
  122018. _huff_lengthlist_line_1024x27_class2,
  122019. 0, 0, 0, 0, 0,
  122020. NULL,
  122021. NULL,
  122022. NULL,
  122023. NULL,
  122024. 0
  122025. };
  122026. static long _huff_lengthlist_line_1024x27_class3[] = {
  122027. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  122028. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  122029. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  122030. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  122031. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  122032. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  122033. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  122034. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  122035. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  122036. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  122037. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  122038. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122039. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  122040. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  122041. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  122042. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122043. };
  122044. static static_codebook _huff_book_line_1024x27_class3 = {
  122045. 1, 256,
  122046. _huff_lengthlist_line_1024x27_class3,
  122047. 0, 0, 0, 0, 0,
  122048. NULL,
  122049. NULL,
  122050. NULL,
  122051. NULL,
  122052. 0
  122053. };
  122054. static long _huff_lengthlist_line_1024x27_class4[] = {
  122055. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  122056. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  122057. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  122058. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  122059. };
  122060. static static_codebook _huff_book_line_1024x27_class4 = {
  122061. 1, 64,
  122062. _huff_lengthlist_line_1024x27_class4,
  122063. 0, 0, 0, 0, 0,
  122064. NULL,
  122065. NULL,
  122066. NULL,
  122067. NULL,
  122068. 0
  122069. };
  122070. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  122071. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122072. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  122073. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  122074. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  122075. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  122076. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  122077. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  122078. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  122079. };
  122080. static static_codebook _huff_book_line_1024x27_0sub0 = {
  122081. 1, 128,
  122082. _huff_lengthlist_line_1024x27_0sub0,
  122083. 0, 0, 0, 0, 0,
  122084. NULL,
  122085. NULL,
  122086. NULL,
  122087. NULL,
  122088. 0
  122089. };
  122090. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  122091. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  122092. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  122093. };
  122094. static static_codebook _huff_book_line_1024x27_1sub0 = {
  122095. 1, 32,
  122096. _huff_lengthlist_line_1024x27_1sub0,
  122097. 0, 0, 0, 0, 0,
  122098. NULL,
  122099. NULL,
  122100. NULL,
  122101. NULL,
  122102. 0
  122103. };
  122104. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  122105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122107. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  122108. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  122109. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  122110. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  122111. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  122112. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  122113. };
  122114. static static_codebook _huff_book_line_1024x27_1sub1 = {
  122115. 1, 128,
  122116. _huff_lengthlist_line_1024x27_1sub1,
  122117. 0, 0, 0, 0, 0,
  122118. NULL,
  122119. NULL,
  122120. NULL,
  122121. NULL,
  122122. 0
  122123. };
  122124. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  122125. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122126. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  122127. };
  122128. static static_codebook _huff_book_line_1024x27_2sub0 = {
  122129. 1, 32,
  122130. _huff_lengthlist_line_1024x27_2sub0,
  122131. 0, 0, 0, 0, 0,
  122132. NULL,
  122133. NULL,
  122134. NULL,
  122135. NULL,
  122136. 0
  122137. };
  122138. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  122139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122141. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122142. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122143. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122144. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122145. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122146. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122147. };
  122148. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122149. 1, 128,
  122150. _huff_lengthlist_line_1024x27_2sub1,
  122151. 0, 0, 0, 0, 0,
  122152. NULL,
  122153. NULL,
  122154. NULL,
  122155. NULL,
  122156. 0
  122157. };
  122158. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122159. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122160. 5, 5,
  122161. };
  122162. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122163. 1, 18,
  122164. _huff_lengthlist_line_1024x27_3sub1,
  122165. 0, 0, 0, 0, 0,
  122166. NULL,
  122167. NULL,
  122168. NULL,
  122169. NULL,
  122170. 0
  122171. };
  122172. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122174. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122175. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122176. 9,11,
  122177. };
  122178. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122179. 1, 50,
  122180. _huff_lengthlist_line_1024x27_3sub2,
  122181. 0, 0, 0, 0, 0,
  122182. NULL,
  122183. NULL,
  122184. NULL,
  122185. NULL,
  122186. 0
  122187. };
  122188. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122192. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122193. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122194. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122195. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122196. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122197. };
  122198. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122199. 1, 128,
  122200. _huff_lengthlist_line_1024x27_3sub3,
  122201. 0, 0, 0, 0, 0,
  122202. NULL,
  122203. NULL,
  122204. NULL,
  122205. NULL,
  122206. 0
  122207. };
  122208. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122209. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122210. 5, 4,
  122211. };
  122212. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122213. 1, 18,
  122214. _huff_lengthlist_line_1024x27_4sub1,
  122215. 0, 0, 0, 0, 0,
  122216. NULL,
  122217. NULL,
  122218. NULL,
  122219. NULL,
  122220. 0
  122221. };
  122222. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122224. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122225. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122226. 9,12,
  122227. };
  122228. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122229. 1, 50,
  122230. _huff_lengthlist_line_1024x27_4sub2,
  122231. 0, 0, 0, 0, 0,
  122232. NULL,
  122233. NULL,
  122234. NULL,
  122235. NULL,
  122236. 0
  122237. };
  122238. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122242. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122243. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122244. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122245. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122246. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122247. };
  122248. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122249. 1, 128,
  122250. _huff_lengthlist_line_1024x27_4sub3,
  122251. 0, 0, 0, 0, 0,
  122252. NULL,
  122253. NULL,
  122254. NULL,
  122255. NULL,
  122256. 0
  122257. };
  122258. static long _huff_lengthlist_line_2048x27_class1[] = {
  122259. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122260. };
  122261. static static_codebook _huff_book_line_2048x27_class1 = {
  122262. 1, 16,
  122263. _huff_lengthlist_line_2048x27_class1,
  122264. 0, 0, 0, 0, 0,
  122265. NULL,
  122266. NULL,
  122267. NULL,
  122268. NULL,
  122269. 0
  122270. };
  122271. static long _huff_lengthlist_line_2048x27_class2[] = {
  122272. 1, 2, 3, 6, 4, 7, 5, 7,
  122273. };
  122274. static static_codebook _huff_book_line_2048x27_class2 = {
  122275. 1, 8,
  122276. _huff_lengthlist_line_2048x27_class2,
  122277. 0, 0, 0, 0, 0,
  122278. NULL,
  122279. NULL,
  122280. NULL,
  122281. NULL,
  122282. 0
  122283. };
  122284. static long _huff_lengthlist_line_2048x27_class3[] = {
  122285. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122286. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122287. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122288. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122289. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122290. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122291. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122292. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122293. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122294. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122295. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122296. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122297. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122298. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122299. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122300. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122301. };
  122302. static static_codebook _huff_book_line_2048x27_class3 = {
  122303. 1, 256,
  122304. _huff_lengthlist_line_2048x27_class3,
  122305. 0, 0, 0, 0, 0,
  122306. NULL,
  122307. NULL,
  122308. NULL,
  122309. NULL,
  122310. 0
  122311. };
  122312. static long _huff_lengthlist_line_2048x27_class4[] = {
  122313. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122314. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122315. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122316. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122317. };
  122318. static static_codebook _huff_book_line_2048x27_class4 = {
  122319. 1, 64,
  122320. _huff_lengthlist_line_2048x27_class4,
  122321. 0, 0, 0, 0, 0,
  122322. NULL,
  122323. NULL,
  122324. NULL,
  122325. NULL,
  122326. 0
  122327. };
  122328. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122329. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122330. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122331. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122332. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122333. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122334. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122335. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122336. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122337. };
  122338. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122339. 1, 128,
  122340. _huff_lengthlist_line_2048x27_0sub0,
  122341. 0, 0, 0, 0, 0,
  122342. NULL,
  122343. NULL,
  122344. NULL,
  122345. NULL,
  122346. 0
  122347. };
  122348. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122349. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122350. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122351. };
  122352. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122353. 1, 32,
  122354. _huff_lengthlist_line_2048x27_1sub0,
  122355. 0, 0, 0, 0, 0,
  122356. NULL,
  122357. NULL,
  122358. NULL,
  122359. NULL,
  122360. 0
  122361. };
  122362. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  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. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122366. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122367. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122368. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122369. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122370. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122371. };
  122372. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122373. 1, 128,
  122374. _huff_lengthlist_line_2048x27_1sub1,
  122375. 0, 0, 0, 0, 0,
  122376. NULL,
  122377. NULL,
  122378. NULL,
  122379. NULL,
  122380. 0
  122381. };
  122382. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122383. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122384. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122385. };
  122386. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122387. 1, 32,
  122388. _huff_lengthlist_line_2048x27_2sub0,
  122389. 0, 0, 0, 0, 0,
  122390. NULL,
  122391. NULL,
  122392. NULL,
  122393. NULL,
  122394. 0
  122395. };
  122396. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  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. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122400. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122401. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122402. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122403. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122404. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122405. };
  122406. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122407. 1, 128,
  122408. _huff_lengthlist_line_2048x27_2sub1,
  122409. 0, 0, 0, 0, 0,
  122410. NULL,
  122411. NULL,
  122412. NULL,
  122413. NULL,
  122414. 0
  122415. };
  122416. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122417. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122418. 5, 5,
  122419. };
  122420. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122421. 1, 18,
  122422. _huff_lengthlist_line_2048x27_3sub1,
  122423. 0, 0, 0, 0, 0,
  122424. NULL,
  122425. NULL,
  122426. NULL,
  122427. NULL,
  122428. 0
  122429. };
  122430. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122433. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122434. 10,12,
  122435. };
  122436. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122437. 1, 50,
  122438. _huff_lengthlist_line_2048x27_3sub2,
  122439. 0, 0, 0, 0, 0,
  122440. NULL,
  122441. NULL,
  122442. NULL,
  122443. NULL,
  122444. 0
  122445. };
  122446. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  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, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122451. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122452. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122453. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122454. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122455. };
  122456. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122457. 1, 128,
  122458. _huff_lengthlist_line_2048x27_3sub3,
  122459. 0, 0, 0, 0, 0,
  122460. NULL,
  122461. NULL,
  122462. NULL,
  122463. NULL,
  122464. 0
  122465. };
  122466. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122467. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122468. 4, 5,
  122469. };
  122470. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122471. 1, 18,
  122472. _huff_lengthlist_line_2048x27_4sub1,
  122473. 0, 0, 0, 0, 0,
  122474. NULL,
  122475. NULL,
  122476. NULL,
  122477. NULL,
  122478. 0
  122479. };
  122480. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122483. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122484. 10,10,
  122485. };
  122486. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122487. 1, 50,
  122488. _huff_lengthlist_line_2048x27_4sub2,
  122489. 0, 0, 0, 0, 0,
  122490. NULL,
  122491. NULL,
  122492. NULL,
  122493. NULL,
  122494. 0
  122495. };
  122496. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  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, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122501. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122502. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122503. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122504. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122505. };
  122506. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122507. 1, 128,
  122508. _huff_lengthlist_line_2048x27_4sub3,
  122509. 0, 0, 0, 0, 0,
  122510. NULL,
  122511. NULL,
  122512. NULL,
  122513. NULL,
  122514. 0
  122515. };
  122516. static long _huff_lengthlist_line_256x4low_class0[] = {
  122517. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122518. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122519. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122520. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122521. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122522. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122523. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122524. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122525. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122526. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122527. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122528. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122529. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122530. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122531. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122532. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122533. };
  122534. static static_codebook _huff_book_line_256x4low_class0 = {
  122535. 1, 256,
  122536. _huff_lengthlist_line_256x4low_class0,
  122537. 0, 0, 0, 0, 0,
  122538. NULL,
  122539. NULL,
  122540. NULL,
  122541. NULL,
  122542. 0
  122543. };
  122544. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122545. 1, 3, 2, 3,
  122546. };
  122547. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122548. 1, 4,
  122549. _huff_lengthlist_line_256x4low_0sub0,
  122550. 0, 0, 0, 0, 0,
  122551. NULL,
  122552. NULL,
  122553. NULL,
  122554. NULL,
  122555. 0
  122556. };
  122557. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122558. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122559. };
  122560. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122561. 1, 10,
  122562. _huff_lengthlist_line_256x4low_0sub1,
  122563. 0, 0, 0, 0, 0,
  122564. NULL,
  122565. NULL,
  122566. NULL,
  122567. NULL,
  122568. 0
  122569. };
  122570. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122572. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122573. };
  122574. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122575. 1, 25,
  122576. _huff_lengthlist_line_256x4low_0sub2,
  122577. 0, 0, 0, 0, 0,
  122578. NULL,
  122579. NULL,
  122580. NULL,
  122581. NULL,
  122582. 0
  122583. };
  122584. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  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, 3, 4, 2, 4, 3, 5, 4,
  122587. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122588. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122589. };
  122590. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122591. 1, 64,
  122592. _huff_lengthlist_line_256x4low_0sub3,
  122593. 0, 0, 0, 0, 0,
  122594. NULL,
  122595. NULL,
  122596. NULL,
  122597. NULL,
  122598. 0
  122599. };
  122600. /*** End of inlined file: floor_books.h ***/
  122601. static static_codebook *_floor_128x4_books[]={
  122602. &_huff_book_line_128x4_class0,
  122603. &_huff_book_line_128x4_0sub0,
  122604. &_huff_book_line_128x4_0sub1,
  122605. &_huff_book_line_128x4_0sub2,
  122606. &_huff_book_line_128x4_0sub3,
  122607. };
  122608. static static_codebook *_floor_256x4_books[]={
  122609. &_huff_book_line_256x4_class0,
  122610. &_huff_book_line_256x4_0sub0,
  122611. &_huff_book_line_256x4_0sub1,
  122612. &_huff_book_line_256x4_0sub2,
  122613. &_huff_book_line_256x4_0sub3,
  122614. };
  122615. static static_codebook *_floor_128x7_books[]={
  122616. &_huff_book_line_128x7_class0,
  122617. &_huff_book_line_128x7_class1,
  122618. &_huff_book_line_128x7_0sub1,
  122619. &_huff_book_line_128x7_0sub2,
  122620. &_huff_book_line_128x7_0sub3,
  122621. &_huff_book_line_128x7_1sub1,
  122622. &_huff_book_line_128x7_1sub2,
  122623. &_huff_book_line_128x7_1sub3,
  122624. };
  122625. static static_codebook *_floor_256x7_books[]={
  122626. &_huff_book_line_256x7_class0,
  122627. &_huff_book_line_256x7_class1,
  122628. &_huff_book_line_256x7_0sub1,
  122629. &_huff_book_line_256x7_0sub2,
  122630. &_huff_book_line_256x7_0sub3,
  122631. &_huff_book_line_256x7_1sub1,
  122632. &_huff_book_line_256x7_1sub2,
  122633. &_huff_book_line_256x7_1sub3,
  122634. };
  122635. static static_codebook *_floor_128x11_books[]={
  122636. &_huff_book_line_128x11_class1,
  122637. &_huff_book_line_128x11_class2,
  122638. &_huff_book_line_128x11_class3,
  122639. &_huff_book_line_128x11_0sub0,
  122640. &_huff_book_line_128x11_1sub0,
  122641. &_huff_book_line_128x11_1sub1,
  122642. &_huff_book_line_128x11_2sub1,
  122643. &_huff_book_line_128x11_2sub2,
  122644. &_huff_book_line_128x11_2sub3,
  122645. &_huff_book_line_128x11_3sub1,
  122646. &_huff_book_line_128x11_3sub2,
  122647. &_huff_book_line_128x11_3sub3,
  122648. };
  122649. static static_codebook *_floor_128x17_books[]={
  122650. &_huff_book_line_128x17_class1,
  122651. &_huff_book_line_128x17_class2,
  122652. &_huff_book_line_128x17_class3,
  122653. &_huff_book_line_128x17_0sub0,
  122654. &_huff_book_line_128x17_1sub0,
  122655. &_huff_book_line_128x17_1sub1,
  122656. &_huff_book_line_128x17_2sub1,
  122657. &_huff_book_line_128x17_2sub2,
  122658. &_huff_book_line_128x17_2sub3,
  122659. &_huff_book_line_128x17_3sub1,
  122660. &_huff_book_line_128x17_3sub2,
  122661. &_huff_book_line_128x17_3sub3,
  122662. };
  122663. static static_codebook *_floor_256x4low_books[]={
  122664. &_huff_book_line_256x4low_class0,
  122665. &_huff_book_line_256x4low_0sub0,
  122666. &_huff_book_line_256x4low_0sub1,
  122667. &_huff_book_line_256x4low_0sub2,
  122668. &_huff_book_line_256x4low_0sub3,
  122669. };
  122670. static static_codebook *_floor_1024x27_books[]={
  122671. &_huff_book_line_1024x27_class1,
  122672. &_huff_book_line_1024x27_class2,
  122673. &_huff_book_line_1024x27_class3,
  122674. &_huff_book_line_1024x27_class4,
  122675. &_huff_book_line_1024x27_0sub0,
  122676. &_huff_book_line_1024x27_1sub0,
  122677. &_huff_book_line_1024x27_1sub1,
  122678. &_huff_book_line_1024x27_2sub0,
  122679. &_huff_book_line_1024x27_2sub1,
  122680. &_huff_book_line_1024x27_3sub1,
  122681. &_huff_book_line_1024x27_3sub2,
  122682. &_huff_book_line_1024x27_3sub3,
  122683. &_huff_book_line_1024x27_4sub1,
  122684. &_huff_book_line_1024x27_4sub2,
  122685. &_huff_book_line_1024x27_4sub3,
  122686. };
  122687. static static_codebook *_floor_2048x27_books[]={
  122688. &_huff_book_line_2048x27_class1,
  122689. &_huff_book_line_2048x27_class2,
  122690. &_huff_book_line_2048x27_class3,
  122691. &_huff_book_line_2048x27_class4,
  122692. &_huff_book_line_2048x27_0sub0,
  122693. &_huff_book_line_2048x27_1sub0,
  122694. &_huff_book_line_2048x27_1sub1,
  122695. &_huff_book_line_2048x27_2sub0,
  122696. &_huff_book_line_2048x27_2sub1,
  122697. &_huff_book_line_2048x27_3sub1,
  122698. &_huff_book_line_2048x27_3sub2,
  122699. &_huff_book_line_2048x27_3sub3,
  122700. &_huff_book_line_2048x27_4sub1,
  122701. &_huff_book_line_2048x27_4sub2,
  122702. &_huff_book_line_2048x27_4sub3,
  122703. };
  122704. static static_codebook *_floor_512x17_books[]={
  122705. &_huff_book_line_512x17_class1,
  122706. &_huff_book_line_512x17_class2,
  122707. &_huff_book_line_512x17_class3,
  122708. &_huff_book_line_512x17_0sub0,
  122709. &_huff_book_line_512x17_1sub0,
  122710. &_huff_book_line_512x17_1sub1,
  122711. &_huff_book_line_512x17_2sub1,
  122712. &_huff_book_line_512x17_2sub2,
  122713. &_huff_book_line_512x17_2sub3,
  122714. &_huff_book_line_512x17_3sub1,
  122715. &_huff_book_line_512x17_3sub2,
  122716. &_huff_book_line_512x17_3sub3,
  122717. };
  122718. static static_codebook **_floor_books[10]={
  122719. _floor_128x4_books,
  122720. _floor_256x4_books,
  122721. _floor_128x7_books,
  122722. _floor_256x7_books,
  122723. _floor_128x11_books,
  122724. _floor_128x17_books,
  122725. _floor_256x4low_books,
  122726. _floor_1024x27_books,
  122727. _floor_2048x27_books,
  122728. _floor_512x17_books,
  122729. };
  122730. static vorbis_info_floor1 _floor[10]={
  122731. /* 128 x 4 */
  122732. {
  122733. 1,{0},{4},{2},{0},
  122734. {{1,2,3,4}},
  122735. 4,{0,128, 33,8,16,70},
  122736. 60,30,500, 1.,18., -1
  122737. },
  122738. /* 256 x 4 */
  122739. {
  122740. 1,{0},{4},{2},{0},
  122741. {{1,2,3,4}},
  122742. 4,{0,256, 66,16,32,140},
  122743. 60,30,500, 1.,18., -1
  122744. },
  122745. /* 128 x 7 */
  122746. {
  122747. 2,{0,1},{3,4},{2,2},{0,1},
  122748. {{-1,2,3,4},{-1,5,6,7}},
  122749. 4,{0,128, 14,4,58, 2,8,28,90},
  122750. 60,30,500, 1.,18., -1
  122751. },
  122752. /* 256 x 7 */
  122753. {
  122754. 2,{0,1},{3,4},{2,2},{0,1},
  122755. {{-1,2,3,4},{-1,5,6,7}},
  122756. 4,{0,256, 28,8,116, 4,16,56,180},
  122757. 60,30,500, 1.,18., -1
  122758. },
  122759. /* 128 x 11 */
  122760. {
  122761. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122762. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122763. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122764. 60,30,500, 1,18., -1
  122765. },
  122766. /* 128 x 17 */
  122767. {
  122768. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122769. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122770. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122771. 60,30,500, 1,18., -1
  122772. },
  122773. /* 256 x 4 (low bitrate version) */
  122774. {
  122775. 1,{0},{4},{2},{0},
  122776. {{1,2,3,4}},
  122777. 4,{0,256, 66,16,32,140},
  122778. 60,30,500, 1.,18., -1
  122779. },
  122780. /* 1024 x 27 */
  122781. {
  122782. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122783. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122784. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122785. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122786. 60,30,500, 3,18., -1 /* lowpass */
  122787. },
  122788. /* 2048 x 27 */
  122789. {
  122790. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122791. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122792. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122793. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122794. 60,30,500, 3,18., -1 /* lowpass */
  122795. },
  122796. /* 512 x 17 */
  122797. {
  122798. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122799. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122800. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122801. 7,23,39, 55,79,110, 156,232,360},
  122802. 60,30,500, 1,18., -1 /* lowpass! */
  122803. },
  122804. };
  122805. /*** End of inlined file: floor_all.h ***/
  122806. /*** Start of inlined file: residue_44.h ***/
  122807. /*** Start of inlined file: res_books_stereo.h ***/
  122808. static long _vq_quantlist__16c0_s_p1_0[] = {
  122809. 1,
  122810. 0,
  122811. 2,
  122812. };
  122813. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122814. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122815. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122820. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122825. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122860. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122865. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122870. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122906. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122911. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122916. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0,
  123225. };
  123226. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123227. -0.5, 0.5,
  123228. };
  123229. static long _vq_quantmap__16c0_s_p1_0[] = {
  123230. 1, 0, 2,
  123231. };
  123232. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123233. _vq_quantthresh__16c0_s_p1_0,
  123234. _vq_quantmap__16c0_s_p1_0,
  123235. 3,
  123236. 3
  123237. };
  123238. static static_codebook _16c0_s_p1_0 = {
  123239. 8, 6561,
  123240. _vq_lengthlist__16c0_s_p1_0,
  123241. 1, -535822336, 1611661312, 2, 0,
  123242. _vq_quantlist__16c0_s_p1_0,
  123243. NULL,
  123244. &_vq_auxt__16c0_s_p1_0,
  123245. NULL,
  123246. 0
  123247. };
  123248. static long _vq_quantlist__16c0_s_p2_0[] = {
  123249. 2,
  123250. 1,
  123251. 3,
  123252. 0,
  123253. 4,
  123254. };
  123255. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0,
  123296. };
  123297. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123298. -1.5, -0.5, 0.5, 1.5,
  123299. };
  123300. static long _vq_quantmap__16c0_s_p2_0[] = {
  123301. 3, 1, 0, 2, 4,
  123302. };
  123303. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123304. _vq_quantthresh__16c0_s_p2_0,
  123305. _vq_quantmap__16c0_s_p2_0,
  123306. 5,
  123307. 5
  123308. };
  123309. static static_codebook _16c0_s_p2_0 = {
  123310. 4, 625,
  123311. _vq_lengthlist__16c0_s_p2_0,
  123312. 1, -533725184, 1611661312, 3, 0,
  123313. _vq_quantlist__16c0_s_p2_0,
  123314. NULL,
  123315. &_vq_auxt__16c0_s_p2_0,
  123316. NULL,
  123317. 0
  123318. };
  123319. static long _vq_quantlist__16c0_s_p3_0[] = {
  123320. 2,
  123321. 1,
  123322. 3,
  123323. 0,
  123324. 4,
  123325. };
  123326. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123327. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0,
  123367. };
  123368. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123369. -1.5, -0.5, 0.5, 1.5,
  123370. };
  123371. static long _vq_quantmap__16c0_s_p3_0[] = {
  123372. 3, 1, 0, 2, 4,
  123373. };
  123374. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123375. _vq_quantthresh__16c0_s_p3_0,
  123376. _vq_quantmap__16c0_s_p3_0,
  123377. 5,
  123378. 5
  123379. };
  123380. static static_codebook _16c0_s_p3_0 = {
  123381. 4, 625,
  123382. _vq_lengthlist__16c0_s_p3_0,
  123383. 1, -533725184, 1611661312, 3, 0,
  123384. _vq_quantlist__16c0_s_p3_0,
  123385. NULL,
  123386. &_vq_auxt__16c0_s_p3_0,
  123387. NULL,
  123388. 0
  123389. };
  123390. static long _vq_quantlist__16c0_s_p4_0[] = {
  123391. 4,
  123392. 3,
  123393. 5,
  123394. 2,
  123395. 6,
  123396. 1,
  123397. 7,
  123398. 0,
  123399. 8,
  123400. };
  123401. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123402. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123403. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123404. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123405. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123406. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0,
  123408. };
  123409. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123410. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123411. };
  123412. static long _vq_quantmap__16c0_s_p4_0[] = {
  123413. 7, 5, 3, 1, 0, 2, 4, 6,
  123414. 8,
  123415. };
  123416. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123417. _vq_quantthresh__16c0_s_p4_0,
  123418. _vq_quantmap__16c0_s_p4_0,
  123419. 9,
  123420. 9
  123421. };
  123422. static static_codebook _16c0_s_p4_0 = {
  123423. 2, 81,
  123424. _vq_lengthlist__16c0_s_p4_0,
  123425. 1, -531628032, 1611661312, 4, 0,
  123426. _vq_quantlist__16c0_s_p4_0,
  123427. NULL,
  123428. &_vq_auxt__16c0_s_p4_0,
  123429. NULL,
  123430. 0
  123431. };
  123432. static long _vq_quantlist__16c0_s_p5_0[] = {
  123433. 4,
  123434. 3,
  123435. 5,
  123436. 2,
  123437. 6,
  123438. 1,
  123439. 7,
  123440. 0,
  123441. 8,
  123442. };
  123443. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123444. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123445. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123446. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123447. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123448. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123449. 10,
  123450. };
  123451. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123452. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123453. };
  123454. static long _vq_quantmap__16c0_s_p5_0[] = {
  123455. 7, 5, 3, 1, 0, 2, 4, 6,
  123456. 8,
  123457. };
  123458. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123459. _vq_quantthresh__16c0_s_p5_0,
  123460. _vq_quantmap__16c0_s_p5_0,
  123461. 9,
  123462. 9
  123463. };
  123464. static static_codebook _16c0_s_p5_0 = {
  123465. 2, 81,
  123466. _vq_lengthlist__16c0_s_p5_0,
  123467. 1, -531628032, 1611661312, 4, 0,
  123468. _vq_quantlist__16c0_s_p5_0,
  123469. NULL,
  123470. &_vq_auxt__16c0_s_p5_0,
  123471. NULL,
  123472. 0
  123473. };
  123474. static long _vq_quantlist__16c0_s_p6_0[] = {
  123475. 8,
  123476. 7,
  123477. 9,
  123478. 6,
  123479. 10,
  123480. 5,
  123481. 11,
  123482. 4,
  123483. 12,
  123484. 3,
  123485. 13,
  123486. 2,
  123487. 14,
  123488. 1,
  123489. 15,
  123490. 0,
  123491. 16,
  123492. };
  123493. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123494. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123495. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123496. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123497. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123498. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123499. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123500. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123501. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123502. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123503. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123504. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123505. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123506. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123507. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123508. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123509. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123510. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123512. 14,
  123513. };
  123514. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123515. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123516. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123517. };
  123518. static long _vq_quantmap__16c0_s_p6_0[] = {
  123519. 15, 13, 11, 9, 7, 5, 3, 1,
  123520. 0, 2, 4, 6, 8, 10, 12, 14,
  123521. 16,
  123522. };
  123523. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123524. _vq_quantthresh__16c0_s_p6_0,
  123525. _vq_quantmap__16c0_s_p6_0,
  123526. 17,
  123527. 17
  123528. };
  123529. static static_codebook _16c0_s_p6_0 = {
  123530. 2, 289,
  123531. _vq_lengthlist__16c0_s_p6_0,
  123532. 1, -529530880, 1611661312, 5, 0,
  123533. _vq_quantlist__16c0_s_p6_0,
  123534. NULL,
  123535. &_vq_auxt__16c0_s_p6_0,
  123536. NULL,
  123537. 0
  123538. };
  123539. static long _vq_quantlist__16c0_s_p7_0[] = {
  123540. 1,
  123541. 0,
  123542. 2,
  123543. };
  123544. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123545. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123546. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123547. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123548. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123549. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123550. 13,
  123551. };
  123552. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123553. -5.5, 5.5,
  123554. };
  123555. static long _vq_quantmap__16c0_s_p7_0[] = {
  123556. 1, 0, 2,
  123557. };
  123558. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123559. _vq_quantthresh__16c0_s_p7_0,
  123560. _vq_quantmap__16c0_s_p7_0,
  123561. 3,
  123562. 3
  123563. };
  123564. static static_codebook _16c0_s_p7_0 = {
  123565. 4, 81,
  123566. _vq_lengthlist__16c0_s_p7_0,
  123567. 1, -529137664, 1618345984, 2, 0,
  123568. _vq_quantlist__16c0_s_p7_0,
  123569. NULL,
  123570. &_vq_auxt__16c0_s_p7_0,
  123571. NULL,
  123572. 0
  123573. };
  123574. static long _vq_quantlist__16c0_s_p7_1[] = {
  123575. 5,
  123576. 4,
  123577. 6,
  123578. 3,
  123579. 7,
  123580. 2,
  123581. 8,
  123582. 1,
  123583. 9,
  123584. 0,
  123585. 10,
  123586. };
  123587. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123588. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123589. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123590. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123591. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123592. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123593. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123594. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123595. 11,11,11, 9, 9, 9, 9,10,10,
  123596. };
  123597. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123598. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123599. 3.5, 4.5,
  123600. };
  123601. static long _vq_quantmap__16c0_s_p7_1[] = {
  123602. 9, 7, 5, 3, 1, 0, 2, 4,
  123603. 6, 8, 10,
  123604. };
  123605. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123606. _vq_quantthresh__16c0_s_p7_1,
  123607. _vq_quantmap__16c0_s_p7_1,
  123608. 11,
  123609. 11
  123610. };
  123611. static static_codebook _16c0_s_p7_1 = {
  123612. 2, 121,
  123613. _vq_lengthlist__16c0_s_p7_1,
  123614. 1, -531365888, 1611661312, 4, 0,
  123615. _vq_quantlist__16c0_s_p7_1,
  123616. NULL,
  123617. &_vq_auxt__16c0_s_p7_1,
  123618. NULL,
  123619. 0
  123620. };
  123621. static long _vq_quantlist__16c0_s_p8_0[] = {
  123622. 6,
  123623. 5,
  123624. 7,
  123625. 4,
  123626. 8,
  123627. 3,
  123628. 9,
  123629. 2,
  123630. 10,
  123631. 1,
  123632. 11,
  123633. 0,
  123634. 12,
  123635. };
  123636. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123637. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123638. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123639. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123640. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123641. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123642. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123643. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123644. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123645. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123646. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123647. 0,12,13,13,12,13,14,14,14,
  123648. };
  123649. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123650. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123651. 12.5, 17.5, 22.5, 27.5,
  123652. };
  123653. static long _vq_quantmap__16c0_s_p8_0[] = {
  123654. 11, 9, 7, 5, 3, 1, 0, 2,
  123655. 4, 6, 8, 10, 12,
  123656. };
  123657. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123658. _vq_quantthresh__16c0_s_p8_0,
  123659. _vq_quantmap__16c0_s_p8_0,
  123660. 13,
  123661. 13
  123662. };
  123663. static static_codebook _16c0_s_p8_0 = {
  123664. 2, 169,
  123665. _vq_lengthlist__16c0_s_p8_0,
  123666. 1, -526516224, 1616117760, 4, 0,
  123667. _vq_quantlist__16c0_s_p8_0,
  123668. NULL,
  123669. &_vq_auxt__16c0_s_p8_0,
  123670. NULL,
  123671. 0
  123672. };
  123673. static long _vq_quantlist__16c0_s_p8_1[] = {
  123674. 2,
  123675. 1,
  123676. 3,
  123677. 0,
  123678. 4,
  123679. };
  123680. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123681. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123682. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123683. };
  123684. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123685. -1.5, -0.5, 0.5, 1.5,
  123686. };
  123687. static long _vq_quantmap__16c0_s_p8_1[] = {
  123688. 3, 1, 0, 2, 4,
  123689. };
  123690. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123691. _vq_quantthresh__16c0_s_p8_1,
  123692. _vq_quantmap__16c0_s_p8_1,
  123693. 5,
  123694. 5
  123695. };
  123696. static static_codebook _16c0_s_p8_1 = {
  123697. 2, 25,
  123698. _vq_lengthlist__16c0_s_p8_1,
  123699. 1, -533725184, 1611661312, 3, 0,
  123700. _vq_quantlist__16c0_s_p8_1,
  123701. NULL,
  123702. &_vq_auxt__16c0_s_p8_1,
  123703. NULL,
  123704. 0
  123705. };
  123706. static long _vq_quantlist__16c0_s_p9_0[] = {
  123707. 1,
  123708. 0,
  123709. 2,
  123710. };
  123711. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123712. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123713. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123714. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123715. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123716. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123717. 7,
  123718. };
  123719. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123720. -157.5, 157.5,
  123721. };
  123722. static long _vq_quantmap__16c0_s_p9_0[] = {
  123723. 1, 0, 2,
  123724. };
  123725. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123726. _vq_quantthresh__16c0_s_p9_0,
  123727. _vq_quantmap__16c0_s_p9_0,
  123728. 3,
  123729. 3
  123730. };
  123731. static static_codebook _16c0_s_p9_0 = {
  123732. 4, 81,
  123733. _vq_lengthlist__16c0_s_p9_0,
  123734. 1, -518803456, 1628680192, 2, 0,
  123735. _vq_quantlist__16c0_s_p9_0,
  123736. NULL,
  123737. &_vq_auxt__16c0_s_p9_0,
  123738. NULL,
  123739. 0
  123740. };
  123741. static long _vq_quantlist__16c0_s_p9_1[] = {
  123742. 7,
  123743. 6,
  123744. 8,
  123745. 5,
  123746. 9,
  123747. 4,
  123748. 10,
  123749. 3,
  123750. 11,
  123751. 2,
  123752. 12,
  123753. 1,
  123754. 13,
  123755. 0,
  123756. 14,
  123757. };
  123758. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123759. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123760. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123761. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123762. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123763. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123764. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123765. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123766. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123767. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123768. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123769. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123770. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123771. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123772. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123773. 10,
  123774. };
  123775. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123776. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123777. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123778. };
  123779. static long _vq_quantmap__16c0_s_p9_1[] = {
  123780. 13, 11, 9, 7, 5, 3, 1, 0,
  123781. 2, 4, 6, 8, 10, 12, 14,
  123782. };
  123783. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123784. _vq_quantthresh__16c0_s_p9_1,
  123785. _vq_quantmap__16c0_s_p9_1,
  123786. 15,
  123787. 15
  123788. };
  123789. static static_codebook _16c0_s_p9_1 = {
  123790. 2, 225,
  123791. _vq_lengthlist__16c0_s_p9_1,
  123792. 1, -520986624, 1620377600, 4, 0,
  123793. _vq_quantlist__16c0_s_p9_1,
  123794. NULL,
  123795. &_vq_auxt__16c0_s_p9_1,
  123796. NULL,
  123797. 0
  123798. };
  123799. static long _vq_quantlist__16c0_s_p9_2[] = {
  123800. 10,
  123801. 9,
  123802. 11,
  123803. 8,
  123804. 12,
  123805. 7,
  123806. 13,
  123807. 6,
  123808. 14,
  123809. 5,
  123810. 15,
  123811. 4,
  123812. 16,
  123813. 3,
  123814. 17,
  123815. 2,
  123816. 18,
  123817. 1,
  123818. 19,
  123819. 0,
  123820. 20,
  123821. };
  123822. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123823. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123824. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123825. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123826. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123827. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123828. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123829. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123830. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123831. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123832. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123833. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123834. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123835. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123836. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123837. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123838. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123839. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123840. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123841. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123842. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123843. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123844. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123845. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123846. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123847. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123848. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123849. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123850. 10,11,10,10,11, 9,10,10,10,
  123851. };
  123852. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123853. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123854. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123855. 6.5, 7.5, 8.5, 9.5,
  123856. };
  123857. static long _vq_quantmap__16c0_s_p9_2[] = {
  123858. 19, 17, 15, 13, 11, 9, 7, 5,
  123859. 3, 1, 0, 2, 4, 6, 8, 10,
  123860. 12, 14, 16, 18, 20,
  123861. };
  123862. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123863. _vq_quantthresh__16c0_s_p9_2,
  123864. _vq_quantmap__16c0_s_p9_2,
  123865. 21,
  123866. 21
  123867. };
  123868. static static_codebook _16c0_s_p9_2 = {
  123869. 2, 441,
  123870. _vq_lengthlist__16c0_s_p9_2,
  123871. 1, -529268736, 1611661312, 5, 0,
  123872. _vq_quantlist__16c0_s_p9_2,
  123873. NULL,
  123874. &_vq_auxt__16c0_s_p9_2,
  123875. NULL,
  123876. 0
  123877. };
  123878. static long _huff_lengthlist__16c0_s_single[] = {
  123879. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123880. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123881. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123882. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123883. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123884. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123885. 16,16,18,18,
  123886. };
  123887. static static_codebook _huff_book__16c0_s_single = {
  123888. 2, 100,
  123889. _huff_lengthlist__16c0_s_single,
  123890. 0, 0, 0, 0, 0,
  123891. NULL,
  123892. NULL,
  123893. NULL,
  123894. NULL,
  123895. 0
  123896. };
  123897. static long _huff_lengthlist__16c1_s_long[] = {
  123898. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123899. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123900. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123901. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123902. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123903. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123904. 12,11,11,13,
  123905. };
  123906. static static_codebook _huff_book__16c1_s_long = {
  123907. 2, 100,
  123908. _huff_lengthlist__16c1_s_long,
  123909. 0, 0, 0, 0, 0,
  123910. NULL,
  123911. NULL,
  123912. NULL,
  123913. NULL,
  123914. 0
  123915. };
  123916. static long _vq_quantlist__16c1_s_p1_0[] = {
  123917. 1,
  123918. 0,
  123919. 2,
  123920. };
  123921. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123922. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123923. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123928. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123933. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123968. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123973. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123978. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124014. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  124019. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  124024. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0,
  124333. };
  124334. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124335. -0.5, 0.5,
  124336. };
  124337. static long _vq_quantmap__16c1_s_p1_0[] = {
  124338. 1, 0, 2,
  124339. };
  124340. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124341. _vq_quantthresh__16c1_s_p1_0,
  124342. _vq_quantmap__16c1_s_p1_0,
  124343. 3,
  124344. 3
  124345. };
  124346. static static_codebook _16c1_s_p1_0 = {
  124347. 8, 6561,
  124348. _vq_lengthlist__16c1_s_p1_0,
  124349. 1, -535822336, 1611661312, 2, 0,
  124350. _vq_quantlist__16c1_s_p1_0,
  124351. NULL,
  124352. &_vq_auxt__16c1_s_p1_0,
  124353. NULL,
  124354. 0
  124355. };
  124356. static long _vq_quantlist__16c1_s_p2_0[] = {
  124357. 2,
  124358. 1,
  124359. 3,
  124360. 0,
  124361. 4,
  124362. };
  124363. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0,
  124404. };
  124405. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124406. -1.5, -0.5, 0.5, 1.5,
  124407. };
  124408. static long _vq_quantmap__16c1_s_p2_0[] = {
  124409. 3, 1, 0, 2, 4,
  124410. };
  124411. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124412. _vq_quantthresh__16c1_s_p2_0,
  124413. _vq_quantmap__16c1_s_p2_0,
  124414. 5,
  124415. 5
  124416. };
  124417. static static_codebook _16c1_s_p2_0 = {
  124418. 4, 625,
  124419. _vq_lengthlist__16c1_s_p2_0,
  124420. 1, -533725184, 1611661312, 3, 0,
  124421. _vq_quantlist__16c1_s_p2_0,
  124422. NULL,
  124423. &_vq_auxt__16c1_s_p2_0,
  124424. NULL,
  124425. 0
  124426. };
  124427. static long _vq_quantlist__16c1_s_p3_0[] = {
  124428. 2,
  124429. 1,
  124430. 3,
  124431. 0,
  124432. 4,
  124433. };
  124434. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124435. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124438. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124441. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124474. 0,
  124475. };
  124476. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124477. -1.5, -0.5, 0.5, 1.5,
  124478. };
  124479. static long _vq_quantmap__16c1_s_p3_0[] = {
  124480. 3, 1, 0, 2, 4,
  124481. };
  124482. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124483. _vq_quantthresh__16c1_s_p3_0,
  124484. _vq_quantmap__16c1_s_p3_0,
  124485. 5,
  124486. 5
  124487. };
  124488. static static_codebook _16c1_s_p3_0 = {
  124489. 4, 625,
  124490. _vq_lengthlist__16c1_s_p3_0,
  124491. 1, -533725184, 1611661312, 3, 0,
  124492. _vq_quantlist__16c1_s_p3_0,
  124493. NULL,
  124494. &_vq_auxt__16c1_s_p3_0,
  124495. NULL,
  124496. 0
  124497. };
  124498. static long _vq_quantlist__16c1_s_p4_0[] = {
  124499. 4,
  124500. 3,
  124501. 5,
  124502. 2,
  124503. 6,
  124504. 1,
  124505. 7,
  124506. 0,
  124507. 8,
  124508. };
  124509. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124510. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124511. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124512. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124513. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124514. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124515. 0,
  124516. };
  124517. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124518. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124519. };
  124520. static long _vq_quantmap__16c1_s_p4_0[] = {
  124521. 7, 5, 3, 1, 0, 2, 4, 6,
  124522. 8,
  124523. };
  124524. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124525. _vq_quantthresh__16c1_s_p4_0,
  124526. _vq_quantmap__16c1_s_p4_0,
  124527. 9,
  124528. 9
  124529. };
  124530. static static_codebook _16c1_s_p4_0 = {
  124531. 2, 81,
  124532. _vq_lengthlist__16c1_s_p4_0,
  124533. 1, -531628032, 1611661312, 4, 0,
  124534. _vq_quantlist__16c1_s_p4_0,
  124535. NULL,
  124536. &_vq_auxt__16c1_s_p4_0,
  124537. NULL,
  124538. 0
  124539. };
  124540. static long _vq_quantlist__16c1_s_p5_0[] = {
  124541. 4,
  124542. 3,
  124543. 5,
  124544. 2,
  124545. 6,
  124546. 1,
  124547. 7,
  124548. 0,
  124549. 8,
  124550. };
  124551. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124552. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124553. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124554. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124555. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124556. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124557. 10,
  124558. };
  124559. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124560. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124561. };
  124562. static long _vq_quantmap__16c1_s_p5_0[] = {
  124563. 7, 5, 3, 1, 0, 2, 4, 6,
  124564. 8,
  124565. };
  124566. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124567. _vq_quantthresh__16c1_s_p5_0,
  124568. _vq_quantmap__16c1_s_p5_0,
  124569. 9,
  124570. 9
  124571. };
  124572. static static_codebook _16c1_s_p5_0 = {
  124573. 2, 81,
  124574. _vq_lengthlist__16c1_s_p5_0,
  124575. 1, -531628032, 1611661312, 4, 0,
  124576. _vq_quantlist__16c1_s_p5_0,
  124577. NULL,
  124578. &_vq_auxt__16c1_s_p5_0,
  124579. NULL,
  124580. 0
  124581. };
  124582. static long _vq_quantlist__16c1_s_p6_0[] = {
  124583. 8,
  124584. 7,
  124585. 9,
  124586. 6,
  124587. 10,
  124588. 5,
  124589. 11,
  124590. 4,
  124591. 12,
  124592. 3,
  124593. 13,
  124594. 2,
  124595. 14,
  124596. 1,
  124597. 15,
  124598. 0,
  124599. 16,
  124600. };
  124601. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124602. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124603. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124604. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124605. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124606. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124607. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124608. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124609. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124610. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124611. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124612. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124613. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124614. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124615. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124616. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124617. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124618. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124619. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124620. 14,
  124621. };
  124622. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124623. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124624. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124625. };
  124626. static long _vq_quantmap__16c1_s_p6_0[] = {
  124627. 15, 13, 11, 9, 7, 5, 3, 1,
  124628. 0, 2, 4, 6, 8, 10, 12, 14,
  124629. 16,
  124630. };
  124631. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124632. _vq_quantthresh__16c1_s_p6_0,
  124633. _vq_quantmap__16c1_s_p6_0,
  124634. 17,
  124635. 17
  124636. };
  124637. static static_codebook _16c1_s_p6_0 = {
  124638. 2, 289,
  124639. _vq_lengthlist__16c1_s_p6_0,
  124640. 1, -529530880, 1611661312, 5, 0,
  124641. _vq_quantlist__16c1_s_p6_0,
  124642. NULL,
  124643. &_vq_auxt__16c1_s_p6_0,
  124644. NULL,
  124645. 0
  124646. };
  124647. static long _vq_quantlist__16c1_s_p7_0[] = {
  124648. 1,
  124649. 0,
  124650. 2,
  124651. };
  124652. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124653. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124654. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124655. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124656. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124657. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124658. 11,
  124659. };
  124660. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124661. -5.5, 5.5,
  124662. };
  124663. static long _vq_quantmap__16c1_s_p7_0[] = {
  124664. 1, 0, 2,
  124665. };
  124666. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124667. _vq_quantthresh__16c1_s_p7_0,
  124668. _vq_quantmap__16c1_s_p7_0,
  124669. 3,
  124670. 3
  124671. };
  124672. static static_codebook _16c1_s_p7_0 = {
  124673. 4, 81,
  124674. _vq_lengthlist__16c1_s_p7_0,
  124675. 1, -529137664, 1618345984, 2, 0,
  124676. _vq_quantlist__16c1_s_p7_0,
  124677. NULL,
  124678. &_vq_auxt__16c1_s_p7_0,
  124679. NULL,
  124680. 0
  124681. };
  124682. static long _vq_quantlist__16c1_s_p7_1[] = {
  124683. 5,
  124684. 4,
  124685. 6,
  124686. 3,
  124687. 7,
  124688. 2,
  124689. 8,
  124690. 1,
  124691. 9,
  124692. 0,
  124693. 10,
  124694. };
  124695. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124696. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124697. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124698. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124699. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124700. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124701. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124702. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124703. 10,10,10, 8, 8, 8, 8, 9, 9,
  124704. };
  124705. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124706. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124707. 3.5, 4.5,
  124708. };
  124709. static long _vq_quantmap__16c1_s_p7_1[] = {
  124710. 9, 7, 5, 3, 1, 0, 2, 4,
  124711. 6, 8, 10,
  124712. };
  124713. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124714. _vq_quantthresh__16c1_s_p7_1,
  124715. _vq_quantmap__16c1_s_p7_1,
  124716. 11,
  124717. 11
  124718. };
  124719. static static_codebook _16c1_s_p7_1 = {
  124720. 2, 121,
  124721. _vq_lengthlist__16c1_s_p7_1,
  124722. 1, -531365888, 1611661312, 4, 0,
  124723. _vq_quantlist__16c1_s_p7_1,
  124724. NULL,
  124725. &_vq_auxt__16c1_s_p7_1,
  124726. NULL,
  124727. 0
  124728. };
  124729. static long _vq_quantlist__16c1_s_p8_0[] = {
  124730. 6,
  124731. 5,
  124732. 7,
  124733. 4,
  124734. 8,
  124735. 3,
  124736. 9,
  124737. 2,
  124738. 10,
  124739. 1,
  124740. 11,
  124741. 0,
  124742. 12,
  124743. };
  124744. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124745. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124746. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124747. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124748. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124749. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124750. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124751. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124752. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124753. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124754. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124755. 0,12,12,12,12,13,13,14,15,
  124756. };
  124757. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124758. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124759. 12.5, 17.5, 22.5, 27.5,
  124760. };
  124761. static long _vq_quantmap__16c1_s_p8_0[] = {
  124762. 11, 9, 7, 5, 3, 1, 0, 2,
  124763. 4, 6, 8, 10, 12,
  124764. };
  124765. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124766. _vq_quantthresh__16c1_s_p8_0,
  124767. _vq_quantmap__16c1_s_p8_0,
  124768. 13,
  124769. 13
  124770. };
  124771. static static_codebook _16c1_s_p8_0 = {
  124772. 2, 169,
  124773. _vq_lengthlist__16c1_s_p8_0,
  124774. 1, -526516224, 1616117760, 4, 0,
  124775. _vq_quantlist__16c1_s_p8_0,
  124776. NULL,
  124777. &_vq_auxt__16c1_s_p8_0,
  124778. NULL,
  124779. 0
  124780. };
  124781. static long _vq_quantlist__16c1_s_p8_1[] = {
  124782. 2,
  124783. 1,
  124784. 3,
  124785. 0,
  124786. 4,
  124787. };
  124788. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124789. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124790. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124791. };
  124792. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124793. -1.5, -0.5, 0.5, 1.5,
  124794. };
  124795. static long _vq_quantmap__16c1_s_p8_1[] = {
  124796. 3, 1, 0, 2, 4,
  124797. };
  124798. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124799. _vq_quantthresh__16c1_s_p8_1,
  124800. _vq_quantmap__16c1_s_p8_1,
  124801. 5,
  124802. 5
  124803. };
  124804. static static_codebook _16c1_s_p8_1 = {
  124805. 2, 25,
  124806. _vq_lengthlist__16c1_s_p8_1,
  124807. 1, -533725184, 1611661312, 3, 0,
  124808. _vq_quantlist__16c1_s_p8_1,
  124809. NULL,
  124810. &_vq_auxt__16c1_s_p8_1,
  124811. NULL,
  124812. 0
  124813. };
  124814. static long _vq_quantlist__16c1_s_p9_0[] = {
  124815. 6,
  124816. 5,
  124817. 7,
  124818. 4,
  124819. 8,
  124820. 3,
  124821. 9,
  124822. 2,
  124823. 10,
  124824. 1,
  124825. 11,
  124826. 0,
  124827. 12,
  124828. };
  124829. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124830. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124831. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124832. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124833. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124834. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124835. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124836. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124837. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124838. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124839. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124840. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124841. };
  124842. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124843. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124844. 787.5, 1102.5, 1417.5, 1732.5,
  124845. };
  124846. static long _vq_quantmap__16c1_s_p9_0[] = {
  124847. 11, 9, 7, 5, 3, 1, 0, 2,
  124848. 4, 6, 8, 10, 12,
  124849. };
  124850. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124851. _vq_quantthresh__16c1_s_p9_0,
  124852. _vq_quantmap__16c1_s_p9_0,
  124853. 13,
  124854. 13
  124855. };
  124856. static static_codebook _16c1_s_p9_0 = {
  124857. 2, 169,
  124858. _vq_lengthlist__16c1_s_p9_0,
  124859. 1, -513964032, 1628680192, 4, 0,
  124860. _vq_quantlist__16c1_s_p9_0,
  124861. NULL,
  124862. &_vq_auxt__16c1_s_p9_0,
  124863. NULL,
  124864. 0
  124865. };
  124866. static long _vq_quantlist__16c1_s_p9_1[] = {
  124867. 7,
  124868. 6,
  124869. 8,
  124870. 5,
  124871. 9,
  124872. 4,
  124873. 10,
  124874. 3,
  124875. 11,
  124876. 2,
  124877. 12,
  124878. 1,
  124879. 13,
  124880. 0,
  124881. 14,
  124882. };
  124883. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124884. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124885. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124886. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124887. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124888. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124889. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124890. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124891. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124892. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124893. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124894. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124895. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124896. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124897. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124898. 13,
  124899. };
  124900. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124901. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124902. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124903. };
  124904. static long _vq_quantmap__16c1_s_p9_1[] = {
  124905. 13, 11, 9, 7, 5, 3, 1, 0,
  124906. 2, 4, 6, 8, 10, 12, 14,
  124907. };
  124908. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124909. _vq_quantthresh__16c1_s_p9_1,
  124910. _vq_quantmap__16c1_s_p9_1,
  124911. 15,
  124912. 15
  124913. };
  124914. static static_codebook _16c1_s_p9_1 = {
  124915. 2, 225,
  124916. _vq_lengthlist__16c1_s_p9_1,
  124917. 1, -520986624, 1620377600, 4, 0,
  124918. _vq_quantlist__16c1_s_p9_1,
  124919. NULL,
  124920. &_vq_auxt__16c1_s_p9_1,
  124921. NULL,
  124922. 0
  124923. };
  124924. static long _vq_quantlist__16c1_s_p9_2[] = {
  124925. 10,
  124926. 9,
  124927. 11,
  124928. 8,
  124929. 12,
  124930. 7,
  124931. 13,
  124932. 6,
  124933. 14,
  124934. 5,
  124935. 15,
  124936. 4,
  124937. 16,
  124938. 3,
  124939. 17,
  124940. 2,
  124941. 18,
  124942. 1,
  124943. 19,
  124944. 0,
  124945. 20,
  124946. };
  124947. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124948. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124949. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124950. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124951. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124952. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124953. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124954. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124955. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124956. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124957. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124958. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124959. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124960. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124961. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124962. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124963. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124964. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124965. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124966. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124967. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124968. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124969. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124970. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124971. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124972. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124973. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124974. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124975. 11,11,11,11,12,11,11,12,11,
  124976. };
  124977. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124978. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124979. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124980. 6.5, 7.5, 8.5, 9.5,
  124981. };
  124982. static long _vq_quantmap__16c1_s_p9_2[] = {
  124983. 19, 17, 15, 13, 11, 9, 7, 5,
  124984. 3, 1, 0, 2, 4, 6, 8, 10,
  124985. 12, 14, 16, 18, 20,
  124986. };
  124987. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124988. _vq_quantthresh__16c1_s_p9_2,
  124989. _vq_quantmap__16c1_s_p9_2,
  124990. 21,
  124991. 21
  124992. };
  124993. static static_codebook _16c1_s_p9_2 = {
  124994. 2, 441,
  124995. _vq_lengthlist__16c1_s_p9_2,
  124996. 1, -529268736, 1611661312, 5, 0,
  124997. _vq_quantlist__16c1_s_p9_2,
  124998. NULL,
  124999. &_vq_auxt__16c1_s_p9_2,
  125000. NULL,
  125001. 0
  125002. };
  125003. static long _huff_lengthlist__16c1_s_short[] = {
  125004. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  125005. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  125006. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  125007. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  125008. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  125009. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  125010. 9, 9,10,13,
  125011. };
  125012. static static_codebook _huff_book__16c1_s_short = {
  125013. 2, 100,
  125014. _huff_lengthlist__16c1_s_short,
  125015. 0, 0, 0, 0, 0,
  125016. NULL,
  125017. NULL,
  125018. NULL,
  125019. NULL,
  125020. 0
  125021. };
  125022. static long _huff_lengthlist__16c2_s_long[] = {
  125023. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  125024. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  125025. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  125026. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  125027. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  125028. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  125029. 14,14,16,18,
  125030. };
  125031. static static_codebook _huff_book__16c2_s_long = {
  125032. 2, 100,
  125033. _huff_lengthlist__16c2_s_long,
  125034. 0, 0, 0, 0, 0,
  125035. NULL,
  125036. NULL,
  125037. NULL,
  125038. NULL,
  125039. 0
  125040. };
  125041. static long _vq_quantlist__16c2_s_p1_0[] = {
  125042. 1,
  125043. 0,
  125044. 2,
  125045. };
  125046. static long _vq_lengthlist__16c2_s_p1_0[] = {
  125047. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  125048. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125052. 0,
  125053. };
  125054. static float _vq_quantthresh__16c2_s_p1_0[] = {
  125055. -0.5, 0.5,
  125056. };
  125057. static long _vq_quantmap__16c2_s_p1_0[] = {
  125058. 1, 0, 2,
  125059. };
  125060. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  125061. _vq_quantthresh__16c2_s_p1_0,
  125062. _vq_quantmap__16c2_s_p1_0,
  125063. 3,
  125064. 3
  125065. };
  125066. static static_codebook _16c2_s_p1_0 = {
  125067. 4, 81,
  125068. _vq_lengthlist__16c2_s_p1_0,
  125069. 1, -535822336, 1611661312, 2, 0,
  125070. _vq_quantlist__16c2_s_p1_0,
  125071. NULL,
  125072. &_vq_auxt__16c2_s_p1_0,
  125073. NULL,
  125074. 0
  125075. };
  125076. static long _vq_quantlist__16c2_s_p2_0[] = {
  125077. 2,
  125078. 1,
  125079. 3,
  125080. 0,
  125081. 4,
  125082. };
  125083. static long _vq_lengthlist__16c2_s_p2_0[] = {
  125084. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  125085. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  125086. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  125087. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  125088. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  125089. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  125090. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  125091. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  125092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  125097. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  125098. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  125099. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  125105. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  125106. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  125107. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125112. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  125113. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  125114. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  125115. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  125120. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  125121. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  125122. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  125123. 13,
  125124. };
  125125. static float _vq_quantthresh__16c2_s_p2_0[] = {
  125126. -1.5, -0.5, 0.5, 1.5,
  125127. };
  125128. static long _vq_quantmap__16c2_s_p2_0[] = {
  125129. 3, 1, 0, 2, 4,
  125130. };
  125131. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  125132. _vq_quantthresh__16c2_s_p2_0,
  125133. _vq_quantmap__16c2_s_p2_0,
  125134. 5,
  125135. 5
  125136. };
  125137. static static_codebook _16c2_s_p2_0 = {
  125138. 4, 625,
  125139. _vq_lengthlist__16c2_s_p2_0,
  125140. 1, -533725184, 1611661312, 3, 0,
  125141. _vq_quantlist__16c2_s_p2_0,
  125142. NULL,
  125143. &_vq_auxt__16c2_s_p2_0,
  125144. NULL,
  125145. 0
  125146. };
  125147. static long _vq_quantlist__16c2_s_p3_0[] = {
  125148. 4,
  125149. 3,
  125150. 5,
  125151. 2,
  125152. 6,
  125153. 1,
  125154. 7,
  125155. 0,
  125156. 8,
  125157. };
  125158. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125159. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125160. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125161. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125162. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125164. 0,
  125165. };
  125166. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125167. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125168. };
  125169. static long _vq_quantmap__16c2_s_p3_0[] = {
  125170. 7, 5, 3, 1, 0, 2, 4, 6,
  125171. 8,
  125172. };
  125173. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125174. _vq_quantthresh__16c2_s_p3_0,
  125175. _vq_quantmap__16c2_s_p3_0,
  125176. 9,
  125177. 9
  125178. };
  125179. static static_codebook _16c2_s_p3_0 = {
  125180. 2, 81,
  125181. _vq_lengthlist__16c2_s_p3_0,
  125182. 1, -531628032, 1611661312, 4, 0,
  125183. _vq_quantlist__16c2_s_p3_0,
  125184. NULL,
  125185. &_vq_auxt__16c2_s_p3_0,
  125186. NULL,
  125187. 0
  125188. };
  125189. static long _vq_quantlist__16c2_s_p4_0[] = {
  125190. 8,
  125191. 7,
  125192. 9,
  125193. 6,
  125194. 10,
  125195. 5,
  125196. 11,
  125197. 4,
  125198. 12,
  125199. 3,
  125200. 13,
  125201. 2,
  125202. 14,
  125203. 1,
  125204. 15,
  125205. 0,
  125206. 16,
  125207. };
  125208. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125209. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125210. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125211. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125212. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125213. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125214. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125215. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125216. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125217. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125218. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125227. 0,
  125228. };
  125229. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125230. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125231. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125232. };
  125233. static long _vq_quantmap__16c2_s_p4_0[] = {
  125234. 15, 13, 11, 9, 7, 5, 3, 1,
  125235. 0, 2, 4, 6, 8, 10, 12, 14,
  125236. 16,
  125237. };
  125238. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125239. _vq_quantthresh__16c2_s_p4_0,
  125240. _vq_quantmap__16c2_s_p4_0,
  125241. 17,
  125242. 17
  125243. };
  125244. static static_codebook _16c2_s_p4_0 = {
  125245. 2, 289,
  125246. _vq_lengthlist__16c2_s_p4_0,
  125247. 1, -529530880, 1611661312, 5, 0,
  125248. _vq_quantlist__16c2_s_p4_0,
  125249. NULL,
  125250. &_vq_auxt__16c2_s_p4_0,
  125251. NULL,
  125252. 0
  125253. };
  125254. static long _vq_quantlist__16c2_s_p5_0[] = {
  125255. 1,
  125256. 0,
  125257. 2,
  125258. };
  125259. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125260. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125261. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125262. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125263. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125264. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125265. 12,
  125266. };
  125267. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125268. -5.5, 5.5,
  125269. };
  125270. static long _vq_quantmap__16c2_s_p5_0[] = {
  125271. 1, 0, 2,
  125272. };
  125273. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125274. _vq_quantthresh__16c2_s_p5_0,
  125275. _vq_quantmap__16c2_s_p5_0,
  125276. 3,
  125277. 3
  125278. };
  125279. static static_codebook _16c2_s_p5_0 = {
  125280. 4, 81,
  125281. _vq_lengthlist__16c2_s_p5_0,
  125282. 1, -529137664, 1618345984, 2, 0,
  125283. _vq_quantlist__16c2_s_p5_0,
  125284. NULL,
  125285. &_vq_auxt__16c2_s_p5_0,
  125286. NULL,
  125287. 0
  125288. };
  125289. static long _vq_quantlist__16c2_s_p5_1[] = {
  125290. 5,
  125291. 4,
  125292. 6,
  125293. 3,
  125294. 7,
  125295. 2,
  125296. 8,
  125297. 1,
  125298. 9,
  125299. 0,
  125300. 10,
  125301. };
  125302. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125303. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125304. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125305. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125306. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125307. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125308. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125309. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125310. 11,11,11, 7, 7, 8, 8, 8, 8,
  125311. };
  125312. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125313. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125314. 3.5, 4.5,
  125315. };
  125316. static long _vq_quantmap__16c2_s_p5_1[] = {
  125317. 9, 7, 5, 3, 1, 0, 2, 4,
  125318. 6, 8, 10,
  125319. };
  125320. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125321. _vq_quantthresh__16c2_s_p5_1,
  125322. _vq_quantmap__16c2_s_p5_1,
  125323. 11,
  125324. 11
  125325. };
  125326. static static_codebook _16c2_s_p5_1 = {
  125327. 2, 121,
  125328. _vq_lengthlist__16c2_s_p5_1,
  125329. 1, -531365888, 1611661312, 4, 0,
  125330. _vq_quantlist__16c2_s_p5_1,
  125331. NULL,
  125332. &_vq_auxt__16c2_s_p5_1,
  125333. NULL,
  125334. 0
  125335. };
  125336. static long _vq_quantlist__16c2_s_p6_0[] = {
  125337. 6,
  125338. 5,
  125339. 7,
  125340. 4,
  125341. 8,
  125342. 3,
  125343. 9,
  125344. 2,
  125345. 10,
  125346. 1,
  125347. 11,
  125348. 0,
  125349. 12,
  125350. };
  125351. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125352. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125353. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125354. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125355. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125356. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125357. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125358. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. };
  125364. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125365. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125366. 12.5, 17.5, 22.5, 27.5,
  125367. };
  125368. static long _vq_quantmap__16c2_s_p6_0[] = {
  125369. 11, 9, 7, 5, 3, 1, 0, 2,
  125370. 4, 6, 8, 10, 12,
  125371. };
  125372. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125373. _vq_quantthresh__16c2_s_p6_0,
  125374. _vq_quantmap__16c2_s_p6_0,
  125375. 13,
  125376. 13
  125377. };
  125378. static static_codebook _16c2_s_p6_0 = {
  125379. 2, 169,
  125380. _vq_lengthlist__16c2_s_p6_0,
  125381. 1, -526516224, 1616117760, 4, 0,
  125382. _vq_quantlist__16c2_s_p6_0,
  125383. NULL,
  125384. &_vq_auxt__16c2_s_p6_0,
  125385. NULL,
  125386. 0
  125387. };
  125388. static long _vq_quantlist__16c2_s_p6_1[] = {
  125389. 2,
  125390. 1,
  125391. 3,
  125392. 0,
  125393. 4,
  125394. };
  125395. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125396. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125397. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125398. };
  125399. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125400. -1.5, -0.5, 0.5, 1.5,
  125401. };
  125402. static long _vq_quantmap__16c2_s_p6_1[] = {
  125403. 3, 1, 0, 2, 4,
  125404. };
  125405. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125406. _vq_quantthresh__16c2_s_p6_1,
  125407. _vq_quantmap__16c2_s_p6_1,
  125408. 5,
  125409. 5
  125410. };
  125411. static static_codebook _16c2_s_p6_1 = {
  125412. 2, 25,
  125413. _vq_lengthlist__16c2_s_p6_1,
  125414. 1, -533725184, 1611661312, 3, 0,
  125415. _vq_quantlist__16c2_s_p6_1,
  125416. NULL,
  125417. &_vq_auxt__16c2_s_p6_1,
  125418. NULL,
  125419. 0
  125420. };
  125421. static long _vq_quantlist__16c2_s_p7_0[] = {
  125422. 6,
  125423. 5,
  125424. 7,
  125425. 4,
  125426. 8,
  125427. 3,
  125428. 9,
  125429. 2,
  125430. 10,
  125431. 1,
  125432. 11,
  125433. 0,
  125434. 12,
  125435. };
  125436. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125437. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125438. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125439. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125440. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125441. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125442. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125443. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125444. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125445. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125446. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125447. 18,13,14,13,13,14,13,15,14,
  125448. };
  125449. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125450. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125451. 27.5, 38.5, 49.5, 60.5,
  125452. };
  125453. static long _vq_quantmap__16c2_s_p7_0[] = {
  125454. 11, 9, 7, 5, 3, 1, 0, 2,
  125455. 4, 6, 8, 10, 12,
  125456. };
  125457. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125458. _vq_quantthresh__16c2_s_p7_0,
  125459. _vq_quantmap__16c2_s_p7_0,
  125460. 13,
  125461. 13
  125462. };
  125463. static static_codebook _16c2_s_p7_0 = {
  125464. 2, 169,
  125465. _vq_lengthlist__16c2_s_p7_0,
  125466. 1, -523206656, 1618345984, 4, 0,
  125467. _vq_quantlist__16c2_s_p7_0,
  125468. NULL,
  125469. &_vq_auxt__16c2_s_p7_0,
  125470. NULL,
  125471. 0
  125472. };
  125473. static long _vq_quantlist__16c2_s_p7_1[] = {
  125474. 5,
  125475. 4,
  125476. 6,
  125477. 3,
  125478. 7,
  125479. 2,
  125480. 8,
  125481. 1,
  125482. 9,
  125483. 0,
  125484. 10,
  125485. };
  125486. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125487. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125488. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125489. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125490. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125491. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125492. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125493. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125494. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125495. };
  125496. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125497. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125498. 3.5, 4.5,
  125499. };
  125500. static long _vq_quantmap__16c2_s_p7_1[] = {
  125501. 9, 7, 5, 3, 1, 0, 2, 4,
  125502. 6, 8, 10,
  125503. };
  125504. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125505. _vq_quantthresh__16c2_s_p7_1,
  125506. _vq_quantmap__16c2_s_p7_1,
  125507. 11,
  125508. 11
  125509. };
  125510. static static_codebook _16c2_s_p7_1 = {
  125511. 2, 121,
  125512. _vq_lengthlist__16c2_s_p7_1,
  125513. 1, -531365888, 1611661312, 4, 0,
  125514. _vq_quantlist__16c2_s_p7_1,
  125515. NULL,
  125516. &_vq_auxt__16c2_s_p7_1,
  125517. NULL,
  125518. 0
  125519. };
  125520. static long _vq_quantlist__16c2_s_p8_0[] = {
  125521. 7,
  125522. 6,
  125523. 8,
  125524. 5,
  125525. 9,
  125526. 4,
  125527. 10,
  125528. 3,
  125529. 11,
  125530. 2,
  125531. 12,
  125532. 1,
  125533. 13,
  125534. 0,
  125535. 14,
  125536. };
  125537. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125538. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125539. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125540. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125541. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125542. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125543. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125544. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125545. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125546. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125547. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125548. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125549. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125550. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125551. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125552. 13,
  125553. };
  125554. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125555. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125556. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125557. };
  125558. static long _vq_quantmap__16c2_s_p8_0[] = {
  125559. 13, 11, 9, 7, 5, 3, 1, 0,
  125560. 2, 4, 6, 8, 10, 12, 14,
  125561. };
  125562. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125563. _vq_quantthresh__16c2_s_p8_0,
  125564. _vq_quantmap__16c2_s_p8_0,
  125565. 15,
  125566. 15
  125567. };
  125568. static static_codebook _16c2_s_p8_0 = {
  125569. 2, 225,
  125570. _vq_lengthlist__16c2_s_p8_0,
  125571. 1, -520986624, 1620377600, 4, 0,
  125572. _vq_quantlist__16c2_s_p8_0,
  125573. NULL,
  125574. &_vq_auxt__16c2_s_p8_0,
  125575. NULL,
  125576. 0
  125577. };
  125578. static long _vq_quantlist__16c2_s_p8_1[] = {
  125579. 10,
  125580. 9,
  125581. 11,
  125582. 8,
  125583. 12,
  125584. 7,
  125585. 13,
  125586. 6,
  125587. 14,
  125588. 5,
  125589. 15,
  125590. 4,
  125591. 16,
  125592. 3,
  125593. 17,
  125594. 2,
  125595. 18,
  125596. 1,
  125597. 19,
  125598. 0,
  125599. 20,
  125600. };
  125601. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125602. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125603. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125604. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125605. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125606. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125607. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125608. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125609. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125610. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125611. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125612. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125613. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125614. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125615. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125616. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125617. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125618. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125619. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125620. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125621. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125622. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125623. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125624. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125625. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125626. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125627. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125628. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125629. 10,11,10,10,10,10,10,10,10,
  125630. };
  125631. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125632. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125633. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125634. 6.5, 7.5, 8.5, 9.5,
  125635. };
  125636. static long _vq_quantmap__16c2_s_p8_1[] = {
  125637. 19, 17, 15, 13, 11, 9, 7, 5,
  125638. 3, 1, 0, 2, 4, 6, 8, 10,
  125639. 12, 14, 16, 18, 20,
  125640. };
  125641. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125642. _vq_quantthresh__16c2_s_p8_1,
  125643. _vq_quantmap__16c2_s_p8_1,
  125644. 21,
  125645. 21
  125646. };
  125647. static static_codebook _16c2_s_p8_1 = {
  125648. 2, 441,
  125649. _vq_lengthlist__16c2_s_p8_1,
  125650. 1, -529268736, 1611661312, 5, 0,
  125651. _vq_quantlist__16c2_s_p8_1,
  125652. NULL,
  125653. &_vq_auxt__16c2_s_p8_1,
  125654. NULL,
  125655. 0
  125656. };
  125657. static long _vq_quantlist__16c2_s_p9_0[] = {
  125658. 6,
  125659. 5,
  125660. 7,
  125661. 4,
  125662. 8,
  125663. 3,
  125664. 9,
  125665. 2,
  125666. 10,
  125667. 1,
  125668. 11,
  125669. 0,
  125670. 12,
  125671. };
  125672. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125673. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125674. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125675. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125676. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125677. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125678. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125679. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125680. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125681. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125682. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125683. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125684. };
  125685. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125686. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125687. 2327.5, 3258.5, 4189.5, 5120.5,
  125688. };
  125689. static long _vq_quantmap__16c2_s_p9_0[] = {
  125690. 11, 9, 7, 5, 3, 1, 0, 2,
  125691. 4, 6, 8, 10, 12,
  125692. };
  125693. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125694. _vq_quantthresh__16c2_s_p9_0,
  125695. _vq_quantmap__16c2_s_p9_0,
  125696. 13,
  125697. 13
  125698. };
  125699. static static_codebook _16c2_s_p9_0 = {
  125700. 2, 169,
  125701. _vq_lengthlist__16c2_s_p9_0,
  125702. 1, -510275072, 1631393792, 4, 0,
  125703. _vq_quantlist__16c2_s_p9_0,
  125704. NULL,
  125705. &_vq_auxt__16c2_s_p9_0,
  125706. NULL,
  125707. 0
  125708. };
  125709. static long _vq_quantlist__16c2_s_p9_1[] = {
  125710. 8,
  125711. 7,
  125712. 9,
  125713. 6,
  125714. 10,
  125715. 5,
  125716. 11,
  125717. 4,
  125718. 12,
  125719. 3,
  125720. 13,
  125721. 2,
  125722. 14,
  125723. 1,
  125724. 15,
  125725. 0,
  125726. 16,
  125727. };
  125728. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125729. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125730. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125731. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125732. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125733. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125734. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125735. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125736. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125737. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125738. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125739. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125740. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125741. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125742. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125743. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125744. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125745. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125746. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125747. 10,
  125748. };
  125749. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125750. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125751. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125752. };
  125753. static long _vq_quantmap__16c2_s_p9_1[] = {
  125754. 15, 13, 11, 9, 7, 5, 3, 1,
  125755. 0, 2, 4, 6, 8, 10, 12, 14,
  125756. 16,
  125757. };
  125758. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125759. _vq_quantthresh__16c2_s_p9_1,
  125760. _vq_quantmap__16c2_s_p9_1,
  125761. 17,
  125762. 17
  125763. };
  125764. static static_codebook _16c2_s_p9_1 = {
  125765. 2, 289,
  125766. _vq_lengthlist__16c2_s_p9_1,
  125767. 1, -518488064, 1622704128, 5, 0,
  125768. _vq_quantlist__16c2_s_p9_1,
  125769. NULL,
  125770. &_vq_auxt__16c2_s_p9_1,
  125771. NULL,
  125772. 0
  125773. };
  125774. static long _vq_quantlist__16c2_s_p9_2[] = {
  125775. 13,
  125776. 12,
  125777. 14,
  125778. 11,
  125779. 15,
  125780. 10,
  125781. 16,
  125782. 9,
  125783. 17,
  125784. 8,
  125785. 18,
  125786. 7,
  125787. 19,
  125788. 6,
  125789. 20,
  125790. 5,
  125791. 21,
  125792. 4,
  125793. 22,
  125794. 3,
  125795. 23,
  125796. 2,
  125797. 24,
  125798. 1,
  125799. 25,
  125800. 0,
  125801. 26,
  125802. };
  125803. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125804. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125805. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125806. };
  125807. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125808. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125809. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125810. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125811. 11.5, 12.5,
  125812. };
  125813. static long _vq_quantmap__16c2_s_p9_2[] = {
  125814. 25, 23, 21, 19, 17, 15, 13, 11,
  125815. 9, 7, 5, 3, 1, 0, 2, 4,
  125816. 6, 8, 10, 12, 14, 16, 18, 20,
  125817. 22, 24, 26,
  125818. };
  125819. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125820. _vq_quantthresh__16c2_s_p9_2,
  125821. _vq_quantmap__16c2_s_p9_2,
  125822. 27,
  125823. 27
  125824. };
  125825. static static_codebook _16c2_s_p9_2 = {
  125826. 1, 27,
  125827. _vq_lengthlist__16c2_s_p9_2,
  125828. 1, -528875520, 1611661312, 5, 0,
  125829. _vq_quantlist__16c2_s_p9_2,
  125830. NULL,
  125831. &_vq_auxt__16c2_s_p9_2,
  125832. NULL,
  125833. 0
  125834. };
  125835. static long _huff_lengthlist__16c2_s_short[] = {
  125836. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125837. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125838. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125839. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125840. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125841. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125842. 15,12,14,14,
  125843. };
  125844. static static_codebook _huff_book__16c2_s_short = {
  125845. 2, 100,
  125846. _huff_lengthlist__16c2_s_short,
  125847. 0, 0, 0, 0, 0,
  125848. NULL,
  125849. NULL,
  125850. NULL,
  125851. NULL,
  125852. 0
  125853. };
  125854. static long _vq_quantlist__8c0_s_p1_0[] = {
  125855. 1,
  125856. 0,
  125857. 2,
  125858. };
  125859. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125860. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125861. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125866. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125871. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125906. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125911. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125916. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125952. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125957. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125962. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0,
  126271. };
  126272. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126273. -0.5, 0.5,
  126274. };
  126275. static long _vq_quantmap__8c0_s_p1_0[] = {
  126276. 1, 0, 2,
  126277. };
  126278. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126279. _vq_quantthresh__8c0_s_p1_0,
  126280. _vq_quantmap__8c0_s_p1_0,
  126281. 3,
  126282. 3
  126283. };
  126284. static static_codebook _8c0_s_p1_0 = {
  126285. 8, 6561,
  126286. _vq_lengthlist__8c0_s_p1_0,
  126287. 1, -535822336, 1611661312, 2, 0,
  126288. _vq_quantlist__8c0_s_p1_0,
  126289. NULL,
  126290. &_vq_auxt__8c0_s_p1_0,
  126291. NULL,
  126292. 0
  126293. };
  126294. static long _vq_quantlist__8c0_s_p2_0[] = {
  126295. 2,
  126296. 1,
  126297. 3,
  126298. 0,
  126299. 4,
  126300. };
  126301. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0,
  126342. };
  126343. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126344. -1.5, -0.5, 0.5, 1.5,
  126345. };
  126346. static long _vq_quantmap__8c0_s_p2_0[] = {
  126347. 3, 1, 0, 2, 4,
  126348. };
  126349. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126350. _vq_quantthresh__8c0_s_p2_0,
  126351. _vq_quantmap__8c0_s_p2_0,
  126352. 5,
  126353. 5
  126354. };
  126355. static static_codebook _8c0_s_p2_0 = {
  126356. 4, 625,
  126357. _vq_lengthlist__8c0_s_p2_0,
  126358. 1, -533725184, 1611661312, 3, 0,
  126359. _vq_quantlist__8c0_s_p2_0,
  126360. NULL,
  126361. &_vq_auxt__8c0_s_p2_0,
  126362. NULL,
  126363. 0
  126364. };
  126365. static long _vq_quantlist__8c0_s_p3_0[] = {
  126366. 2,
  126367. 1,
  126368. 3,
  126369. 0,
  126370. 4,
  126371. };
  126372. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126373. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0,
  126413. };
  126414. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126415. -1.5, -0.5, 0.5, 1.5,
  126416. };
  126417. static long _vq_quantmap__8c0_s_p3_0[] = {
  126418. 3, 1, 0, 2, 4,
  126419. };
  126420. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126421. _vq_quantthresh__8c0_s_p3_0,
  126422. _vq_quantmap__8c0_s_p3_0,
  126423. 5,
  126424. 5
  126425. };
  126426. static static_codebook _8c0_s_p3_0 = {
  126427. 4, 625,
  126428. _vq_lengthlist__8c0_s_p3_0,
  126429. 1, -533725184, 1611661312, 3, 0,
  126430. _vq_quantlist__8c0_s_p3_0,
  126431. NULL,
  126432. &_vq_auxt__8c0_s_p3_0,
  126433. NULL,
  126434. 0
  126435. };
  126436. static long _vq_quantlist__8c0_s_p4_0[] = {
  126437. 4,
  126438. 3,
  126439. 5,
  126440. 2,
  126441. 6,
  126442. 1,
  126443. 7,
  126444. 0,
  126445. 8,
  126446. };
  126447. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126448. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126449. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126450. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126451. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126452. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0,
  126454. };
  126455. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126456. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126457. };
  126458. static long _vq_quantmap__8c0_s_p4_0[] = {
  126459. 7, 5, 3, 1, 0, 2, 4, 6,
  126460. 8,
  126461. };
  126462. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126463. _vq_quantthresh__8c0_s_p4_0,
  126464. _vq_quantmap__8c0_s_p4_0,
  126465. 9,
  126466. 9
  126467. };
  126468. static static_codebook _8c0_s_p4_0 = {
  126469. 2, 81,
  126470. _vq_lengthlist__8c0_s_p4_0,
  126471. 1, -531628032, 1611661312, 4, 0,
  126472. _vq_quantlist__8c0_s_p4_0,
  126473. NULL,
  126474. &_vq_auxt__8c0_s_p4_0,
  126475. NULL,
  126476. 0
  126477. };
  126478. static long _vq_quantlist__8c0_s_p5_0[] = {
  126479. 4,
  126480. 3,
  126481. 5,
  126482. 2,
  126483. 6,
  126484. 1,
  126485. 7,
  126486. 0,
  126487. 8,
  126488. };
  126489. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126490. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126491. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126492. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126493. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126494. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126495. 10,
  126496. };
  126497. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126498. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126499. };
  126500. static long _vq_quantmap__8c0_s_p5_0[] = {
  126501. 7, 5, 3, 1, 0, 2, 4, 6,
  126502. 8,
  126503. };
  126504. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126505. _vq_quantthresh__8c0_s_p5_0,
  126506. _vq_quantmap__8c0_s_p5_0,
  126507. 9,
  126508. 9
  126509. };
  126510. static static_codebook _8c0_s_p5_0 = {
  126511. 2, 81,
  126512. _vq_lengthlist__8c0_s_p5_0,
  126513. 1, -531628032, 1611661312, 4, 0,
  126514. _vq_quantlist__8c0_s_p5_0,
  126515. NULL,
  126516. &_vq_auxt__8c0_s_p5_0,
  126517. NULL,
  126518. 0
  126519. };
  126520. static long _vq_quantlist__8c0_s_p6_0[] = {
  126521. 8,
  126522. 7,
  126523. 9,
  126524. 6,
  126525. 10,
  126526. 5,
  126527. 11,
  126528. 4,
  126529. 12,
  126530. 3,
  126531. 13,
  126532. 2,
  126533. 14,
  126534. 1,
  126535. 15,
  126536. 0,
  126537. 16,
  126538. };
  126539. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126540. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126541. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126542. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126543. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126544. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126545. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126546. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126547. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126548. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126549. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126550. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126551. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126552. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126553. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126554. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126555. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126556. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126558. 14,
  126559. };
  126560. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126561. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126562. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126563. };
  126564. static long _vq_quantmap__8c0_s_p6_0[] = {
  126565. 15, 13, 11, 9, 7, 5, 3, 1,
  126566. 0, 2, 4, 6, 8, 10, 12, 14,
  126567. 16,
  126568. };
  126569. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126570. _vq_quantthresh__8c0_s_p6_0,
  126571. _vq_quantmap__8c0_s_p6_0,
  126572. 17,
  126573. 17
  126574. };
  126575. static static_codebook _8c0_s_p6_0 = {
  126576. 2, 289,
  126577. _vq_lengthlist__8c0_s_p6_0,
  126578. 1, -529530880, 1611661312, 5, 0,
  126579. _vq_quantlist__8c0_s_p6_0,
  126580. NULL,
  126581. &_vq_auxt__8c0_s_p6_0,
  126582. NULL,
  126583. 0
  126584. };
  126585. static long _vq_quantlist__8c0_s_p7_0[] = {
  126586. 1,
  126587. 0,
  126588. 2,
  126589. };
  126590. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126591. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126592. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126593. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126594. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126595. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126596. 10,
  126597. };
  126598. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126599. -5.5, 5.5,
  126600. };
  126601. static long _vq_quantmap__8c0_s_p7_0[] = {
  126602. 1, 0, 2,
  126603. };
  126604. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126605. _vq_quantthresh__8c0_s_p7_0,
  126606. _vq_quantmap__8c0_s_p7_0,
  126607. 3,
  126608. 3
  126609. };
  126610. static static_codebook _8c0_s_p7_0 = {
  126611. 4, 81,
  126612. _vq_lengthlist__8c0_s_p7_0,
  126613. 1, -529137664, 1618345984, 2, 0,
  126614. _vq_quantlist__8c0_s_p7_0,
  126615. NULL,
  126616. &_vq_auxt__8c0_s_p7_0,
  126617. NULL,
  126618. 0
  126619. };
  126620. static long _vq_quantlist__8c0_s_p7_1[] = {
  126621. 5,
  126622. 4,
  126623. 6,
  126624. 3,
  126625. 7,
  126626. 2,
  126627. 8,
  126628. 1,
  126629. 9,
  126630. 0,
  126631. 10,
  126632. };
  126633. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126634. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126635. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126636. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126637. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126638. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126639. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126640. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126641. 10,10,10, 9, 9, 9,10,10,10,
  126642. };
  126643. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126644. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126645. 3.5, 4.5,
  126646. };
  126647. static long _vq_quantmap__8c0_s_p7_1[] = {
  126648. 9, 7, 5, 3, 1, 0, 2, 4,
  126649. 6, 8, 10,
  126650. };
  126651. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126652. _vq_quantthresh__8c0_s_p7_1,
  126653. _vq_quantmap__8c0_s_p7_1,
  126654. 11,
  126655. 11
  126656. };
  126657. static static_codebook _8c0_s_p7_1 = {
  126658. 2, 121,
  126659. _vq_lengthlist__8c0_s_p7_1,
  126660. 1, -531365888, 1611661312, 4, 0,
  126661. _vq_quantlist__8c0_s_p7_1,
  126662. NULL,
  126663. &_vq_auxt__8c0_s_p7_1,
  126664. NULL,
  126665. 0
  126666. };
  126667. static long _vq_quantlist__8c0_s_p8_0[] = {
  126668. 6,
  126669. 5,
  126670. 7,
  126671. 4,
  126672. 8,
  126673. 3,
  126674. 9,
  126675. 2,
  126676. 10,
  126677. 1,
  126678. 11,
  126679. 0,
  126680. 12,
  126681. };
  126682. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126683. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126684. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126685. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126686. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126687. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126688. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126689. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126690. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126691. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126692. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126693. 0, 0,13,13,11,13,13,11,12,
  126694. };
  126695. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126696. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126697. 12.5, 17.5, 22.5, 27.5,
  126698. };
  126699. static long _vq_quantmap__8c0_s_p8_0[] = {
  126700. 11, 9, 7, 5, 3, 1, 0, 2,
  126701. 4, 6, 8, 10, 12,
  126702. };
  126703. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126704. _vq_quantthresh__8c0_s_p8_0,
  126705. _vq_quantmap__8c0_s_p8_0,
  126706. 13,
  126707. 13
  126708. };
  126709. static static_codebook _8c0_s_p8_0 = {
  126710. 2, 169,
  126711. _vq_lengthlist__8c0_s_p8_0,
  126712. 1, -526516224, 1616117760, 4, 0,
  126713. _vq_quantlist__8c0_s_p8_0,
  126714. NULL,
  126715. &_vq_auxt__8c0_s_p8_0,
  126716. NULL,
  126717. 0
  126718. };
  126719. static long _vq_quantlist__8c0_s_p8_1[] = {
  126720. 2,
  126721. 1,
  126722. 3,
  126723. 0,
  126724. 4,
  126725. };
  126726. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126727. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126728. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126729. };
  126730. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126731. -1.5, -0.5, 0.5, 1.5,
  126732. };
  126733. static long _vq_quantmap__8c0_s_p8_1[] = {
  126734. 3, 1, 0, 2, 4,
  126735. };
  126736. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126737. _vq_quantthresh__8c0_s_p8_1,
  126738. _vq_quantmap__8c0_s_p8_1,
  126739. 5,
  126740. 5
  126741. };
  126742. static static_codebook _8c0_s_p8_1 = {
  126743. 2, 25,
  126744. _vq_lengthlist__8c0_s_p8_1,
  126745. 1, -533725184, 1611661312, 3, 0,
  126746. _vq_quantlist__8c0_s_p8_1,
  126747. NULL,
  126748. &_vq_auxt__8c0_s_p8_1,
  126749. NULL,
  126750. 0
  126751. };
  126752. static long _vq_quantlist__8c0_s_p9_0[] = {
  126753. 1,
  126754. 0,
  126755. 2,
  126756. };
  126757. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126758. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126759. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126760. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126761. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126762. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126763. 7,
  126764. };
  126765. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126766. -157.5, 157.5,
  126767. };
  126768. static long _vq_quantmap__8c0_s_p9_0[] = {
  126769. 1, 0, 2,
  126770. };
  126771. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126772. _vq_quantthresh__8c0_s_p9_0,
  126773. _vq_quantmap__8c0_s_p9_0,
  126774. 3,
  126775. 3
  126776. };
  126777. static static_codebook _8c0_s_p9_0 = {
  126778. 4, 81,
  126779. _vq_lengthlist__8c0_s_p9_0,
  126780. 1, -518803456, 1628680192, 2, 0,
  126781. _vq_quantlist__8c0_s_p9_0,
  126782. NULL,
  126783. &_vq_auxt__8c0_s_p9_0,
  126784. NULL,
  126785. 0
  126786. };
  126787. static long _vq_quantlist__8c0_s_p9_1[] = {
  126788. 7,
  126789. 6,
  126790. 8,
  126791. 5,
  126792. 9,
  126793. 4,
  126794. 10,
  126795. 3,
  126796. 11,
  126797. 2,
  126798. 12,
  126799. 1,
  126800. 13,
  126801. 0,
  126802. 14,
  126803. };
  126804. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126805. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126806. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126807. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126808. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126809. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126810. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126811. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126812. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126813. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126815. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126816. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126819. 11,
  126820. };
  126821. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126822. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126823. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126824. };
  126825. static long _vq_quantmap__8c0_s_p9_1[] = {
  126826. 13, 11, 9, 7, 5, 3, 1, 0,
  126827. 2, 4, 6, 8, 10, 12, 14,
  126828. };
  126829. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126830. _vq_quantthresh__8c0_s_p9_1,
  126831. _vq_quantmap__8c0_s_p9_1,
  126832. 15,
  126833. 15
  126834. };
  126835. static static_codebook _8c0_s_p9_1 = {
  126836. 2, 225,
  126837. _vq_lengthlist__8c0_s_p9_1,
  126838. 1, -520986624, 1620377600, 4, 0,
  126839. _vq_quantlist__8c0_s_p9_1,
  126840. NULL,
  126841. &_vq_auxt__8c0_s_p9_1,
  126842. NULL,
  126843. 0
  126844. };
  126845. static long _vq_quantlist__8c0_s_p9_2[] = {
  126846. 10,
  126847. 9,
  126848. 11,
  126849. 8,
  126850. 12,
  126851. 7,
  126852. 13,
  126853. 6,
  126854. 14,
  126855. 5,
  126856. 15,
  126857. 4,
  126858. 16,
  126859. 3,
  126860. 17,
  126861. 2,
  126862. 18,
  126863. 1,
  126864. 19,
  126865. 0,
  126866. 20,
  126867. };
  126868. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126869. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126870. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126871. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126872. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126873. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126874. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126875. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126876. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126877. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126878. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126879. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126880. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126881. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126882. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126883. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126884. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126885. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126886. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126887. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126888. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126889. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126890. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126891. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126892. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126893. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126894. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126895. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126896. 10,11, 9,11,10, 9,10, 9,10,
  126897. };
  126898. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126899. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126900. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126901. 6.5, 7.5, 8.5, 9.5,
  126902. };
  126903. static long _vq_quantmap__8c0_s_p9_2[] = {
  126904. 19, 17, 15, 13, 11, 9, 7, 5,
  126905. 3, 1, 0, 2, 4, 6, 8, 10,
  126906. 12, 14, 16, 18, 20,
  126907. };
  126908. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126909. _vq_quantthresh__8c0_s_p9_2,
  126910. _vq_quantmap__8c0_s_p9_2,
  126911. 21,
  126912. 21
  126913. };
  126914. static static_codebook _8c0_s_p9_2 = {
  126915. 2, 441,
  126916. _vq_lengthlist__8c0_s_p9_2,
  126917. 1, -529268736, 1611661312, 5, 0,
  126918. _vq_quantlist__8c0_s_p9_2,
  126919. NULL,
  126920. &_vq_auxt__8c0_s_p9_2,
  126921. NULL,
  126922. 0
  126923. };
  126924. static long _huff_lengthlist__8c0_s_single[] = {
  126925. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126926. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126927. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126928. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126929. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126930. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126931. 17,16,17,17,
  126932. };
  126933. static static_codebook _huff_book__8c0_s_single = {
  126934. 2, 100,
  126935. _huff_lengthlist__8c0_s_single,
  126936. 0, 0, 0, 0, 0,
  126937. NULL,
  126938. NULL,
  126939. NULL,
  126940. NULL,
  126941. 0
  126942. };
  126943. static long _vq_quantlist__8c1_s_p1_0[] = {
  126944. 1,
  126945. 0,
  126946. 2,
  126947. };
  126948. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126949. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126950. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126955. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126960. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126995. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  127000. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  127005. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127041. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127046. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127051. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0,
  127360. };
  127361. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127362. -0.5, 0.5,
  127363. };
  127364. static long _vq_quantmap__8c1_s_p1_0[] = {
  127365. 1, 0, 2,
  127366. };
  127367. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127368. _vq_quantthresh__8c1_s_p1_0,
  127369. _vq_quantmap__8c1_s_p1_0,
  127370. 3,
  127371. 3
  127372. };
  127373. static static_codebook _8c1_s_p1_0 = {
  127374. 8, 6561,
  127375. _vq_lengthlist__8c1_s_p1_0,
  127376. 1, -535822336, 1611661312, 2, 0,
  127377. _vq_quantlist__8c1_s_p1_0,
  127378. NULL,
  127379. &_vq_auxt__8c1_s_p1_0,
  127380. NULL,
  127381. 0
  127382. };
  127383. static long _vq_quantlist__8c1_s_p2_0[] = {
  127384. 2,
  127385. 1,
  127386. 3,
  127387. 0,
  127388. 4,
  127389. };
  127390. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127430. 0,
  127431. };
  127432. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127433. -1.5, -0.5, 0.5, 1.5,
  127434. };
  127435. static long _vq_quantmap__8c1_s_p2_0[] = {
  127436. 3, 1, 0, 2, 4,
  127437. };
  127438. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127439. _vq_quantthresh__8c1_s_p2_0,
  127440. _vq_quantmap__8c1_s_p2_0,
  127441. 5,
  127442. 5
  127443. };
  127444. static static_codebook _8c1_s_p2_0 = {
  127445. 4, 625,
  127446. _vq_lengthlist__8c1_s_p2_0,
  127447. 1, -533725184, 1611661312, 3, 0,
  127448. _vq_quantlist__8c1_s_p2_0,
  127449. NULL,
  127450. &_vq_auxt__8c1_s_p2_0,
  127451. NULL,
  127452. 0
  127453. };
  127454. static long _vq_quantlist__8c1_s_p3_0[] = {
  127455. 2,
  127456. 1,
  127457. 3,
  127458. 0,
  127459. 4,
  127460. };
  127461. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127462. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127468. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0,
  127502. };
  127503. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127504. -1.5, -0.5, 0.5, 1.5,
  127505. };
  127506. static long _vq_quantmap__8c1_s_p3_0[] = {
  127507. 3, 1, 0, 2, 4,
  127508. };
  127509. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127510. _vq_quantthresh__8c1_s_p3_0,
  127511. _vq_quantmap__8c1_s_p3_0,
  127512. 5,
  127513. 5
  127514. };
  127515. static static_codebook _8c1_s_p3_0 = {
  127516. 4, 625,
  127517. _vq_lengthlist__8c1_s_p3_0,
  127518. 1, -533725184, 1611661312, 3, 0,
  127519. _vq_quantlist__8c1_s_p3_0,
  127520. NULL,
  127521. &_vq_auxt__8c1_s_p3_0,
  127522. NULL,
  127523. 0
  127524. };
  127525. static long _vq_quantlist__8c1_s_p4_0[] = {
  127526. 4,
  127527. 3,
  127528. 5,
  127529. 2,
  127530. 6,
  127531. 1,
  127532. 7,
  127533. 0,
  127534. 8,
  127535. };
  127536. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127537. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127538. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127539. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127540. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127541. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127542. 0,
  127543. };
  127544. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127545. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127546. };
  127547. static long _vq_quantmap__8c1_s_p4_0[] = {
  127548. 7, 5, 3, 1, 0, 2, 4, 6,
  127549. 8,
  127550. };
  127551. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127552. _vq_quantthresh__8c1_s_p4_0,
  127553. _vq_quantmap__8c1_s_p4_0,
  127554. 9,
  127555. 9
  127556. };
  127557. static static_codebook _8c1_s_p4_0 = {
  127558. 2, 81,
  127559. _vq_lengthlist__8c1_s_p4_0,
  127560. 1, -531628032, 1611661312, 4, 0,
  127561. _vq_quantlist__8c1_s_p4_0,
  127562. NULL,
  127563. &_vq_auxt__8c1_s_p4_0,
  127564. NULL,
  127565. 0
  127566. };
  127567. static long _vq_quantlist__8c1_s_p5_0[] = {
  127568. 4,
  127569. 3,
  127570. 5,
  127571. 2,
  127572. 6,
  127573. 1,
  127574. 7,
  127575. 0,
  127576. 8,
  127577. };
  127578. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127579. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127580. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127581. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127582. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127583. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127584. 10,
  127585. };
  127586. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127587. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127588. };
  127589. static long _vq_quantmap__8c1_s_p5_0[] = {
  127590. 7, 5, 3, 1, 0, 2, 4, 6,
  127591. 8,
  127592. };
  127593. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127594. _vq_quantthresh__8c1_s_p5_0,
  127595. _vq_quantmap__8c1_s_p5_0,
  127596. 9,
  127597. 9
  127598. };
  127599. static static_codebook _8c1_s_p5_0 = {
  127600. 2, 81,
  127601. _vq_lengthlist__8c1_s_p5_0,
  127602. 1, -531628032, 1611661312, 4, 0,
  127603. _vq_quantlist__8c1_s_p5_0,
  127604. NULL,
  127605. &_vq_auxt__8c1_s_p5_0,
  127606. NULL,
  127607. 0
  127608. };
  127609. static long _vq_quantlist__8c1_s_p6_0[] = {
  127610. 8,
  127611. 7,
  127612. 9,
  127613. 6,
  127614. 10,
  127615. 5,
  127616. 11,
  127617. 4,
  127618. 12,
  127619. 3,
  127620. 13,
  127621. 2,
  127622. 14,
  127623. 1,
  127624. 15,
  127625. 0,
  127626. 16,
  127627. };
  127628. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127629. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127630. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127631. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127632. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127633. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127634. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127635. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127636. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127637. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127638. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127639. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127640. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127641. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127642. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127643. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127644. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127645. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127646. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127647. 14,
  127648. };
  127649. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127650. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127651. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127652. };
  127653. static long _vq_quantmap__8c1_s_p6_0[] = {
  127654. 15, 13, 11, 9, 7, 5, 3, 1,
  127655. 0, 2, 4, 6, 8, 10, 12, 14,
  127656. 16,
  127657. };
  127658. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127659. _vq_quantthresh__8c1_s_p6_0,
  127660. _vq_quantmap__8c1_s_p6_0,
  127661. 17,
  127662. 17
  127663. };
  127664. static static_codebook _8c1_s_p6_0 = {
  127665. 2, 289,
  127666. _vq_lengthlist__8c1_s_p6_0,
  127667. 1, -529530880, 1611661312, 5, 0,
  127668. _vq_quantlist__8c1_s_p6_0,
  127669. NULL,
  127670. &_vq_auxt__8c1_s_p6_0,
  127671. NULL,
  127672. 0
  127673. };
  127674. static long _vq_quantlist__8c1_s_p7_0[] = {
  127675. 1,
  127676. 0,
  127677. 2,
  127678. };
  127679. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127680. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127681. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127682. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127683. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127684. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127685. 9,
  127686. };
  127687. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127688. -5.5, 5.5,
  127689. };
  127690. static long _vq_quantmap__8c1_s_p7_0[] = {
  127691. 1, 0, 2,
  127692. };
  127693. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127694. _vq_quantthresh__8c1_s_p7_0,
  127695. _vq_quantmap__8c1_s_p7_0,
  127696. 3,
  127697. 3
  127698. };
  127699. static static_codebook _8c1_s_p7_0 = {
  127700. 4, 81,
  127701. _vq_lengthlist__8c1_s_p7_0,
  127702. 1, -529137664, 1618345984, 2, 0,
  127703. _vq_quantlist__8c1_s_p7_0,
  127704. NULL,
  127705. &_vq_auxt__8c1_s_p7_0,
  127706. NULL,
  127707. 0
  127708. };
  127709. static long _vq_quantlist__8c1_s_p7_1[] = {
  127710. 5,
  127711. 4,
  127712. 6,
  127713. 3,
  127714. 7,
  127715. 2,
  127716. 8,
  127717. 1,
  127718. 9,
  127719. 0,
  127720. 10,
  127721. };
  127722. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127723. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127724. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127725. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127726. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127727. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127728. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127729. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127730. 10,10,10, 8, 8, 8, 8, 8, 8,
  127731. };
  127732. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127733. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127734. 3.5, 4.5,
  127735. };
  127736. static long _vq_quantmap__8c1_s_p7_1[] = {
  127737. 9, 7, 5, 3, 1, 0, 2, 4,
  127738. 6, 8, 10,
  127739. };
  127740. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127741. _vq_quantthresh__8c1_s_p7_1,
  127742. _vq_quantmap__8c1_s_p7_1,
  127743. 11,
  127744. 11
  127745. };
  127746. static static_codebook _8c1_s_p7_1 = {
  127747. 2, 121,
  127748. _vq_lengthlist__8c1_s_p7_1,
  127749. 1, -531365888, 1611661312, 4, 0,
  127750. _vq_quantlist__8c1_s_p7_1,
  127751. NULL,
  127752. &_vq_auxt__8c1_s_p7_1,
  127753. NULL,
  127754. 0
  127755. };
  127756. static long _vq_quantlist__8c1_s_p8_0[] = {
  127757. 6,
  127758. 5,
  127759. 7,
  127760. 4,
  127761. 8,
  127762. 3,
  127763. 9,
  127764. 2,
  127765. 10,
  127766. 1,
  127767. 11,
  127768. 0,
  127769. 12,
  127770. };
  127771. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127772. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127773. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127774. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127775. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127776. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127777. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127778. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127779. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127780. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127781. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127782. 0,12,12,11,10,12,11,13,12,
  127783. };
  127784. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127785. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127786. 12.5, 17.5, 22.5, 27.5,
  127787. };
  127788. static long _vq_quantmap__8c1_s_p8_0[] = {
  127789. 11, 9, 7, 5, 3, 1, 0, 2,
  127790. 4, 6, 8, 10, 12,
  127791. };
  127792. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127793. _vq_quantthresh__8c1_s_p8_0,
  127794. _vq_quantmap__8c1_s_p8_0,
  127795. 13,
  127796. 13
  127797. };
  127798. static static_codebook _8c1_s_p8_0 = {
  127799. 2, 169,
  127800. _vq_lengthlist__8c1_s_p8_0,
  127801. 1, -526516224, 1616117760, 4, 0,
  127802. _vq_quantlist__8c1_s_p8_0,
  127803. NULL,
  127804. &_vq_auxt__8c1_s_p8_0,
  127805. NULL,
  127806. 0
  127807. };
  127808. static long _vq_quantlist__8c1_s_p8_1[] = {
  127809. 2,
  127810. 1,
  127811. 3,
  127812. 0,
  127813. 4,
  127814. };
  127815. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127816. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127817. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127818. };
  127819. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127820. -1.5, -0.5, 0.5, 1.5,
  127821. };
  127822. static long _vq_quantmap__8c1_s_p8_1[] = {
  127823. 3, 1, 0, 2, 4,
  127824. };
  127825. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127826. _vq_quantthresh__8c1_s_p8_1,
  127827. _vq_quantmap__8c1_s_p8_1,
  127828. 5,
  127829. 5
  127830. };
  127831. static static_codebook _8c1_s_p8_1 = {
  127832. 2, 25,
  127833. _vq_lengthlist__8c1_s_p8_1,
  127834. 1, -533725184, 1611661312, 3, 0,
  127835. _vq_quantlist__8c1_s_p8_1,
  127836. NULL,
  127837. &_vq_auxt__8c1_s_p8_1,
  127838. NULL,
  127839. 0
  127840. };
  127841. static long _vq_quantlist__8c1_s_p9_0[] = {
  127842. 6,
  127843. 5,
  127844. 7,
  127845. 4,
  127846. 8,
  127847. 3,
  127848. 9,
  127849. 2,
  127850. 10,
  127851. 1,
  127852. 11,
  127853. 0,
  127854. 12,
  127855. };
  127856. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127857. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127858. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127859. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127860. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127861. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127862. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127863. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127864. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127865. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127866. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127867. 10,10,10,10,10, 9, 9, 9, 9,
  127868. };
  127869. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127870. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127871. 787.5, 1102.5, 1417.5, 1732.5,
  127872. };
  127873. static long _vq_quantmap__8c1_s_p9_0[] = {
  127874. 11, 9, 7, 5, 3, 1, 0, 2,
  127875. 4, 6, 8, 10, 12,
  127876. };
  127877. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127878. _vq_quantthresh__8c1_s_p9_0,
  127879. _vq_quantmap__8c1_s_p9_0,
  127880. 13,
  127881. 13
  127882. };
  127883. static static_codebook _8c1_s_p9_0 = {
  127884. 2, 169,
  127885. _vq_lengthlist__8c1_s_p9_0,
  127886. 1, -513964032, 1628680192, 4, 0,
  127887. _vq_quantlist__8c1_s_p9_0,
  127888. NULL,
  127889. &_vq_auxt__8c1_s_p9_0,
  127890. NULL,
  127891. 0
  127892. };
  127893. static long _vq_quantlist__8c1_s_p9_1[] = {
  127894. 7,
  127895. 6,
  127896. 8,
  127897. 5,
  127898. 9,
  127899. 4,
  127900. 10,
  127901. 3,
  127902. 11,
  127903. 2,
  127904. 12,
  127905. 1,
  127906. 13,
  127907. 0,
  127908. 14,
  127909. };
  127910. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127911. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127912. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127913. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127914. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127915. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127916. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127917. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127918. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127919. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127920. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127921. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127922. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127923. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127924. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127925. 15,
  127926. };
  127927. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127928. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127929. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127930. };
  127931. static long _vq_quantmap__8c1_s_p9_1[] = {
  127932. 13, 11, 9, 7, 5, 3, 1, 0,
  127933. 2, 4, 6, 8, 10, 12, 14,
  127934. };
  127935. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127936. _vq_quantthresh__8c1_s_p9_1,
  127937. _vq_quantmap__8c1_s_p9_1,
  127938. 15,
  127939. 15
  127940. };
  127941. static static_codebook _8c1_s_p9_1 = {
  127942. 2, 225,
  127943. _vq_lengthlist__8c1_s_p9_1,
  127944. 1, -520986624, 1620377600, 4, 0,
  127945. _vq_quantlist__8c1_s_p9_1,
  127946. NULL,
  127947. &_vq_auxt__8c1_s_p9_1,
  127948. NULL,
  127949. 0
  127950. };
  127951. static long _vq_quantlist__8c1_s_p9_2[] = {
  127952. 10,
  127953. 9,
  127954. 11,
  127955. 8,
  127956. 12,
  127957. 7,
  127958. 13,
  127959. 6,
  127960. 14,
  127961. 5,
  127962. 15,
  127963. 4,
  127964. 16,
  127965. 3,
  127966. 17,
  127967. 2,
  127968. 18,
  127969. 1,
  127970. 19,
  127971. 0,
  127972. 20,
  127973. };
  127974. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127975. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127976. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127977. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127978. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127979. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127980. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127981. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127982. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127983. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127984. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127985. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127986. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127987. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127988. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127989. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127990. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127991. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127992. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127993. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127994. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127995. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127996. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127997. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127998. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127999. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  128000. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  128001. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  128002. 10,10,10,10,10,10,10,10,10,
  128003. };
  128004. static float _vq_quantthresh__8c1_s_p9_2[] = {
  128005. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128006. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128007. 6.5, 7.5, 8.5, 9.5,
  128008. };
  128009. static long _vq_quantmap__8c1_s_p9_2[] = {
  128010. 19, 17, 15, 13, 11, 9, 7, 5,
  128011. 3, 1, 0, 2, 4, 6, 8, 10,
  128012. 12, 14, 16, 18, 20,
  128013. };
  128014. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  128015. _vq_quantthresh__8c1_s_p9_2,
  128016. _vq_quantmap__8c1_s_p9_2,
  128017. 21,
  128018. 21
  128019. };
  128020. static static_codebook _8c1_s_p9_2 = {
  128021. 2, 441,
  128022. _vq_lengthlist__8c1_s_p9_2,
  128023. 1, -529268736, 1611661312, 5, 0,
  128024. _vq_quantlist__8c1_s_p9_2,
  128025. NULL,
  128026. &_vq_auxt__8c1_s_p9_2,
  128027. NULL,
  128028. 0
  128029. };
  128030. static long _huff_lengthlist__8c1_s_single[] = {
  128031. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  128032. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  128033. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  128034. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  128035. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  128036. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  128037. 9, 7, 7, 8,
  128038. };
  128039. static static_codebook _huff_book__8c1_s_single = {
  128040. 2, 100,
  128041. _huff_lengthlist__8c1_s_single,
  128042. 0, 0, 0, 0, 0,
  128043. NULL,
  128044. NULL,
  128045. NULL,
  128046. NULL,
  128047. 0
  128048. };
  128049. static long _huff_lengthlist__44c2_s_long[] = {
  128050. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  128051. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  128052. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  128053. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  128054. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  128055. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  128056. 10, 8, 8, 9,
  128057. };
  128058. static static_codebook _huff_book__44c2_s_long = {
  128059. 2, 100,
  128060. _huff_lengthlist__44c2_s_long,
  128061. 0, 0, 0, 0, 0,
  128062. NULL,
  128063. NULL,
  128064. NULL,
  128065. NULL,
  128066. 0
  128067. };
  128068. static long _vq_quantlist__44c2_s_p1_0[] = {
  128069. 1,
  128070. 0,
  128071. 2,
  128072. };
  128073. static long _vq_lengthlist__44c2_s_p1_0[] = {
  128074. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128075. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128080. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128085. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128120. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128125. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128130. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128166. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128171. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128176. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0,
  128485. };
  128486. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128487. -0.5, 0.5,
  128488. };
  128489. static long _vq_quantmap__44c2_s_p1_0[] = {
  128490. 1, 0, 2,
  128491. };
  128492. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128493. _vq_quantthresh__44c2_s_p1_0,
  128494. _vq_quantmap__44c2_s_p1_0,
  128495. 3,
  128496. 3
  128497. };
  128498. static static_codebook _44c2_s_p1_0 = {
  128499. 8, 6561,
  128500. _vq_lengthlist__44c2_s_p1_0,
  128501. 1, -535822336, 1611661312, 2, 0,
  128502. _vq_quantlist__44c2_s_p1_0,
  128503. NULL,
  128504. &_vq_auxt__44c2_s_p1_0,
  128505. NULL,
  128506. 0
  128507. };
  128508. static long _vq_quantlist__44c2_s_p2_0[] = {
  128509. 2,
  128510. 1,
  128511. 3,
  128512. 0,
  128513. 4,
  128514. };
  128515. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128516. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128517. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128518. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128519. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128520. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128525. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128526. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128527. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128528. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128533. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128534. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128535. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128541. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128542. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128543. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128555. 0,
  128556. };
  128557. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128558. -1.5, -0.5, 0.5, 1.5,
  128559. };
  128560. static long _vq_quantmap__44c2_s_p2_0[] = {
  128561. 3, 1, 0, 2, 4,
  128562. };
  128563. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128564. _vq_quantthresh__44c2_s_p2_0,
  128565. _vq_quantmap__44c2_s_p2_0,
  128566. 5,
  128567. 5
  128568. };
  128569. static static_codebook _44c2_s_p2_0 = {
  128570. 4, 625,
  128571. _vq_lengthlist__44c2_s_p2_0,
  128572. 1, -533725184, 1611661312, 3, 0,
  128573. _vq_quantlist__44c2_s_p2_0,
  128574. NULL,
  128575. &_vq_auxt__44c2_s_p2_0,
  128576. NULL,
  128577. 0
  128578. };
  128579. static long _vq_quantlist__44c2_s_p3_0[] = {
  128580. 2,
  128581. 1,
  128582. 3,
  128583. 0,
  128584. 4,
  128585. };
  128586. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128587. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128590. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128593. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0,
  128627. };
  128628. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128629. -1.5, -0.5, 0.5, 1.5,
  128630. };
  128631. static long _vq_quantmap__44c2_s_p3_0[] = {
  128632. 3, 1, 0, 2, 4,
  128633. };
  128634. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128635. _vq_quantthresh__44c2_s_p3_0,
  128636. _vq_quantmap__44c2_s_p3_0,
  128637. 5,
  128638. 5
  128639. };
  128640. static static_codebook _44c2_s_p3_0 = {
  128641. 4, 625,
  128642. _vq_lengthlist__44c2_s_p3_0,
  128643. 1, -533725184, 1611661312, 3, 0,
  128644. _vq_quantlist__44c2_s_p3_0,
  128645. NULL,
  128646. &_vq_auxt__44c2_s_p3_0,
  128647. NULL,
  128648. 0
  128649. };
  128650. static long _vq_quantlist__44c2_s_p4_0[] = {
  128651. 4,
  128652. 3,
  128653. 5,
  128654. 2,
  128655. 6,
  128656. 1,
  128657. 7,
  128658. 0,
  128659. 8,
  128660. };
  128661. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128662. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128663. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128664. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128665. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128666. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128667. 0,
  128668. };
  128669. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128670. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128671. };
  128672. static long _vq_quantmap__44c2_s_p4_0[] = {
  128673. 7, 5, 3, 1, 0, 2, 4, 6,
  128674. 8,
  128675. };
  128676. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128677. _vq_quantthresh__44c2_s_p4_0,
  128678. _vq_quantmap__44c2_s_p4_0,
  128679. 9,
  128680. 9
  128681. };
  128682. static static_codebook _44c2_s_p4_0 = {
  128683. 2, 81,
  128684. _vq_lengthlist__44c2_s_p4_0,
  128685. 1, -531628032, 1611661312, 4, 0,
  128686. _vq_quantlist__44c2_s_p4_0,
  128687. NULL,
  128688. &_vq_auxt__44c2_s_p4_0,
  128689. NULL,
  128690. 0
  128691. };
  128692. static long _vq_quantlist__44c2_s_p5_0[] = {
  128693. 4,
  128694. 3,
  128695. 5,
  128696. 2,
  128697. 6,
  128698. 1,
  128699. 7,
  128700. 0,
  128701. 8,
  128702. };
  128703. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128704. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128705. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128706. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128707. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128708. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128709. 11,
  128710. };
  128711. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128712. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128713. };
  128714. static long _vq_quantmap__44c2_s_p5_0[] = {
  128715. 7, 5, 3, 1, 0, 2, 4, 6,
  128716. 8,
  128717. };
  128718. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128719. _vq_quantthresh__44c2_s_p5_0,
  128720. _vq_quantmap__44c2_s_p5_0,
  128721. 9,
  128722. 9
  128723. };
  128724. static static_codebook _44c2_s_p5_0 = {
  128725. 2, 81,
  128726. _vq_lengthlist__44c2_s_p5_0,
  128727. 1, -531628032, 1611661312, 4, 0,
  128728. _vq_quantlist__44c2_s_p5_0,
  128729. NULL,
  128730. &_vq_auxt__44c2_s_p5_0,
  128731. NULL,
  128732. 0
  128733. };
  128734. static long _vq_quantlist__44c2_s_p6_0[] = {
  128735. 8,
  128736. 7,
  128737. 9,
  128738. 6,
  128739. 10,
  128740. 5,
  128741. 11,
  128742. 4,
  128743. 12,
  128744. 3,
  128745. 13,
  128746. 2,
  128747. 14,
  128748. 1,
  128749. 15,
  128750. 0,
  128751. 16,
  128752. };
  128753. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128754. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128755. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128756. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128757. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128758. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128759. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128760. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128761. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128762. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128763. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128764. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128765. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128766. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128767. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128768. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128769. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128770. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128771. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128772. 14,
  128773. };
  128774. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128775. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128776. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128777. };
  128778. static long _vq_quantmap__44c2_s_p6_0[] = {
  128779. 15, 13, 11, 9, 7, 5, 3, 1,
  128780. 0, 2, 4, 6, 8, 10, 12, 14,
  128781. 16,
  128782. };
  128783. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128784. _vq_quantthresh__44c2_s_p6_0,
  128785. _vq_quantmap__44c2_s_p6_0,
  128786. 17,
  128787. 17
  128788. };
  128789. static static_codebook _44c2_s_p6_0 = {
  128790. 2, 289,
  128791. _vq_lengthlist__44c2_s_p6_0,
  128792. 1, -529530880, 1611661312, 5, 0,
  128793. _vq_quantlist__44c2_s_p6_0,
  128794. NULL,
  128795. &_vq_auxt__44c2_s_p6_0,
  128796. NULL,
  128797. 0
  128798. };
  128799. static long _vq_quantlist__44c2_s_p7_0[] = {
  128800. 1,
  128801. 0,
  128802. 2,
  128803. };
  128804. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128805. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128806. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128807. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128808. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128809. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128810. 11,
  128811. };
  128812. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128813. -5.5, 5.5,
  128814. };
  128815. static long _vq_quantmap__44c2_s_p7_0[] = {
  128816. 1, 0, 2,
  128817. };
  128818. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128819. _vq_quantthresh__44c2_s_p7_0,
  128820. _vq_quantmap__44c2_s_p7_0,
  128821. 3,
  128822. 3
  128823. };
  128824. static static_codebook _44c2_s_p7_0 = {
  128825. 4, 81,
  128826. _vq_lengthlist__44c2_s_p7_0,
  128827. 1, -529137664, 1618345984, 2, 0,
  128828. _vq_quantlist__44c2_s_p7_0,
  128829. NULL,
  128830. &_vq_auxt__44c2_s_p7_0,
  128831. NULL,
  128832. 0
  128833. };
  128834. static long _vq_quantlist__44c2_s_p7_1[] = {
  128835. 5,
  128836. 4,
  128837. 6,
  128838. 3,
  128839. 7,
  128840. 2,
  128841. 8,
  128842. 1,
  128843. 9,
  128844. 0,
  128845. 10,
  128846. };
  128847. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128848. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128849. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128850. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128851. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128852. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128853. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128854. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128855. 10,10,10, 8, 8, 8, 8, 8, 8,
  128856. };
  128857. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128858. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128859. 3.5, 4.5,
  128860. };
  128861. static long _vq_quantmap__44c2_s_p7_1[] = {
  128862. 9, 7, 5, 3, 1, 0, 2, 4,
  128863. 6, 8, 10,
  128864. };
  128865. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128866. _vq_quantthresh__44c2_s_p7_1,
  128867. _vq_quantmap__44c2_s_p7_1,
  128868. 11,
  128869. 11
  128870. };
  128871. static static_codebook _44c2_s_p7_1 = {
  128872. 2, 121,
  128873. _vq_lengthlist__44c2_s_p7_1,
  128874. 1, -531365888, 1611661312, 4, 0,
  128875. _vq_quantlist__44c2_s_p7_1,
  128876. NULL,
  128877. &_vq_auxt__44c2_s_p7_1,
  128878. NULL,
  128879. 0
  128880. };
  128881. static long _vq_quantlist__44c2_s_p8_0[] = {
  128882. 6,
  128883. 5,
  128884. 7,
  128885. 4,
  128886. 8,
  128887. 3,
  128888. 9,
  128889. 2,
  128890. 10,
  128891. 1,
  128892. 11,
  128893. 0,
  128894. 12,
  128895. };
  128896. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128897. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128898. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128899. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128900. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128901. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128902. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128903. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128904. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128905. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128906. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128907. 0,12,12,12,12,13,12,14,14,
  128908. };
  128909. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128910. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128911. 12.5, 17.5, 22.5, 27.5,
  128912. };
  128913. static long _vq_quantmap__44c2_s_p8_0[] = {
  128914. 11, 9, 7, 5, 3, 1, 0, 2,
  128915. 4, 6, 8, 10, 12,
  128916. };
  128917. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128918. _vq_quantthresh__44c2_s_p8_0,
  128919. _vq_quantmap__44c2_s_p8_0,
  128920. 13,
  128921. 13
  128922. };
  128923. static static_codebook _44c2_s_p8_0 = {
  128924. 2, 169,
  128925. _vq_lengthlist__44c2_s_p8_0,
  128926. 1, -526516224, 1616117760, 4, 0,
  128927. _vq_quantlist__44c2_s_p8_0,
  128928. NULL,
  128929. &_vq_auxt__44c2_s_p8_0,
  128930. NULL,
  128931. 0
  128932. };
  128933. static long _vq_quantlist__44c2_s_p8_1[] = {
  128934. 2,
  128935. 1,
  128936. 3,
  128937. 0,
  128938. 4,
  128939. };
  128940. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128941. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128942. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128943. };
  128944. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128945. -1.5, -0.5, 0.5, 1.5,
  128946. };
  128947. static long _vq_quantmap__44c2_s_p8_1[] = {
  128948. 3, 1, 0, 2, 4,
  128949. };
  128950. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128951. _vq_quantthresh__44c2_s_p8_1,
  128952. _vq_quantmap__44c2_s_p8_1,
  128953. 5,
  128954. 5
  128955. };
  128956. static static_codebook _44c2_s_p8_1 = {
  128957. 2, 25,
  128958. _vq_lengthlist__44c2_s_p8_1,
  128959. 1, -533725184, 1611661312, 3, 0,
  128960. _vq_quantlist__44c2_s_p8_1,
  128961. NULL,
  128962. &_vq_auxt__44c2_s_p8_1,
  128963. NULL,
  128964. 0
  128965. };
  128966. static long _vq_quantlist__44c2_s_p9_0[] = {
  128967. 6,
  128968. 5,
  128969. 7,
  128970. 4,
  128971. 8,
  128972. 3,
  128973. 9,
  128974. 2,
  128975. 10,
  128976. 1,
  128977. 11,
  128978. 0,
  128979. 12,
  128980. };
  128981. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128982. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128983. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128984. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128985. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128986. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128987. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128988. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128989. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128990. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128991. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128992. 11,11,11,11,11,11,11,11,11,
  128993. };
  128994. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128995. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128996. 552.5, 773.5, 994.5, 1215.5,
  128997. };
  128998. static long _vq_quantmap__44c2_s_p9_0[] = {
  128999. 11, 9, 7, 5, 3, 1, 0, 2,
  129000. 4, 6, 8, 10, 12,
  129001. };
  129002. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  129003. _vq_quantthresh__44c2_s_p9_0,
  129004. _vq_quantmap__44c2_s_p9_0,
  129005. 13,
  129006. 13
  129007. };
  129008. static static_codebook _44c2_s_p9_0 = {
  129009. 2, 169,
  129010. _vq_lengthlist__44c2_s_p9_0,
  129011. 1, -514541568, 1627103232, 4, 0,
  129012. _vq_quantlist__44c2_s_p9_0,
  129013. NULL,
  129014. &_vq_auxt__44c2_s_p9_0,
  129015. NULL,
  129016. 0
  129017. };
  129018. static long _vq_quantlist__44c2_s_p9_1[] = {
  129019. 6,
  129020. 5,
  129021. 7,
  129022. 4,
  129023. 8,
  129024. 3,
  129025. 9,
  129026. 2,
  129027. 10,
  129028. 1,
  129029. 11,
  129030. 0,
  129031. 12,
  129032. };
  129033. static long _vq_lengthlist__44c2_s_p9_1[] = {
  129034. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  129035. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  129036. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  129037. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  129038. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  129039. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  129040. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  129041. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  129042. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  129043. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  129044. 17,13,12,12,10,13,11,14,14,
  129045. };
  129046. static float _vq_quantthresh__44c2_s_p9_1[] = {
  129047. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  129048. 42.5, 59.5, 76.5, 93.5,
  129049. };
  129050. static long _vq_quantmap__44c2_s_p9_1[] = {
  129051. 11, 9, 7, 5, 3, 1, 0, 2,
  129052. 4, 6, 8, 10, 12,
  129053. };
  129054. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  129055. _vq_quantthresh__44c2_s_p9_1,
  129056. _vq_quantmap__44c2_s_p9_1,
  129057. 13,
  129058. 13
  129059. };
  129060. static static_codebook _44c2_s_p9_1 = {
  129061. 2, 169,
  129062. _vq_lengthlist__44c2_s_p9_1,
  129063. 1, -522616832, 1620115456, 4, 0,
  129064. _vq_quantlist__44c2_s_p9_1,
  129065. NULL,
  129066. &_vq_auxt__44c2_s_p9_1,
  129067. NULL,
  129068. 0
  129069. };
  129070. static long _vq_quantlist__44c2_s_p9_2[] = {
  129071. 8,
  129072. 7,
  129073. 9,
  129074. 6,
  129075. 10,
  129076. 5,
  129077. 11,
  129078. 4,
  129079. 12,
  129080. 3,
  129081. 13,
  129082. 2,
  129083. 14,
  129084. 1,
  129085. 15,
  129086. 0,
  129087. 16,
  129088. };
  129089. static long _vq_lengthlist__44c2_s_p9_2[] = {
  129090. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129091. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129092. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  129093. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  129094. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  129095. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129096. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  129097. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  129098. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  129099. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  129100. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  129101. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  129102. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  129103. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  129104. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  129105. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129106. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  129107. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  129108. 10,
  129109. };
  129110. static float _vq_quantthresh__44c2_s_p9_2[] = {
  129111. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129112. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129113. };
  129114. static long _vq_quantmap__44c2_s_p9_2[] = {
  129115. 15, 13, 11, 9, 7, 5, 3, 1,
  129116. 0, 2, 4, 6, 8, 10, 12, 14,
  129117. 16,
  129118. };
  129119. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  129120. _vq_quantthresh__44c2_s_p9_2,
  129121. _vq_quantmap__44c2_s_p9_2,
  129122. 17,
  129123. 17
  129124. };
  129125. static static_codebook _44c2_s_p9_2 = {
  129126. 2, 289,
  129127. _vq_lengthlist__44c2_s_p9_2,
  129128. 1, -529530880, 1611661312, 5, 0,
  129129. _vq_quantlist__44c2_s_p9_2,
  129130. NULL,
  129131. &_vq_auxt__44c2_s_p9_2,
  129132. NULL,
  129133. 0
  129134. };
  129135. static long _huff_lengthlist__44c2_s_short[] = {
  129136. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  129137. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  129138. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  129139. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129140. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129141. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129142. 6, 8, 9,12,
  129143. };
  129144. static static_codebook _huff_book__44c2_s_short = {
  129145. 2, 100,
  129146. _huff_lengthlist__44c2_s_short,
  129147. 0, 0, 0, 0, 0,
  129148. NULL,
  129149. NULL,
  129150. NULL,
  129151. NULL,
  129152. 0
  129153. };
  129154. static long _huff_lengthlist__44c3_s_long[] = {
  129155. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129156. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129157. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129158. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129159. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129160. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129161. 9, 8, 8, 8,
  129162. };
  129163. static static_codebook _huff_book__44c3_s_long = {
  129164. 2, 100,
  129165. _huff_lengthlist__44c3_s_long,
  129166. 0, 0, 0, 0, 0,
  129167. NULL,
  129168. NULL,
  129169. NULL,
  129170. NULL,
  129171. 0
  129172. };
  129173. static long _vq_quantlist__44c3_s_p1_0[] = {
  129174. 1,
  129175. 0,
  129176. 2,
  129177. };
  129178. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129179. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129180. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129185. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129190. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129225. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129230. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129235. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129271. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129276. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129281. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0,
  129590. };
  129591. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129592. -0.5, 0.5,
  129593. };
  129594. static long _vq_quantmap__44c3_s_p1_0[] = {
  129595. 1, 0, 2,
  129596. };
  129597. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129598. _vq_quantthresh__44c3_s_p1_0,
  129599. _vq_quantmap__44c3_s_p1_0,
  129600. 3,
  129601. 3
  129602. };
  129603. static static_codebook _44c3_s_p1_0 = {
  129604. 8, 6561,
  129605. _vq_lengthlist__44c3_s_p1_0,
  129606. 1, -535822336, 1611661312, 2, 0,
  129607. _vq_quantlist__44c3_s_p1_0,
  129608. NULL,
  129609. &_vq_auxt__44c3_s_p1_0,
  129610. NULL,
  129611. 0
  129612. };
  129613. static long _vq_quantlist__44c3_s_p2_0[] = {
  129614. 2,
  129615. 1,
  129616. 3,
  129617. 0,
  129618. 4,
  129619. };
  129620. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129621. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129622. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129623. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129624. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129625. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129630. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129631. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129632. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129633. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129638. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129639. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129640. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129646. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129647. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129648. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129660. 0,
  129661. };
  129662. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129663. -1.5, -0.5, 0.5, 1.5,
  129664. };
  129665. static long _vq_quantmap__44c3_s_p2_0[] = {
  129666. 3, 1, 0, 2, 4,
  129667. };
  129668. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129669. _vq_quantthresh__44c3_s_p2_0,
  129670. _vq_quantmap__44c3_s_p2_0,
  129671. 5,
  129672. 5
  129673. };
  129674. static static_codebook _44c3_s_p2_0 = {
  129675. 4, 625,
  129676. _vq_lengthlist__44c3_s_p2_0,
  129677. 1, -533725184, 1611661312, 3, 0,
  129678. _vq_quantlist__44c3_s_p2_0,
  129679. NULL,
  129680. &_vq_auxt__44c3_s_p2_0,
  129681. NULL,
  129682. 0
  129683. };
  129684. static long _vq_quantlist__44c3_s_p3_0[] = {
  129685. 2,
  129686. 1,
  129687. 3,
  129688. 0,
  129689. 4,
  129690. };
  129691. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129692. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129695. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129698. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0,
  129732. };
  129733. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129734. -1.5, -0.5, 0.5, 1.5,
  129735. };
  129736. static long _vq_quantmap__44c3_s_p3_0[] = {
  129737. 3, 1, 0, 2, 4,
  129738. };
  129739. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129740. _vq_quantthresh__44c3_s_p3_0,
  129741. _vq_quantmap__44c3_s_p3_0,
  129742. 5,
  129743. 5
  129744. };
  129745. static static_codebook _44c3_s_p3_0 = {
  129746. 4, 625,
  129747. _vq_lengthlist__44c3_s_p3_0,
  129748. 1, -533725184, 1611661312, 3, 0,
  129749. _vq_quantlist__44c3_s_p3_0,
  129750. NULL,
  129751. &_vq_auxt__44c3_s_p3_0,
  129752. NULL,
  129753. 0
  129754. };
  129755. static long _vq_quantlist__44c3_s_p4_0[] = {
  129756. 4,
  129757. 3,
  129758. 5,
  129759. 2,
  129760. 6,
  129761. 1,
  129762. 7,
  129763. 0,
  129764. 8,
  129765. };
  129766. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129767. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129768. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129769. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129770. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129771. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129772. 0,
  129773. };
  129774. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129775. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129776. };
  129777. static long _vq_quantmap__44c3_s_p4_0[] = {
  129778. 7, 5, 3, 1, 0, 2, 4, 6,
  129779. 8,
  129780. };
  129781. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129782. _vq_quantthresh__44c3_s_p4_0,
  129783. _vq_quantmap__44c3_s_p4_0,
  129784. 9,
  129785. 9
  129786. };
  129787. static static_codebook _44c3_s_p4_0 = {
  129788. 2, 81,
  129789. _vq_lengthlist__44c3_s_p4_0,
  129790. 1, -531628032, 1611661312, 4, 0,
  129791. _vq_quantlist__44c3_s_p4_0,
  129792. NULL,
  129793. &_vq_auxt__44c3_s_p4_0,
  129794. NULL,
  129795. 0
  129796. };
  129797. static long _vq_quantlist__44c3_s_p5_0[] = {
  129798. 4,
  129799. 3,
  129800. 5,
  129801. 2,
  129802. 6,
  129803. 1,
  129804. 7,
  129805. 0,
  129806. 8,
  129807. };
  129808. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129809. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129810. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129811. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129812. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129813. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129814. 11,
  129815. };
  129816. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129817. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129818. };
  129819. static long _vq_quantmap__44c3_s_p5_0[] = {
  129820. 7, 5, 3, 1, 0, 2, 4, 6,
  129821. 8,
  129822. };
  129823. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129824. _vq_quantthresh__44c3_s_p5_0,
  129825. _vq_quantmap__44c3_s_p5_0,
  129826. 9,
  129827. 9
  129828. };
  129829. static static_codebook _44c3_s_p5_0 = {
  129830. 2, 81,
  129831. _vq_lengthlist__44c3_s_p5_0,
  129832. 1, -531628032, 1611661312, 4, 0,
  129833. _vq_quantlist__44c3_s_p5_0,
  129834. NULL,
  129835. &_vq_auxt__44c3_s_p5_0,
  129836. NULL,
  129837. 0
  129838. };
  129839. static long _vq_quantlist__44c3_s_p6_0[] = {
  129840. 8,
  129841. 7,
  129842. 9,
  129843. 6,
  129844. 10,
  129845. 5,
  129846. 11,
  129847. 4,
  129848. 12,
  129849. 3,
  129850. 13,
  129851. 2,
  129852. 14,
  129853. 1,
  129854. 15,
  129855. 0,
  129856. 16,
  129857. };
  129858. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129859. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129860. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129861. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129862. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129863. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129864. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129865. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129866. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129867. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129868. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129869. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129870. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129871. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129872. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129873. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129874. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129875. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129876. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129877. 13,
  129878. };
  129879. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129880. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129881. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129882. };
  129883. static long _vq_quantmap__44c3_s_p6_0[] = {
  129884. 15, 13, 11, 9, 7, 5, 3, 1,
  129885. 0, 2, 4, 6, 8, 10, 12, 14,
  129886. 16,
  129887. };
  129888. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129889. _vq_quantthresh__44c3_s_p6_0,
  129890. _vq_quantmap__44c3_s_p6_0,
  129891. 17,
  129892. 17
  129893. };
  129894. static static_codebook _44c3_s_p6_0 = {
  129895. 2, 289,
  129896. _vq_lengthlist__44c3_s_p6_0,
  129897. 1, -529530880, 1611661312, 5, 0,
  129898. _vq_quantlist__44c3_s_p6_0,
  129899. NULL,
  129900. &_vq_auxt__44c3_s_p6_0,
  129901. NULL,
  129902. 0
  129903. };
  129904. static long _vq_quantlist__44c3_s_p7_0[] = {
  129905. 1,
  129906. 0,
  129907. 2,
  129908. };
  129909. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129910. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129911. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129912. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129913. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129914. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129915. 10,
  129916. };
  129917. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129918. -5.5, 5.5,
  129919. };
  129920. static long _vq_quantmap__44c3_s_p7_0[] = {
  129921. 1, 0, 2,
  129922. };
  129923. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129924. _vq_quantthresh__44c3_s_p7_0,
  129925. _vq_quantmap__44c3_s_p7_0,
  129926. 3,
  129927. 3
  129928. };
  129929. static static_codebook _44c3_s_p7_0 = {
  129930. 4, 81,
  129931. _vq_lengthlist__44c3_s_p7_0,
  129932. 1, -529137664, 1618345984, 2, 0,
  129933. _vq_quantlist__44c3_s_p7_0,
  129934. NULL,
  129935. &_vq_auxt__44c3_s_p7_0,
  129936. NULL,
  129937. 0
  129938. };
  129939. static long _vq_quantlist__44c3_s_p7_1[] = {
  129940. 5,
  129941. 4,
  129942. 6,
  129943. 3,
  129944. 7,
  129945. 2,
  129946. 8,
  129947. 1,
  129948. 9,
  129949. 0,
  129950. 10,
  129951. };
  129952. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129953. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129954. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129955. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129956. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129957. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129958. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129959. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129960. 10,10,10, 8, 8, 8, 8, 8, 8,
  129961. };
  129962. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129963. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129964. 3.5, 4.5,
  129965. };
  129966. static long _vq_quantmap__44c3_s_p7_1[] = {
  129967. 9, 7, 5, 3, 1, 0, 2, 4,
  129968. 6, 8, 10,
  129969. };
  129970. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129971. _vq_quantthresh__44c3_s_p7_1,
  129972. _vq_quantmap__44c3_s_p7_1,
  129973. 11,
  129974. 11
  129975. };
  129976. static static_codebook _44c3_s_p7_1 = {
  129977. 2, 121,
  129978. _vq_lengthlist__44c3_s_p7_1,
  129979. 1, -531365888, 1611661312, 4, 0,
  129980. _vq_quantlist__44c3_s_p7_1,
  129981. NULL,
  129982. &_vq_auxt__44c3_s_p7_1,
  129983. NULL,
  129984. 0
  129985. };
  129986. static long _vq_quantlist__44c3_s_p8_0[] = {
  129987. 6,
  129988. 5,
  129989. 7,
  129990. 4,
  129991. 8,
  129992. 3,
  129993. 9,
  129994. 2,
  129995. 10,
  129996. 1,
  129997. 11,
  129998. 0,
  129999. 12,
  130000. };
  130001. static long _vq_lengthlist__44c3_s_p8_0[] = {
  130002. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130003. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  130004. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130005. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130006. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  130007. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  130008. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  130009. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130010. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  130011. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  130012. 0,13,13,12,12,13,12,14,13,
  130013. };
  130014. static float _vq_quantthresh__44c3_s_p8_0[] = {
  130015. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130016. 12.5, 17.5, 22.5, 27.5,
  130017. };
  130018. static long _vq_quantmap__44c3_s_p8_0[] = {
  130019. 11, 9, 7, 5, 3, 1, 0, 2,
  130020. 4, 6, 8, 10, 12,
  130021. };
  130022. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  130023. _vq_quantthresh__44c3_s_p8_0,
  130024. _vq_quantmap__44c3_s_p8_0,
  130025. 13,
  130026. 13
  130027. };
  130028. static static_codebook _44c3_s_p8_0 = {
  130029. 2, 169,
  130030. _vq_lengthlist__44c3_s_p8_0,
  130031. 1, -526516224, 1616117760, 4, 0,
  130032. _vq_quantlist__44c3_s_p8_0,
  130033. NULL,
  130034. &_vq_auxt__44c3_s_p8_0,
  130035. NULL,
  130036. 0
  130037. };
  130038. static long _vq_quantlist__44c3_s_p8_1[] = {
  130039. 2,
  130040. 1,
  130041. 3,
  130042. 0,
  130043. 4,
  130044. };
  130045. static long _vq_lengthlist__44c3_s_p8_1[] = {
  130046. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  130047. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130048. };
  130049. static float _vq_quantthresh__44c3_s_p8_1[] = {
  130050. -1.5, -0.5, 0.5, 1.5,
  130051. };
  130052. static long _vq_quantmap__44c3_s_p8_1[] = {
  130053. 3, 1, 0, 2, 4,
  130054. };
  130055. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  130056. _vq_quantthresh__44c3_s_p8_1,
  130057. _vq_quantmap__44c3_s_p8_1,
  130058. 5,
  130059. 5
  130060. };
  130061. static static_codebook _44c3_s_p8_1 = {
  130062. 2, 25,
  130063. _vq_lengthlist__44c3_s_p8_1,
  130064. 1, -533725184, 1611661312, 3, 0,
  130065. _vq_quantlist__44c3_s_p8_1,
  130066. NULL,
  130067. &_vq_auxt__44c3_s_p8_1,
  130068. NULL,
  130069. 0
  130070. };
  130071. static long _vq_quantlist__44c3_s_p9_0[] = {
  130072. 6,
  130073. 5,
  130074. 7,
  130075. 4,
  130076. 8,
  130077. 3,
  130078. 9,
  130079. 2,
  130080. 10,
  130081. 1,
  130082. 11,
  130083. 0,
  130084. 12,
  130085. };
  130086. static long _vq_lengthlist__44c3_s_p9_0[] = {
  130087. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  130088. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  130089. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130090. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  130091. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130092. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130093. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130094. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130095. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130097. 11,11,11,11,11,11,11,11,11,
  130098. };
  130099. static float _vq_quantthresh__44c3_s_p9_0[] = {
  130100. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  130101. 637.5, 892.5, 1147.5, 1402.5,
  130102. };
  130103. static long _vq_quantmap__44c3_s_p9_0[] = {
  130104. 11, 9, 7, 5, 3, 1, 0, 2,
  130105. 4, 6, 8, 10, 12,
  130106. };
  130107. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  130108. _vq_quantthresh__44c3_s_p9_0,
  130109. _vq_quantmap__44c3_s_p9_0,
  130110. 13,
  130111. 13
  130112. };
  130113. static static_codebook _44c3_s_p9_0 = {
  130114. 2, 169,
  130115. _vq_lengthlist__44c3_s_p9_0,
  130116. 1, -514332672, 1627381760, 4, 0,
  130117. _vq_quantlist__44c3_s_p9_0,
  130118. NULL,
  130119. &_vq_auxt__44c3_s_p9_0,
  130120. NULL,
  130121. 0
  130122. };
  130123. static long _vq_quantlist__44c3_s_p9_1[] = {
  130124. 7,
  130125. 6,
  130126. 8,
  130127. 5,
  130128. 9,
  130129. 4,
  130130. 10,
  130131. 3,
  130132. 11,
  130133. 2,
  130134. 12,
  130135. 1,
  130136. 13,
  130137. 0,
  130138. 14,
  130139. };
  130140. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130141. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130142. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130143. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130144. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130145. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130146. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130147. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130148. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130149. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130150. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130151. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130152. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130153. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130154. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130155. 15,
  130156. };
  130157. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130158. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130159. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130160. };
  130161. static long _vq_quantmap__44c3_s_p9_1[] = {
  130162. 13, 11, 9, 7, 5, 3, 1, 0,
  130163. 2, 4, 6, 8, 10, 12, 14,
  130164. };
  130165. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130166. _vq_quantthresh__44c3_s_p9_1,
  130167. _vq_quantmap__44c3_s_p9_1,
  130168. 15,
  130169. 15
  130170. };
  130171. static static_codebook _44c3_s_p9_1 = {
  130172. 2, 225,
  130173. _vq_lengthlist__44c3_s_p9_1,
  130174. 1, -522338304, 1620115456, 4, 0,
  130175. _vq_quantlist__44c3_s_p9_1,
  130176. NULL,
  130177. &_vq_auxt__44c3_s_p9_1,
  130178. NULL,
  130179. 0
  130180. };
  130181. static long _vq_quantlist__44c3_s_p9_2[] = {
  130182. 8,
  130183. 7,
  130184. 9,
  130185. 6,
  130186. 10,
  130187. 5,
  130188. 11,
  130189. 4,
  130190. 12,
  130191. 3,
  130192. 13,
  130193. 2,
  130194. 14,
  130195. 1,
  130196. 15,
  130197. 0,
  130198. 16,
  130199. };
  130200. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130201. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130202. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130203. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130204. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130205. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130206. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130207. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130208. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130209. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130210. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130211. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130212. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130213. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130214. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130215. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130216. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130217. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130218. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130219. 10,
  130220. };
  130221. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130222. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130223. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130224. };
  130225. static long _vq_quantmap__44c3_s_p9_2[] = {
  130226. 15, 13, 11, 9, 7, 5, 3, 1,
  130227. 0, 2, 4, 6, 8, 10, 12, 14,
  130228. 16,
  130229. };
  130230. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130231. _vq_quantthresh__44c3_s_p9_2,
  130232. _vq_quantmap__44c3_s_p9_2,
  130233. 17,
  130234. 17
  130235. };
  130236. static static_codebook _44c3_s_p9_2 = {
  130237. 2, 289,
  130238. _vq_lengthlist__44c3_s_p9_2,
  130239. 1, -529530880, 1611661312, 5, 0,
  130240. _vq_quantlist__44c3_s_p9_2,
  130241. NULL,
  130242. &_vq_auxt__44c3_s_p9_2,
  130243. NULL,
  130244. 0
  130245. };
  130246. static long _huff_lengthlist__44c3_s_short[] = {
  130247. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130248. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130249. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130250. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130251. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130252. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130253. 6, 8, 9,11,
  130254. };
  130255. static static_codebook _huff_book__44c3_s_short = {
  130256. 2, 100,
  130257. _huff_lengthlist__44c3_s_short,
  130258. 0, 0, 0, 0, 0,
  130259. NULL,
  130260. NULL,
  130261. NULL,
  130262. NULL,
  130263. 0
  130264. };
  130265. static long _huff_lengthlist__44c4_s_long[] = {
  130266. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130267. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130268. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130269. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130270. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130271. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130272. 9, 8, 7, 7,
  130273. };
  130274. static static_codebook _huff_book__44c4_s_long = {
  130275. 2, 100,
  130276. _huff_lengthlist__44c4_s_long,
  130277. 0, 0, 0, 0, 0,
  130278. NULL,
  130279. NULL,
  130280. NULL,
  130281. NULL,
  130282. 0
  130283. };
  130284. static long _vq_quantlist__44c4_s_p1_0[] = {
  130285. 1,
  130286. 0,
  130287. 2,
  130288. };
  130289. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130290. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130291. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130296. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130301. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130336. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130341. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130346. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130382. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130387. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130392. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0,
  130701. };
  130702. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130703. -0.5, 0.5,
  130704. };
  130705. static long _vq_quantmap__44c4_s_p1_0[] = {
  130706. 1, 0, 2,
  130707. };
  130708. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130709. _vq_quantthresh__44c4_s_p1_0,
  130710. _vq_quantmap__44c4_s_p1_0,
  130711. 3,
  130712. 3
  130713. };
  130714. static static_codebook _44c4_s_p1_0 = {
  130715. 8, 6561,
  130716. _vq_lengthlist__44c4_s_p1_0,
  130717. 1, -535822336, 1611661312, 2, 0,
  130718. _vq_quantlist__44c4_s_p1_0,
  130719. NULL,
  130720. &_vq_auxt__44c4_s_p1_0,
  130721. NULL,
  130722. 0
  130723. };
  130724. static long _vq_quantlist__44c4_s_p2_0[] = {
  130725. 2,
  130726. 1,
  130727. 3,
  130728. 0,
  130729. 4,
  130730. };
  130731. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130732. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130733. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130734. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130735. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130736. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130741. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130742. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130743. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130744. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130749. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130750. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130751. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130757. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130758. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130759. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130771. 0,
  130772. };
  130773. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130774. -1.5, -0.5, 0.5, 1.5,
  130775. };
  130776. static long _vq_quantmap__44c4_s_p2_0[] = {
  130777. 3, 1, 0, 2, 4,
  130778. };
  130779. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130780. _vq_quantthresh__44c4_s_p2_0,
  130781. _vq_quantmap__44c4_s_p2_0,
  130782. 5,
  130783. 5
  130784. };
  130785. static static_codebook _44c4_s_p2_0 = {
  130786. 4, 625,
  130787. _vq_lengthlist__44c4_s_p2_0,
  130788. 1, -533725184, 1611661312, 3, 0,
  130789. _vq_quantlist__44c4_s_p2_0,
  130790. NULL,
  130791. &_vq_auxt__44c4_s_p2_0,
  130792. NULL,
  130793. 0
  130794. };
  130795. static long _vq_quantlist__44c4_s_p3_0[] = {
  130796. 2,
  130797. 1,
  130798. 3,
  130799. 0,
  130800. 4,
  130801. };
  130802. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130803. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130806. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130809. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0,
  130843. };
  130844. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130845. -1.5, -0.5, 0.5, 1.5,
  130846. };
  130847. static long _vq_quantmap__44c4_s_p3_0[] = {
  130848. 3, 1, 0, 2, 4,
  130849. };
  130850. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130851. _vq_quantthresh__44c4_s_p3_0,
  130852. _vq_quantmap__44c4_s_p3_0,
  130853. 5,
  130854. 5
  130855. };
  130856. static static_codebook _44c4_s_p3_0 = {
  130857. 4, 625,
  130858. _vq_lengthlist__44c4_s_p3_0,
  130859. 1, -533725184, 1611661312, 3, 0,
  130860. _vq_quantlist__44c4_s_p3_0,
  130861. NULL,
  130862. &_vq_auxt__44c4_s_p3_0,
  130863. NULL,
  130864. 0
  130865. };
  130866. static long _vq_quantlist__44c4_s_p4_0[] = {
  130867. 4,
  130868. 3,
  130869. 5,
  130870. 2,
  130871. 6,
  130872. 1,
  130873. 7,
  130874. 0,
  130875. 8,
  130876. };
  130877. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130878. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130879. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130880. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130881. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130882. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130883. 0,
  130884. };
  130885. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130886. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130887. };
  130888. static long _vq_quantmap__44c4_s_p4_0[] = {
  130889. 7, 5, 3, 1, 0, 2, 4, 6,
  130890. 8,
  130891. };
  130892. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130893. _vq_quantthresh__44c4_s_p4_0,
  130894. _vq_quantmap__44c4_s_p4_0,
  130895. 9,
  130896. 9
  130897. };
  130898. static static_codebook _44c4_s_p4_0 = {
  130899. 2, 81,
  130900. _vq_lengthlist__44c4_s_p4_0,
  130901. 1, -531628032, 1611661312, 4, 0,
  130902. _vq_quantlist__44c4_s_p4_0,
  130903. NULL,
  130904. &_vq_auxt__44c4_s_p4_0,
  130905. NULL,
  130906. 0
  130907. };
  130908. static long _vq_quantlist__44c4_s_p5_0[] = {
  130909. 4,
  130910. 3,
  130911. 5,
  130912. 2,
  130913. 6,
  130914. 1,
  130915. 7,
  130916. 0,
  130917. 8,
  130918. };
  130919. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130920. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130921. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130922. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130923. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130924. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130925. 10,
  130926. };
  130927. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130928. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130929. };
  130930. static long _vq_quantmap__44c4_s_p5_0[] = {
  130931. 7, 5, 3, 1, 0, 2, 4, 6,
  130932. 8,
  130933. };
  130934. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130935. _vq_quantthresh__44c4_s_p5_0,
  130936. _vq_quantmap__44c4_s_p5_0,
  130937. 9,
  130938. 9
  130939. };
  130940. static static_codebook _44c4_s_p5_0 = {
  130941. 2, 81,
  130942. _vq_lengthlist__44c4_s_p5_0,
  130943. 1, -531628032, 1611661312, 4, 0,
  130944. _vq_quantlist__44c4_s_p5_0,
  130945. NULL,
  130946. &_vq_auxt__44c4_s_p5_0,
  130947. NULL,
  130948. 0
  130949. };
  130950. static long _vq_quantlist__44c4_s_p6_0[] = {
  130951. 8,
  130952. 7,
  130953. 9,
  130954. 6,
  130955. 10,
  130956. 5,
  130957. 11,
  130958. 4,
  130959. 12,
  130960. 3,
  130961. 13,
  130962. 2,
  130963. 14,
  130964. 1,
  130965. 15,
  130966. 0,
  130967. 16,
  130968. };
  130969. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130970. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130971. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130972. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130973. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130974. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130975. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130976. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130977. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130978. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130979. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130980. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130981. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130982. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130983. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130984. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130985. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130986. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130988. 13,
  130989. };
  130990. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130991. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130992. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130993. };
  130994. static long _vq_quantmap__44c4_s_p6_0[] = {
  130995. 15, 13, 11, 9, 7, 5, 3, 1,
  130996. 0, 2, 4, 6, 8, 10, 12, 14,
  130997. 16,
  130998. };
  130999. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  131000. _vq_quantthresh__44c4_s_p6_0,
  131001. _vq_quantmap__44c4_s_p6_0,
  131002. 17,
  131003. 17
  131004. };
  131005. static static_codebook _44c4_s_p6_0 = {
  131006. 2, 289,
  131007. _vq_lengthlist__44c4_s_p6_0,
  131008. 1, -529530880, 1611661312, 5, 0,
  131009. _vq_quantlist__44c4_s_p6_0,
  131010. NULL,
  131011. &_vq_auxt__44c4_s_p6_0,
  131012. NULL,
  131013. 0
  131014. };
  131015. static long _vq_quantlist__44c4_s_p7_0[] = {
  131016. 1,
  131017. 0,
  131018. 2,
  131019. };
  131020. static long _vq_lengthlist__44c4_s_p7_0[] = {
  131021. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131022. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131023. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131024. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131025. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131026. 10,
  131027. };
  131028. static float _vq_quantthresh__44c4_s_p7_0[] = {
  131029. -5.5, 5.5,
  131030. };
  131031. static long _vq_quantmap__44c4_s_p7_0[] = {
  131032. 1, 0, 2,
  131033. };
  131034. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  131035. _vq_quantthresh__44c4_s_p7_0,
  131036. _vq_quantmap__44c4_s_p7_0,
  131037. 3,
  131038. 3
  131039. };
  131040. static static_codebook _44c4_s_p7_0 = {
  131041. 4, 81,
  131042. _vq_lengthlist__44c4_s_p7_0,
  131043. 1, -529137664, 1618345984, 2, 0,
  131044. _vq_quantlist__44c4_s_p7_0,
  131045. NULL,
  131046. &_vq_auxt__44c4_s_p7_0,
  131047. NULL,
  131048. 0
  131049. };
  131050. static long _vq_quantlist__44c4_s_p7_1[] = {
  131051. 5,
  131052. 4,
  131053. 6,
  131054. 3,
  131055. 7,
  131056. 2,
  131057. 8,
  131058. 1,
  131059. 9,
  131060. 0,
  131061. 10,
  131062. };
  131063. static long _vq_lengthlist__44c4_s_p7_1[] = {
  131064. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  131065. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131066. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131067. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131068. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131069. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131070. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  131071. 10,10,10, 8, 8, 8, 8, 9, 9,
  131072. };
  131073. static float _vq_quantthresh__44c4_s_p7_1[] = {
  131074. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131075. 3.5, 4.5,
  131076. };
  131077. static long _vq_quantmap__44c4_s_p7_1[] = {
  131078. 9, 7, 5, 3, 1, 0, 2, 4,
  131079. 6, 8, 10,
  131080. };
  131081. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  131082. _vq_quantthresh__44c4_s_p7_1,
  131083. _vq_quantmap__44c4_s_p7_1,
  131084. 11,
  131085. 11
  131086. };
  131087. static static_codebook _44c4_s_p7_1 = {
  131088. 2, 121,
  131089. _vq_lengthlist__44c4_s_p7_1,
  131090. 1, -531365888, 1611661312, 4, 0,
  131091. _vq_quantlist__44c4_s_p7_1,
  131092. NULL,
  131093. &_vq_auxt__44c4_s_p7_1,
  131094. NULL,
  131095. 0
  131096. };
  131097. static long _vq_quantlist__44c4_s_p8_0[] = {
  131098. 6,
  131099. 5,
  131100. 7,
  131101. 4,
  131102. 8,
  131103. 3,
  131104. 9,
  131105. 2,
  131106. 10,
  131107. 1,
  131108. 11,
  131109. 0,
  131110. 12,
  131111. };
  131112. static long _vq_lengthlist__44c4_s_p8_0[] = {
  131113. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131114. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  131115. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131116. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131117. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  131118. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131119. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  131120. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131121. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  131122. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131123. 0,13,12,12,12,12,12,13,13,
  131124. };
  131125. static float _vq_quantthresh__44c4_s_p8_0[] = {
  131126. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131127. 12.5, 17.5, 22.5, 27.5,
  131128. };
  131129. static long _vq_quantmap__44c4_s_p8_0[] = {
  131130. 11, 9, 7, 5, 3, 1, 0, 2,
  131131. 4, 6, 8, 10, 12,
  131132. };
  131133. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  131134. _vq_quantthresh__44c4_s_p8_0,
  131135. _vq_quantmap__44c4_s_p8_0,
  131136. 13,
  131137. 13
  131138. };
  131139. static static_codebook _44c4_s_p8_0 = {
  131140. 2, 169,
  131141. _vq_lengthlist__44c4_s_p8_0,
  131142. 1, -526516224, 1616117760, 4, 0,
  131143. _vq_quantlist__44c4_s_p8_0,
  131144. NULL,
  131145. &_vq_auxt__44c4_s_p8_0,
  131146. NULL,
  131147. 0
  131148. };
  131149. static long _vq_quantlist__44c4_s_p8_1[] = {
  131150. 2,
  131151. 1,
  131152. 3,
  131153. 0,
  131154. 4,
  131155. };
  131156. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131157. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131158. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131159. };
  131160. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131161. -1.5, -0.5, 0.5, 1.5,
  131162. };
  131163. static long _vq_quantmap__44c4_s_p8_1[] = {
  131164. 3, 1, 0, 2, 4,
  131165. };
  131166. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131167. _vq_quantthresh__44c4_s_p8_1,
  131168. _vq_quantmap__44c4_s_p8_1,
  131169. 5,
  131170. 5
  131171. };
  131172. static static_codebook _44c4_s_p8_1 = {
  131173. 2, 25,
  131174. _vq_lengthlist__44c4_s_p8_1,
  131175. 1, -533725184, 1611661312, 3, 0,
  131176. _vq_quantlist__44c4_s_p8_1,
  131177. NULL,
  131178. &_vq_auxt__44c4_s_p8_1,
  131179. NULL,
  131180. 0
  131181. };
  131182. static long _vq_quantlist__44c4_s_p9_0[] = {
  131183. 6,
  131184. 5,
  131185. 7,
  131186. 4,
  131187. 8,
  131188. 3,
  131189. 9,
  131190. 2,
  131191. 10,
  131192. 1,
  131193. 11,
  131194. 0,
  131195. 12,
  131196. };
  131197. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131198. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131199. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131200. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131201. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131202. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131203. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131204. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131205. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131206. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131207. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131208. 12,12,12,12,12,12,12,12,12,
  131209. };
  131210. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131211. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131212. 787.5, 1102.5, 1417.5, 1732.5,
  131213. };
  131214. static long _vq_quantmap__44c4_s_p9_0[] = {
  131215. 11, 9, 7, 5, 3, 1, 0, 2,
  131216. 4, 6, 8, 10, 12,
  131217. };
  131218. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131219. _vq_quantthresh__44c4_s_p9_0,
  131220. _vq_quantmap__44c4_s_p9_0,
  131221. 13,
  131222. 13
  131223. };
  131224. static static_codebook _44c4_s_p9_0 = {
  131225. 2, 169,
  131226. _vq_lengthlist__44c4_s_p9_0,
  131227. 1, -513964032, 1628680192, 4, 0,
  131228. _vq_quantlist__44c4_s_p9_0,
  131229. NULL,
  131230. &_vq_auxt__44c4_s_p9_0,
  131231. NULL,
  131232. 0
  131233. };
  131234. static long _vq_quantlist__44c4_s_p9_1[] = {
  131235. 7,
  131236. 6,
  131237. 8,
  131238. 5,
  131239. 9,
  131240. 4,
  131241. 10,
  131242. 3,
  131243. 11,
  131244. 2,
  131245. 12,
  131246. 1,
  131247. 13,
  131248. 0,
  131249. 14,
  131250. };
  131251. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131252. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131253. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131254. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131255. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131256. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131257. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131258. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131259. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131260. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131261. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131262. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131263. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131264. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131265. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131266. 15,
  131267. };
  131268. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131269. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131270. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131271. };
  131272. static long _vq_quantmap__44c4_s_p9_1[] = {
  131273. 13, 11, 9, 7, 5, 3, 1, 0,
  131274. 2, 4, 6, 8, 10, 12, 14,
  131275. };
  131276. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131277. _vq_quantthresh__44c4_s_p9_1,
  131278. _vq_quantmap__44c4_s_p9_1,
  131279. 15,
  131280. 15
  131281. };
  131282. static static_codebook _44c4_s_p9_1 = {
  131283. 2, 225,
  131284. _vq_lengthlist__44c4_s_p9_1,
  131285. 1, -520986624, 1620377600, 4, 0,
  131286. _vq_quantlist__44c4_s_p9_1,
  131287. NULL,
  131288. &_vq_auxt__44c4_s_p9_1,
  131289. NULL,
  131290. 0
  131291. };
  131292. static long _vq_quantlist__44c4_s_p9_2[] = {
  131293. 10,
  131294. 9,
  131295. 11,
  131296. 8,
  131297. 12,
  131298. 7,
  131299. 13,
  131300. 6,
  131301. 14,
  131302. 5,
  131303. 15,
  131304. 4,
  131305. 16,
  131306. 3,
  131307. 17,
  131308. 2,
  131309. 18,
  131310. 1,
  131311. 19,
  131312. 0,
  131313. 20,
  131314. };
  131315. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131316. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131317. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131318. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131319. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131320. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131321. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131322. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131323. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131324. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131325. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131326. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131327. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131328. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131329. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131330. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131331. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131332. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131333. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131334. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131335. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131336. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131337. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131338. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131339. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131340. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131341. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131342. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131343. 10,10,10,10,10,10,10,10,10,
  131344. };
  131345. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131346. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131347. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131348. 6.5, 7.5, 8.5, 9.5,
  131349. };
  131350. static long _vq_quantmap__44c4_s_p9_2[] = {
  131351. 19, 17, 15, 13, 11, 9, 7, 5,
  131352. 3, 1, 0, 2, 4, 6, 8, 10,
  131353. 12, 14, 16, 18, 20,
  131354. };
  131355. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131356. _vq_quantthresh__44c4_s_p9_2,
  131357. _vq_quantmap__44c4_s_p9_2,
  131358. 21,
  131359. 21
  131360. };
  131361. static static_codebook _44c4_s_p9_2 = {
  131362. 2, 441,
  131363. _vq_lengthlist__44c4_s_p9_2,
  131364. 1, -529268736, 1611661312, 5, 0,
  131365. _vq_quantlist__44c4_s_p9_2,
  131366. NULL,
  131367. &_vq_auxt__44c4_s_p9_2,
  131368. NULL,
  131369. 0
  131370. };
  131371. static long _huff_lengthlist__44c4_s_short[] = {
  131372. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131373. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131374. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131375. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131376. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131377. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131378. 7, 9,12,17,
  131379. };
  131380. static static_codebook _huff_book__44c4_s_short = {
  131381. 2, 100,
  131382. _huff_lengthlist__44c4_s_short,
  131383. 0, 0, 0, 0, 0,
  131384. NULL,
  131385. NULL,
  131386. NULL,
  131387. NULL,
  131388. 0
  131389. };
  131390. static long _huff_lengthlist__44c5_s_long[] = {
  131391. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131392. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131393. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131394. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131395. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131396. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131397. 9, 8, 7, 7,
  131398. };
  131399. static static_codebook _huff_book__44c5_s_long = {
  131400. 2, 100,
  131401. _huff_lengthlist__44c5_s_long,
  131402. 0, 0, 0, 0, 0,
  131403. NULL,
  131404. NULL,
  131405. NULL,
  131406. NULL,
  131407. 0
  131408. };
  131409. static long _vq_quantlist__44c5_s_p1_0[] = {
  131410. 1,
  131411. 0,
  131412. 2,
  131413. };
  131414. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131415. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131416. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131421. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131426. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131461. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131466. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131471. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131507. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131512. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131517. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131825. 0,
  131826. };
  131827. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131828. -0.5, 0.5,
  131829. };
  131830. static long _vq_quantmap__44c5_s_p1_0[] = {
  131831. 1, 0, 2,
  131832. };
  131833. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131834. _vq_quantthresh__44c5_s_p1_0,
  131835. _vq_quantmap__44c5_s_p1_0,
  131836. 3,
  131837. 3
  131838. };
  131839. static static_codebook _44c5_s_p1_0 = {
  131840. 8, 6561,
  131841. _vq_lengthlist__44c5_s_p1_0,
  131842. 1, -535822336, 1611661312, 2, 0,
  131843. _vq_quantlist__44c5_s_p1_0,
  131844. NULL,
  131845. &_vq_auxt__44c5_s_p1_0,
  131846. NULL,
  131847. 0
  131848. };
  131849. static long _vq_quantlist__44c5_s_p2_0[] = {
  131850. 2,
  131851. 1,
  131852. 3,
  131853. 0,
  131854. 4,
  131855. };
  131856. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131857. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131858. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131859. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131860. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131861. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131866. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131867. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131868. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131869. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131874. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131875. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131876. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131882. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131883. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131884. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131896. 0,
  131897. };
  131898. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131899. -1.5, -0.5, 0.5, 1.5,
  131900. };
  131901. static long _vq_quantmap__44c5_s_p2_0[] = {
  131902. 3, 1, 0, 2, 4,
  131903. };
  131904. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131905. _vq_quantthresh__44c5_s_p2_0,
  131906. _vq_quantmap__44c5_s_p2_0,
  131907. 5,
  131908. 5
  131909. };
  131910. static static_codebook _44c5_s_p2_0 = {
  131911. 4, 625,
  131912. _vq_lengthlist__44c5_s_p2_0,
  131913. 1, -533725184, 1611661312, 3, 0,
  131914. _vq_quantlist__44c5_s_p2_0,
  131915. NULL,
  131916. &_vq_auxt__44c5_s_p2_0,
  131917. NULL,
  131918. 0
  131919. };
  131920. static long _vq_quantlist__44c5_s_p3_0[] = {
  131921. 2,
  131922. 1,
  131923. 3,
  131924. 0,
  131925. 4,
  131926. };
  131927. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131928. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131931. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131934. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0,
  131968. };
  131969. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131970. -1.5, -0.5, 0.5, 1.5,
  131971. };
  131972. static long _vq_quantmap__44c5_s_p3_0[] = {
  131973. 3, 1, 0, 2, 4,
  131974. };
  131975. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131976. _vq_quantthresh__44c5_s_p3_0,
  131977. _vq_quantmap__44c5_s_p3_0,
  131978. 5,
  131979. 5
  131980. };
  131981. static static_codebook _44c5_s_p3_0 = {
  131982. 4, 625,
  131983. _vq_lengthlist__44c5_s_p3_0,
  131984. 1, -533725184, 1611661312, 3, 0,
  131985. _vq_quantlist__44c5_s_p3_0,
  131986. NULL,
  131987. &_vq_auxt__44c5_s_p3_0,
  131988. NULL,
  131989. 0
  131990. };
  131991. static long _vq_quantlist__44c5_s_p4_0[] = {
  131992. 4,
  131993. 3,
  131994. 5,
  131995. 2,
  131996. 6,
  131997. 1,
  131998. 7,
  131999. 0,
  132000. 8,
  132001. };
  132002. static long _vq_lengthlist__44c5_s_p4_0[] = {
  132003. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  132004. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  132005. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  132006. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  132007. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132008. 0,
  132009. };
  132010. static float _vq_quantthresh__44c5_s_p4_0[] = {
  132011. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132012. };
  132013. static long _vq_quantmap__44c5_s_p4_0[] = {
  132014. 7, 5, 3, 1, 0, 2, 4, 6,
  132015. 8,
  132016. };
  132017. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  132018. _vq_quantthresh__44c5_s_p4_0,
  132019. _vq_quantmap__44c5_s_p4_0,
  132020. 9,
  132021. 9
  132022. };
  132023. static static_codebook _44c5_s_p4_0 = {
  132024. 2, 81,
  132025. _vq_lengthlist__44c5_s_p4_0,
  132026. 1, -531628032, 1611661312, 4, 0,
  132027. _vq_quantlist__44c5_s_p4_0,
  132028. NULL,
  132029. &_vq_auxt__44c5_s_p4_0,
  132030. NULL,
  132031. 0
  132032. };
  132033. static long _vq_quantlist__44c5_s_p5_0[] = {
  132034. 4,
  132035. 3,
  132036. 5,
  132037. 2,
  132038. 6,
  132039. 1,
  132040. 7,
  132041. 0,
  132042. 8,
  132043. };
  132044. static long _vq_lengthlist__44c5_s_p5_0[] = {
  132045. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132046. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  132047. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  132048. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132049. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132050. 10,
  132051. };
  132052. static float _vq_quantthresh__44c5_s_p5_0[] = {
  132053. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132054. };
  132055. static long _vq_quantmap__44c5_s_p5_0[] = {
  132056. 7, 5, 3, 1, 0, 2, 4, 6,
  132057. 8,
  132058. };
  132059. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  132060. _vq_quantthresh__44c5_s_p5_0,
  132061. _vq_quantmap__44c5_s_p5_0,
  132062. 9,
  132063. 9
  132064. };
  132065. static static_codebook _44c5_s_p5_0 = {
  132066. 2, 81,
  132067. _vq_lengthlist__44c5_s_p5_0,
  132068. 1, -531628032, 1611661312, 4, 0,
  132069. _vq_quantlist__44c5_s_p5_0,
  132070. NULL,
  132071. &_vq_auxt__44c5_s_p5_0,
  132072. NULL,
  132073. 0
  132074. };
  132075. static long _vq_quantlist__44c5_s_p6_0[] = {
  132076. 8,
  132077. 7,
  132078. 9,
  132079. 6,
  132080. 10,
  132081. 5,
  132082. 11,
  132083. 4,
  132084. 12,
  132085. 3,
  132086. 13,
  132087. 2,
  132088. 14,
  132089. 1,
  132090. 15,
  132091. 0,
  132092. 16,
  132093. };
  132094. static long _vq_lengthlist__44c5_s_p6_0[] = {
  132095. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  132096. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  132097. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  132098. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132099. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132100. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132101. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  132102. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  132103. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132104. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132105. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  132106. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  132107. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132108. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132109. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  132110. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  132111. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  132112. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  132113. 13,
  132114. };
  132115. static float _vq_quantthresh__44c5_s_p6_0[] = {
  132116. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132117. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132118. };
  132119. static long _vq_quantmap__44c5_s_p6_0[] = {
  132120. 15, 13, 11, 9, 7, 5, 3, 1,
  132121. 0, 2, 4, 6, 8, 10, 12, 14,
  132122. 16,
  132123. };
  132124. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  132125. _vq_quantthresh__44c5_s_p6_0,
  132126. _vq_quantmap__44c5_s_p6_0,
  132127. 17,
  132128. 17
  132129. };
  132130. static static_codebook _44c5_s_p6_0 = {
  132131. 2, 289,
  132132. _vq_lengthlist__44c5_s_p6_0,
  132133. 1, -529530880, 1611661312, 5, 0,
  132134. _vq_quantlist__44c5_s_p6_0,
  132135. NULL,
  132136. &_vq_auxt__44c5_s_p6_0,
  132137. NULL,
  132138. 0
  132139. };
  132140. static long _vq_quantlist__44c5_s_p7_0[] = {
  132141. 1,
  132142. 0,
  132143. 2,
  132144. };
  132145. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132146. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132147. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132148. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132149. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132150. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132151. 10,
  132152. };
  132153. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132154. -5.5, 5.5,
  132155. };
  132156. static long _vq_quantmap__44c5_s_p7_0[] = {
  132157. 1, 0, 2,
  132158. };
  132159. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132160. _vq_quantthresh__44c5_s_p7_0,
  132161. _vq_quantmap__44c5_s_p7_0,
  132162. 3,
  132163. 3
  132164. };
  132165. static static_codebook _44c5_s_p7_0 = {
  132166. 4, 81,
  132167. _vq_lengthlist__44c5_s_p7_0,
  132168. 1, -529137664, 1618345984, 2, 0,
  132169. _vq_quantlist__44c5_s_p7_0,
  132170. NULL,
  132171. &_vq_auxt__44c5_s_p7_0,
  132172. NULL,
  132173. 0
  132174. };
  132175. static long _vq_quantlist__44c5_s_p7_1[] = {
  132176. 5,
  132177. 4,
  132178. 6,
  132179. 3,
  132180. 7,
  132181. 2,
  132182. 8,
  132183. 1,
  132184. 9,
  132185. 0,
  132186. 10,
  132187. };
  132188. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132189. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132190. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132191. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132192. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132193. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132194. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132195. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132196. 10,10,10, 8, 8, 8, 8, 8, 8,
  132197. };
  132198. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132199. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132200. 3.5, 4.5,
  132201. };
  132202. static long _vq_quantmap__44c5_s_p7_1[] = {
  132203. 9, 7, 5, 3, 1, 0, 2, 4,
  132204. 6, 8, 10,
  132205. };
  132206. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132207. _vq_quantthresh__44c5_s_p7_1,
  132208. _vq_quantmap__44c5_s_p7_1,
  132209. 11,
  132210. 11
  132211. };
  132212. static static_codebook _44c5_s_p7_1 = {
  132213. 2, 121,
  132214. _vq_lengthlist__44c5_s_p7_1,
  132215. 1, -531365888, 1611661312, 4, 0,
  132216. _vq_quantlist__44c5_s_p7_1,
  132217. NULL,
  132218. &_vq_auxt__44c5_s_p7_1,
  132219. NULL,
  132220. 0
  132221. };
  132222. static long _vq_quantlist__44c5_s_p8_0[] = {
  132223. 6,
  132224. 5,
  132225. 7,
  132226. 4,
  132227. 8,
  132228. 3,
  132229. 9,
  132230. 2,
  132231. 10,
  132232. 1,
  132233. 11,
  132234. 0,
  132235. 12,
  132236. };
  132237. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132238. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132239. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132240. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132241. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132242. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132243. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132244. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132245. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132246. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132247. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132248. 0,12,12,12,12,12,12,13,13,
  132249. };
  132250. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132251. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132252. 12.5, 17.5, 22.5, 27.5,
  132253. };
  132254. static long _vq_quantmap__44c5_s_p8_0[] = {
  132255. 11, 9, 7, 5, 3, 1, 0, 2,
  132256. 4, 6, 8, 10, 12,
  132257. };
  132258. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132259. _vq_quantthresh__44c5_s_p8_0,
  132260. _vq_quantmap__44c5_s_p8_0,
  132261. 13,
  132262. 13
  132263. };
  132264. static static_codebook _44c5_s_p8_0 = {
  132265. 2, 169,
  132266. _vq_lengthlist__44c5_s_p8_0,
  132267. 1, -526516224, 1616117760, 4, 0,
  132268. _vq_quantlist__44c5_s_p8_0,
  132269. NULL,
  132270. &_vq_auxt__44c5_s_p8_0,
  132271. NULL,
  132272. 0
  132273. };
  132274. static long _vq_quantlist__44c5_s_p8_1[] = {
  132275. 2,
  132276. 1,
  132277. 3,
  132278. 0,
  132279. 4,
  132280. };
  132281. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132282. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132283. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132284. };
  132285. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132286. -1.5, -0.5, 0.5, 1.5,
  132287. };
  132288. static long _vq_quantmap__44c5_s_p8_1[] = {
  132289. 3, 1, 0, 2, 4,
  132290. };
  132291. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132292. _vq_quantthresh__44c5_s_p8_1,
  132293. _vq_quantmap__44c5_s_p8_1,
  132294. 5,
  132295. 5
  132296. };
  132297. static static_codebook _44c5_s_p8_1 = {
  132298. 2, 25,
  132299. _vq_lengthlist__44c5_s_p8_1,
  132300. 1, -533725184, 1611661312, 3, 0,
  132301. _vq_quantlist__44c5_s_p8_1,
  132302. NULL,
  132303. &_vq_auxt__44c5_s_p8_1,
  132304. NULL,
  132305. 0
  132306. };
  132307. static long _vq_quantlist__44c5_s_p9_0[] = {
  132308. 7,
  132309. 6,
  132310. 8,
  132311. 5,
  132312. 9,
  132313. 4,
  132314. 10,
  132315. 3,
  132316. 11,
  132317. 2,
  132318. 12,
  132319. 1,
  132320. 13,
  132321. 0,
  132322. 14,
  132323. };
  132324. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132325. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132326. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132327. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132328. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132329. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132330. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132331. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132332. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132333. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132334. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132335. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132336. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132337. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132338. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132339. 12,
  132340. };
  132341. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132342. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132343. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132344. };
  132345. static long _vq_quantmap__44c5_s_p9_0[] = {
  132346. 13, 11, 9, 7, 5, 3, 1, 0,
  132347. 2, 4, 6, 8, 10, 12, 14,
  132348. };
  132349. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132350. _vq_quantthresh__44c5_s_p9_0,
  132351. _vq_quantmap__44c5_s_p9_0,
  132352. 15,
  132353. 15
  132354. };
  132355. static static_codebook _44c5_s_p9_0 = {
  132356. 2, 225,
  132357. _vq_lengthlist__44c5_s_p9_0,
  132358. 1, -512522752, 1628852224, 4, 0,
  132359. _vq_quantlist__44c5_s_p9_0,
  132360. NULL,
  132361. &_vq_auxt__44c5_s_p9_0,
  132362. NULL,
  132363. 0
  132364. };
  132365. static long _vq_quantlist__44c5_s_p9_1[] = {
  132366. 8,
  132367. 7,
  132368. 9,
  132369. 6,
  132370. 10,
  132371. 5,
  132372. 11,
  132373. 4,
  132374. 12,
  132375. 3,
  132376. 13,
  132377. 2,
  132378. 14,
  132379. 1,
  132380. 15,
  132381. 0,
  132382. 16,
  132383. };
  132384. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132385. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132386. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132387. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132388. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132389. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132390. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132391. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132392. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132393. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132394. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132395. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132396. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132397. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132398. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132399. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132400. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132401. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132402. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132403. 15,
  132404. };
  132405. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132406. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132407. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132408. };
  132409. static long _vq_quantmap__44c5_s_p9_1[] = {
  132410. 15, 13, 11, 9, 7, 5, 3, 1,
  132411. 0, 2, 4, 6, 8, 10, 12, 14,
  132412. 16,
  132413. };
  132414. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132415. _vq_quantthresh__44c5_s_p9_1,
  132416. _vq_quantmap__44c5_s_p9_1,
  132417. 17,
  132418. 17
  132419. };
  132420. static static_codebook _44c5_s_p9_1 = {
  132421. 2, 289,
  132422. _vq_lengthlist__44c5_s_p9_1,
  132423. 1, -520814592, 1620377600, 5, 0,
  132424. _vq_quantlist__44c5_s_p9_1,
  132425. NULL,
  132426. &_vq_auxt__44c5_s_p9_1,
  132427. NULL,
  132428. 0
  132429. };
  132430. static long _vq_quantlist__44c5_s_p9_2[] = {
  132431. 10,
  132432. 9,
  132433. 11,
  132434. 8,
  132435. 12,
  132436. 7,
  132437. 13,
  132438. 6,
  132439. 14,
  132440. 5,
  132441. 15,
  132442. 4,
  132443. 16,
  132444. 3,
  132445. 17,
  132446. 2,
  132447. 18,
  132448. 1,
  132449. 19,
  132450. 0,
  132451. 20,
  132452. };
  132453. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132454. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132455. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132456. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132457. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132458. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132459. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132460. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132461. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132462. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132463. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132464. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132465. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132466. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132467. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132468. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132469. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132470. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132471. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132472. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132473. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132474. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132475. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132476. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132477. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132478. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132479. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132480. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132481. 10,10,10,10,10,10,10,10,10,
  132482. };
  132483. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132484. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132485. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132486. 6.5, 7.5, 8.5, 9.5,
  132487. };
  132488. static long _vq_quantmap__44c5_s_p9_2[] = {
  132489. 19, 17, 15, 13, 11, 9, 7, 5,
  132490. 3, 1, 0, 2, 4, 6, 8, 10,
  132491. 12, 14, 16, 18, 20,
  132492. };
  132493. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132494. _vq_quantthresh__44c5_s_p9_2,
  132495. _vq_quantmap__44c5_s_p9_2,
  132496. 21,
  132497. 21
  132498. };
  132499. static static_codebook _44c5_s_p9_2 = {
  132500. 2, 441,
  132501. _vq_lengthlist__44c5_s_p9_2,
  132502. 1, -529268736, 1611661312, 5, 0,
  132503. _vq_quantlist__44c5_s_p9_2,
  132504. NULL,
  132505. &_vq_auxt__44c5_s_p9_2,
  132506. NULL,
  132507. 0
  132508. };
  132509. static long _huff_lengthlist__44c5_s_short[] = {
  132510. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132511. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132512. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132513. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132514. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132515. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132516. 6, 8,11,16,
  132517. };
  132518. static static_codebook _huff_book__44c5_s_short = {
  132519. 2, 100,
  132520. _huff_lengthlist__44c5_s_short,
  132521. 0, 0, 0, 0, 0,
  132522. NULL,
  132523. NULL,
  132524. NULL,
  132525. NULL,
  132526. 0
  132527. };
  132528. static long _huff_lengthlist__44c6_s_long[] = {
  132529. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132530. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132531. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132532. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132533. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132534. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132535. 11,10,10,12,
  132536. };
  132537. static static_codebook _huff_book__44c6_s_long = {
  132538. 2, 100,
  132539. _huff_lengthlist__44c6_s_long,
  132540. 0, 0, 0, 0, 0,
  132541. NULL,
  132542. NULL,
  132543. NULL,
  132544. NULL,
  132545. 0
  132546. };
  132547. static long _vq_quantlist__44c6_s_p1_0[] = {
  132548. 1,
  132549. 0,
  132550. 2,
  132551. };
  132552. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132553. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132554. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132555. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132556. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132557. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132558. 8,
  132559. };
  132560. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132561. -0.5, 0.5,
  132562. };
  132563. static long _vq_quantmap__44c6_s_p1_0[] = {
  132564. 1, 0, 2,
  132565. };
  132566. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132567. _vq_quantthresh__44c6_s_p1_0,
  132568. _vq_quantmap__44c6_s_p1_0,
  132569. 3,
  132570. 3
  132571. };
  132572. static static_codebook _44c6_s_p1_0 = {
  132573. 4, 81,
  132574. _vq_lengthlist__44c6_s_p1_0,
  132575. 1, -535822336, 1611661312, 2, 0,
  132576. _vq_quantlist__44c6_s_p1_0,
  132577. NULL,
  132578. &_vq_auxt__44c6_s_p1_0,
  132579. NULL,
  132580. 0
  132581. };
  132582. static long _vq_quantlist__44c6_s_p2_0[] = {
  132583. 2,
  132584. 1,
  132585. 3,
  132586. 0,
  132587. 4,
  132588. };
  132589. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132590. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132591. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132592. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132593. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132594. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132595. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132596. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132597. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132599. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132600. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132601. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132602. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132603. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132604. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132605. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132607. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132608. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132609. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132610. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132611. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132612. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132613. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132615. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132616. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132617. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132618. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132619. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132620. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132621. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132626. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132627. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132628. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132629. 13,
  132630. };
  132631. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132632. -1.5, -0.5, 0.5, 1.5,
  132633. };
  132634. static long _vq_quantmap__44c6_s_p2_0[] = {
  132635. 3, 1, 0, 2, 4,
  132636. };
  132637. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132638. _vq_quantthresh__44c6_s_p2_0,
  132639. _vq_quantmap__44c6_s_p2_0,
  132640. 5,
  132641. 5
  132642. };
  132643. static static_codebook _44c6_s_p2_0 = {
  132644. 4, 625,
  132645. _vq_lengthlist__44c6_s_p2_0,
  132646. 1, -533725184, 1611661312, 3, 0,
  132647. _vq_quantlist__44c6_s_p2_0,
  132648. NULL,
  132649. &_vq_auxt__44c6_s_p2_0,
  132650. NULL,
  132651. 0
  132652. };
  132653. static long _vq_quantlist__44c6_s_p3_0[] = {
  132654. 4,
  132655. 3,
  132656. 5,
  132657. 2,
  132658. 6,
  132659. 1,
  132660. 7,
  132661. 0,
  132662. 8,
  132663. };
  132664. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132665. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132666. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132667. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132668. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132670. 0,
  132671. };
  132672. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132673. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132674. };
  132675. static long _vq_quantmap__44c6_s_p3_0[] = {
  132676. 7, 5, 3, 1, 0, 2, 4, 6,
  132677. 8,
  132678. };
  132679. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132680. _vq_quantthresh__44c6_s_p3_0,
  132681. _vq_quantmap__44c6_s_p3_0,
  132682. 9,
  132683. 9
  132684. };
  132685. static static_codebook _44c6_s_p3_0 = {
  132686. 2, 81,
  132687. _vq_lengthlist__44c6_s_p3_0,
  132688. 1, -531628032, 1611661312, 4, 0,
  132689. _vq_quantlist__44c6_s_p3_0,
  132690. NULL,
  132691. &_vq_auxt__44c6_s_p3_0,
  132692. NULL,
  132693. 0
  132694. };
  132695. static long _vq_quantlist__44c6_s_p4_0[] = {
  132696. 8,
  132697. 7,
  132698. 9,
  132699. 6,
  132700. 10,
  132701. 5,
  132702. 11,
  132703. 4,
  132704. 12,
  132705. 3,
  132706. 13,
  132707. 2,
  132708. 14,
  132709. 1,
  132710. 15,
  132711. 0,
  132712. 16,
  132713. };
  132714. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132715. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132716. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132717. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132718. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132719. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132720. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132721. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132722. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132723. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132724. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132733. 0,
  132734. };
  132735. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132736. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132737. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132738. };
  132739. static long _vq_quantmap__44c6_s_p4_0[] = {
  132740. 15, 13, 11, 9, 7, 5, 3, 1,
  132741. 0, 2, 4, 6, 8, 10, 12, 14,
  132742. 16,
  132743. };
  132744. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132745. _vq_quantthresh__44c6_s_p4_0,
  132746. _vq_quantmap__44c6_s_p4_0,
  132747. 17,
  132748. 17
  132749. };
  132750. static static_codebook _44c6_s_p4_0 = {
  132751. 2, 289,
  132752. _vq_lengthlist__44c6_s_p4_0,
  132753. 1, -529530880, 1611661312, 5, 0,
  132754. _vq_quantlist__44c6_s_p4_0,
  132755. NULL,
  132756. &_vq_auxt__44c6_s_p4_0,
  132757. NULL,
  132758. 0
  132759. };
  132760. static long _vq_quantlist__44c6_s_p5_0[] = {
  132761. 1,
  132762. 0,
  132763. 2,
  132764. };
  132765. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132766. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132767. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132768. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132769. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132770. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132771. 12,
  132772. };
  132773. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132774. -5.5, 5.5,
  132775. };
  132776. static long _vq_quantmap__44c6_s_p5_0[] = {
  132777. 1, 0, 2,
  132778. };
  132779. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132780. _vq_quantthresh__44c6_s_p5_0,
  132781. _vq_quantmap__44c6_s_p5_0,
  132782. 3,
  132783. 3
  132784. };
  132785. static static_codebook _44c6_s_p5_0 = {
  132786. 4, 81,
  132787. _vq_lengthlist__44c6_s_p5_0,
  132788. 1, -529137664, 1618345984, 2, 0,
  132789. _vq_quantlist__44c6_s_p5_0,
  132790. NULL,
  132791. &_vq_auxt__44c6_s_p5_0,
  132792. NULL,
  132793. 0
  132794. };
  132795. static long _vq_quantlist__44c6_s_p5_1[] = {
  132796. 5,
  132797. 4,
  132798. 6,
  132799. 3,
  132800. 7,
  132801. 2,
  132802. 8,
  132803. 1,
  132804. 9,
  132805. 0,
  132806. 10,
  132807. };
  132808. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132809. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132810. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132811. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132812. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132813. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132814. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132815. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132816. 11,10,10, 7, 7, 8, 8, 8, 8,
  132817. };
  132818. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132819. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132820. 3.5, 4.5,
  132821. };
  132822. static long _vq_quantmap__44c6_s_p5_1[] = {
  132823. 9, 7, 5, 3, 1, 0, 2, 4,
  132824. 6, 8, 10,
  132825. };
  132826. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132827. _vq_quantthresh__44c6_s_p5_1,
  132828. _vq_quantmap__44c6_s_p5_1,
  132829. 11,
  132830. 11
  132831. };
  132832. static static_codebook _44c6_s_p5_1 = {
  132833. 2, 121,
  132834. _vq_lengthlist__44c6_s_p5_1,
  132835. 1, -531365888, 1611661312, 4, 0,
  132836. _vq_quantlist__44c6_s_p5_1,
  132837. NULL,
  132838. &_vq_auxt__44c6_s_p5_1,
  132839. NULL,
  132840. 0
  132841. };
  132842. static long _vq_quantlist__44c6_s_p6_0[] = {
  132843. 6,
  132844. 5,
  132845. 7,
  132846. 4,
  132847. 8,
  132848. 3,
  132849. 9,
  132850. 2,
  132851. 10,
  132852. 1,
  132853. 11,
  132854. 0,
  132855. 12,
  132856. };
  132857. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132858. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132859. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132860. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132861. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132862. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132863. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132868. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132869. };
  132870. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132871. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132872. 12.5, 17.5, 22.5, 27.5,
  132873. };
  132874. static long _vq_quantmap__44c6_s_p6_0[] = {
  132875. 11, 9, 7, 5, 3, 1, 0, 2,
  132876. 4, 6, 8, 10, 12,
  132877. };
  132878. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132879. _vq_quantthresh__44c6_s_p6_0,
  132880. _vq_quantmap__44c6_s_p6_0,
  132881. 13,
  132882. 13
  132883. };
  132884. static static_codebook _44c6_s_p6_0 = {
  132885. 2, 169,
  132886. _vq_lengthlist__44c6_s_p6_0,
  132887. 1, -526516224, 1616117760, 4, 0,
  132888. _vq_quantlist__44c6_s_p6_0,
  132889. NULL,
  132890. &_vq_auxt__44c6_s_p6_0,
  132891. NULL,
  132892. 0
  132893. };
  132894. static long _vq_quantlist__44c6_s_p6_1[] = {
  132895. 2,
  132896. 1,
  132897. 3,
  132898. 0,
  132899. 4,
  132900. };
  132901. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132902. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132903. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132904. };
  132905. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132906. -1.5, -0.5, 0.5, 1.5,
  132907. };
  132908. static long _vq_quantmap__44c6_s_p6_1[] = {
  132909. 3, 1, 0, 2, 4,
  132910. };
  132911. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132912. _vq_quantthresh__44c6_s_p6_1,
  132913. _vq_quantmap__44c6_s_p6_1,
  132914. 5,
  132915. 5
  132916. };
  132917. static static_codebook _44c6_s_p6_1 = {
  132918. 2, 25,
  132919. _vq_lengthlist__44c6_s_p6_1,
  132920. 1, -533725184, 1611661312, 3, 0,
  132921. _vq_quantlist__44c6_s_p6_1,
  132922. NULL,
  132923. &_vq_auxt__44c6_s_p6_1,
  132924. NULL,
  132925. 0
  132926. };
  132927. static long _vq_quantlist__44c6_s_p7_0[] = {
  132928. 6,
  132929. 5,
  132930. 7,
  132931. 4,
  132932. 8,
  132933. 3,
  132934. 9,
  132935. 2,
  132936. 10,
  132937. 1,
  132938. 11,
  132939. 0,
  132940. 12,
  132941. };
  132942. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132943. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132944. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132945. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132946. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132947. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132948. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132949. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132950. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132951. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132952. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132953. 20,13,13,13,13,13,13,14,14,
  132954. };
  132955. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132956. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132957. 27.5, 38.5, 49.5, 60.5,
  132958. };
  132959. static long _vq_quantmap__44c6_s_p7_0[] = {
  132960. 11, 9, 7, 5, 3, 1, 0, 2,
  132961. 4, 6, 8, 10, 12,
  132962. };
  132963. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132964. _vq_quantthresh__44c6_s_p7_0,
  132965. _vq_quantmap__44c6_s_p7_0,
  132966. 13,
  132967. 13
  132968. };
  132969. static static_codebook _44c6_s_p7_0 = {
  132970. 2, 169,
  132971. _vq_lengthlist__44c6_s_p7_0,
  132972. 1, -523206656, 1618345984, 4, 0,
  132973. _vq_quantlist__44c6_s_p7_0,
  132974. NULL,
  132975. &_vq_auxt__44c6_s_p7_0,
  132976. NULL,
  132977. 0
  132978. };
  132979. static long _vq_quantlist__44c6_s_p7_1[] = {
  132980. 5,
  132981. 4,
  132982. 6,
  132983. 3,
  132984. 7,
  132985. 2,
  132986. 8,
  132987. 1,
  132988. 9,
  132989. 0,
  132990. 10,
  132991. };
  132992. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132993. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132994. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132995. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132996. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132997. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132998. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132999. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  133000. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  133001. };
  133002. static float _vq_quantthresh__44c6_s_p7_1[] = {
  133003. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133004. 3.5, 4.5,
  133005. };
  133006. static long _vq_quantmap__44c6_s_p7_1[] = {
  133007. 9, 7, 5, 3, 1, 0, 2, 4,
  133008. 6, 8, 10,
  133009. };
  133010. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  133011. _vq_quantthresh__44c6_s_p7_1,
  133012. _vq_quantmap__44c6_s_p7_1,
  133013. 11,
  133014. 11
  133015. };
  133016. static static_codebook _44c6_s_p7_1 = {
  133017. 2, 121,
  133018. _vq_lengthlist__44c6_s_p7_1,
  133019. 1, -531365888, 1611661312, 4, 0,
  133020. _vq_quantlist__44c6_s_p7_1,
  133021. NULL,
  133022. &_vq_auxt__44c6_s_p7_1,
  133023. NULL,
  133024. 0
  133025. };
  133026. static long _vq_quantlist__44c6_s_p8_0[] = {
  133027. 7,
  133028. 6,
  133029. 8,
  133030. 5,
  133031. 9,
  133032. 4,
  133033. 10,
  133034. 3,
  133035. 11,
  133036. 2,
  133037. 12,
  133038. 1,
  133039. 13,
  133040. 0,
  133041. 14,
  133042. };
  133043. static long _vq_lengthlist__44c6_s_p8_0[] = {
  133044. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  133045. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  133046. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  133047. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  133048. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  133049. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  133050. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  133051. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  133052. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  133053. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  133054. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  133055. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  133056. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  133057. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  133058. 14,
  133059. };
  133060. static float _vq_quantthresh__44c6_s_p8_0[] = {
  133061. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133062. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133063. };
  133064. static long _vq_quantmap__44c6_s_p8_0[] = {
  133065. 13, 11, 9, 7, 5, 3, 1, 0,
  133066. 2, 4, 6, 8, 10, 12, 14,
  133067. };
  133068. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  133069. _vq_quantthresh__44c6_s_p8_0,
  133070. _vq_quantmap__44c6_s_p8_0,
  133071. 15,
  133072. 15
  133073. };
  133074. static static_codebook _44c6_s_p8_0 = {
  133075. 2, 225,
  133076. _vq_lengthlist__44c6_s_p8_0,
  133077. 1, -520986624, 1620377600, 4, 0,
  133078. _vq_quantlist__44c6_s_p8_0,
  133079. NULL,
  133080. &_vq_auxt__44c6_s_p8_0,
  133081. NULL,
  133082. 0
  133083. };
  133084. static long _vq_quantlist__44c6_s_p8_1[] = {
  133085. 10,
  133086. 9,
  133087. 11,
  133088. 8,
  133089. 12,
  133090. 7,
  133091. 13,
  133092. 6,
  133093. 14,
  133094. 5,
  133095. 15,
  133096. 4,
  133097. 16,
  133098. 3,
  133099. 17,
  133100. 2,
  133101. 18,
  133102. 1,
  133103. 19,
  133104. 0,
  133105. 20,
  133106. };
  133107. static long _vq_lengthlist__44c6_s_p8_1[] = {
  133108. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  133109. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  133110. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133111. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133112. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133113. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  133114. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  133115. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  133116. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133117. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133118. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  133119. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  133120. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  133121. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  133122. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  133123. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  133124. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  133125. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  133126. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  133127. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  133128. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  133129. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  133130. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  133131. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  133132. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  133133. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  133134. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  133135. 10,10,10,10,10,10,10,10,10,
  133136. };
  133137. static float _vq_quantthresh__44c6_s_p8_1[] = {
  133138. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133139. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133140. 6.5, 7.5, 8.5, 9.5,
  133141. };
  133142. static long _vq_quantmap__44c6_s_p8_1[] = {
  133143. 19, 17, 15, 13, 11, 9, 7, 5,
  133144. 3, 1, 0, 2, 4, 6, 8, 10,
  133145. 12, 14, 16, 18, 20,
  133146. };
  133147. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133148. _vq_quantthresh__44c6_s_p8_1,
  133149. _vq_quantmap__44c6_s_p8_1,
  133150. 21,
  133151. 21
  133152. };
  133153. static static_codebook _44c6_s_p8_1 = {
  133154. 2, 441,
  133155. _vq_lengthlist__44c6_s_p8_1,
  133156. 1, -529268736, 1611661312, 5, 0,
  133157. _vq_quantlist__44c6_s_p8_1,
  133158. NULL,
  133159. &_vq_auxt__44c6_s_p8_1,
  133160. NULL,
  133161. 0
  133162. };
  133163. static long _vq_quantlist__44c6_s_p9_0[] = {
  133164. 6,
  133165. 5,
  133166. 7,
  133167. 4,
  133168. 8,
  133169. 3,
  133170. 9,
  133171. 2,
  133172. 10,
  133173. 1,
  133174. 11,
  133175. 0,
  133176. 12,
  133177. };
  133178. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133179. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133180. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133181. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133182. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133183. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133184. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133185. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133186. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133187. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133188. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133189. 10,10,10,10,10,10,10,10,10,
  133190. };
  133191. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133192. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133193. 1592.5, 2229.5, 2866.5, 3503.5,
  133194. };
  133195. static long _vq_quantmap__44c6_s_p9_0[] = {
  133196. 11, 9, 7, 5, 3, 1, 0, 2,
  133197. 4, 6, 8, 10, 12,
  133198. };
  133199. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133200. _vq_quantthresh__44c6_s_p9_0,
  133201. _vq_quantmap__44c6_s_p9_0,
  133202. 13,
  133203. 13
  133204. };
  133205. static static_codebook _44c6_s_p9_0 = {
  133206. 2, 169,
  133207. _vq_lengthlist__44c6_s_p9_0,
  133208. 1, -511845376, 1630791680, 4, 0,
  133209. _vq_quantlist__44c6_s_p9_0,
  133210. NULL,
  133211. &_vq_auxt__44c6_s_p9_0,
  133212. NULL,
  133213. 0
  133214. };
  133215. static long _vq_quantlist__44c6_s_p9_1[] = {
  133216. 6,
  133217. 5,
  133218. 7,
  133219. 4,
  133220. 8,
  133221. 3,
  133222. 9,
  133223. 2,
  133224. 10,
  133225. 1,
  133226. 11,
  133227. 0,
  133228. 12,
  133229. };
  133230. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133231. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133232. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133233. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133234. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133235. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133236. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133237. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133238. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133239. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133240. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133241. 15,12,10,11,11,13,11,12,13,
  133242. };
  133243. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133244. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133245. 122.5, 171.5, 220.5, 269.5,
  133246. };
  133247. static long _vq_quantmap__44c6_s_p9_1[] = {
  133248. 11, 9, 7, 5, 3, 1, 0, 2,
  133249. 4, 6, 8, 10, 12,
  133250. };
  133251. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133252. _vq_quantthresh__44c6_s_p9_1,
  133253. _vq_quantmap__44c6_s_p9_1,
  133254. 13,
  133255. 13
  133256. };
  133257. static static_codebook _44c6_s_p9_1 = {
  133258. 2, 169,
  133259. _vq_lengthlist__44c6_s_p9_1,
  133260. 1, -518889472, 1622704128, 4, 0,
  133261. _vq_quantlist__44c6_s_p9_1,
  133262. NULL,
  133263. &_vq_auxt__44c6_s_p9_1,
  133264. NULL,
  133265. 0
  133266. };
  133267. static long _vq_quantlist__44c6_s_p9_2[] = {
  133268. 24,
  133269. 23,
  133270. 25,
  133271. 22,
  133272. 26,
  133273. 21,
  133274. 27,
  133275. 20,
  133276. 28,
  133277. 19,
  133278. 29,
  133279. 18,
  133280. 30,
  133281. 17,
  133282. 31,
  133283. 16,
  133284. 32,
  133285. 15,
  133286. 33,
  133287. 14,
  133288. 34,
  133289. 13,
  133290. 35,
  133291. 12,
  133292. 36,
  133293. 11,
  133294. 37,
  133295. 10,
  133296. 38,
  133297. 9,
  133298. 39,
  133299. 8,
  133300. 40,
  133301. 7,
  133302. 41,
  133303. 6,
  133304. 42,
  133305. 5,
  133306. 43,
  133307. 4,
  133308. 44,
  133309. 3,
  133310. 45,
  133311. 2,
  133312. 46,
  133313. 1,
  133314. 47,
  133315. 0,
  133316. 48,
  133317. };
  133318. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133319. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133320. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133321. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133322. 7,
  133323. };
  133324. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133325. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133326. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133327. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133328. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133329. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133330. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133331. };
  133332. static long _vq_quantmap__44c6_s_p9_2[] = {
  133333. 47, 45, 43, 41, 39, 37, 35, 33,
  133334. 31, 29, 27, 25, 23, 21, 19, 17,
  133335. 15, 13, 11, 9, 7, 5, 3, 1,
  133336. 0, 2, 4, 6, 8, 10, 12, 14,
  133337. 16, 18, 20, 22, 24, 26, 28, 30,
  133338. 32, 34, 36, 38, 40, 42, 44, 46,
  133339. 48,
  133340. };
  133341. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133342. _vq_quantthresh__44c6_s_p9_2,
  133343. _vq_quantmap__44c6_s_p9_2,
  133344. 49,
  133345. 49
  133346. };
  133347. static static_codebook _44c6_s_p9_2 = {
  133348. 1, 49,
  133349. _vq_lengthlist__44c6_s_p9_2,
  133350. 1, -526909440, 1611661312, 6, 0,
  133351. _vq_quantlist__44c6_s_p9_2,
  133352. NULL,
  133353. &_vq_auxt__44c6_s_p9_2,
  133354. NULL,
  133355. 0
  133356. };
  133357. static long _huff_lengthlist__44c6_s_short[] = {
  133358. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133359. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133360. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133361. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133362. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133363. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133364. 9,10,17,18,
  133365. };
  133366. static static_codebook _huff_book__44c6_s_short = {
  133367. 2, 100,
  133368. _huff_lengthlist__44c6_s_short,
  133369. 0, 0, 0, 0, 0,
  133370. NULL,
  133371. NULL,
  133372. NULL,
  133373. NULL,
  133374. 0
  133375. };
  133376. static long _huff_lengthlist__44c7_s_long[] = {
  133377. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133378. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133379. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133380. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133381. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133382. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133383. 11,10,10,12,
  133384. };
  133385. static static_codebook _huff_book__44c7_s_long = {
  133386. 2, 100,
  133387. _huff_lengthlist__44c7_s_long,
  133388. 0, 0, 0, 0, 0,
  133389. NULL,
  133390. NULL,
  133391. NULL,
  133392. NULL,
  133393. 0
  133394. };
  133395. static long _vq_quantlist__44c7_s_p1_0[] = {
  133396. 1,
  133397. 0,
  133398. 2,
  133399. };
  133400. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133401. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133402. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133403. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133404. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133405. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133406. 8,
  133407. };
  133408. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133409. -0.5, 0.5,
  133410. };
  133411. static long _vq_quantmap__44c7_s_p1_0[] = {
  133412. 1, 0, 2,
  133413. };
  133414. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133415. _vq_quantthresh__44c7_s_p1_0,
  133416. _vq_quantmap__44c7_s_p1_0,
  133417. 3,
  133418. 3
  133419. };
  133420. static static_codebook _44c7_s_p1_0 = {
  133421. 4, 81,
  133422. _vq_lengthlist__44c7_s_p1_0,
  133423. 1, -535822336, 1611661312, 2, 0,
  133424. _vq_quantlist__44c7_s_p1_0,
  133425. NULL,
  133426. &_vq_auxt__44c7_s_p1_0,
  133427. NULL,
  133428. 0
  133429. };
  133430. static long _vq_quantlist__44c7_s_p2_0[] = {
  133431. 2,
  133432. 1,
  133433. 3,
  133434. 0,
  133435. 4,
  133436. };
  133437. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133438. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133439. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133440. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133441. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133442. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133443. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133444. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133445. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133447. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133448. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133449. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133450. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133451. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133452. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133453. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133455. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133456. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133457. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133458. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133459. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133460. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133461. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133463. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133464. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133465. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133466. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133467. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133468. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133469. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133474. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133475. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133476. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133477. 13,
  133478. };
  133479. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133480. -1.5, -0.5, 0.5, 1.5,
  133481. };
  133482. static long _vq_quantmap__44c7_s_p2_0[] = {
  133483. 3, 1, 0, 2, 4,
  133484. };
  133485. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133486. _vq_quantthresh__44c7_s_p2_0,
  133487. _vq_quantmap__44c7_s_p2_0,
  133488. 5,
  133489. 5
  133490. };
  133491. static static_codebook _44c7_s_p2_0 = {
  133492. 4, 625,
  133493. _vq_lengthlist__44c7_s_p2_0,
  133494. 1, -533725184, 1611661312, 3, 0,
  133495. _vq_quantlist__44c7_s_p2_0,
  133496. NULL,
  133497. &_vq_auxt__44c7_s_p2_0,
  133498. NULL,
  133499. 0
  133500. };
  133501. static long _vq_quantlist__44c7_s_p3_0[] = {
  133502. 4,
  133503. 3,
  133504. 5,
  133505. 2,
  133506. 6,
  133507. 1,
  133508. 7,
  133509. 0,
  133510. 8,
  133511. };
  133512. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133513. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133514. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133515. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133516. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133518. 0,
  133519. };
  133520. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133521. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133522. };
  133523. static long _vq_quantmap__44c7_s_p3_0[] = {
  133524. 7, 5, 3, 1, 0, 2, 4, 6,
  133525. 8,
  133526. };
  133527. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133528. _vq_quantthresh__44c7_s_p3_0,
  133529. _vq_quantmap__44c7_s_p3_0,
  133530. 9,
  133531. 9
  133532. };
  133533. static static_codebook _44c7_s_p3_0 = {
  133534. 2, 81,
  133535. _vq_lengthlist__44c7_s_p3_0,
  133536. 1, -531628032, 1611661312, 4, 0,
  133537. _vq_quantlist__44c7_s_p3_0,
  133538. NULL,
  133539. &_vq_auxt__44c7_s_p3_0,
  133540. NULL,
  133541. 0
  133542. };
  133543. static long _vq_quantlist__44c7_s_p4_0[] = {
  133544. 8,
  133545. 7,
  133546. 9,
  133547. 6,
  133548. 10,
  133549. 5,
  133550. 11,
  133551. 4,
  133552. 12,
  133553. 3,
  133554. 13,
  133555. 2,
  133556. 14,
  133557. 1,
  133558. 15,
  133559. 0,
  133560. 16,
  133561. };
  133562. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133563. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133564. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133565. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133566. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133567. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133568. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133569. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133570. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133571. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133572. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133581. 0,
  133582. };
  133583. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133584. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133585. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133586. };
  133587. static long _vq_quantmap__44c7_s_p4_0[] = {
  133588. 15, 13, 11, 9, 7, 5, 3, 1,
  133589. 0, 2, 4, 6, 8, 10, 12, 14,
  133590. 16,
  133591. };
  133592. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133593. _vq_quantthresh__44c7_s_p4_0,
  133594. _vq_quantmap__44c7_s_p4_0,
  133595. 17,
  133596. 17
  133597. };
  133598. static static_codebook _44c7_s_p4_0 = {
  133599. 2, 289,
  133600. _vq_lengthlist__44c7_s_p4_0,
  133601. 1, -529530880, 1611661312, 5, 0,
  133602. _vq_quantlist__44c7_s_p4_0,
  133603. NULL,
  133604. &_vq_auxt__44c7_s_p4_0,
  133605. NULL,
  133606. 0
  133607. };
  133608. static long _vq_quantlist__44c7_s_p5_0[] = {
  133609. 1,
  133610. 0,
  133611. 2,
  133612. };
  133613. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133614. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133615. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133616. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133617. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133618. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133619. 12,
  133620. };
  133621. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133622. -5.5, 5.5,
  133623. };
  133624. static long _vq_quantmap__44c7_s_p5_0[] = {
  133625. 1, 0, 2,
  133626. };
  133627. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133628. _vq_quantthresh__44c7_s_p5_0,
  133629. _vq_quantmap__44c7_s_p5_0,
  133630. 3,
  133631. 3
  133632. };
  133633. static static_codebook _44c7_s_p5_0 = {
  133634. 4, 81,
  133635. _vq_lengthlist__44c7_s_p5_0,
  133636. 1, -529137664, 1618345984, 2, 0,
  133637. _vq_quantlist__44c7_s_p5_0,
  133638. NULL,
  133639. &_vq_auxt__44c7_s_p5_0,
  133640. NULL,
  133641. 0
  133642. };
  133643. static long _vq_quantlist__44c7_s_p5_1[] = {
  133644. 5,
  133645. 4,
  133646. 6,
  133647. 3,
  133648. 7,
  133649. 2,
  133650. 8,
  133651. 1,
  133652. 9,
  133653. 0,
  133654. 10,
  133655. };
  133656. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133657. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133658. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133659. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133660. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133661. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133662. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133663. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133664. 11,11,11, 7, 7, 8, 8, 8, 8,
  133665. };
  133666. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133667. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133668. 3.5, 4.5,
  133669. };
  133670. static long _vq_quantmap__44c7_s_p5_1[] = {
  133671. 9, 7, 5, 3, 1, 0, 2, 4,
  133672. 6, 8, 10,
  133673. };
  133674. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133675. _vq_quantthresh__44c7_s_p5_1,
  133676. _vq_quantmap__44c7_s_p5_1,
  133677. 11,
  133678. 11
  133679. };
  133680. static static_codebook _44c7_s_p5_1 = {
  133681. 2, 121,
  133682. _vq_lengthlist__44c7_s_p5_1,
  133683. 1, -531365888, 1611661312, 4, 0,
  133684. _vq_quantlist__44c7_s_p5_1,
  133685. NULL,
  133686. &_vq_auxt__44c7_s_p5_1,
  133687. NULL,
  133688. 0
  133689. };
  133690. static long _vq_quantlist__44c7_s_p6_0[] = {
  133691. 6,
  133692. 5,
  133693. 7,
  133694. 4,
  133695. 8,
  133696. 3,
  133697. 9,
  133698. 2,
  133699. 10,
  133700. 1,
  133701. 11,
  133702. 0,
  133703. 12,
  133704. };
  133705. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133706. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133707. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133708. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133709. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133710. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133711. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133716. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133717. };
  133718. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133719. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133720. 12.5, 17.5, 22.5, 27.5,
  133721. };
  133722. static long _vq_quantmap__44c7_s_p6_0[] = {
  133723. 11, 9, 7, 5, 3, 1, 0, 2,
  133724. 4, 6, 8, 10, 12,
  133725. };
  133726. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133727. _vq_quantthresh__44c7_s_p6_0,
  133728. _vq_quantmap__44c7_s_p6_0,
  133729. 13,
  133730. 13
  133731. };
  133732. static static_codebook _44c7_s_p6_0 = {
  133733. 2, 169,
  133734. _vq_lengthlist__44c7_s_p6_0,
  133735. 1, -526516224, 1616117760, 4, 0,
  133736. _vq_quantlist__44c7_s_p6_0,
  133737. NULL,
  133738. &_vq_auxt__44c7_s_p6_0,
  133739. NULL,
  133740. 0
  133741. };
  133742. static long _vq_quantlist__44c7_s_p6_1[] = {
  133743. 2,
  133744. 1,
  133745. 3,
  133746. 0,
  133747. 4,
  133748. };
  133749. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133750. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133751. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133752. };
  133753. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133754. -1.5, -0.5, 0.5, 1.5,
  133755. };
  133756. static long _vq_quantmap__44c7_s_p6_1[] = {
  133757. 3, 1, 0, 2, 4,
  133758. };
  133759. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133760. _vq_quantthresh__44c7_s_p6_1,
  133761. _vq_quantmap__44c7_s_p6_1,
  133762. 5,
  133763. 5
  133764. };
  133765. static static_codebook _44c7_s_p6_1 = {
  133766. 2, 25,
  133767. _vq_lengthlist__44c7_s_p6_1,
  133768. 1, -533725184, 1611661312, 3, 0,
  133769. _vq_quantlist__44c7_s_p6_1,
  133770. NULL,
  133771. &_vq_auxt__44c7_s_p6_1,
  133772. NULL,
  133773. 0
  133774. };
  133775. static long _vq_quantlist__44c7_s_p7_0[] = {
  133776. 6,
  133777. 5,
  133778. 7,
  133779. 4,
  133780. 8,
  133781. 3,
  133782. 9,
  133783. 2,
  133784. 10,
  133785. 1,
  133786. 11,
  133787. 0,
  133788. 12,
  133789. };
  133790. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133791. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133792. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133793. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133794. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133795. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133796. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133797. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133798. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133799. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133800. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133801. 19,13,13,13,13,14,14,15,15,
  133802. };
  133803. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133804. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133805. 27.5, 38.5, 49.5, 60.5,
  133806. };
  133807. static long _vq_quantmap__44c7_s_p7_0[] = {
  133808. 11, 9, 7, 5, 3, 1, 0, 2,
  133809. 4, 6, 8, 10, 12,
  133810. };
  133811. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133812. _vq_quantthresh__44c7_s_p7_0,
  133813. _vq_quantmap__44c7_s_p7_0,
  133814. 13,
  133815. 13
  133816. };
  133817. static static_codebook _44c7_s_p7_0 = {
  133818. 2, 169,
  133819. _vq_lengthlist__44c7_s_p7_0,
  133820. 1, -523206656, 1618345984, 4, 0,
  133821. _vq_quantlist__44c7_s_p7_0,
  133822. NULL,
  133823. &_vq_auxt__44c7_s_p7_0,
  133824. NULL,
  133825. 0
  133826. };
  133827. static long _vq_quantlist__44c7_s_p7_1[] = {
  133828. 5,
  133829. 4,
  133830. 6,
  133831. 3,
  133832. 7,
  133833. 2,
  133834. 8,
  133835. 1,
  133836. 9,
  133837. 0,
  133838. 10,
  133839. };
  133840. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133841. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133842. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133843. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133844. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133845. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133846. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133847. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133848. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133849. };
  133850. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133851. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133852. 3.5, 4.5,
  133853. };
  133854. static long _vq_quantmap__44c7_s_p7_1[] = {
  133855. 9, 7, 5, 3, 1, 0, 2, 4,
  133856. 6, 8, 10,
  133857. };
  133858. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133859. _vq_quantthresh__44c7_s_p7_1,
  133860. _vq_quantmap__44c7_s_p7_1,
  133861. 11,
  133862. 11
  133863. };
  133864. static static_codebook _44c7_s_p7_1 = {
  133865. 2, 121,
  133866. _vq_lengthlist__44c7_s_p7_1,
  133867. 1, -531365888, 1611661312, 4, 0,
  133868. _vq_quantlist__44c7_s_p7_1,
  133869. NULL,
  133870. &_vq_auxt__44c7_s_p7_1,
  133871. NULL,
  133872. 0
  133873. };
  133874. static long _vq_quantlist__44c7_s_p8_0[] = {
  133875. 7,
  133876. 6,
  133877. 8,
  133878. 5,
  133879. 9,
  133880. 4,
  133881. 10,
  133882. 3,
  133883. 11,
  133884. 2,
  133885. 12,
  133886. 1,
  133887. 13,
  133888. 0,
  133889. 14,
  133890. };
  133891. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133892. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133893. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133894. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133895. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133896. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133897. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133898. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133899. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133900. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133901. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133902. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133903. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133904. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133905. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133906. 14,
  133907. };
  133908. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133909. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133910. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133911. };
  133912. static long _vq_quantmap__44c7_s_p8_0[] = {
  133913. 13, 11, 9, 7, 5, 3, 1, 0,
  133914. 2, 4, 6, 8, 10, 12, 14,
  133915. };
  133916. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133917. _vq_quantthresh__44c7_s_p8_0,
  133918. _vq_quantmap__44c7_s_p8_0,
  133919. 15,
  133920. 15
  133921. };
  133922. static static_codebook _44c7_s_p8_0 = {
  133923. 2, 225,
  133924. _vq_lengthlist__44c7_s_p8_0,
  133925. 1, -520986624, 1620377600, 4, 0,
  133926. _vq_quantlist__44c7_s_p8_0,
  133927. NULL,
  133928. &_vq_auxt__44c7_s_p8_0,
  133929. NULL,
  133930. 0
  133931. };
  133932. static long _vq_quantlist__44c7_s_p8_1[] = {
  133933. 10,
  133934. 9,
  133935. 11,
  133936. 8,
  133937. 12,
  133938. 7,
  133939. 13,
  133940. 6,
  133941. 14,
  133942. 5,
  133943. 15,
  133944. 4,
  133945. 16,
  133946. 3,
  133947. 17,
  133948. 2,
  133949. 18,
  133950. 1,
  133951. 19,
  133952. 0,
  133953. 20,
  133954. };
  133955. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133956. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133957. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133958. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133959. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133960. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133961. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133962. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133963. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133964. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133965. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133966. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133967. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133968. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133969. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133970. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133971. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133972. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133973. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133974. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133975. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133976. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133977. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133978. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133979. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133980. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133981. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133982. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133983. 10,10,10,10,10,10,10,10,10,
  133984. };
  133985. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133986. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133987. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133988. 6.5, 7.5, 8.5, 9.5,
  133989. };
  133990. static long _vq_quantmap__44c7_s_p8_1[] = {
  133991. 19, 17, 15, 13, 11, 9, 7, 5,
  133992. 3, 1, 0, 2, 4, 6, 8, 10,
  133993. 12, 14, 16, 18, 20,
  133994. };
  133995. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133996. _vq_quantthresh__44c7_s_p8_1,
  133997. _vq_quantmap__44c7_s_p8_1,
  133998. 21,
  133999. 21
  134000. };
  134001. static static_codebook _44c7_s_p8_1 = {
  134002. 2, 441,
  134003. _vq_lengthlist__44c7_s_p8_1,
  134004. 1, -529268736, 1611661312, 5, 0,
  134005. _vq_quantlist__44c7_s_p8_1,
  134006. NULL,
  134007. &_vq_auxt__44c7_s_p8_1,
  134008. NULL,
  134009. 0
  134010. };
  134011. static long _vq_quantlist__44c7_s_p9_0[] = {
  134012. 6,
  134013. 5,
  134014. 7,
  134015. 4,
  134016. 8,
  134017. 3,
  134018. 9,
  134019. 2,
  134020. 10,
  134021. 1,
  134022. 11,
  134023. 0,
  134024. 12,
  134025. };
  134026. static long _vq_lengthlist__44c7_s_p9_0[] = {
  134027. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  134028. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  134029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134030. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134031. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134032. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134035. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134036. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134037. 11,11,11,11,11,11,11,11,11,
  134038. };
  134039. static float _vq_quantthresh__44c7_s_p9_0[] = {
  134040. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  134041. 1592.5, 2229.5, 2866.5, 3503.5,
  134042. };
  134043. static long _vq_quantmap__44c7_s_p9_0[] = {
  134044. 11, 9, 7, 5, 3, 1, 0, 2,
  134045. 4, 6, 8, 10, 12,
  134046. };
  134047. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  134048. _vq_quantthresh__44c7_s_p9_0,
  134049. _vq_quantmap__44c7_s_p9_0,
  134050. 13,
  134051. 13
  134052. };
  134053. static static_codebook _44c7_s_p9_0 = {
  134054. 2, 169,
  134055. _vq_lengthlist__44c7_s_p9_0,
  134056. 1, -511845376, 1630791680, 4, 0,
  134057. _vq_quantlist__44c7_s_p9_0,
  134058. NULL,
  134059. &_vq_auxt__44c7_s_p9_0,
  134060. NULL,
  134061. 0
  134062. };
  134063. static long _vq_quantlist__44c7_s_p9_1[] = {
  134064. 6,
  134065. 5,
  134066. 7,
  134067. 4,
  134068. 8,
  134069. 3,
  134070. 9,
  134071. 2,
  134072. 10,
  134073. 1,
  134074. 11,
  134075. 0,
  134076. 12,
  134077. };
  134078. static long _vq_lengthlist__44c7_s_p9_1[] = {
  134079. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  134080. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  134081. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  134082. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  134083. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  134084. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  134085. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  134086. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  134087. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  134088. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  134089. 15,11,11,10,10,12,12,12,12,
  134090. };
  134091. static float _vq_quantthresh__44c7_s_p9_1[] = {
  134092. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  134093. 122.5, 171.5, 220.5, 269.5,
  134094. };
  134095. static long _vq_quantmap__44c7_s_p9_1[] = {
  134096. 11, 9, 7, 5, 3, 1, 0, 2,
  134097. 4, 6, 8, 10, 12,
  134098. };
  134099. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  134100. _vq_quantthresh__44c7_s_p9_1,
  134101. _vq_quantmap__44c7_s_p9_1,
  134102. 13,
  134103. 13
  134104. };
  134105. static static_codebook _44c7_s_p9_1 = {
  134106. 2, 169,
  134107. _vq_lengthlist__44c7_s_p9_1,
  134108. 1, -518889472, 1622704128, 4, 0,
  134109. _vq_quantlist__44c7_s_p9_1,
  134110. NULL,
  134111. &_vq_auxt__44c7_s_p9_1,
  134112. NULL,
  134113. 0
  134114. };
  134115. static long _vq_quantlist__44c7_s_p9_2[] = {
  134116. 24,
  134117. 23,
  134118. 25,
  134119. 22,
  134120. 26,
  134121. 21,
  134122. 27,
  134123. 20,
  134124. 28,
  134125. 19,
  134126. 29,
  134127. 18,
  134128. 30,
  134129. 17,
  134130. 31,
  134131. 16,
  134132. 32,
  134133. 15,
  134134. 33,
  134135. 14,
  134136. 34,
  134137. 13,
  134138. 35,
  134139. 12,
  134140. 36,
  134141. 11,
  134142. 37,
  134143. 10,
  134144. 38,
  134145. 9,
  134146. 39,
  134147. 8,
  134148. 40,
  134149. 7,
  134150. 41,
  134151. 6,
  134152. 42,
  134153. 5,
  134154. 43,
  134155. 4,
  134156. 44,
  134157. 3,
  134158. 45,
  134159. 2,
  134160. 46,
  134161. 1,
  134162. 47,
  134163. 0,
  134164. 48,
  134165. };
  134166. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134167. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134168. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134169. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134170. 7,
  134171. };
  134172. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134173. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134174. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134175. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134176. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134177. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134178. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134179. };
  134180. static long _vq_quantmap__44c7_s_p9_2[] = {
  134181. 47, 45, 43, 41, 39, 37, 35, 33,
  134182. 31, 29, 27, 25, 23, 21, 19, 17,
  134183. 15, 13, 11, 9, 7, 5, 3, 1,
  134184. 0, 2, 4, 6, 8, 10, 12, 14,
  134185. 16, 18, 20, 22, 24, 26, 28, 30,
  134186. 32, 34, 36, 38, 40, 42, 44, 46,
  134187. 48,
  134188. };
  134189. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134190. _vq_quantthresh__44c7_s_p9_2,
  134191. _vq_quantmap__44c7_s_p9_2,
  134192. 49,
  134193. 49
  134194. };
  134195. static static_codebook _44c7_s_p9_2 = {
  134196. 1, 49,
  134197. _vq_lengthlist__44c7_s_p9_2,
  134198. 1, -526909440, 1611661312, 6, 0,
  134199. _vq_quantlist__44c7_s_p9_2,
  134200. NULL,
  134201. &_vq_auxt__44c7_s_p9_2,
  134202. NULL,
  134203. 0
  134204. };
  134205. static long _huff_lengthlist__44c7_s_short[] = {
  134206. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134207. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134208. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134209. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134210. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134211. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134212. 10, 9,11,14,
  134213. };
  134214. static static_codebook _huff_book__44c7_s_short = {
  134215. 2, 100,
  134216. _huff_lengthlist__44c7_s_short,
  134217. 0, 0, 0, 0, 0,
  134218. NULL,
  134219. NULL,
  134220. NULL,
  134221. NULL,
  134222. 0
  134223. };
  134224. static long _huff_lengthlist__44c8_s_long[] = {
  134225. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134226. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134227. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134228. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134229. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134230. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134231. 11, 9, 9,10,
  134232. };
  134233. static static_codebook _huff_book__44c8_s_long = {
  134234. 2, 100,
  134235. _huff_lengthlist__44c8_s_long,
  134236. 0, 0, 0, 0, 0,
  134237. NULL,
  134238. NULL,
  134239. NULL,
  134240. NULL,
  134241. 0
  134242. };
  134243. static long _vq_quantlist__44c8_s_p1_0[] = {
  134244. 1,
  134245. 0,
  134246. 2,
  134247. };
  134248. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134249. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134250. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134251. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134252. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134253. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134254. 8,
  134255. };
  134256. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134257. -0.5, 0.5,
  134258. };
  134259. static long _vq_quantmap__44c8_s_p1_0[] = {
  134260. 1, 0, 2,
  134261. };
  134262. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134263. _vq_quantthresh__44c8_s_p1_0,
  134264. _vq_quantmap__44c8_s_p1_0,
  134265. 3,
  134266. 3
  134267. };
  134268. static static_codebook _44c8_s_p1_0 = {
  134269. 4, 81,
  134270. _vq_lengthlist__44c8_s_p1_0,
  134271. 1, -535822336, 1611661312, 2, 0,
  134272. _vq_quantlist__44c8_s_p1_0,
  134273. NULL,
  134274. &_vq_auxt__44c8_s_p1_0,
  134275. NULL,
  134276. 0
  134277. };
  134278. static long _vq_quantlist__44c8_s_p2_0[] = {
  134279. 2,
  134280. 1,
  134281. 3,
  134282. 0,
  134283. 4,
  134284. };
  134285. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134286. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134287. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134288. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134289. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134290. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134291. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134292. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134293. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134295. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134296. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134297. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134298. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134299. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134300. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134301. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134303. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134304. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134305. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134306. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134307. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134308. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134309. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134311. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134312. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134313. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134314. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134315. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134316. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134317. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134322. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134323. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134324. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134325. 13,
  134326. };
  134327. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134328. -1.5, -0.5, 0.5, 1.5,
  134329. };
  134330. static long _vq_quantmap__44c8_s_p2_0[] = {
  134331. 3, 1, 0, 2, 4,
  134332. };
  134333. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134334. _vq_quantthresh__44c8_s_p2_0,
  134335. _vq_quantmap__44c8_s_p2_0,
  134336. 5,
  134337. 5
  134338. };
  134339. static static_codebook _44c8_s_p2_0 = {
  134340. 4, 625,
  134341. _vq_lengthlist__44c8_s_p2_0,
  134342. 1, -533725184, 1611661312, 3, 0,
  134343. _vq_quantlist__44c8_s_p2_0,
  134344. NULL,
  134345. &_vq_auxt__44c8_s_p2_0,
  134346. NULL,
  134347. 0
  134348. };
  134349. static long _vq_quantlist__44c8_s_p3_0[] = {
  134350. 4,
  134351. 3,
  134352. 5,
  134353. 2,
  134354. 6,
  134355. 1,
  134356. 7,
  134357. 0,
  134358. 8,
  134359. };
  134360. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134361. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134362. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134363. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134364. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134366. 0,
  134367. };
  134368. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134369. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134370. };
  134371. static long _vq_quantmap__44c8_s_p3_0[] = {
  134372. 7, 5, 3, 1, 0, 2, 4, 6,
  134373. 8,
  134374. };
  134375. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134376. _vq_quantthresh__44c8_s_p3_0,
  134377. _vq_quantmap__44c8_s_p3_0,
  134378. 9,
  134379. 9
  134380. };
  134381. static static_codebook _44c8_s_p3_0 = {
  134382. 2, 81,
  134383. _vq_lengthlist__44c8_s_p3_0,
  134384. 1, -531628032, 1611661312, 4, 0,
  134385. _vq_quantlist__44c8_s_p3_0,
  134386. NULL,
  134387. &_vq_auxt__44c8_s_p3_0,
  134388. NULL,
  134389. 0
  134390. };
  134391. static long _vq_quantlist__44c8_s_p4_0[] = {
  134392. 8,
  134393. 7,
  134394. 9,
  134395. 6,
  134396. 10,
  134397. 5,
  134398. 11,
  134399. 4,
  134400. 12,
  134401. 3,
  134402. 13,
  134403. 2,
  134404. 14,
  134405. 1,
  134406. 15,
  134407. 0,
  134408. 16,
  134409. };
  134410. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134411. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134412. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134413. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134414. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134415. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134416. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134417. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134418. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134419. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134420. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134429. 0,
  134430. };
  134431. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134432. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134433. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134434. };
  134435. static long _vq_quantmap__44c8_s_p4_0[] = {
  134436. 15, 13, 11, 9, 7, 5, 3, 1,
  134437. 0, 2, 4, 6, 8, 10, 12, 14,
  134438. 16,
  134439. };
  134440. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134441. _vq_quantthresh__44c8_s_p4_0,
  134442. _vq_quantmap__44c8_s_p4_0,
  134443. 17,
  134444. 17
  134445. };
  134446. static static_codebook _44c8_s_p4_0 = {
  134447. 2, 289,
  134448. _vq_lengthlist__44c8_s_p4_0,
  134449. 1, -529530880, 1611661312, 5, 0,
  134450. _vq_quantlist__44c8_s_p4_0,
  134451. NULL,
  134452. &_vq_auxt__44c8_s_p4_0,
  134453. NULL,
  134454. 0
  134455. };
  134456. static long _vq_quantlist__44c8_s_p5_0[] = {
  134457. 1,
  134458. 0,
  134459. 2,
  134460. };
  134461. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134462. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134463. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134464. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134465. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134466. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134467. 12,
  134468. };
  134469. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134470. -5.5, 5.5,
  134471. };
  134472. static long _vq_quantmap__44c8_s_p5_0[] = {
  134473. 1, 0, 2,
  134474. };
  134475. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134476. _vq_quantthresh__44c8_s_p5_0,
  134477. _vq_quantmap__44c8_s_p5_0,
  134478. 3,
  134479. 3
  134480. };
  134481. static static_codebook _44c8_s_p5_0 = {
  134482. 4, 81,
  134483. _vq_lengthlist__44c8_s_p5_0,
  134484. 1, -529137664, 1618345984, 2, 0,
  134485. _vq_quantlist__44c8_s_p5_0,
  134486. NULL,
  134487. &_vq_auxt__44c8_s_p5_0,
  134488. NULL,
  134489. 0
  134490. };
  134491. static long _vq_quantlist__44c8_s_p5_1[] = {
  134492. 5,
  134493. 4,
  134494. 6,
  134495. 3,
  134496. 7,
  134497. 2,
  134498. 8,
  134499. 1,
  134500. 9,
  134501. 0,
  134502. 10,
  134503. };
  134504. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134505. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134506. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134507. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134508. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134509. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134510. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134511. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134512. 11,11,11, 7, 7, 7, 7, 8, 8,
  134513. };
  134514. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134515. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134516. 3.5, 4.5,
  134517. };
  134518. static long _vq_quantmap__44c8_s_p5_1[] = {
  134519. 9, 7, 5, 3, 1, 0, 2, 4,
  134520. 6, 8, 10,
  134521. };
  134522. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134523. _vq_quantthresh__44c8_s_p5_1,
  134524. _vq_quantmap__44c8_s_p5_1,
  134525. 11,
  134526. 11
  134527. };
  134528. static static_codebook _44c8_s_p5_1 = {
  134529. 2, 121,
  134530. _vq_lengthlist__44c8_s_p5_1,
  134531. 1, -531365888, 1611661312, 4, 0,
  134532. _vq_quantlist__44c8_s_p5_1,
  134533. NULL,
  134534. &_vq_auxt__44c8_s_p5_1,
  134535. NULL,
  134536. 0
  134537. };
  134538. static long _vq_quantlist__44c8_s_p6_0[] = {
  134539. 6,
  134540. 5,
  134541. 7,
  134542. 4,
  134543. 8,
  134544. 3,
  134545. 9,
  134546. 2,
  134547. 10,
  134548. 1,
  134549. 11,
  134550. 0,
  134551. 12,
  134552. };
  134553. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134554. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134555. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134556. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134557. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134558. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134559. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134564. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134565. };
  134566. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134567. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134568. 12.5, 17.5, 22.5, 27.5,
  134569. };
  134570. static long _vq_quantmap__44c8_s_p6_0[] = {
  134571. 11, 9, 7, 5, 3, 1, 0, 2,
  134572. 4, 6, 8, 10, 12,
  134573. };
  134574. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134575. _vq_quantthresh__44c8_s_p6_0,
  134576. _vq_quantmap__44c8_s_p6_0,
  134577. 13,
  134578. 13
  134579. };
  134580. static static_codebook _44c8_s_p6_0 = {
  134581. 2, 169,
  134582. _vq_lengthlist__44c8_s_p6_0,
  134583. 1, -526516224, 1616117760, 4, 0,
  134584. _vq_quantlist__44c8_s_p6_0,
  134585. NULL,
  134586. &_vq_auxt__44c8_s_p6_0,
  134587. NULL,
  134588. 0
  134589. };
  134590. static long _vq_quantlist__44c8_s_p6_1[] = {
  134591. 2,
  134592. 1,
  134593. 3,
  134594. 0,
  134595. 4,
  134596. };
  134597. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134598. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134599. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134600. };
  134601. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134602. -1.5, -0.5, 0.5, 1.5,
  134603. };
  134604. static long _vq_quantmap__44c8_s_p6_1[] = {
  134605. 3, 1, 0, 2, 4,
  134606. };
  134607. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134608. _vq_quantthresh__44c8_s_p6_1,
  134609. _vq_quantmap__44c8_s_p6_1,
  134610. 5,
  134611. 5
  134612. };
  134613. static static_codebook _44c8_s_p6_1 = {
  134614. 2, 25,
  134615. _vq_lengthlist__44c8_s_p6_1,
  134616. 1, -533725184, 1611661312, 3, 0,
  134617. _vq_quantlist__44c8_s_p6_1,
  134618. NULL,
  134619. &_vq_auxt__44c8_s_p6_1,
  134620. NULL,
  134621. 0
  134622. };
  134623. static long _vq_quantlist__44c8_s_p7_0[] = {
  134624. 6,
  134625. 5,
  134626. 7,
  134627. 4,
  134628. 8,
  134629. 3,
  134630. 9,
  134631. 2,
  134632. 10,
  134633. 1,
  134634. 11,
  134635. 0,
  134636. 12,
  134637. };
  134638. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134639. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134640. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134641. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134642. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134643. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134644. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134645. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134646. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134647. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134648. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134649. 20,13,13,13,13,14,13,15,15,
  134650. };
  134651. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134652. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134653. 27.5, 38.5, 49.5, 60.5,
  134654. };
  134655. static long _vq_quantmap__44c8_s_p7_0[] = {
  134656. 11, 9, 7, 5, 3, 1, 0, 2,
  134657. 4, 6, 8, 10, 12,
  134658. };
  134659. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134660. _vq_quantthresh__44c8_s_p7_0,
  134661. _vq_quantmap__44c8_s_p7_0,
  134662. 13,
  134663. 13
  134664. };
  134665. static static_codebook _44c8_s_p7_0 = {
  134666. 2, 169,
  134667. _vq_lengthlist__44c8_s_p7_0,
  134668. 1, -523206656, 1618345984, 4, 0,
  134669. _vq_quantlist__44c8_s_p7_0,
  134670. NULL,
  134671. &_vq_auxt__44c8_s_p7_0,
  134672. NULL,
  134673. 0
  134674. };
  134675. static long _vq_quantlist__44c8_s_p7_1[] = {
  134676. 5,
  134677. 4,
  134678. 6,
  134679. 3,
  134680. 7,
  134681. 2,
  134682. 8,
  134683. 1,
  134684. 9,
  134685. 0,
  134686. 10,
  134687. };
  134688. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134689. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134690. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134691. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134692. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134693. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134694. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134695. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134696. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134697. };
  134698. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134699. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134700. 3.5, 4.5,
  134701. };
  134702. static long _vq_quantmap__44c8_s_p7_1[] = {
  134703. 9, 7, 5, 3, 1, 0, 2, 4,
  134704. 6, 8, 10,
  134705. };
  134706. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134707. _vq_quantthresh__44c8_s_p7_1,
  134708. _vq_quantmap__44c8_s_p7_1,
  134709. 11,
  134710. 11
  134711. };
  134712. static static_codebook _44c8_s_p7_1 = {
  134713. 2, 121,
  134714. _vq_lengthlist__44c8_s_p7_1,
  134715. 1, -531365888, 1611661312, 4, 0,
  134716. _vq_quantlist__44c8_s_p7_1,
  134717. NULL,
  134718. &_vq_auxt__44c8_s_p7_1,
  134719. NULL,
  134720. 0
  134721. };
  134722. static long _vq_quantlist__44c8_s_p8_0[] = {
  134723. 7,
  134724. 6,
  134725. 8,
  134726. 5,
  134727. 9,
  134728. 4,
  134729. 10,
  134730. 3,
  134731. 11,
  134732. 2,
  134733. 12,
  134734. 1,
  134735. 13,
  134736. 0,
  134737. 14,
  134738. };
  134739. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134740. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134741. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134742. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134743. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134744. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134745. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134746. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134747. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134748. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134749. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134750. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134751. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134752. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134753. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134754. 15,
  134755. };
  134756. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134757. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134758. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134759. };
  134760. static long _vq_quantmap__44c8_s_p8_0[] = {
  134761. 13, 11, 9, 7, 5, 3, 1, 0,
  134762. 2, 4, 6, 8, 10, 12, 14,
  134763. };
  134764. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134765. _vq_quantthresh__44c8_s_p8_0,
  134766. _vq_quantmap__44c8_s_p8_0,
  134767. 15,
  134768. 15
  134769. };
  134770. static static_codebook _44c8_s_p8_0 = {
  134771. 2, 225,
  134772. _vq_lengthlist__44c8_s_p8_0,
  134773. 1, -520986624, 1620377600, 4, 0,
  134774. _vq_quantlist__44c8_s_p8_0,
  134775. NULL,
  134776. &_vq_auxt__44c8_s_p8_0,
  134777. NULL,
  134778. 0
  134779. };
  134780. static long _vq_quantlist__44c8_s_p8_1[] = {
  134781. 10,
  134782. 9,
  134783. 11,
  134784. 8,
  134785. 12,
  134786. 7,
  134787. 13,
  134788. 6,
  134789. 14,
  134790. 5,
  134791. 15,
  134792. 4,
  134793. 16,
  134794. 3,
  134795. 17,
  134796. 2,
  134797. 18,
  134798. 1,
  134799. 19,
  134800. 0,
  134801. 20,
  134802. };
  134803. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134804. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134805. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134806. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134807. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134808. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134809. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134810. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134811. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134812. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134813. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134814. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134815. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134816. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134817. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134818. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134819. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134820. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134821. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134822. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134823. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134824. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134825. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134826. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134827. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134828. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134829. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134830. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134831. 10, 9, 9,10,10, 9,10, 9, 9,
  134832. };
  134833. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134834. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134835. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134836. 6.5, 7.5, 8.5, 9.5,
  134837. };
  134838. static long _vq_quantmap__44c8_s_p8_1[] = {
  134839. 19, 17, 15, 13, 11, 9, 7, 5,
  134840. 3, 1, 0, 2, 4, 6, 8, 10,
  134841. 12, 14, 16, 18, 20,
  134842. };
  134843. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134844. _vq_quantthresh__44c8_s_p8_1,
  134845. _vq_quantmap__44c8_s_p8_1,
  134846. 21,
  134847. 21
  134848. };
  134849. static static_codebook _44c8_s_p8_1 = {
  134850. 2, 441,
  134851. _vq_lengthlist__44c8_s_p8_1,
  134852. 1, -529268736, 1611661312, 5, 0,
  134853. _vq_quantlist__44c8_s_p8_1,
  134854. NULL,
  134855. &_vq_auxt__44c8_s_p8_1,
  134856. NULL,
  134857. 0
  134858. };
  134859. static long _vq_quantlist__44c8_s_p9_0[] = {
  134860. 8,
  134861. 7,
  134862. 9,
  134863. 6,
  134864. 10,
  134865. 5,
  134866. 11,
  134867. 4,
  134868. 12,
  134869. 3,
  134870. 13,
  134871. 2,
  134872. 14,
  134873. 1,
  134874. 15,
  134875. 0,
  134876. 16,
  134877. };
  134878. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134879. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134880. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134881. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134882. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134883. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134884. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134885. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134888. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134890. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134891. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134892. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134893. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134894. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134895. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134896. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134897. 10,
  134898. };
  134899. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134900. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134901. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134902. };
  134903. static long _vq_quantmap__44c8_s_p9_0[] = {
  134904. 15, 13, 11, 9, 7, 5, 3, 1,
  134905. 0, 2, 4, 6, 8, 10, 12, 14,
  134906. 16,
  134907. };
  134908. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134909. _vq_quantthresh__44c8_s_p9_0,
  134910. _vq_quantmap__44c8_s_p9_0,
  134911. 17,
  134912. 17
  134913. };
  134914. static static_codebook _44c8_s_p9_0 = {
  134915. 2, 289,
  134916. _vq_lengthlist__44c8_s_p9_0,
  134917. 1, -509798400, 1631393792, 5, 0,
  134918. _vq_quantlist__44c8_s_p9_0,
  134919. NULL,
  134920. &_vq_auxt__44c8_s_p9_0,
  134921. NULL,
  134922. 0
  134923. };
  134924. static long _vq_quantlist__44c8_s_p9_1[] = {
  134925. 9,
  134926. 8,
  134927. 10,
  134928. 7,
  134929. 11,
  134930. 6,
  134931. 12,
  134932. 5,
  134933. 13,
  134934. 4,
  134935. 14,
  134936. 3,
  134937. 15,
  134938. 2,
  134939. 16,
  134940. 1,
  134941. 17,
  134942. 0,
  134943. 18,
  134944. };
  134945. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134946. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134947. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134948. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134949. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134950. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134951. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134952. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134953. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134954. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134955. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134956. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134957. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134958. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134959. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134960. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134961. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134962. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134963. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134964. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134965. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134966. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134967. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134968. 14,13,13,14,14,15,14,15,14,
  134969. };
  134970. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134971. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134972. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134973. 367.5, 416.5,
  134974. };
  134975. static long _vq_quantmap__44c8_s_p9_1[] = {
  134976. 17, 15, 13, 11, 9, 7, 5, 3,
  134977. 1, 0, 2, 4, 6, 8, 10, 12,
  134978. 14, 16, 18,
  134979. };
  134980. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134981. _vq_quantthresh__44c8_s_p9_1,
  134982. _vq_quantmap__44c8_s_p9_1,
  134983. 19,
  134984. 19
  134985. };
  134986. static static_codebook _44c8_s_p9_1 = {
  134987. 2, 361,
  134988. _vq_lengthlist__44c8_s_p9_1,
  134989. 1, -518287360, 1622704128, 5, 0,
  134990. _vq_quantlist__44c8_s_p9_1,
  134991. NULL,
  134992. &_vq_auxt__44c8_s_p9_1,
  134993. NULL,
  134994. 0
  134995. };
  134996. static long _vq_quantlist__44c8_s_p9_2[] = {
  134997. 24,
  134998. 23,
  134999. 25,
  135000. 22,
  135001. 26,
  135002. 21,
  135003. 27,
  135004. 20,
  135005. 28,
  135006. 19,
  135007. 29,
  135008. 18,
  135009. 30,
  135010. 17,
  135011. 31,
  135012. 16,
  135013. 32,
  135014. 15,
  135015. 33,
  135016. 14,
  135017. 34,
  135018. 13,
  135019. 35,
  135020. 12,
  135021. 36,
  135022. 11,
  135023. 37,
  135024. 10,
  135025. 38,
  135026. 9,
  135027. 39,
  135028. 8,
  135029. 40,
  135030. 7,
  135031. 41,
  135032. 6,
  135033. 42,
  135034. 5,
  135035. 43,
  135036. 4,
  135037. 44,
  135038. 3,
  135039. 45,
  135040. 2,
  135041. 46,
  135042. 1,
  135043. 47,
  135044. 0,
  135045. 48,
  135046. };
  135047. static long _vq_lengthlist__44c8_s_p9_2[] = {
  135048. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135049. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135050. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135051. 7,
  135052. };
  135053. static float _vq_quantthresh__44c8_s_p9_2[] = {
  135054. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135055. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135056. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135057. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135058. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135059. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135060. };
  135061. static long _vq_quantmap__44c8_s_p9_2[] = {
  135062. 47, 45, 43, 41, 39, 37, 35, 33,
  135063. 31, 29, 27, 25, 23, 21, 19, 17,
  135064. 15, 13, 11, 9, 7, 5, 3, 1,
  135065. 0, 2, 4, 6, 8, 10, 12, 14,
  135066. 16, 18, 20, 22, 24, 26, 28, 30,
  135067. 32, 34, 36, 38, 40, 42, 44, 46,
  135068. 48,
  135069. };
  135070. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  135071. _vq_quantthresh__44c8_s_p9_2,
  135072. _vq_quantmap__44c8_s_p9_2,
  135073. 49,
  135074. 49
  135075. };
  135076. static static_codebook _44c8_s_p9_2 = {
  135077. 1, 49,
  135078. _vq_lengthlist__44c8_s_p9_2,
  135079. 1, -526909440, 1611661312, 6, 0,
  135080. _vq_quantlist__44c8_s_p9_2,
  135081. NULL,
  135082. &_vq_auxt__44c8_s_p9_2,
  135083. NULL,
  135084. 0
  135085. };
  135086. static long _huff_lengthlist__44c8_s_short[] = {
  135087. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  135088. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  135089. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  135090. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  135091. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  135092. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  135093. 10, 9,11,14,
  135094. };
  135095. static static_codebook _huff_book__44c8_s_short = {
  135096. 2, 100,
  135097. _huff_lengthlist__44c8_s_short,
  135098. 0, 0, 0, 0, 0,
  135099. NULL,
  135100. NULL,
  135101. NULL,
  135102. NULL,
  135103. 0
  135104. };
  135105. static long _huff_lengthlist__44c9_s_long[] = {
  135106. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  135107. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  135108. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  135109. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  135110. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  135111. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  135112. 10, 9, 8, 9,
  135113. };
  135114. static static_codebook _huff_book__44c9_s_long = {
  135115. 2, 100,
  135116. _huff_lengthlist__44c9_s_long,
  135117. 0, 0, 0, 0, 0,
  135118. NULL,
  135119. NULL,
  135120. NULL,
  135121. NULL,
  135122. 0
  135123. };
  135124. static long _vq_quantlist__44c9_s_p1_0[] = {
  135125. 1,
  135126. 0,
  135127. 2,
  135128. };
  135129. static long _vq_lengthlist__44c9_s_p1_0[] = {
  135130. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  135131. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  135132. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  135133. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  135134. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  135135. 7,
  135136. };
  135137. static float _vq_quantthresh__44c9_s_p1_0[] = {
  135138. -0.5, 0.5,
  135139. };
  135140. static long _vq_quantmap__44c9_s_p1_0[] = {
  135141. 1, 0, 2,
  135142. };
  135143. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135144. _vq_quantthresh__44c9_s_p1_0,
  135145. _vq_quantmap__44c9_s_p1_0,
  135146. 3,
  135147. 3
  135148. };
  135149. static static_codebook _44c9_s_p1_0 = {
  135150. 4, 81,
  135151. _vq_lengthlist__44c9_s_p1_0,
  135152. 1, -535822336, 1611661312, 2, 0,
  135153. _vq_quantlist__44c9_s_p1_0,
  135154. NULL,
  135155. &_vq_auxt__44c9_s_p1_0,
  135156. NULL,
  135157. 0
  135158. };
  135159. static long _vq_quantlist__44c9_s_p2_0[] = {
  135160. 2,
  135161. 1,
  135162. 3,
  135163. 0,
  135164. 4,
  135165. };
  135166. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135167. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135168. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135169. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135170. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135171. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135172. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135173. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135174. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  135175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135176. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135177. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135178. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135179. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135180. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135181. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135182. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135184. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135185. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135186. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135187. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135188. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135189. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135190. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135192. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135193. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135194. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135195. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135196. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135197. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135198. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135203. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135204. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135205. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135206. 12,
  135207. };
  135208. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135209. -1.5, -0.5, 0.5, 1.5,
  135210. };
  135211. static long _vq_quantmap__44c9_s_p2_0[] = {
  135212. 3, 1, 0, 2, 4,
  135213. };
  135214. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135215. _vq_quantthresh__44c9_s_p2_0,
  135216. _vq_quantmap__44c9_s_p2_0,
  135217. 5,
  135218. 5
  135219. };
  135220. static static_codebook _44c9_s_p2_0 = {
  135221. 4, 625,
  135222. _vq_lengthlist__44c9_s_p2_0,
  135223. 1, -533725184, 1611661312, 3, 0,
  135224. _vq_quantlist__44c9_s_p2_0,
  135225. NULL,
  135226. &_vq_auxt__44c9_s_p2_0,
  135227. NULL,
  135228. 0
  135229. };
  135230. static long _vq_quantlist__44c9_s_p3_0[] = {
  135231. 4,
  135232. 3,
  135233. 5,
  135234. 2,
  135235. 6,
  135236. 1,
  135237. 7,
  135238. 0,
  135239. 8,
  135240. };
  135241. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135242. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135243. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135244. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135245. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135247. 0,
  135248. };
  135249. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135250. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135251. };
  135252. static long _vq_quantmap__44c9_s_p3_0[] = {
  135253. 7, 5, 3, 1, 0, 2, 4, 6,
  135254. 8,
  135255. };
  135256. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135257. _vq_quantthresh__44c9_s_p3_0,
  135258. _vq_quantmap__44c9_s_p3_0,
  135259. 9,
  135260. 9
  135261. };
  135262. static static_codebook _44c9_s_p3_0 = {
  135263. 2, 81,
  135264. _vq_lengthlist__44c9_s_p3_0,
  135265. 1, -531628032, 1611661312, 4, 0,
  135266. _vq_quantlist__44c9_s_p3_0,
  135267. NULL,
  135268. &_vq_auxt__44c9_s_p3_0,
  135269. NULL,
  135270. 0
  135271. };
  135272. static long _vq_quantlist__44c9_s_p4_0[] = {
  135273. 8,
  135274. 7,
  135275. 9,
  135276. 6,
  135277. 10,
  135278. 5,
  135279. 11,
  135280. 4,
  135281. 12,
  135282. 3,
  135283. 13,
  135284. 2,
  135285. 14,
  135286. 1,
  135287. 15,
  135288. 0,
  135289. 16,
  135290. };
  135291. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135292. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135293. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135294. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135295. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135296. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135297. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135298. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135299. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135300. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135301. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0,
  135311. };
  135312. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135313. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135314. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135315. };
  135316. static long _vq_quantmap__44c9_s_p4_0[] = {
  135317. 15, 13, 11, 9, 7, 5, 3, 1,
  135318. 0, 2, 4, 6, 8, 10, 12, 14,
  135319. 16,
  135320. };
  135321. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135322. _vq_quantthresh__44c9_s_p4_0,
  135323. _vq_quantmap__44c9_s_p4_0,
  135324. 17,
  135325. 17
  135326. };
  135327. static static_codebook _44c9_s_p4_0 = {
  135328. 2, 289,
  135329. _vq_lengthlist__44c9_s_p4_0,
  135330. 1, -529530880, 1611661312, 5, 0,
  135331. _vq_quantlist__44c9_s_p4_0,
  135332. NULL,
  135333. &_vq_auxt__44c9_s_p4_0,
  135334. NULL,
  135335. 0
  135336. };
  135337. static long _vq_quantlist__44c9_s_p5_0[] = {
  135338. 1,
  135339. 0,
  135340. 2,
  135341. };
  135342. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135343. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135344. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135345. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135346. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135347. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135348. 12,
  135349. };
  135350. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135351. -5.5, 5.5,
  135352. };
  135353. static long _vq_quantmap__44c9_s_p5_0[] = {
  135354. 1, 0, 2,
  135355. };
  135356. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135357. _vq_quantthresh__44c9_s_p5_0,
  135358. _vq_quantmap__44c9_s_p5_0,
  135359. 3,
  135360. 3
  135361. };
  135362. static static_codebook _44c9_s_p5_0 = {
  135363. 4, 81,
  135364. _vq_lengthlist__44c9_s_p5_0,
  135365. 1, -529137664, 1618345984, 2, 0,
  135366. _vq_quantlist__44c9_s_p5_0,
  135367. NULL,
  135368. &_vq_auxt__44c9_s_p5_0,
  135369. NULL,
  135370. 0
  135371. };
  135372. static long _vq_quantlist__44c9_s_p5_1[] = {
  135373. 5,
  135374. 4,
  135375. 6,
  135376. 3,
  135377. 7,
  135378. 2,
  135379. 8,
  135380. 1,
  135381. 9,
  135382. 0,
  135383. 10,
  135384. };
  135385. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135386. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135387. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135388. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135389. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135390. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135391. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135392. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135393. 11,11,11, 7, 7, 7, 7, 7, 7,
  135394. };
  135395. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135396. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135397. 3.5, 4.5,
  135398. };
  135399. static long _vq_quantmap__44c9_s_p5_1[] = {
  135400. 9, 7, 5, 3, 1, 0, 2, 4,
  135401. 6, 8, 10,
  135402. };
  135403. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135404. _vq_quantthresh__44c9_s_p5_1,
  135405. _vq_quantmap__44c9_s_p5_1,
  135406. 11,
  135407. 11
  135408. };
  135409. static static_codebook _44c9_s_p5_1 = {
  135410. 2, 121,
  135411. _vq_lengthlist__44c9_s_p5_1,
  135412. 1, -531365888, 1611661312, 4, 0,
  135413. _vq_quantlist__44c9_s_p5_1,
  135414. NULL,
  135415. &_vq_auxt__44c9_s_p5_1,
  135416. NULL,
  135417. 0
  135418. };
  135419. static long _vq_quantlist__44c9_s_p6_0[] = {
  135420. 6,
  135421. 5,
  135422. 7,
  135423. 4,
  135424. 8,
  135425. 3,
  135426. 9,
  135427. 2,
  135428. 10,
  135429. 1,
  135430. 11,
  135431. 0,
  135432. 12,
  135433. };
  135434. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135435. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135436. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135437. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135438. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135439. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135440. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135445. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135446. };
  135447. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135448. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135449. 12.5, 17.5, 22.5, 27.5,
  135450. };
  135451. static long _vq_quantmap__44c9_s_p6_0[] = {
  135452. 11, 9, 7, 5, 3, 1, 0, 2,
  135453. 4, 6, 8, 10, 12,
  135454. };
  135455. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135456. _vq_quantthresh__44c9_s_p6_0,
  135457. _vq_quantmap__44c9_s_p6_0,
  135458. 13,
  135459. 13
  135460. };
  135461. static static_codebook _44c9_s_p6_0 = {
  135462. 2, 169,
  135463. _vq_lengthlist__44c9_s_p6_0,
  135464. 1, -526516224, 1616117760, 4, 0,
  135465. _vq_quantlist__44c9_s_p6_0,
  135466. NULL,
  135467. &_vq_auxt__44c9_s_p6_0,
  135468. NULL,
  135469. 0
  135470. };
  135471. static long _vq_quantlist__44c9_s_p6_1[] = {
  135472. 2,
  135473. 1,
  135474. 3,
  135475. 0,
  135476. 4,
  135477. };
  135478. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135479. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135480. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135481. };
  135482. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135483. -1.5, -0.5, 0.5, 1.5,
  135484. };
  135485. static long _vq_quantmap__44c9_s_p6_1[] = {
  135486. 3, 1, 0, 2, 4,
  135487. };
  135488. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135489. _vq_quantthresh__44c9_s_p6_1,
  135490. _vq_quantmap__44c9_s_p6_1,
  135491. 5,
  135492. 5
  135493. };
  135494. static static_codebook _44c9_s_p6_1 = {
  135495. 2, 25,
  135496. _vq_lengthlist__44c9_s_p6_1,
  135497. 1, -533725184, 1611661312, 3, 0,
  135498. _vq_quantlist__44c9_s_p6_1,
  135499. NULL,
  135500. &_vq_auxt__44c9_s_p6_1,
  135501. NULL,
  135502. 0
  135503. };
  135504. static long _vq_quantlist__44c9_s_p7_0[] = {
  135505. 6,
  135506. 5,
  135507. 7,
  135508. 4,
  135509. 8,
  135510. 3,
  135511. 9,
  135512. 2,
  135513. 10,
  135514. 1,
  135515. 11,
  135516. 0,
  135517. 12,
  135518. };
  135519. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135520. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135521. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135522. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135523. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135524. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135525. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135526. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135527. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135528. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135529. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135530. 19,12,12,12,12,13,13,14,14,
  135531. };
  135532. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135533. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135534. 27.5, 38.5, 49.5, 60.5,
  135535. };
  135536. static long _vq_quantmap__44c9_s_p7_0[] = {
  135537. 11, 9, 7, 5, 3, 1, 0, 2,
  135538. 4, 6, 8, 10, 12,
  135539. };
  135540. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135541. _vq_quantthresh__44c9_s_p7_0,
  135542. _vq_quantmap__44c9_s_p7_0,
  135543. 13,
  135544. 13
  135545. };
  135546. static static_codebook _44c9_s_p7_0 = {
  135547. 2, 169,
  135548. _vq_lengthlist__44c9_s_p7_0,
  135549. 1, -523206656, 1618345984, 4, 0,
  135550. _vq_quantlist__44c9_s_p7_0,
  135551. NULL,
  135552. &_vq_auxt__44c9_s_p7_0,
  135553. NULL,
  135554. 0
  135555. };
  135556. static long _vq_quantlist__44c9_s_p7_1[] = {
  135557. 5,
  135558. 4,
  135559. 6,
  135560. 3,
  135561. 7,
  135562. 2,
  135563. 8,
  135564. 1,
  135565. 9,
  135566. 0,
  135567. 10,
  135568. };
  135569. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135570. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135571. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135572. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135573. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135574. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135575. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135576. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135577. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135578. };
  135579. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135580. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135581. 3.5, 4.5,
  135582. };
  135583. static long _vq_quantmap__44c9_s_p7_1[] = {
  135584. 9, 7, 5, 3, 1, 0, 2, 4,
  135585. 6, 8, 10,
  135586. };
  135587. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135588. _vq_quantthresh__44c9_s_p7_1,
  135589. _vq_quantmap__44c9_s_p7_1,
  135590. 11,
  135591. 11
  135592. };
  135593. static static_codebook _44c9_s_p7_1 = {
  135594. 2, 121,
  135595. _vq_lengthlist__44c9_s_p7_1,
  135596. 1, -531365888, 1611661312, 4, 0,
  135597. _vq_quantlist__44c9_s_p7_1,
  135598. NULL,
  135599. &_vq_auxt__44c9_s_p7_1,
  135600. NULL,
  135601. 0
  135602. };
  135603. static long _vq_quantlist__44c9_s_p8_0[] = {
  135604. 7,
  135605. 6,
  135606. 8,
  135607. 5,
  135608. 9,
  135609. 4,
  135610. 10,
  135611. 3,
  135612. 11,
  135613. 2,
  135614. 12,
  135615. 1,
  135616. 13,
  135617. 0,
  135618. 14,
  135619. };
  135620. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135621. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135622. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135623. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135624. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135625. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135626. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135627. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135628. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135629. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135630. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135631. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135632. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135633. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135634. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135635. 14,
  135636. };
  135637. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135638. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135639. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135640. };
  135641. static long _vq_quantmap__44c9_s_p8_0[] = {
  135642. 13, 11, 9, 7, 5, 3, 1, 0,
  135643. 2, 4, 6, 8, 10, 12, 14,
  135644. };
  135645. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135646. _vq_quantthresh__44c9_s_p8_0,
  135647. _vq_quantmap__44c9_s_p8_0,
  135648. 15,
  135649. 15
  135650. };
  135651. static static_codebook _44c9_s_p8_0 = {
  135652. 2, 225,
  135653. _vq_lengthlist__44c9_s_p8_0,
  135654. 1, -520986624, 1620377600, 4, 0,
  135655. _vq_quantlist__44c9_s_p8_0,
  135656. NULL,
  135657. &_vq_auxt__44c9_s_p8_0,
  135658. NULL,
  135659. 0
  135660. };
  135661. static long _vq_quantlist__44c9_s_p8_1[] = {
  135662. 10,
  135663. 9,
  135664. 11,
  135665. 8,
  135666. 12,
  135667. 7,
  135668. 13,
  135669. 6,
  135670. 14,
  135671. 5,
  135672. 15,
  135673. 4,
  135674. 16,
  135675. 3,
  135676. 17,
  135677. 2,
  135678. 18,
  135679. 1,
  135680. 19,
  135681. 0,
  135682. 20,
  135683. };
  135684. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135685. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135686. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135687. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135688. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135689. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135690. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135691. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135692. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135693. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135694. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135695. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135696. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135697. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135698. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135699. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135700. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135701. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135702. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135703. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135704. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135705. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135706. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135707. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135708. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135709. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135710. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135711. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135712. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135713. };
  135714. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135715. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135716. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135717. 6.5, 7.5, 8.5, 9.5,
  135718. };
  135719. static long _vq_quantmap__44c9_s_p8_1[] = {
  135720. 19, 17, 15, 13, 11, 9, 7, 5,
  135721. 3, 1, 0, 2, 4, 6, 8, 10,
  135722. 12, 14, 16, 18, 20,
  135723. };
  135724. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135725. _vq_quantthresh__44c9_s_p8_1,
  135726. _vq_quantmap__44c9_s_p8_1,
  135727. 21,
  135728. 21
  135729. };
  135730. static static_codebook _44c9_s_p8_1 = {
  135731. 2, 441,
  135732. _vq_lengthlist__44c9_s_p8_1,
  135733. 1, -529268736, 1611661312, 5, 0,
  135734. _vq_quantlist__44c9_s_p8_1,
  135735. NULL,
  135736. &_vq_auxt__44c9_s_p8_1,
  135737. NULL,
  135738. 0
  135739. };
  135740. static long _vq_quantlist__44c9_s_p9_0[] = {
  135741. 9,
  135742. 8,
  135743. 10,
  135744. 7,
  135745. 11,
  135746. 6,
  135747. 12,
  135748. 5,
  135749. 13,
  135750. 4,
  135751. 14,
  135752. 3,
  135753. 15,
  135754. 2,
  135755. 16,
  135756. 1,
  135757. 17,
  135758. 0,
  135759. 18,
  135760. };
  135761. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135762. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135763. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135764. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135765. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135766. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135767. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135768. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135769. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135770. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135771. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135772. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135773. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135774. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135775. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135776. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135777. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135778. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135779. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135780. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135781. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135784. 11,11,11,11,11,11,11,11,11,
  135785. };
  135786. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135787. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135788. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135789. 6982.5, 7913.5,
  135790. };
  135791. static long _vq_quantmap__44c9_s_p9_0[] = {
  135792. 17, 15, 13, 11, 9, 7, 5, 3,
  135793. 1, 0, 2, 4, 6, 8, 10, 12,
  135794. 14, 16, 18,
  135795. };
  135796. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135797. _vq_quantthresh__44c9_s_p9_0,
  135798. _vq_quantmap__44c9_s_p9_0,
  135799. 19,
  135800. 19
  135801. };
  135802. static static_codebook _44c9_s_p9_0 = {
  135803. 2, 361,
  135804. _vq_lengthlist__44c9_s_p9_0,
  135805. 1, -508535424, 1631393792, 5, 0,
  135806. _vq_quantlist__44c9_s_p9_0,
  135807. NULL,
  135808. &_vq_auxt__44c9_s_p9_0,
  135809. NULL,
  135810. 0
  135811. };
  135812. static long _vq_quantlist__44c9_s_p9_1[] = {
  135813. 9,
  135814. 8,
  135815. 10,
  135816. 7,
  135817. 11,
  135818. 6,
  135819. 12,
  135820. 5,
  135821. 13,
  135822. 4,
  135823. 14,
  135824. 3,
  135825. 15,
  135826. 2,
  135827. 16,
  135828. 1,
  135829. 17,
  135830. 0,
  135831. 18,
  135832. };
  135833. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135834. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135835. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135836. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135837. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135838. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135839. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135840. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135841. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135842. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135843. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135844. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135845. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135846. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135847. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135848. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135849. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135850. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135851. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135852. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135853. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135854. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135855. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135856. 13,13,13,14,13,14,15,15,15,
  135857. };
  135858. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135859. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135860. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135861. 367.5, 416.5,
  135862. };
  135863. static long _vq_quantmap__44c9_s_p9_1[] = {
  135864. 17, 15, 13, 11, 9, 7, 5, 3,
  135865. 1, 0, 2, 4, 6, 8, 10, 12,
  135866. 14, 16, 18,
  135867. };
  135868. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135869. _vq_quantthresh__44c9_s_p9_1,
  135870. _vq_quantmap__44c9_s_p9_1,
  135871. 19,
  135872. 19
  135873. };
  135874. static static_codebook _44c9_s_p9_1 = {
  135875. 2, 361,
  135876. _vq_lengthlist__44c9_s_p9_1,
  135877. 1, -518287360, 1622704128, 5, 0,
  135878. _vq_quantlist__44c9_s_p9_1,
  135879. NULL,
  135880. &_vq_auxt__44c9_s_p9_1,
  135881. NULL,
  135882. 0
  135883. };
  135884. static long _vq_quantlist__44c9_s_p9_2[] = {
  135885. 24,
  135886. 23,
  135887. 25,
  135888. 22,
  135889. 26,
  135890. 21,
  135891. 27,
  135892. 20,
  135893. 28,
  135894. 19,
  135895. 29,
  135896. 18,
  135897. 30,
  135898. 17,
  135899. 31,
  135900. 16,
  135901. 32,
  135902. 15,
  135903. 33,
  135904. 14,
  135905. 34,
  135906. 13,
  135907. 35,
  135908. 12,
  135909. 36,
  135910. 11,
  135911. 37,
  135912. 10,
  135913. 38,
  135914. 9,
  135915. 39,
  135916. 8,
  135917. 40,
  135918. 7,
  135919. 41,
  135920. 6,
  135921. 42,
  135922. 5,
  135923. 43,
  135924. 4,
  135925. 44,
  135926. 3,
  135927. 45,
  135928. 2,
  135929. 46,
  135930. 1,
  135931. 47,
  135932. 0,
  135933. 48,
  135934. };
  135935. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135936. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135937. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135938. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135939. 7,
  135940. };
  135941. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135942. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135943. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135944. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135945. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135946. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135947. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135948. };
  135949. static long _vq_quantmap__44c9_s_p9_2[] = {
  135950. 47, 45, 43, 41, 39, 37, 35, 33,
  135951. 31, 29, 27, 25, 23, 21, 19, 17,
  135952. 15, 13, 11, 9, 7, 5, 3, 1,
  135953. 0, 2, 4, 6, 8, 10, 12, 14,
  135954. 16, 18, 20, 22, 24, 26, 28, 30,
  135955. 32, 34, 36, 38, 40, 42, 44, 46,
  135956. 48,
  135957. };
  135958. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135959. _vq_quantthresh__44c9_s_p9_2,
  135960. _vq_quantmap__44c9_s_p9_2,
  135961. 49,
  135962. 49
  135963. };
  135964. static static_codebook _44c9_s_p9_2 = {
  135965. 1, 49,
  135966. _vq_lengthlist__44c9_s_p9_2,
  135967. 1, -526909440, 1611661312, 6, 0,
  135968. _vq_quantlist__44c9_s_p9_2,
  135969. NULL,
  135970. &_vq_auxt__44c9_s_p9_2,
  135971. NULL,
  135972. 0
  135973. };
  135974. static long _huff_lengthlist__44c9_s_short[] = {
  135975. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135976. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135977. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135978. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135979. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135980. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135981. 9, 8,10,13,
  135982. };
  135983. static static_codebook _huff_book__44c9_s_short = {
  135984. 2, 100,
  135985. _huff_lengthlist__44c9_s_short,
  135986. 0, 0, 0, 0, 0,
  135987. NULL,
  135988. NULL,
  135989. NULL,
  135990. NULL,
  135991. 0
  135992. };
  135993. static long _huff_lengthlist__44c0_s_long[] = {
  135994. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135995. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135996. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135997. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135998. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135999. 12,
  136000. };
  136001. static static_codebook _huff_book__44c0_s_long = {
  136002. 2, 81,
  136003. _huff_lengthlist__44c0_s_long,
  136004. 0, 0, 0, 0, 0,
  136005. NULL,
  136006. NULL,
  136007. NULL,
  136008. NULL,
  136009. 0
  136010. };
  136011. static long _vq_quantlist__44c0_s_p1_0[] = {
  136012. 1,
  136013. 0,
  136014. 2,
  136015. };
  136016. static long _vq_lengthlist__44c0_s_p1_0[] = {
  136017. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136018. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136023. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136028. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136063. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136068. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136073. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136109. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136114. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  136119. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0,
  136428. };
  136429. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136430. -0.5, 0.5,
  136431. };
  136432. static long _vq_quantmap__44c0_s_p1_0[] = {
  136433. 1, 0, 2,
  136434. };
  136435. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136436. _vq_quantthresh__44c0_s_p1_0,
  136437. _vq_quantmap__44c0_s_p1_0,
  136438. 3,
  136439. 3
  136440. };
  136441. static static_codebook _44c0_s_p1_0 = {
  136442. 8, 6561,
  136443. _vq_lengthlist__44c0_s_p1_0,
  136444. 1, -535822336, 1611661312, 2, 0,
  136445. _vq_quantlist__44c0_s_p1_0,
  136446. NULL,
  136447. &_vq_auxt__44c0_s_p1_0,
  136448. NULL,
  136449. 0
  136450. };
  136451. static long _vq_quantlist__44c0_s_p2_0[] = {
  136452. 2,
  136453. 1,
  136454. 3,
  136455. 0,
  136456. 4,
  136457. };
  136458. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136459. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136462. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136465. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0,
  136499. };
  136500. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136501. -1.5, -0.5, 0.5, 1.5,
  136502. };
  136503. static long _vq_quantmap__44c0_s_p2_0[] = {
  136504. 3, 1, 0, 2, 4,
  136505. };
  136506. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136507. _vq_quantthresh__44c0_s_p2_0,
  136508. _vq_quantmap__44c0_s_p2_0,
  136509. 5,
  136510. 5
  136511. };
  136512. static static_codebook _44c0_s_p2_0 = {
  136513. 4, 625,
  136514. _vq_lengthlist__44c0_s_p2_0,
  136515. 1, -533725184, 1611661312, 3, 0,
  136516. _vq_quantlist__44c0_s_p2_0,
  136517. NULL,
  136518. &_vq_auxt__44c0_s_p2_0,
  136519. NULL,
  136520. 0
  136521. };
  136522. static long _vq_quantlist__44c0_s_p3_0[] = {
  136523. 4,
  136524. 3,
  136525. 5,
  136526. 2,
  136527. 6,
  136528. 1,
  136529. 7,
  136530. 0,
  136531. 8,
  136532. };
  136533. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136534. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136535. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136536. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136537. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136538. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136539. 0,
  136540. };
  136541. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136542. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136543. };
  136544. static long _vq_quantmap__44c0_s_p3_0[] = {
  136545. 7, 5, 3, 1, 0, 2, 4, 6,
  136546. 8,
  136547. };
  136548. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136549. _vq_quantthresh__44c0_s_p3_0,
  136550. _vq_quantmap__44c0_s_p3_0,
  136551. 9,
  136552. 9
  136553. };
  136554. static static_codebook _44c0_s_p3_0 = {
  136555. 2, 81,
  136556. _vq_lengthlist__44c0_s_p3_0,
  136557. 1, -531628032, 1611661312, 4, 0,
  136558. _vq_quantlist__44c0_s_p3_0,
  136559. NULL,
  136560. &_vq_auxt__44c0_s_p3_0,
  136561. NULL,
  136562. 0
  136563. };
  136564. static long _vq_quantlist__44c0_s_p4_0[] = {
  136565. 4,
  136566. 3,
  136567. 5,
  136568. 2,
  136569. 6,
  136570. 1,
  136571. 7,
  136572. 0,
  136573. 8,
  136574. };
  136575. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136576. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136577. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136578. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136579. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136580. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136581. 10,
  136582. };
  136583. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136584. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136585. };
  136586. static long _vq_quantmap__44c0_s_p4_0[] = {
  136587. 7, 5, 3, 1, 0, 2, 4, 6,
  136588. 8,
  136589. };
  136590. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136591. _vq_quantthresh__44c0_s_p4_0,
  136592. _vq_quantmap__44c0_s_p4_0,
  136593. 9,
  136594. 9
  136595. };
  136596. static static_codebook _44c0_s_p4_0 = {
  136597. 2, 81,
  136598. _vq_lengthlist__44c0_s_p4_0,
  136599. 1, -531628032, 1611661312, 4, 0,
  136600. _vq_quantlist__44c0_s_p4_0,
  136601. NULL,
  136602. &_vq_auxt__44c0_s_p4_0,
  136603. NULL,
  136604. 0
  136605. };
  136606. static long _vq_quantlist__44c0_s_p5_0[] = {
  136607. 8,
  136608. 7,
  136609. 9,
  136610. 6,
  136611. 10,
  136612. 5,
  136613. 11,
  136614. 4,
  136615. 12,
  136616. 3,
  136617. 13,
  136618. 2,
  136619. 14,
  136620. 1,
  136621. 15,
  136622. 0,
  136623. 16,
  136624. };
  136625. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136626. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136627. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136628. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136629. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136630. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136631. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136632. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136633. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136634. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136635. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136636. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136637. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136638. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136639. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136640. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136641. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136642. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136643. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136644. 14,
  136645. };
  136646. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136647. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136648. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136649. };
  136650. static long _vq_quantmap__44c0_s_p5_0[] = {
  136651. 15, 13, 11, 9, 7, 5, 3, 1,
  136652. 0, 2, 4, 6, 8, 10, 12, 14,
  136653. 16,
  136654. };
  136655. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136656. _vq_quantthresh__44c0_s_p5_0,
  136657. _vq_quantmap__44c0_s_p5_0,
  136658. 17,
  136659. 17
  136660. };
  136661. static static_codebook _44c0_s_p5_0 = {
  136662. 2, 289,
  136663. _vq_lengthlist__44c0_s_p5_0,
  136664. 1, -529530880, 1611661312, 5, 0,
  136665. _vq_quantlist__44c0_s_p5_0,
  136666. NULL,
  136667. &_vq_auxt__44c0_s_p5_0,
  136668. NULL,
  136669. 0
  136670. };
  136671. static long _vq_quantlist__44c0_s_p6_0[] = {
  136672. 1,
  136673. 0,
  136674. 2,
  136675. };
  136676. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136677. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136678. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136679. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136680. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136681. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136682. 10,
  136683. };
  136684. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136685. -5.5, 5.5,
  136686. };
  136687. static long _vq_quantmap__44c0_s_p6_0[] = {
  136688. 1, 0, 2,
  136689. };
  136690. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136691. _vq_quantthresh__44c0_s_p6_0,
  136692. _vq_quantmap__44c0_s_p6_0,
  136693. 3,
  136694. 3
  136695. };
  136696. static static_codebook _44c0_s_p6_0 = {
  136697. 4, 81,
  136698. _vq_lengthlist__44c0_s_p6_0,
  136699. 1, -529137664, 1618345984, 2, 0,
  136700. _vq_quantlist__44c0_s_p6_0,
  136701. NULL,
  136702. &_vq_auxt__44c0_s_p6_0,
  136703. NULL,
  136704. 0
  136705. };
  136706. static long _vq_quantlist__44c0_s_p6_1[] = {
  136707. 5,
  136708. 4,
  136709. 6,
  136710. 3,
  136711. 7,
  136712. 2,
  136713. 8,
  136714. 1,
  136715. 9,
  136716. 0,
  136717. 10,
  136718. };
  136719. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136720. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136721. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136722. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136723. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136724. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136725. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136726. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136727. 10,10,10, 8, 8, 8, 8, 8, 8,
  136728. };
  136729. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136730. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136731. 3.5, 4.5,
  136732. };
  136733. static long _vq_quantmap__44c0_s_p6_1[] = {
  136734. 9, 7, 5, 3, 1, 0, 2, 4,
  136735. 6, 8, 10,
  136736. };
  136737. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136738. _vq_quantthresh__44c0_s_p6_1,
  136739. _vq_quantmap__44c0_s_p6_1,
  136740. 11,
  136741. 11
  136742. };
  136743. static static_codebook _44c0_s_p6_1 = {
  136744. 2, 121,
  136745. _vq_lengthlist__44c0_s_p6_1,
  136746. 1, -531365888, 1611661312, 4, 0,
  136747. _vq_quantlist__44c0_s_p6_1,
  136748. NULL,
  136749. &_vq_auxt__44c0_s_p6_1,
  136750. NULL,
  136751. 0
  136752. };
  136753. static long _vq_quantlist__44c0_s_p7_0[] = {
  136754. 6,
  136755. 5,
  136756. 7,
  136757. 4,
  136758. 8,
  136759. 3,
  136760. 9,
  136761. 2,
  136762. 10,
  136763. 1,
  136764. 11,
  136765. 0,
  136766. 12,
  136767. };
  136768. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136769. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136770. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136771. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136772. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136773. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136774. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136775. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136776. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136777. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136778. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136779. 0,12,12,11,11,12,12,13,13,
  136780. };
  136781. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136782. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136783. 12.5, 17.5, 22.5, 27.5,
  136784. };
  136785. static long _vq_quantmap__44c0_s_p7_0[] = {
  136786. 11, 9, 7, 5, 3, 1, 0, 2,
  136787. 4, 6, 8, 10, 12,
  136788. };
  136789. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136790. _vq_quantthresh__44c0_s_p7_0,
  136791. _vq_quantmap__44c0_s_p7_0,
  136792. 13,
  136793. 13
  136794. };
  136795. static static_codebook _44c0_s_p7_0 = {
  136796. 2, 169,
  136797. _vq_lengthlist__44c0_s_p7_0,
  136798. 1, -526516224, 1616117760, 4, 0,
  136799. _vq_quantlist__44c0_s_p7_0,
  136800. NULL,
  136801. &_vq_auxt__44c0_s_p7_0,
  136802. NULL,
  136803. 0
  136804. };
  136805. static long _vq_quantlist__44c0_s_p7_1[] = {
  136806. 2,
  136807. 1,
  136808. 3,
  136809. 0,
  136810. 4,
  136811. };
  136812. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136813. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136814. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136815. };
  136816. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136817. -1.5, -0.5, 0.5, 1.5,
  136818. };
  136819. static long _vq_quantmap__44c0_s_p7_1[] = {
  136820. 3, 1, 0, 2, 4,
  136821. };
  136822. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136823. _vq_quantthresh__44c0_s_p7_1,
  136824. _vq_quantmap__44c0_s_p7_1,
  136825. 5,
  136826. 5
  136827. };
  136828. static static_codebook _44c0_s_p7_1 = {
  136829. 2, 25,
  136830. _vq_lengthlist__44c0_s_p7_1,
  136831. 1, -533725184, 1611661312, 3, 0,
  136832. _vq_quantlist__44c0_s_p7_1,
  136833. NULL,
  136834. &_vq_auxt__44c0_s_p7_1,
  136835. NULL,
  136836. 0
  136837. };
  136838. static long _vq_quantlist__44c0_s_p8_0[] = {
  136839. 2,
  136840. 1,
  136841. 3,
  136842. 0,
  136843. 4,
  136844. };
  136845. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136846. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136847. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136848. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136849. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136850. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136851. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136852. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136853. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136854. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136855. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136857. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136858. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136860. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136861. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136867. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136874. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136875. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136876. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136877. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136878. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136880. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136881. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136882. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136883. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136884. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136885. 11,
  136886. };
  136887. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136888. -331.5, -110.5, 110.5, 331.5,
  136889. };
  136890. static long _vq_quantmap__44c0_s_p8_0[] = {
  136891. 3, 1, 0, 2, 4,
  136892. };
  136893. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136894. _vq_quantthresh__44c0_s_p8_0,
  136895. _vq_quantmap__44c0_s_p8_0,
  136896. 5,
  136897. 5
  136898. };
  136899. static static_codebook _44c0_s_p8_0 = {
  136900. 4, 625,
  136901. _vq_lengthlist__44c0_s_p8_0,
  136902. 1, -518283264, 1627103232, 3, 0,
  136903. _vq_quantlist__44c0_s_p8_0,
  136904. NULL,
  136905. &_vq_auxt__44c0_s_p8_0,
  136906. NULL,
  136907. 0
  136908. };
  136909. static long _vq_quantlist__44c0_s_p8_1[] = {
  136910. 6,
  136911. 5,
  136912. 7,
  136913. 4,
  136914. 8,
  136915. 3,
  136916. 9,
  136917. 2,
  136918. 10,
  136919. 1,
  136920. 11,
  136921. 0,
  136922. 12,
  136923. };
  136924. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136925. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136926. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136927. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136928. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136929. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136930. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136931. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136932. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136933. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136934. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136935. 16,13,13,12,12,14,14,15,13,
  136936. };
  136937. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136938. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136939. 42.5, 59.5, 76.5, 93.5,
  136940. };
  136941. static long _vq_quantmap__44c0_s_p8_1[] = {
  136942. 11, 9, 7, 5, 3, 1, 0, 2,
  136943. 4, 6, 8, 10, 12,
  136944. };
  136945. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136946. _vq_quantthresh__44c0_s_p8_1,
  136947. _vq_quantmap__44c0_s_p8_1,
  136948. 13,
  136949. 13
  136950. };
  136951. static static_codebook _44c0_s_p8_1 = {
  136952. 2, 169,
  136953. _vq_lengthlist__44c0_s_p8_1,
  136954. 1, -522616832, 1620115456, 4, 0,
  136955. _vq_quantlist__44c0_s_p8_1,
  136956. NULL,
  136957. &_vq_auxt__44c0_s_p8_1,
  136958. NULL,
  136959. 0
  136960. };
  136961. static long _vq_quantlist__44c0_s_p8_2[] = {
  136962. 8,
  136963. 7,
  136964. 9,
  136965. 6,
  136966. 10,
  136967. 5,
  136968. 11,
  136969. 4,
  136970. 12,
  136971. 3,
  136972. 13,
  136973. 2,
  136974. 14,
  136975. 1,
  136976. 15,
  136977. 0,
  136978. 16,
  136979. };
  136980. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136981. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136982. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136983. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136984. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136985. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136986. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136987. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136988. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136989. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136990. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136991. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136992. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136993. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136994. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136995. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136996. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136997. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136998. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136999. 10,
  137000. };
  137001. static float _vq_quantthresh__44c0_s_p8_2[] = {
  137002. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137003. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137004. };
  137005. static long _vq_quantmap__44c0_s_p8_2[] = {
  137006. 15, 13, 11, 9, 7, 5, 3, 1,
  137007. 0, 2, 4, 6, 8, 10, 12, 14,
  137008. 16,
  137009. };
  137010. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  137011. _vq_quantthresh__44c0_s_p8_2,
  137012. _vq_quantmap__44c0_s_p8_2,
  137013. 17,
  137014. 17
  137015. };
  137016. static static_codebook _44c0_s_p8_2 = {
  137017. 2, 289,
  137018. _vq_lengthlist__44c0_s_p8_2,
  137019. 1, -529530880, 1611661312, 5, 0,
  137020. _vq_quantlist__44c0_s_p8_2,
  137021. NULL,
  137022. &_vq_auxt__44c0_s_p8_2,
  137023. NULL,
  137024. 0
  137025. };
  137026. static long _huff_lengthlist__44c0_s_short[] = {
  137027. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  137028. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  137029. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  137030. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  137031. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  137032. 12,
  137033. };
  137034. static static_codebook _huff_book__44c0_s_short = {
  137035. 2, 81,
  137036. _huff_lengthlist__44c0_s_short,
  137037. 0, 0, 0, 0, 0,
  137038. NULL,
  137039. NULL,
  137040. NULL,
  137041. NULL,
  137042. 0
  137043. };
  137044. static long _huff_lengthlist__44c0_sm_long[] = {
  137045. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  137046. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  137047. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  137048. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  137049. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  137050. 13,
  137051. };
  137052. static static_codebook _huff_book__44c0_sm_long = {
  137053. 2, 81,
  137054. _huff_lengthlist__44c0_sm_long,
  137055. 0, 0, 0, 0, 0,
  137056. NULL,
  137057. NULL,
  137058. NULL,
  137059. NULL,
  137060. 0
  137061. };
  137062. static long _vq_quantlist__44c0_sm_p1_0[] = {
  137063. 1,
  137064. 0,
  137065. 2,
  137066. };
  137067. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  137068. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137069. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137074. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137079. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  137114. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137119. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137124. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137160. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137165. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137170. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0,
  137479. };
  137480. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137481. -0.5, 0.5,
  137482. };
  137483. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137484. 1, 0, 2,
  137485. };
  137486. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137487. _vq_quantthresh__44c0_sm_p1_0,
  137488. _vq_quantmap__44c0_sm_p1_0,
  137489. 3,
  137490. 3
  137491. };
  137492. static static_codebook _44c0_sm_p1_0 = {
  137493. 8, 6561,
  137494. _vq_lengthlist__44c0_sm_p1_0,
  137495. 1, -535822336, 1611661312, 2, 0,
  137496. _vq_quantlist__44c0_sm_p1_0,
  137497. NULL,
  137498. &_vq_auxt__44c0_sm_p1_0,
  137499. NULL,
  137500. 0
  137501. };
  137502. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137503. 2,
  137504. 1,
  137505. 3,
  137506. 0,
  137507. 4,
  137508. };
  137509. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137510. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137513. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137516. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0,
  137550. };
  137551. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137552. -1.5, -0.5, 0.5, 1.5,
  137553. };
  137554. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137555. 3, 1, 0, 2, 4,
  137556. };
  137557. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137558. _vq_quantthresh__44c0_sm_p2_0,
  137559. _vq_quantmap__44c0_sm_p2_0,
  137560. 5,
  137561. 5
  137562. };
  137563. static static_codebook _44c0_sm_p2_0 = {
  137564. 4, 625,
  137565. _vq_lengthlist__44c0_sm_p2_0,
  137566. 1, -533725184, 1611661312, 3, 0,
  137567. _vq_quantlist__44c0_sm_p2_0,
  137568. NULL,
  137569. &_vq_auxt__44c0_sm_p2_0,
  137570. NULL,
  137571. 0
  137572. };
  137573. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137574. 4,
  137575. 3,
  137576. 5,
  137577. 2,
  137578. 6,
  137579. 1,
  137580. 7,
  137581. 0,
  137582. 8,
  137583. };
  137584. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137585. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137586. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137587. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137588. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137589. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0,
  137591. };
  137592. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137593. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137594. };
  137595. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137596. 7, 5, 3, 1, 0, 2, 4, 6,
  137597. 8,
  137598. };
  137599. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137600. _vq_quantthresh__44c0_sm_p3_0,
  137601. _vq_quantmap__44c0_sm_p3_0,
  137602. 9,
  137603. 9
  137604. };
  137605. static static_codebook _44c0_sm_p3_0 = {
  137606. 2, 81,
  137607. _vq_lengthlist__44c0_sm_p3_0,
  137608. 1, -531628032, 1611661312, 4, 0,
  137609. _vq_quantlist__44c0_sm_p3_0,
  137610. NULL,
  137611. &_vq_auxt__44c0_sm_p3_0,
  137612. NULL,
  137613. 0
  137614. };
  137615. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137616. 4,
  137617. 3,
  137618. 5,
  137619. 2,
  137620. 6,
  137621. 1,
  137622. 7,
  137623. 0,
  137624. 8,
  137625. };
  137626. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137627. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137628. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137629. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137630. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137631. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137632. 11,
  137633. };
  137634. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137635. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137636. };
  137637. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137638. 7, 5, 3, 1, 0, 2, 4, 6,
  137639. 8,
  137640. };
  137641. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137642. _vq_quantthresh__44c0_sm_p4_0,
  137643. _vq_quantmap__44c0_sm_p4_0,
  137644. 9,
  137645. 9
  137646. };
  137647. static static_codebook _44c0_sm_p4_0 = {
  137648. 2, 81,
  137649. _vq_lengthlist__44c0_sm_p4_0,
  137650. 1, -531628032, 1611661312, 4, 0,
  137651. _vq_quantlist__44c0_sm_p4_0,
  137652. NULL,
  137653. &_vq_auxt__44c0_sm_p4_0,
  137654. NULL,
  137655. 0
  137656. };
  137657. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137658. 8,
  137659. 7,
  137660. 9,
  137661. 6,
  137662. 10,
  137663. 5,
  137664. 11,
  137665. 4,
  137666. 12,
  137667. 3,
  137668. 13,
  137669. 2,
  137670. 14,
  137671. 1,
  137672. 15,
  137673. 0,
  137674. 16,
  137675. };
  137676. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137677. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137678. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137679. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137680. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137681. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137682. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137683. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137684. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137685. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137686. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137687. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137688. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137689. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137690. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137691. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137692. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137693. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137694. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137695. 14,
  137696. };
  137697. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137698. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137699. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137700. };
  137701. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137702. 15, 13, 11, 9, 7, 5, 3, 1,
  137703. 0, 2, 4, 6, 8, 10, 12, 14,
  137704. 16,
  137705. };
  137706. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137707. _vq_quantthresh__44c0_sm_p5_0,
  137708. _vq_quantmap__44c0_sm_p5_0,
  137709. 17,
  137710. 17
  137711. };
  137712. static static_codebook _44c0_sm_p5_0 = {
  137713. 2, 289,
  137714. _vq_lengthlist__44c0_sm_p5_0,
  137715. 1, -529530880, 1611661312, 5, 0,
  137716. _vq_quantlist__44c0_sm_p5_0,
  137717. NULL,
  137718. &_vq_auxt__44c0_sm_p5_0,
  137719. NULL,
  137720. 0
  137721. };
  137722. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137723. 1,
  137724. 0,
  137725. 2,
  137726. };
  137727. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137728. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137729. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137730. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137731. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137732. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137733. 11,
  137734. };
  137735. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137736. -5.5, 5.5,
  137737. };
  137738. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137739. 1, 0, 2,
  137740. };
  137741. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137742. _vq_quantthresh__44c0_sm_p6_0,
  137743. _vq_quantmap__44c0_sm_p6_0,
  137744. 3,
  137745. 3
  137746. };
  137747. static static_codebook _44c0_sm_p6_0 = {
  137748. 4, 81,
  137749. _vq_lengthlist__44c0_sm_p6_0,
  137750. 1, -529137664, 1618345984, 2, 0,
  137751. _vq_quantlist__44c0_sm_p6_0,
  137752. NULL,
  137753. &_vq_auxt__44c0_sm_p6_0,
  137754. NULL,
  137755. 0
  137756. };
  137757. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137758. 5,
  137759. 4,
  137760. 6,
  137761. 3,
  137762. 7,
  137763. 2,
  137764. 8,
  137765. 1,
  137766. 9,
  137767. 0,
  137768. 10,
  137769. };
  137770. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137771. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137772. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137773. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137774. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137775. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137776. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137777. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137778. 10,10,10, 8, 8, 8, 8, 8, 8,
  137779. };
  137780. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137781. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137782. 3.5, 4.5,
  137783. };
  137784. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137785. 9, 7, 5, 3, 1, 0, 2, 4,
  137786. 6, 8, 10,
  137787. };
  137788. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137789. _vq_quantthresh__44c0_sm_p6_1,
  137790. _vq_quantmap__44c0_sm_p6_1,
  137791. 11,
  137792. 11
  137793. };
  137794. static static_codebook _44c0_sm_p6_1 = {
  137795. 2, 121,
  137796. _vq_lengthlist__44c0_sm_p6_1,
  137797. 1, -531365888, 1611661312, 4, 0,
  137798. _vq_quantlist__44c0_sm_p6_1,
  137799. NULL,
  137800. &_vq_auxt__44c0_sm_p6_1,
  137801. NULL,
  137802. 0
  137803. };
  137804. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137805. 6,
  137806. 5,
  137807. 7,
  137808. 4,
  137809. 8,
  137810. 3,
  137811. 9,
  137812. 2,
  137813. 10,
  137814. 1,
  137815. 11,
  137816. 0,
  137817. 12,
  137818. };
  137819. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137820. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137821. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137822. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137823. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137824. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137825. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137826. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137827. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137828. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137829. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137830. 0,12,12,11,11,13,12,14,14,
  137831. };
  137832. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137833. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137834. 12.5, 17.5, 22.5, 27.5,
  137835. };
  137836. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137837. 11, 9, 7, 5, 3, 1, 0, 2,
  137838. 4, 6, 8, 10, 12,
  137839. };
  137840. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137841. _vq_quantthresh__44c0_sm_p7_0,
  137842. _vq_quantmap__44c0_sm_p7_0,
  137843. 13,
  137844. 13
  137845. };
  137846. static static_codebook _44c0_sm_p7_0 = {
  137847. 2, 169,
  137848. _vq_lengthlist__44c0_sm_p7_0,
  137849. 1, -526516224, 1616117760, 4, 0,
  137850. _vq_quantlist__44c0_sm_p7_0,
  137851. NULL,
  137852. &_vq_auxt__44c0_sm_p7_0,
  137853. NULL,
  137854. 0
  137855. };
  137856. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137857. 2,
  137858. 1,
  137859. 3,
  137860. 0,
  137861. 4,
  137862. };
  137863. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137864. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137865. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137866. };
  137867. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137868. -1.5, -0.5, 0.5, 1.5,
  137869. };
  137870. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137871. 3, 1, 0, 2, 4,
  137872. };
  137873. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137874. _vq_quantthresh__44c0_sm_p7_1,
  137875. _vq_quantmap__44c0_sm_p7_1,
  137876. 5,
  137877. 5
  137878. };
  137879. static static_codebook _44c0_sm_p7_1 = {
  137880. 2, 25,
  137881. _vq_lengthlist__44c0_sm_p7_1,
  137882. 1, -533725184, 1611661312, 3, 0,
  137883. _vq_quantlist__44c0_sm_p7_1,
  137884. NULL,
  137885. &_vq_auxt__44c0_sm_p7_1,
  137886. NULL,
  137887. 0
  137888. };
  137889. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137890. 4,
  137891. 3,
  137892. 5,
  137893. 2,
  137894. 6,
  137895. 1,
  137896. 7,
  137897. 0,
  137898. 8,
  137899. };
  137900. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137901. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137902. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137903. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137904. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137905. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137906. 12,
  137907. };
  137908. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137909. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137910. };
  137911. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137912. 7, 5, 3, 1, 0, 2, 4, 6,
  137913. 8,
  137914. };
  137915. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137916. _vq_quantthresh__44c0_sm_p8_0,
  137917. _vq_quantmap__44c0_sm_p8_0,
  137918. 9,
  137919. 9
  137920. };
  137921. static static_codebook _44c0_sm_p8_0 = {
  137922. 2, 81,
  137923. _vq_lengthlist__44c0_sm_p8_0,
  137924. 1, -516186112, 1627103232, 4, 0,
  137925. _vq_quantlist__44c0_sm_p8_0,
  137926. NULL,
  137927. &_vq_auxt__44c0_sm_p8_0,
  137928. NULL,
  137929. 0
  137930. };
  137931. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137932. 6,
  137933. 5,
  137934. 7,
  137935. 4,
  137936. 8,
  137937. 3,
  137938. 9,
  137939. 2,
  137940. 10,
  137941. 1,
  137942. 11,
  137943. 0,
  137944. 12,
  137945. };
  137946. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137947. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137948. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137949. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137950. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137951. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137952. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137953. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137954. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137955. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137956. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137957. 20,13,13,12,12,16,13,15,13,
  137958. };
  137959. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137960. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137961. 42.5, 59.5, 76.5, 93.5,
  137962. };
  137963. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137964. 11, 9, 7, 5, 3, 1, 0, 2,
  137965. 4, 6, 8, 10, 12,
  137966. };
  137967. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137968. _vq_quantthresh__44c0_sm_p8_1,
  137969. _vq_quantmap__44c0_sm_p8_1,
  137970. 13,
  137971. 13
  137972. };
  137973. static static_codebook _44c0_sm_p8_1 = {
  137974. 2, 169,
  137975. _vq_lengthlist__44c0_sm_p8_1,
  137976. 1, -522616832, 1620115456, 4, 0,
  137977. _vq_quantlist__44c0_sm_p8_1,
  137978. NULL,
  137979. &_vq_auxt__44c0_sm_p8_1,
  137980. NULL,
  137981. 0
  137982. };
  137983. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137984. 8,
  137985. 7,
  137986. 9,
  137987. 6,
  137988. 10,
  137989. 5,
  137990. 11,
  137991. 4,
  137992. 12,
  137993. 3,
  137994. 13,
  137995. 2,
  137996. 14,
  137997. 1,
  137998. 15,
  137999. 0,
  138000. 16,
  138001. };
  138002. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  138003. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138004. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138005. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138006. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138007. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138008. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138009. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138010. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138011. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  138012. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  138013. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  138014. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  138015. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  138016. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  138017. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138018. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138019. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138020. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138021. 9,
  138022. };
  138023. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  138024. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138025. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138026. };
  138027. static long _vq_quantmap__44c0_sm_p8_2[] = {
  138028. 15, 13, 11, 9, 7, 5, 3, 1,
  138029. 0, 2, 4, 6, 8, 10, 12, 14,
  138030. 16,
  138031. };
  138032. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  138033. _vq_quantthresh__44c0_sm_p8_2,
  138034. _vq_quantmap__44c0_sm_p8_2,
  138035. 17,
  138036. 17
  138037. };
  138038. static static_codebook _44c0_sm_p8_2 = {
  138039. 2, 289,
  138040. _vq_lengthlist__44c0_sm_p8_2,
  138041. 1, -529530880, 1611661312, 5, 0,
  138042. _vq_quantlist__44c0_sm_p8_2,
  138043. NULL,
  138044. &_vq_auxt__44c0_sm_p8_2,
  138045. NULL,
  138046. 0
  138047. };
  138048. static long _huff_lengthlist__44c0_sm_short[] = {
  138049. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  138050. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  138051. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  138052. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  138053. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  138054. 12,
  138055. };
  138056. static static_codebook _huff_book__44c0_sm_short = {
  138057. 2, 81,
  138058. _huff_lengthlist__44c0_sm_short,
  138059. 0, 0, 0, 0, 0,
  138060. NULL,
  138061. NULL,
  138062. NULL,
  138063. NULL,
  138064. 0
  138065. };
  138066. static long _huff_lengthlist__44c1_s_long[] = {
  138067. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  138068. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  138069. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  138070. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  138071. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  138072. 11,
  138073. };
  138074. static static_codebook _huff_book__44c1_s_long = {
  138075. 2, 81,
  138076. _huff_lengthlist__44c1_s_long,
  138077. 0, 0, 0, 0, 0,
  138078. NULL,
  138079. NULL,
  138080. NULL,
  138081. NULL,
  138082. 0
  138083. };
  138084. static long _vq_quantlist__44c1_s_p1_0[] = {
  138085. 1,
  138086. 0,
  138087. 2,
  138088. };
  138089. static long _vq_lengthlist__44c1_s_p1_0[] = {
  138090. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  138091. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138096. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138101. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  138136. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138141. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  138146. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138182. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138187. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138192. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0,
  138501. };
  138502. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138503. -0.5, 0.5,
  138504. };
  138505. static long _vq_quantmap__44c1_s_p1_0[] = {
  138506. 1, 0, 2,
  138507. };
  138508. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138509. _vq_quantthresh__44c1_s_p1_0,
  138510. _vq_quantmap__44c1_s_p1_0,
  138511. 3,
  138512. 3
  138513. };
  138514. static static_codebook _44c1_s_p1_0 = {
  138515. 8, 6561,
  138516. _vq_lengthlist__44c1_s_p1_0,
  138517. 1, -535822336, 1611661312, 2, 0,
  138518. _vq_quantlist__44c1_s_p1_0,
  138519. NULL,
  138520. &_vq_auxt__44c1_s_p1_0,
  138521. NULL,
  138522. 0
  138523. };
  138524. static long _vq_quantlist__44c1_s_p2_0[] = {
  138525. 2,
  138526. 1,
  138527. 3,
  138528. 0,
  138529. 4,
  138530. };
  138531. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138532. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138535. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138538. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0,
  138572. };
  138573. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138574. -1.5, -0.5, 0.5, 1.5,
  138575. };
  138576. static long _vq_quantmap__44c1_s_p2_0[] = {
  138577. 3, 1, 0, 2, 4,
  138578. };
  138579. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138580. _vq_quantthresh__44c1_s_p2_0,
  138581. _vq_quantmap__44c1_s_p2_0,
  138582. 5,
  138583. 5
  138584. };
  138585. static static_codebook _44c1_s_p2_0 = {
  138586. 4, 625,
  138587. _vq_lengthlist__44c1_s_p2_0,
  138588. 1, -533725184, 1611661312, 3, 0,
  138589. _vq_quantlist__44c1_s_p2_0,
  138590. NULL,
  138591. &_vq_auxt__44c1_s_p2_0,
  138592. NULL,
  138593. 0
  138594. };
  138595. static long _vq_quantlist__44c1_s_p3_0[] = {
  138596. 4,
  138597. 3,
  138598. 5,
  138599. 2,
  138600. 6,
  138601. 1,
  138602. 7,
  138603. 0,
  138604. 8,
  138605. };
  138606. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138607. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138608. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138609. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138610. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138611. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138612. 0,
  138613. };
  138614. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138615. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138616. };
  138617. static long _vq_quantmap__44c1_s_p3_0[] = {
  138618. 7, 5, 3, 1, 0, 2, 4, 6,
  138619. 8,
  138620. };
  138621. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138622. _vq_quantthresh__44c1_s_p3_0,
  138623. _vq_quantmap__44c1_s_p3_0,
  138624. 9,
  138625. 9
  138626. };
  138627. static static_codebook _44c1_s_p3_0 = {
  138628. 2, 81,
  138629. _vq_lengthlist__44c1_s_p3_0,
  138630. 1, -531628032, 1611661312, 4, 0,
  138631. _vq_quantlist__44c1_s_p3_0,
  138632. NULL,
  138633. &_vq_auxt__44c1_s_p3_0,
  138634. NULL,
  138635. 0
  138636. };
  138637. static long _vq_quantlist__44c1_s_p4_0[] = {
  138638. 4,
  138639. 3,
  138640. 5,
  138641. 2,
  138642. 6,
  138643. 1,
  138644. 7,
  138645. 0,
  138646. 8,
  138647. };
  138648. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138649. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138650. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138651. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138652. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138653. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138654. 11,
  138655. };
  138656. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138657. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138658. };
  138659. static long _vq_quantmap__44c1_s_p4_0[] = {
  138660. 7, 5, 3, 1, 0, 2, 4, 6,
  138661. 8,
  138662. };
  138663. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138664. _vq_quantthresh__44c1_s_p4_0,
  138665. _vq_quantmap__44c1_s_p4_0,
  138666. 9,
  138667. 9
  138668. };
  138669. static static_codebook _44c1_s_p4_0 = {
  138670. 2, 81,
  138671. _vq_lengthlist__44c1_s_p4_0,
  138672. 1, -531628032, 1611661312, 4, 0,
  138673. _vq_quantlist__44c1_s_p4_0,
  138674. NULL,
  138675. &_vq_auxt__44c1_s_p4_0,
  138676. NULL,
  138677. 0
  138678. };
  138679. static long _vq_quantlist__44c1_s_p5_0[] = {
  138680. 8,
  138681. 7,
  138682. 9,
  138683. 6,
  138684. 10,
  138685. 5,
  138686. 11,
  138687. 4,
  138688. 12,
  138689. 3,
  138690. 13,
  138691. 2,
  138692. 14,
  138693. 1,
  138694. 15,
  138695. 0,
  138696. 16,
  138697. };
  138698. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138699. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138700. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138701. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138702. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138703. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138704. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138705. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138706. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138707. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138708. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138709. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138710. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138711. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138712. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138713. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138714. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138715. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138716. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138717. 14,
  138718. };
  138719. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138720. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138721. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138722. };
  138723. static long _vq_quantmap__44c1_s_p5_0[] = {
  138724. 15, 13, 11, 9, 7, 5, 3, 1,
  138725. 0, 2, 4, 6, 8, 10, 12, 14,
  138726. 16,
  138727. };
  138728. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138729. _vq_quantthresh__44c1_s_p5_0,
  138730. _vq_quantmap__44c1_s_p5_0,
  138731. 17,
  138732. 17
  138733. };
  138734. static static_codebook _44c1_s_p5_0 = {
  138735. 2, 289,
  138736. _vq_lengthlist__44c1_s_p5_0,
  138737. 1, -529530880, 1611661312, 5, 0,
  138738. _vq_quantlist__44c1_s_p5_0,
  138739. NULL,
  138740. &_vq_auxt__44c1_s_p5_0,
  138741. NULL,
  138742. 0
  138743. };
  138744. static long _vq_quantlist__44c1_s_p6_0[] = {
  138745. 1,
  138746. 0,
  138747. 2,
  138748. };
  138749. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138750. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138751. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138752. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138753. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138754. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138755. 11,
  138756. };
  138757. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138758. -5.5, 5.5,
  138759. };
  138760. static long _vq_quantmap__44c1_s_p6_0[] = {
  138761. 1, 0, 2,
  138762. };
  138763. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138764. _vq_quantthresh__44c1_s_p6_0,
  138765. _vq_quantmap__44c1_s_p6_0,
  138766. 3,
  138767. 3
  138768. };
  138769. static static_codebook _44c1_s_p6_0 = {
  138770. 4, 81,
  138771. _vq_lengthlist__44c1_s_p6_0,
  138772. 1, -529137664, 1618345984, 2, 0,
  138773. _vq_quantlist__44c1_s_p6_0,
  138774. NULL,
  138775. &_vq_auxt__44c1_s_p6_0,
  138776. NULL,
  138777. 0
  138778. };
  138779. static long _vq_quantlist__44c1_s_p6_1[] = {
  138780. 5,
  138781. 4,
  138782. 6,
  138783. 3,
  138784. 7,
  138785. 2,
  138786. 8,
  138787. 1,
  138788. 9,
  138789. 0,
  138790. 10,
  138791. };
  138792. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138793. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138794. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138795. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138796. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138797. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138798. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138799. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138800. 10,10,10, 8, 8, 8, 8, 8, 8,
  138801. };
  138802. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138803. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138804. 3.5, 4.5,
  138805. };
  138806. static long _vq_quantmap__44c1_s_p6_1[] = {
  138807. 9, 7, 5, 3, 1, 0, 2, 4,
  138808. 6, 8, 10,
  138809. };
  138810. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138811. _vq_quantthresh__44c1_s_p6_1,
  138812. _vq_quantmap__44c1_s_p6_1,
  138813. 11,
  138814. 11
  138815. };
  138816. static static_codebook _44c1_s_p6_1 = {
  138817. 2, 121,
  138818. _vq_lengthlist__44c1_s_p6_1,
  138819. 1, -531365888, 1611661312, 4, 0,
  138820. _vq_quantlist__44c1_s_p6_1,
  138821. NULL,
  138822. &_vq_auxt__44c1_s_p6_1,
  138823. NULL,
  138824. 0
  138825. };
  138826. static long _vq_quantlist__44c1_s_p7_0[] = {
  138827. 6,
  138828. 5,
  138829. 7,
  138830. 4,
  138831. 8,
  138832. 3,
  138833. 9,
  138834. 2,
  138835. 10,
  138836. 1,
  138837. 11,
  138838. 0,
  138839. 12,
  138840. };
  138841. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138842. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138843. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138844. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138845. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138846. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138847. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138848. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138849. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138850. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138851. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138852. 0,12,11,11,11,13,10,14,13,
  138853. };
  138854. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138855. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138856. 12.5, 17.5, 22.5, 27.5,
  138857. };
  138858. static long _vq_quantmap__44c1_s_p7_0[] = {
  138859. 11, 9, 7, 5, 3, 1, 0, 2,
  138860. 4, 6, 8, 10, 12,
  138861. };
  138862. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138863. _vq_quantthresh__44c1_s_p7_0,
  138864. _vq_quantmap__44c1_s_p7_0,
  138865. 13,
  138866. 13
  138867. };
  138868. static static_codebook _44c1_s_p7_0 = {
  138869. 2, 169,
  138870. _vq_lengthlist__44c1_s_p7_0,
  138871. 1, -526516224, 1616117760, 4, 0,
  138872. _vq_quantlist__44c1_s_p7_0,
  138873. NULL,
  138874. &_vq_auxt__44c1_s_p7_0,
  138875. NULL,
  138876. 0
  138877. };
  138878. static long _vq_quantlist__44c1_s_p7_1[] = {
  138879. 2,
  138880. 1,
  138881. 3,
  138882. 0,
  138883. 4,
  138884. };
  138885. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138886. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138887. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138888. };
  138889. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138890. -1.5, -0.5, 0.5, 1.5,
  138891. };
  138892. static long _vq_quantmap__44c1_s_p7_1[] = {
  138893. 3, 1, 0, 2, 4,
  138894. };
  138895. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138896. _vq_quantthresh__44c1_s_p7_1,
  138897. _vq_quantmap__44c1_s_p7_1,
  138898. 5,
  138899. 5
  138900. };
  138901. static static_codebook _44c1_s_p7_1 = {
  138902. 2, 25,
  138903. _vq_lengthlist__44c1_s_p7_1,
  138904. 1, -533725184, 1611661312, 3, 0,
  138905. _vq_quantlist__44c1_s_p7_1,
  138906. NULL,
  138907. &_vq_auxt__44c1_s_p7_1,
  138908. NULL,
  138909. 0
  138910. };
  138911. static long _vq_quantlist__44c1_s_p8_0[] = {
  138912. 6,
  138913. 5,
  138914. 7,
  138915. 4,
  138916. 8,
  138917. 3,
  138918. 9,
  138919. 2,
  138920. 10,
  138921. 1,
  138922. 11,
  138923. 0,
  138924. 12,
  138925. };
  138926. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138927. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138928. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138929. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138930. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138931. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138932. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138933. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138934. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138935. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138936. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138937. 10,10,10,10,10,10,10,10,10,
  138938. };
  138939. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138940. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138941. 552.5, 773.5, 994.5, 1215.5,
  138942. };
  138943. static long _vq_quantmap__44c1_s_p8_0[] = {
  138944. 11, 9, 7, 5, 3, 1, 0, 2,
  138945. 4, 6, 8, 10, 12,
  138946. };
  138947. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138948. _vq_quantthresh__44c1_s_p8_0,
  138949. _vq_quantmap__44c1_s_p8_0,
  138950. 13,
  138951. 13
  138952. };
  138953. static static_codebook _44c1_s_p8_0 = {
  138954. 2, 169,
  138955. _vq_lengthlist__44c1_s_p8_0,
  138956. 1, -514541568, 1627103232, 4, 0,
  138957. _vq_quantlist__44c1_s_p8_0,
  138958. NULL,
  138959. &_vq_auxt__44c1_s_p8_0,
  138960. NULL,
  138961. 0
  138962. };
  138963. static long _vq_quantlist__44c1_s_p8_1[] = {
  138964. 6,
  138965. 5,
  138966. 7,
  138967. 4,
  138968. 8,
  138969. 3,
  138970. 9,
  138971. 2,
  138972. 10,
  138973. 1,
  138974. 11,
  138975. 0,
  138976. 12,
  138977. };
  138978. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138979. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138980. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138981. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138982. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138983. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138984. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138985. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138986. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138987. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138988. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138989. 16,13,12,12,11,14,12,15,13,
  138990. };
  138991. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138992. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138993. 42.5, 59.5, 76.5, 93.5,
  138994. };
  138995. static long _vq_quantmap__44c1_s_p8_1[] = {
  138996. 11, 9, 7, 5, 3, 1, 0, 2,
  138997. 4, 6, 8, 10, 12,
  138998. };
  138999. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  139000. _vq_quantthresh__44c1_s_p8_1,
  139001. _vq_quantmap__44c1_s_p8_1,
  139002. 13,
  139003. 13
  139004. };
  139005. static static_codebook _44c1_s_p8_1 = {
  139006. 2, 169,
  139007. _vq_lengthlist__44c1_s_p8_1,
  139008. 1, -522616832, 1620115456, 4, 0,
  139009. _vq_quantlist__44c1_s_p8_1,
  139010. NULL,
  139011. &_vq_auxt__44c1_s_p8_1,
  139012. NULL,
  139013. 0
  139014. };
  139015. static long _vq_quantlist__44c1_s_p8_2[] = {
  139016. 8,
  139017. 7,
  139018. 9,
  139019. 6,
  139020. 10,
  139021. 5,
  139022. 11,
  139023. 4,
  139024. 12,
  139025. 3,
  139026. 13,
  139027. 2,
  139028. 14,
  139029. 1,
  139030. 15,
  139031. 0,
  139032. 16,
  139033. };
  139034. static long _vq_lengthlist__44c1_s_p8_2[] = {
  139035. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139036. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139037. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  139038. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139039. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  139040. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139041. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139042. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  139043. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  139044. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139045. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  139046. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139047. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  139048. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  139049. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139050. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  139051. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139052. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  139053. 9,
  139054. };
  139055. static float _vq_quantthresh__44c1_s_p8_2[] = {
  139056. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139057. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139058. };
  139059. static long _vq_quantmap__44c1_s_p8_2[] = {
  139060. 15, 13, 11, 9, 7, 5, 3, 1,
  139061. 0, 2, 4, 6, 8, 10, 12, 14,
  139062. 16,
  139063. };
  139064. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  139065. _vq_quantthresh__44c1_s_p8_2,
  139066. _vq_quantmap__44c1_s_p8_2,
  139067. 17,
  139068. 17
  139069. };
  139070. static static_codebook _44c1_s_p8_2 = {
  139071. 2, 289,
  139072. _vq_lengthlist__44c1_s_p8_2,
  139073. 1, -529530880, 1611661312, 5, 0,
  139074. _vq_quantlist__44c1_s_p8_2,
  139075. NULL,
  139076. &_vq_auxt__44c1_s_p8_2,
  139077. NULL,
  139078. 0
  139079. };
  139080. static long _huff_lengthlist__44c1_s_short[] = {
  139081. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  139082. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  139083. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  139084. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  139085. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  139086. 11,
  139087. };
  139088. static static_codebook _huff_book__44c1_s_short = {
  139089. 2, 81,
  139090. _huff_lengthlist__44c1_s_short,
  139091. 0, 0, 0, 0, 0,
  139092. NULL,
  139093. NULL,
  139094. NULL,
  139095. NULL,
  139096. 0
  139097. };
  139098. static long _huff_lengthlist__44c1_sm_long[] = {
  139099. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  139100. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  139101. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  139102. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  139103. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  139104. 11,
  139105. };
  139106. static static_codebook _huff_book__44c1_sm_long = {
  139107. 2, 81,
  139108. _huff_lengthlist__44c1_sm_long,
  139109. 0, 0, 0, 0, 0,
  139110. NULL,
  139111. NULL,
  139112. NULL,
  139113. NULL,
  139114. 0
  139115. };
  139116. static long _vq_quantlist__44c1_sm_p1_0[] = {
  139117. 1,
  139118. 0,
  139119. 2,
  139120. };
  139121. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  139122. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139123. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139128. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139133. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  139168. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139173. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  139178. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139214. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139219. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139224. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0,
  139533. };
  139534. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139535. -0.5, 0.5,
  139536. };
  139537. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139538. 1, 0, 2,
  139539. };
  139540. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139541. _vq_quantthresh__44c1_sm_p1_0,
  139542. _vq_quantmap__44c1_sm_p1_0,
  139543. 3,
  139544. 3
  139545. };
  139546. static static_codebook _44c1_sm_p1_0 = {
  139547. 8, 6561,
  139548. _vq_lengthlist__44c1_sm_p1_0,
  139549. 1, -535822336, 1611661312, 2, 0,
  139550. _vq_quantlist__44c1_sm_p1_0,
  139551. NULL,
  139552. &_vq_auxt__44c1_sm_p1_0,
  139553. NULL,
  139554. 0
  139555. };
  139556. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139557. 2,
  139558. 1,
  139559. 3,
  139560. 0,
  139561. 4,
  139562. };
  139563. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139564. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139567. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139570. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0,
  139604. };
  139605. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139606. -1.5, -0.5, 0.5, 1.5,
  139607. };
  139608. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139609. 3, 1, 0, 2, 4,
  139610. };
  139611. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139612. _vq_quantthresh__44c1_sm_p2_0,
  139613. _vq_quantmap__44c1_sm_p2_0,
  139614. 5,
  139615. 5
  139616. };
  139617. static static_codebook _44c1_sm_p2_0 = {
  139618. 4, 625,
  139619. _vq_lengthlist__44c1_sm_p2_0,
  139620. 1, -533725184, 1611661312, 3, 0,
  139621. _vq_quantlist__44c1_sm_p2_0,
  139622. NULL,
  139623. &_vq_auxt__44c1_sm_p2_0,
  139624. NULL,
  139625. 0
  139626. };
  139627. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139628. 4,
  139629. 3,
  139630. 5,
  139631. 2,
  139632. 6,
  139633. 1,
  139634. 7,
  139635. 0,
  139636. 8,
  139637. };
  139638. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139639. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139640. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139641. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139642. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139643. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139644. 0,
  139645. };
  139646. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139647. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139648. };
  139649. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139650. 7, 5, 3, 1, 0, 2, 4, 6,
  139651. 8,
  139652. };
  139653. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139654. _vq_quantthresh__44c1_sm_p3_0,
  139655. _vq_quantmap__44c1_sm_p3_0,
  139656. 9,
  139657. 9
  139658. };
  139659. static static_codebook _44c1_sm_p3_0 = {
  139660. 2, 81,
  139661. _vq_lengthlist__44c1_sm_p3_0,
  139662. 1, -531628032, 1611661312, 4, 0,
  139663. _vq_quantlist__44c1_sm_p3_0,
  139664. NULL,
  139665. &_vq_auxt__44c1_sm_p3_0,
  139666. NULL,
  139667. 0
  139668. };
  139669. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139670. 4,
  139671. 3,
  139672. 5,
  139673. 2,
  139674. 6,
  139675. 1,
  139676. 7,
  139677. 0,
  139678. 8,
  139679. };
  139680. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139681. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139682. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139683. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139684. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139685. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139686. 11,
  139687. };
  139688. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139689. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139690. };
  139691. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139692. 7, 5, 3, 1, 0, 2, 4, 6,
  139693. 8,
  139694. };
  139695. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139696. _vq_quantthresh__44c1_sm_p4_0,
  139697. _vq_quantmap__44c1_sm_p4_0,
  139698. 9,
  139699. 9
  139700. };
  139701. static static_codebook _44c1_sm_p4_0 = {
  139702. 2, 81,
  139703. _vq_lengthlist__44c1_sm_p4_0,
  139704. 1, -531628032, 1611661312, 4, 0,
  139705. _vq_quantlist__44c1_sm_p4_0,
  139706. NULL,
  139707. &_vq_auxt__44c1_sm_p4_0,
  139708. NULL,
  139709. 0
  139710. };
  139711. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139712. 8,
  139713. 7,
  139714. 9,
  139715. 6,
  139716. 10,
  139717. 5,
  139718. 11,
  139719. 4,
  139720. 12,
  139721. 3,
  139722. 13,
  139723. 2,
  139724. 14,
  139725. 1,
  139726. 15,
  139727. 0,
  139728. 16,
  139729. };
  139730. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139731. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139732. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139733. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139734. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139735. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139736. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139737. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139738. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139739. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139740. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139741. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139742. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139743. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139744. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139745. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139746. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139747. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139748. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139749. 14,
  139750. };
  139751. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139752. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139753. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139754. };
  139755. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139756. 15, 13, 11, 9, 7, 5, 3, 1,
  139757. 0, 2, 4, 6, 8, 10, 12, 14,
  139758. 16,
  139759. };
  139760. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139761. _vq_quantthresh__44c1_sm_p5_0,
  139762. _vq_quantmap__44c1_sm_p5_0,
  139763. 17,
  139764. 17
  139765. };
  139766. static static_codebook _44c1_sm_p5_0 = {
  139767. 2, 289,
  139768. _vq_lengthlist__44c1_sm_p5_0,
  139769. 1, -529530880, 1611661312, 5, 0,
  139770. _vq_quantlist__44c1_sm_p5_0,
  139771. NULL,
  139772. &_vq_auxt__44c1_sm_p5_0,
  139773. NULL,
  139774. 0
  139775. };
  139776. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139777. 1,
  139778. 0,
  139779. 2,
  139780. };
  139781. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139782. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139783. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139784. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139785. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139786. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139787. 11,
  139788. };
  139789. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139790. -5.5, 5.5,
  139791. };
  139792. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139793. 1, 0, 2,
  139794. };
  139795. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139796. _vq_quantthresh__44c1_sm_p6_0,
  139797. _vq_quantmap__44c1_sm_p6_0,
  139798. 3,
  139799. 3
  139800. };
  139801. static static_codebook _44c1_sm_p6_0 = {
  139802. 4, 81,
  139803. _vq_lengthlist__44c1_sm_p6_0,
  139804. 1, -529137664, 1618345984, 2, 0,
  139805. _vq_quantlist__44c1_sm_p6_0,
  139806. NULL,
  139807. &_vq_auxt__44c1_sm_p6_0,
  139808. NULL,
  139809. 0
  139810. };
  139811. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139812. 5,
  139813. 4,
  139814. 6,
  139815. 3,
  139816. 7,
  139817. 2,
  139818. 8,
  139819. 1,
  139820. 9,
  139821. 0,
  139822. 10,
  139823. };
  139824. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139825. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139826. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139827. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139828. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139829. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139830. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139831. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139832. 10,10,10, 8, 8, 8, 8, 8, 8,
  139833. };
  139834. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139835. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139836. 3.5, 4.5,
  139837. };
  139838. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139839. 9, 7, 5, 3, 1, 0, 2, 4,
  139840. 6, 8, 10,
  139841. };
  139842. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139843. _vq_quantthresh__44c1_sm_p6_1,
  139844. _vq_quantmap__44c1_sm_p6_1,
  139845. 11,
  139846. 11
  139847. };
  139848. static static_codebook _44c1_sm_p6_1 = {
  139849. 2, 121,
  139850. _vq_lengthlist__44c1_sm_p6_1,
  139851. 1, -531365888, 1611661312, 4, 0,
  139852. _vq_quantlist__44c1_sm_p6_1,
  139853. NULL,
  139854. &_vq_auxt__44c1_sm_p6_1,
  139855. NULL,
  139856. 0
  139857. };
  139858. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139859. 6,
  139860. 5,
  139861. 7,
  139862. 4,
  139863. 8,
  139864. 3,
  139865. 9,
  139866. 2,
  139867. 10,
  139868. 1,
  139869. 11,
  139870. 0,
  139871. 12,
  139872. };
  139873. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139874. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139875. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139876. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139877. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139878. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139879. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139880. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139881. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139882. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139883. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139884. 0,12,12,11,11,13,12,14,13,
  139885. };
  139886. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139887. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139888. 12.5, 17.5, 22.5, 27.5,
  139889. };
  139890. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139891. 11, 9, 7, 5, 3, 1, 0, 2,
  139892. 4, 6, 8, 10, 12,
  139893. };
  139894. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139895. _vq_quantthresh__44c1_sm_p7_0,
  139896. _vq_quantmap__44c1_sm_p7_0,
  139897. 13,
  139898. 13
  139899. };
  139900. static static_codebook _44c1_sm_p7_0 = {
  139901. 2, 169,
  139902. _vq_lengthlist__44c1_sm_p7_0,
  139903. 1, -526516224, 1616117760, 4, 0,
  139904. _vq_quantlist__44c1_sm_p7_0,
  139905. NULL,
  139906. &_vq_auxt__44c1_sm_p7_0,
  139907. NULL,
  139908. 0
  139909. };
  139910. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139911. 2,
  139912. 1,
  139913. 3,
  139914. 0,
  139915. 4,
  139916. };
  139917. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139918. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139919. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139920. };
  139921. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139922. -1.5, -0.5, 0.5, 1.5,
  139923. };
  139924. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139925. 3, 1, 0, 2, 4,
  139926. };
  139927. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139928. _vq_quantthresh__44c1_sm_p7_1,
  139929. _vq_quantmap__44c1_sm_p7_1,
  139930. 5,
  139931. 5
  139932. };
  139933. static static_codebook _44c1_sm_p7_1 = {
  139934. 2, 25,
  139935. _vq_lengthlist__44c1_sm_p7_1,
  139936. 1, -533725184, 1611661312, 3, 0,
  139937. _vq_quantlist__44c1_sm_p7_1,
  139938. NULL,
  139939. &_vq_auxt__44c1_sm_p7_1,
  139940. NULL,
  139941. 0
  139942. };
  139943. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139944. 6,
  139945. 5,
  139946. 7,
  139947. 4,
  139948. 8,
  139949. 3,
  139950. 9,
  139951. 2,
  139952. 10,
  139953. 1,
  139954. 11,
  139955. 0,
  139956. 12,
  139957. };
  139958. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139959. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139960. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139961. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139962. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139963. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139964. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139965. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139966. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139967. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139968. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139969. 13,13,13,13,13,13,13,13,13,
  139970. };
  139971. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139972. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139973. 552.5, 773.5, 994.5, 1215.5,
  139974. };
  139975. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139976. 11, 9, 7, 5, 3, 1, 0, 2,
  139977. 4, 6, 8, 10, 12,
  139978. };
  139979. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139980. _vq_quantthresh__44c1_sm_p8_0,
  139981. _vq_quantmap__44c1_sm_p8_0,
  139982. 13,
  139983. 13
  139984. };
  139985. static static_codebook _44c1_sm_p8_0 = {
  139986. 2, 169,
  139987. _vq_lengthlist__44c1_sm_p8_0,
  139988. 1, -514541568, 1627103232, 4, 0,
  139989. _vq_quantlist__44c1_sm_p8_0,
  139990. NULL,
  139991. &_vq_auxt__44c1_sm_p8_0,
  139992. NULL,
  139993. 0
  139994. };
  139995. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139996. 6,
  139997. 5,
  139998. 7,
  139999. 4,
  140000. 8,
  140001. 3,
  140002. 9,
  140003. 2,
  140004. 10,
  140005. 1,
  140006. 11,
  140007. 0,
  140008. 12,
  140009. };
  140010. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  140011. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  140012. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  140013. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  140014. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  140015. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  140016. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  140017. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  140018. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  140019. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  140020. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  140021. 20,13,12,12,12,14,12,14,13,
  140022. };
  140023. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  140024. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140025. 42.5, 59.5, 76.5, 93.5,
  140026. };
  140027. static long _vq_quantmap__44c1_sm_p8_1[] = {
  140028. 11, 9, 7, 5, 3, 1, 0, 2,
  140029. 4, 6, 8, 10, 12,
  140030. };
  140031. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  140032. _vq_quantthresh__44c1_sm_p8_1,
  140033. _vq_quantmap__44c1_sm_p8_1,
  140034. 13,
  140035. 13
  140036. };
  140037. static static_codebook _44c1_sm_p8_1 = {
  140038. 2, 169,
  140039. _vq_lengthlist__44c1_sm_p8_1,
  140040. 1, -522616832, 1620115456, 4, 0,
  140041. _vq_quantlist__44c1_sm_p8_1,
  140042. NULL,
  140043. &_vq_auxt__44c1_sm_p8_1,
  140044. NULL,
  140045. 0
  140046. };
  140047. static long _vq_quantlist__44c1_sm_p8_2[] = {
  140048. 8,
  140049. 7,
  140050. 9,
  140051. 6,
  140052. 10,
  140053. 5,
  140054. 11,
  140055. 4,
  140056. 12,
  140057. 3,
  140058. 13,
  140059. 2,
  140060. 14,
  140061. 1,
  140062. 15,
  140063. 0,
  140064. 16,
  140065. };
  140066. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  140067. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  140068. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140069. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140070. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140071. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140072. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  140073. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  140074. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  140075. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  140076. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  140077. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  140078. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  140079. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  140080. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  140081. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  140082. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  140083. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  140084. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  140085. 9,
  140086. };
  140087. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  140088. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140089. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140090. };
  140091. static long _vq_quantmap__44c1_sm_p8_2[] = {
  140092. 15, 13, 11, 9, 7, 5, 3, 1,
  140093. 0, 2, 4, 6, 8, 10, 12, 14,
  140094. 16,
  140095. };
  140096. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  140097. _vq_quantthresh__44c1_sm_p8_2,
  140098. _vq_quantmap__44c1_sm_p8_2,
  140099. 17,
  140100. 17
  140101. };
  140102. static static_codebook _44c1_sm_p8_2 = {
  140103. 2, 289,
  140104. _vq_lengthlist__44c1_sm_p8_2,
  140105. 1, -529530880, 1611661312, 5, 0,
  140106. _vq_quantlist__44c1_sm_p8_2,
  140107. NULL,
  140108. &_vq_auxt__44c1_sm_p8_2,
  140109. NULL,
  140110. 0
  140111. };
  140112. static long _huff_lengthlist__44c1_sm_short[] = {
  140113. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  140114. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  140115. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  140116. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  140117. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  140118. 11,
  140119. };
  140120. static static_codebook _huff_book__44c1_sm_short = {
  140121. 2, 81,
  140122. _huff_lengthlist__44c1_sm_short,
  140123. 0, 0, 0, 0, 0,
  140124. NULL,
  140125. NULL,
  140126. NULL,
  140127. NULL,
  140128. 0
  140129. };
  140130. static long _huff_lengthlist__44cn1_s_long[] = {
  140131. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  140132. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  140133. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  140134. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  140135. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  140136. 20,
  140137. };
  140138. static static_codebook _huff_book__44cn1_s_long = {
  140139. 2, 81,
  140140. _huff_lengthlist__44cn1_s_long,
  140141. 0, 0, 0, 0, 0,
  140142. NULL,
  140143. NULL,
  140144. NULL,
  140145. NULL,
  140146. 0
  140147. };
  140148. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140149. 1,
  140150. 0,
  140151. 2,
  140152. };
  140153. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140154. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140155. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140160. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140165. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140200. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  140205. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  140210. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140246. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140251. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140256. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140564. 0,
  140565. };
  140566. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140567. -0.5, 0.5,
  140568. };
  140569. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140570. 1, 0, 2,
  140571. };
  140572. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140573. _vq_quantthresh__44cn1_s_p1_0,
  140574. _vq_quantmap__44cn1_s_p1_0,
  140575. 3,
  140576. 3
  140577. };
  140578. static static_codebook _44cn1_s_p1_0 = {
  140579. 8, 6561,
  140580. _vq_lengthlist__44cn1_s_p1_0,
  140581. 1, -535822336, 1611661312, 2, 0,
  140582. _vq_quantlist__44cn1_s_p1_0,
  140583. NULL,
  140584. &_vq_auxt__44cn1_s_p1_0,
  140585. NULL,
  140586. 0
  140587. };
  140588. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140589. 2,
  140590. 1,
  140591. 3,
  140592. 0,
  140593. 4,
  140594. };
  140595. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140596. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140599. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140602. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140635. 0,
  140636. };
  140637. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140638. -1.5, -0.5, 0.5, 1.5,
  140639. };
  140640. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140641. 3, 1, 0, 2, 4,
  140642. };
  140643. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140644. _vq_quantthresh__44cn1_s_p2_0,
  140645. _vq_quantmap__44cn1_s_p2_0,
  140646. 5,
  140647. 5
  140648. };
  140649. static static_codebook _44cn1_s_p2_0 = {
  140650. 4, 625,
  140651. _vq_lengthlist__44cn1_s_p2_0,
  140652. 1, -533725184, 1611661312, 3, 0,
  140653. _vq_quantlist__44cn1_s_p2_0,
  140654. NULL,
  140655. &_vq_auxt__44cn1_s_p2_0,
  140656. NULL,
  140657. 0
  140658. };
  140659. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140660. 4,
  140661. 3,
  140662. 5,
  140663. 2,
  140664. 6,
  140665. 1,
  140666. 7,
  140667. 0,
  140668. 8,
  140669. };
  140670. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140671. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140672. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140673. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140674. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140675. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140676. 0,
  140677. };
  140678. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140679. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140680. };
  140681. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140682. 7, 5, 3, 1, 0, 2, 4, 6,
  140683. 8,
  140684. };
  140685. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140686. _vq_quantthresh__44cn1_s_p3_0,
  140687. _vq_quantmap__44cn1_s_p3_0,
  140688. 9,
  140689. 9
  140690. };
  140691. static static_codebook _44cn1_s_p3_0 = {
  140692. 2, 81,
  140693. _vq_lengthlist__44cn1_s_p3_0,
  140694. 1, -531628032, 1611661312, 4, 0,
  140695. _vq_quantlist__44cn1_s_p3_0,
  140696. NULL,
  140697. &_vq_auxt__44cn1_s_p3_0,
  140698. NULL,
  140699. 0
  140700. };
  140701. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140702. 4,
  140703. 3,
  140704. 5,
  140705. 2,
  140706. 6,
  140707. 1,
  140708. 7,
  140709. 0,
  140710. 8,
  140711. };
  140712. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140713. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140714. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140715. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140716. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140717. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140718. 11,
  140719. };
  140720. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140721. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140722. };
  140723. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140724. 7, 5, 3, 1, 0, 2, 4, 6,
  140725. 8,
  140726. };
  140727. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140728. _vq_quantthresh__44cn1_s_p4_0,
  140729. _vq_quantmap__44cn1_s_p4_0,
  140730. 9,
  140731. 9
  140732. };
  140733. static static_codebook _44cn1_s_p4_0 = {
  140734. 2, 81,
  140735. _vq_lengthlist__44cn1_s_p4_0,
  140736. 1, -531628032, 1611661312, 4, 0,
  140737. _vq_quantlist__44cn1_s_p4_0,
  140738. NULL,
  140739. &_vq_auxt__44cn1_s_p4_0,
  140740. NULL,
  140741. 0
  140742. };
  140743. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140744. 8,
  140745. 7,
  140746. 9,
  140747. 6,
  140748. 10,
  140749. 5,
  140750. 11,
  140751. 4,
  140752. 12,
  140753. 3,
  140754. 13,
  140755. 2,
  140756. 14,
  140757. 1,
  140758. 15,
  140759. 0,
  140760. 16,
  140761. };
  140762. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140763. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140764. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140765. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140766. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140767. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140768. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140769. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140770. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140771. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140772. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140773. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140774. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140775. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140776. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140777. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140778. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140779. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140780. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140781. 14,
  140782. };
  140783. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140784. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140785. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140786. };
  140787. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140788. 15, 13, 11, 9, 7, 5, 3, 1,
  140789. 0, 2, 4, 6, 8, 10, 12, 14,
  140790. 16,
  140791. };
  140792. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140793. _vq_quantthresh__44cn1_s_p5_0,
  140794. _vq_quantmap__44cn1_s_p5_0,
  140795. 17,
  140796. 17
  140797. };
  140798. static static_codebook _44cn1_s_p5_0 = {
  140799. 2, 289,
  140800. _vq_lengthlist__44cn1_s_p5_0,
  140801. 1, -529530880, 1611661312, 5, 0,
  140802. _vq_quantlist__44cn1_s_p5_0,
  140803. NULL,
  140804. &_vq_auxt__44cn1_s_p5_0,
  140805. NULL,
  140806. 0
  140807. };
  140808. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140809. 1,
  140810. 0,
  140811. 2,
  140812. };
  140813. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140814. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140815. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140816. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140817. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140818. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140819. 10,
  140820. };
  140821. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140822. -5.5, 5.5,
  140823. };
  140824. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140825. 1, 0, 2,
  140826. };
  140827. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140828. _vq_quantthresh__44cn1_s_p6_0,
  140829. _vq_quantmap__44cn1_s_p6_0,
  140830. 3,
  140831. 3
  140832. };
  140833. static static_codebook _44cn1_s_p6_0 = {
  140834. 4, 81,
  140835. _vq_lengthlist__44cn1_s_p6_0,
  140836. 1, -529137664, 1618345984, 2, 0,
  140837. _vq_quantlist__44cn1_s_p6_0,
  140838. NULL,
  140839. &_vq_auxt__44cn1_s_p6_0,
  140840. NULL,
  140841. 0
  140842. };
  140843. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140844. 5,
  140845. 4,
  140846. 6,
  140847. 3,
  140848. 7,
  140849. 2,
  140850. 8,
  140851. 1,
  140852. 9,
  140853. 0,
  140854. 10,
  140855. };
  140856. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140857. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140858. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140859. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140860. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140861. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140862. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140863. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140864. 10,10,10, 9, 9, 9, 9, 9, 9,
  140865. };
  140866. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140867. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140868. 3.5, 4.5,
  140869. };
  140870. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140871. 9, 7, 5, 3, 1, 0, 2, 4,
  140872. 6, 8, 10,
  140873. };
  140874. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140875. _vq_quantthresh__44cn1_s_p6_1,
  140876. _vq_quantmap__44cn1_s_p6_1,
  140877. 11,
  140878. 11
  140879. };
  140880. static static_codebook _44cn1_s_p6_1 = {
  140881. 2, 121,
  140882. _vq_lengthlist__44cn1_s_p6_1,
  140883. 1, -531365888, 1611661312, 4, 0,
  140884. _vq_quantlist__44cn1_s_p6_1,
  140885. NULL,
  140886. &_vq_auxt__44cn1_s_p6_1,
  140887. NULL,
  140888. 0
  140889. };
  140890. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140891. 6,
  140892. 5,
  140893. 7,
  140894. 4,
  140895. 8,
  140896. 3,
  140897. 9,
  140898. 2,
  140899. 10,
  140900. 1,
  140901. 11,
  140902. 0,
  140903. 12,
  140904. };
  140905. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140906. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140907. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140908. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140909. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140910. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140911. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140912. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140913. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140914. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140915. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140916. 0,13,13,12,12,13,13,13,14,
  140917. };
  140918. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140919. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140920. 12.5, 17.5, 22.5, 27.5,
  140921. };
  140922. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140923. 11, 9, 7, 5, 3, 1, 0, 2,
  140924. 4, 6, 8, 10, 12,
  140925. };
  140926. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140927. _vq_quantthresh__44cn1_s_p7_0,
  140928. _vq_quantmap__44cn1_s_p7_0,
  140929. 13,
  140930. 13
  140931. };
  140932. static static_codebook _44cn1_s_p7_0 = {
  140933. 2, 169,
  140934. _vq_lengthlist__44cn1_s_p7_0,
  140935. 1, -526516224, 1616117760, 4, 0,
  140936. _vq_quantlist__44cn1_s_p7_0,
  140937. NULL,
  140938. &_vq_auxt__44cn1_s_p7_0,
  140939. NULL,
  140940. 0
  140941. };
  140942. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140943. 2,
  140944. 1,
  140945. 3,
  140946. 0,
  140947. 4,
  140948. };
  140949. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140950. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140951. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140952. };
  140953. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140954. -1.5, -0.5, 0.5, 1.5,
  140955. };
  140956. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140957. 3, 1, 0, 2, 4,
  140958. };
  140959. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140960. _vq_quantthresh__44cn1_s_p7_1,
  140961. _vq_quantmap__44cn1_s_p7_1,
  140962. 5,
  140963. 5
  140964. };
  140965. static static_codebook _44cn1_s_p7_1 = {
  140966. 2, 25,
  140967. _vq_lengthlist__44cn1_s_p7_1,
  140968. 1, -533725184, 1611661312, 3, 0,
  140969. _vq_quantlist__44cn1_s_p7_1,
  140970. NULL,
  140971. &_vq_auxt__44cn1_s_p7_1,
  140972. NULL,
  140973. 0
  140974. };
  140975. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140976. 2,
  140977. 1,
  140978. 3,
  140979. 0,
  140980. 4,
  140981. };
  140982. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140983. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140984. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140985. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140986. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140987. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140988. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140989. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140990. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140991. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140992. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140993. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140994. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140995. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140996. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140997. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140998. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141000. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141001. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141002. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141003. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141016. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  141017. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141018. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141019. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141020. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141021. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141022. 12,
  141023. };
  141024. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  141025. -331.5, -110.5, 110.5, 331.5,
  141026. };
  141027. static long _vq_quantmap__44cn1_s_p8_0[] = {
  141028. 3, 1, 0, 2, 4,
  141029. };
  141030. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  141031. _vq_quantthresh__44cn1_s_p8_0,
  141032. _vq_quantmap__44cn1_s_p8_0,
  141033. 5,
  141034. 5
  141035. };
  141036. static static_codebook _44cn1_s_p8_0 = {
  141037. 4, 625,
  141038. _vq_lengthlist__44cn1_s_p8_0,
  141039. 1, -518283264, 1627103232, 3, 0,
  141040. _vq_quantlist__44cn1_s_p8_0,
  141041. NULL,
  141042. &_vq_auxt__44cn1_s_p8_0,
  141043. NULL,
  141044. 0
  141045. };
  141046. static long _vq_quantlist__44cn1_s_p8_1[] = {
  141047. 6,
  141048. 5,
  141049. 7,
  141050. 4,
  141051. 8,
  141052. 3,
  141053. 9,
  141054. 2,
  141055. 10,
  141056. 1,
  141057. 11,
  141058. 0,
  141059. 12,
  141060. };
  141061. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  141062. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  141063. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  141064. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  141065. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  141066. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  141067. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  141068. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  141069. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  141070. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  141071. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  141072. 15,12,12,11,11,14,12,13,14,
  141073. };
  141074. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  141075. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141076. 42.5, 59.5, 76.5, 93.5,
  141077. };
  141078. static long _vq_quantmap__44cn1_s_p8_1[] = {
  141079. 11, 9, 7, 5, 3, 1, 0, 2,
  141080. 4, 6, 8, 10, 12,
  141081. };
  141082. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  141083. _vq_quantthresh__44cn1_s_p8_1,
  141084. _vq_quantmap__44cn1_s_p8_1,
  141085. 13,
  141086. 13
  141087. };
  141088. static static_codebook _44cn1_s_p8_1 = {
  141089. 2, 169,
  141090. _vq_lengthlist__44cn1_s_p8_1,
  141091. 1, -522616832, 1620115456, 4, 0,
  141092. _vq_quantlist__44cn1_s_p8_1,
  141093. NULL,
  141094. &_vq_auxt__44cn1_s_p8_1,
  141095. NULL,
  141096. 0
  141097. };
  141098. static long _vq_quantlist__44cn1_s_p8_2[] = {
  141099. 8,
  141100. 7,
  141101. 9,
  141102. 6,
  141103. 10,
  141104. 5,
  141105. 11,
  141106. 4,
  141107. 12,
  141108. 3,
  141109. 13,
  141110. 2,
  141111. 14,
  141112. 1,
  141113. 15,
  141114. 0,
  141115. 16,
  141116. };
  141117. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  141118. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141119. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  141120. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  141121. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  141122. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  141123. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  141124. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  141125. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  141126. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  141127. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  141128. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  141129. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  141130. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  141131. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  141132. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  141133. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141134. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141135. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  141136. 9,
  141137. };
  141138. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  141139. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141140. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141141. };
  141142. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141143. 15, 13, 11, 9, 7, 5, 3, 1,
  141144. 0, 2, 4, 6, 8, 10, 12, 14,
  141145. 16,
  141146. };
  141147. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141148. _vq_quantthresh__44cn1_s_p8_2,
  141149. _vq_quantmap__44cn1_s_p8_2,
  141150. 17,
  141151. 17
  141152. };
  141153. static static_codebook _44cn1_s_p8_2 = {
  141154. 2, 289,
  141155. _vq_lengthlist__44cn1_s_p8_2,
  141156. 1, -529530880, 1611661312, 5, 0,
  141157. _vq_quantlist__44cn1_s_p8_2,
  141158. NULL,
  141159. &_vq_auxt__44cn1_s_p8_2,
  141160. NULL,
  141161. 0
  141162. };
  141163. static long _huff_lengthlist__44cn1_s_short[] = {
  141164. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141165. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141166. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141167. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141168. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141169. 10,
  141170. };
  141171. static static_codebook _huff_book__44cn1_s_short = {
  141172. 2, 81,
  141173. _huff_lengthlist__44cn1_s_short,
  141174. 0, 0, 0, 0, 0,
  141175. NULL,
  141176. NULL,
  141177. NULL,
  141178. NULL,
  141179. 0
  141180. };
  141181. static long _huff_lengthlist__44cn1_sm_long[] = {
  141182. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141183. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141184. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141185. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141186. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141187. 17,
  141188. };
  141189. static static_codebook _huff_book__44cn1_sm_long = {
  141190. 2, 81,
  141191. _huff_lengthlist__44cn1_sm_long,
  141192. 0, 0, 0, 0, 0,
  141193. NULL,
  141194. NULL,
  141195. NULL,
  141196. NULL,
  141197. 0
  141198. };
  141199. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141200. 1,
  141201. 0,
  141202. 2,
  141203. };
  141204. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141205. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141206. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141211. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141216. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  141251. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  141256. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  141261. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141296. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141297. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141301. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141302. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  141303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141306. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141307. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141615. 0,
  141616. };
  141617. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141618. -0.5, 0.5,
  141619. };
  141620. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141621. 1, 0, 2,
  141622. };
  141623. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141624. _vq_quantthresh__44cn1_sm_p1_0,
  141625. _vq_quantmap__44cn1_sm_p1_0,
  141626. 3,
  141627. 3
  141628. };
  141629. static static_codebook _44cn1_sm_p1_0 = {
  141630. 8, 6561,
  141631. _vq_lengthlist__44cn1_sm_p1_0,
  141632. 1, -535822336, 1611661312, 2, 0,
  141633. _vq_quantlist__44cn1_sm_p1_0,
  141634. NULL,
  141635. &_vq_auxt__44cn1_sm_p1_0,
  141636. NULL,
  141637. 0
  141638. };
  141639. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141640. 2,
  141641. 1,
  141642. 3,
  141643. 0,
  141644. 4,
  141645. };
  141646. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141647. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141650. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141653. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141686. 0,
  141687. };
  141688. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141689. -1.5, -0.5, 0.5, 1.5,
  141690. };
  141691. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141692. 3, 1, 0, 2, 4,
  141693. };
  141694. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141695. _vq_quantthresh__44cn1_sm_p2_0,
  141696. _vq_quantmap__44cn1_sm_p2_0,
  141697. 5,
  141698. 5
  141699. };
  141700. static static_codebook _44cn1_sm_p2_0 = {
  141701. 4, 625,
  141702. _vq_lengthlist__44cn1_sm_p2_0,
  141703. 1, -533725184, 1611661312, 3, 0,
  141704. _vq_quantlist__44cn1_sm_p2_0,
  141705. NULL,
  141706. &_vq_auxt__44cn1_sm_p2_0,
  141707. NULL,
  141708. 0
  141709. };
  141710. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141711. 4,
  141712. 3,
  141713. 5,
  141714. 2,
  141715. 6,
  141716. 1,
  141717. 7,
  141718. 0,
  141719. 8,
  141720. };
  141721. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141722. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141723. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141724. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141725. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141726. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141727. 0,
  141728. };
  141729. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141730. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141731. };
  141732. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141733. 7, 5, 3, 1, 0, 2, 4, 6,
  141734. 8,
  141735. };
  141736. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141737. _vq_quantthresh__44cn1_sm_p3_0,
  141738. _vq_quantmap__44cn1_sm_p3_0,
  141739. 9,
  141740. 9
  141741. };
  141742. static static_codebook _44cn1_sm_p3_0 = {
  141743. 2, 81,
  141744. _vq_lengthlist__44cn1_sm_p3_0,
  141745. 1, -531628032, 1611661312, 4, 0,
  141746. _vq_quantlist__44cn1_sm_p3_0,
  141747. NULL,
  141748. &_vq_auxt__44cn1_sm_p3_0,
  141749. NULL,
  141750. 0
  141751. };
  141752. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141753. 4,
  141754. 3,
  141755. 5,
  141756. 2,
  141757. 6,
  141758. 1,
  141759. 7,
  141760. 0,
  141761. 8,
  141762. };
  141763. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141764. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141765. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141766. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141767. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141768. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141769. 11,
  141770. };
  141771. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141772. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141773. };
  141774. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141775. 7, 5, 3, 1, 0, 2, 4, 6,
  141776. 8,
  141777. };
  141778. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141779. _vq_quantthresh__44cn1_sm_p4_0,
  141780. _vq_quantmap__44cn1_sm_p4_0,
  141781. 9,
  141782. 9
  141783. };
  141784. static static_codebook _44cn1_sm_p4_0 = {
  141785. 2, 81,
  141786. _vq_lengthlist__44cn1_sm_p4_0,
  141787. 1, -531628032, 1611661312, 4, 0,
  141788. _vq_quantlist__44cn1_sm_p4_0,
  141789. NULL,
  141790. &_vq_auxt__44cn1_sm_p4_0,
  141791. NULL,
  141792. 0
  141793. };
  141794. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141795. 8,
  141796. 7,
  141797. 9,
  141798. 6,
  141799. 10,
  141800. 5,
  141801. 11,
  141802. 4,
  141803. 12,
  141804. 3,
  141805. 13,
  141806. 2,
  141807. 14,
  141808. 1,
  141809. 15,
  141810. 0,
  141811. 16,
  141812. };
  141813. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141814. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141815. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141816. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141817. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141818. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141819. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141820. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141821. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141822. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141823. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141824. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141825. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141826. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141827. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141828. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141829. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141830. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141831. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141832. 14,
  141833. };
  141834. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141835. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141836. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141837. };
  141838. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141839. 15, 13, 11, 9, 7, 5, 3, 1,
  141840. 0, 2, 4, 6, 8, 10, 12, 14,
  141841. 16,
  141842. };
  141843. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141844. _vq_quantthresh__44cn1_sm_p5_0,
  141845. _vq_quantmap__44cn1_sm_p5_0,
  141846. 17,
  141847. 17
  141848. };
  141849. static static_codebook _44cn1_sm_p5_0 = {
  141850. 2, 289,
  141851. _vq_lengthlist__44cn1_sm_p5_0,
  141852. 1, -529530880, 1611661312, 5, 0,
  141853. _vq_quantlist__44cn1_sm_p5_0,
  141854. NULL,
  141855. &_vq_auxt__44cn1_sm_p5_0,
  141856. NULL,
  141857. 0
  141858. };
  141859. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141860. 1,
  141861. 0,
  141862. 2,
  141863. };
  141864. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141865. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141866. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141867. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141868. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141869. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141870. 10,
  141871. };
  141872. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141873. -5.5, 5.5,
  141874. };
  141875. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141876. 1, 0, 2,
  141877. };
  141878. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141879. _vq_quantthresh__44cn1_sm_p6_0,
  141880. _vq_quantmap__44cn1_sm_p6_0,
  141881. 3,
  141882. 3
  141883. };
  141884. static static_codebook _44cn1_sm_p6_0 = {
  141885. 4, 81,
  141886. _vq_lengthlist__44cn1_sm_p6_0,
  141887. 1, -529137664, 1618345984, 2, 0,
  141888. _vq_quantlist__44cn1_sm_p6_0,
  141889. NULL,
  141890. &_vq_auxt__44cn1_sm_p6_0,
  141891. NULL,
  141892. 0
  141893. };
  141894. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141895. 5,
  141896. 4,
  141897. 6,
  141898. 3,
  141899. 7,
  141900. 2,
  141901. 8,
  141902. 1,
  141903. 9,
  141904. 0,
  141905. 10,
  141906. };
  141907. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141908. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141909. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141910. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141911. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141912. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141913. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141914. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141915. 10,10,10, 8, 9, 8, 8, 9, 8,
  141916. };
  141917. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141918. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141919. 3.5, 4.5,
  141920. };
  141921. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141922. 9, 7, 5, 3, 1, 0, 2, 4,
  141923. 6, 8, 10,
  141924. };
  141925. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141926. _vq_quantthresh__44cn1_sm_p6_1,
  141927. _vq_quantmap__44cn1_sm_p6_1,
  141928. 11,
  141929. 11
  141930. };
  141931. static static_codebook _44cn1_sm_p6_1 = {
  141932. 2, 121,
  141933. _vq_lengthlist__44cn1_sm_p6_1,
  141934. 1, -531365888, 1611661312, 4, 0,
  141935. _vq_quantlist__44cn1_sm_p6_1,
  141936. NULL,
  141937. &_vq_auxt__44cn1_sm_p6_1,
  141938. NULL,
  141939. 0
  141940. };
  141941. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141942. 6,
  141943. 5,
  141944. 7,
  141945. 4,
  141946. 8,
  141947. 3,
  141948. 9,
  141949. 2,
  141950. 10,
  141951. 1,
  141952. 11,
  141953. 0,
  141954. 12,
  141955. };
  141956. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141957. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141958. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141959. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141960. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141961. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141962. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141963. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141964. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141965. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141966. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141967. 0,13,12,12,12,13,13,13,14,
  141968. };
  141969. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141970. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141971. 12.5, 17.5, 22.5, 27.5,
  141972. };
  141973. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141974. 11, 9, 7, 5, 3, 1, 0, 2,
  141975. 4, 6, 8, 10, 12,
  141976. };
  141977. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141978. _vq_quantthresh__44cn1_sm_p7_0,
  141979. _vq_quantmap__44cn1_sm_p7_0,
  141980. 13,
  141981. 13
  141982. };
  141983. static static_codebook _44cn1_sm_p7_0 = {
  141984. 2, 169,
  141985. _vq_lengthlist__44cn1_sm_p7_0,
  141986. 1, -526516224, 1616117760, 4, 0,
  141987. _vq_quantlist__44cn1_sm_p7_0,
  141988. NULL,
  141989. &_vq_auxt__44cn1_sm_p7_0,
  141990. NULL,
  141991. 0
  141992. };
  141993. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141994. 2,
  141995. 1,
  141996. 3,
  141997. 0,
  141998. 4,
  141999. };
  142000. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  142001. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  142002. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  142003. };
  142004. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  142005. -1.5, -0.5, 0.5, 1.5,
  142006. };
  142007. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  142008. 3, 1, 0, 2, 4,
  142009. };
  142010. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  142011. _vq_quantthresh__44cn1_sm_p7_1,
  142012. _vq_quantmap__44cn1_sm_p7_1,
  142013. 5,
  142014. 5
  142015. };
  142016. static static_codebook _44cn1_sm_p7_1 = {
  142017. 2, 25,
  142018. _vq_lengthlist__44cn1_sm_p7_1,
  142019. 1, -533725184, 1611661312, 3, 0,
  142020. _vq_quantlist__44cn1_sm_p7_1,
  142021. NULL,
  142022. &_vq_auxt__44cn1_sm_p7_1,
  142023. NULL,
  142024. 0
  142025. };
  142026. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  142027. 4,
  142028. 3,
  142029. 5,
  142030. 2,
  142031. 6,
  142032. 1,
  142033. 7,
  142034. 0,
  142035. 8,
  142036. };
  142037. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  142038. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  142039. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  142040. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  142041. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  142042. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  142043. 14,
  142044. };
  142045. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  142046. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  142047. };
  142048. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  142049. 7, 5, 3, 1, 0, 2, 4, 6,
  142050. 8,
  142051. };
  142052. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  142053. _vq_quantthresh__44cn1_sm_p8_0,
  142054. _vq_quantmap__44cn1_sm_p8_0,
  142055. 9,
  142056. 9
  142057. };
  142058. static static_codebook _44cn1_sm_p8_0 = {
  142059. 2, 81,
  142060. _vq_lengthlist__44cn1_sm_p8_0,
  142061. 1, -516186112, 1627103232, 4, 0,
  142062. _vq_quantlist__44cn1_sm_p8_0,
  142063. NULL,
  142064. &_vq_auxt__44cn1_sm_p8_0,
  142065. NULL,
  142066. 0
  142067. };
  142068. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  142069. 6,
  142070. 5,
  142071. 7,
  142072. 4,
  142073. 8,
  142074. 3,
  142075. 9,
  142076. 2,
  142077. 10,
  142078. 1,
  142079. 11,
  142080. 0,
  142081. 12,
  142082. };
  142083. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  142084. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  142085. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  142086. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  142087. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  142088. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  142089. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  142090. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  142091. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  142092. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  142093. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  142094. 17,12,12,11,10,13,11,13,13,
  142095. };
  142096. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  142097. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  142098. 42.5, 59.5, 76.5, 93.5,
  142099. };
  142100. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  142101. 11, 9, 7, 5, 3, 1, 0, 2,
  142102. 4, 6, 8, 10, 12,
  142103. };
  142104. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  142105. _vq_quantthresh__44cn1_sm_p8_1,
  142106. _vq_quantmap__44cn1_sm_p8_1,
  142107. 13,
  142108. 13
  142109. };
  142110. static static_codebook _44cn1_sm_p8_1 = {
  142111. 2, 169,
  142112. _vq_lengthlist__44cn1_sm_p8_1,
  142113. 1, -522616832, 1620115456, 4, 0,
  142114. _vq_quantlist__44cn1_sm_p8_1,
  142115. NULL,
  142116. &_vq_auxt__44cn1_sm_p8_1,
  142117. NULL,
  142118. 0
  142119. };
  142120. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  142121. 8,
  142122. 7,
  142123. 9,
  142124. 6,
  142125. 10,
  142126. 5,
  142127. 11,
  142128. 4,
  142129. 12,
  142130. 3,
  142131. 13,
  142132. 2,
  142133. 14,
  142134. 1,
  142135. 15,
  142136. 0,
  142137. 16,
  142138. };
  142139. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142140. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142141. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142142. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142143. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142144. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142145. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142146. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142147. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142148. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142149. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142150. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142151. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142152. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142153. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142154. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142155. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142156. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142157. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142158. 9,
  142159. };
  142160. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142161. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142162. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142163. };
  142164. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142165. 15, 13, 11, 9, 7, 5, 3, 1,
  142166. 0, 2, 4, 6, 8, 10, 12, 14,
  142167. 16,
  142168. };
  142169. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142170. _vq_quantthresh__44cn1_sm_p8_2,
  142171. _vq_quantmap__44cn1_sm_p8_2,
  142172. 17,
  142173. 17
  142174. };
  142175. static static_codebook _44cn1_sm_p8_2 = {
  142176. 2, 289,
  142177. _vq_lengthlist__44cn1_sm_p8_2,
  142178. 1, -529530880, 1611661312, 5, 0,
  142179. _vq_quantlist__44cn1_sm_p8_2,
  142180. NULL,
  142181. &_vq_auxt__44cn1_sm_p8_2,
  142182. NULL,
  142183. 0
  142184. };
  142185. static long _huff_lengthlist__44cn1_sm_short[] = {
  142186. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142187. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142188. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142189. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142190. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142191. 9,
  142192. };
  142193. static static_codebook _huff_book__44cn1_sm_short = {
  142194. 2, 81,
  142195. _huff_lengthlist__44cn1_sm_short,
  142196. 0, 0, 0, 0, 0,
  142197. NULL,
  142198. NULL,
  142199. NULL,
  142200. NULL,
  142201. 0
  142202. };
  142203. /*** End of inlined file: res_books_stereo.h ***/
  142204. /***** residue backends *********************************************/
  142205. static vorbis_info_residue0 _residue_44_low={
  142206. 0,-1, -1, 9,-1,
  142207. /* 0 1 2 3 4 5 6 7 */
  142208. {0},
  142209. {-1},
  142210. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142211. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142212. };
  142213. static vorbis_info_residue0 _residue_44_mid={
  142214. 0,-1, -1, 10,-1,
  142215. /* 0 1 2 3 4 5 6 7 8 */
  142216. {0},
  142217. {-1},
  142218. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142219. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142220. };
  142221. static vorbis_info_residue0 _residue_44_high={
  142222. 0,-1, -1, 10,-1,
  142223. /* 0 1 2 3 4 5 6 7 8 */
  142224. {0},
  142225. {-1},
  142226. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142227. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142228. };
  142229. static static_bookblock _resbook_44s_n1={
  142230. {
  142231. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142232. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142233. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142234. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142235. }
  142236. };
  142237. static static_bookblock _resbook_44sm_n1={
  142238. {
  142239. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142240. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142241. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142242. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142243. }
  142244. };
  142245. static static_bookblock _resbook_44s_0={
  142246. {
  142247. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142248. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142249. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142250. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142251. }
  142252. };
  142253. static static_bookblock _resbook_44sm_0={
  142254. {
  142255. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142256. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142257. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142258. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142259. }
  142260. };
  142261. static static_bookblock _resbook_44s_1={
  142262. {
  142263. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142264. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142265. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142266. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142267. }
  142268. };
  142269. static static_bookblock _resbook_44sm_1={
  142270. {
  142271. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142272. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142273. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142274. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142275. }
  142276. };
  142277. static static_bookblock _resbook_44s_2={
  142278. {
  142279. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142280. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142281. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142282. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142283. }
  142284. };
  142285. static static_bookblock _resbook_44s_3={
  142286. {
  142287. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142288. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142289. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142290. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142291. }
  142292. };
  142293. static static_bookblock _resbook_44s_4={
  142294. {
  142295. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142296. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142297. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142298. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142299. }
  142300. };
  142301. static static_bookblock _resbook_44s_5={
  142302. {
  142303. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142304. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142305. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142306. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142307. }
  142308. };
  142309. static static_bookblock _resbook_44s_6={
  142310. {
  142311. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142312. {0,0,&_44c6_s_p4_0},
  142313. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142314. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142315. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142316. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142317. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142318. }
  142319. };
  142320. static static_bookblock _resbook_44s_7={
  142321. {
  142322. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142323. {0,0,&_44c7_s_p4_0},
  142324. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142325. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142326. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142327. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142328. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142329. }
  142330. };
  142331. static static_bookblock _resbook_44s_8={
  142332. {
  142333. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142334. {0,0,&_44c8_s_p4_0},
  142335. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142336. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142337. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142338. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142339. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142340. }
  142341. };
  142342. static static_bookblock _resbook_44s_9={
  142343. {
  142344. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142345. {0,0,&_44c9_s_p4_0},
  142346. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142347. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142348. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142349. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142350. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142351. }
  142352. };
  142353. static vorbis_residue_template _res_44s_n1[]={
  142354. {2,0, &_residue_44_low,
  142355. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142356. &_resbook_44s_n1,&_resbook_44sm_n1},
  142357. {2,0, &_residue_44_low,
  142358. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142359. &_resbook_44s_n1,&_resbook_44sm_n1}
  142360. };
  142361. static vorbis_residue_template _res_44s_0[]={
  142362. {2,0, &_residue_44_low,
  142363. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142364. &_resbook_44s_0,&_resbook_44sm_0},
  142365. {2,0, &_residue_44_low,
  142366. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142367. &_resbook_44s_0,&_resbook_44sm_0}
  142368. };
  142369. static vorbis_residue_template _res_44s_1[]={
  142370. {2,0, &_residue_44_low,
  142371. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142372. &_resbook_44s_1,&_resbook_44sm_1},
  142373. {2,0, &_residue_44_low,
  142374. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142375. &_resbook_44s_1,&_resbook_44sm_1}
  142376. };
  142377. static vorbis_residue_template _res_44s_2[]={
  142378. {2,0, &_residue_44_mid,
  142379. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142380. &_resbook_44s_2,&_resbook_44s_2},
  142381. {2,0, &_residue_44_mid,
  142382. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142383. &_resbook_44s_2,&_resbook_44s_2}
  142384. };
  142385. static vorbis_residue_template _res_44s_3[]={
  142386. {2,0, &_residue_44_mid,
  142387. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142388. &_resbook_44s_3,&_resbook_44s_3},
  142389. {2,0, &_residue_44_mid,
  142390. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142391. &_resbook_44s_3,&_resbook_44s_3}
  142392. };
  142393. static vorbis_residue_template _res_44s_4[]={
  142394. {2,0, &_residue_44_mid,
  142395. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142396. &_resbook_44s_4,&_resbook_44s_4},
  142397. {2,0, &_residue_44_mid,
  142398. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142399. &_resbook_44s_4,&_resbook_44s_4}
  142400. };
  142401. static vorbis_residue_template _res_44s_5[]={
  142402. {2,0, &_residue_44_mid,
  142403. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142404. &_resbook_44s_5,&_resbook_44s_5},
  142405. {2,0, &_residue_44_mid,
  142406. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142407. &_resbook_44s_5,&_resbook_44s_5}
  142408. };
  142409. static vorbis_residue_template _res_44s_6[]={
  142410. {2,0, &_residue_44_high,
  142411. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142412. &_resbook_44s_6,&_resbook_44s_6},
  142413. {2,0, &_residue_44_high,
  142414. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142415. &_resbook_44s_6,&_resbook_44s_6}
  142416. };
  142417. static vorbis_residue_template _res_44s_7[]={
  142418. {2,0, &_residue_44_high,
  142419. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142420. &_resbook_44s_7,&_resbook_44s_7},
  142421. {2,0, &_residue_44_high,
  142422. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142423. &_resbook_44s_7,&_resbook_44s_7}
  142424. };
  142425. static vorbis_residue_template _res_44s_8[]={
  142426. {2,0, &_residue_44_high,
  142427. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142428. &_resbook_44s_8,&_resbook_44s_8},
  142429. {2,0, &_residue_44_high,
  142430. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142431. &_resbook_44s_8,&_resbook_44s_8}
  142432. };
  142433. static vorbis_residue_template _res_44s_9[]={
  142434. {2,0, &_residue_44_high,
  142435. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142436. &_resbook_44s_9,&_resbook_44s_9},
  142437. {2,0, &_residue_44_high,
  142438. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142439. &_resbook_44s_9,&_resbook_44s_9}
  142440. };
  142441. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142442. { _map_nominal, _res_44s_n1 }, /* -1 */
  142443. { _map_nominal, _res_44s_0 }, /* 0 */
  142444. { _map_nominal, _res_44s_1 }, /* 1 */
  142445. { _map_nominal, _res_44s_2 }, /* 2 */
  142446. { _map_nominal, _res_44s_3 }, /* 3 */
  142447. { _map_nominal, _res_44s_4 }, /* 4 */
  142448. { _map_nominal, _res_44s_5 }, /* 5 */
  142449. { _map_nominal, _res_44s_6 }, /* 6 */
  142450. { _map_nominal, _res_44s_7 }, /* 7 */
  142451. { _map_nominal, _res_44s_8 }, /* 8 */
  142452. { _map_nominal, _res_44s_9 }, /* 9 */
  142453. };
  142454. /*** End of inlined file: residue_44.h ***/
  142455. /*** Start of inlined file: psych_44.h ***/
  142456. /* preecho trigger settings *****************************************/
  142457. static vorbis_info_psy_global _psy_global_44[5]={
  142458. {8, /* lines per eighth octave */
  142459. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142460. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142461. -6.f,
  142462. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142463. },
  142464. {8, /* lines per eighth octave */
  142465. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142466. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142467. -6.f,
  142468. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142469. },
  142470. {8, /* lines per eighth octave */
  142471. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142472. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142473. -6.f,
  142474. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142475. },
  142476. {8, /* lines per eighth octave */
  142477. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142478. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142479. -6.f,
  142480. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142481. },
  142482. {8, /* lines per eighth octave */
  142483. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142484. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142485. -6.f,
  142486. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142487. },
  142488. };
  142489. /* noise compander lookups * low, mid, high quality ****************/
  142490. static compandblock _psy_compand_44[6]={
  142491. /* sub-mode Z short */
  142492. {{
  142493. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142494. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142495. 16,17,18,19,20,21,22, 23, /* 23dB */
  142496. 24,25,26,27,28,29,30, 31, /* 31dB */
  142497. 32,33,34,35,36,37,38, 39, /* 39dB */
  142498. }},
  142499. /* mode_Z nominal short */
  142500. {{
  142501. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142502. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142503. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142504. 15,16,17,17,17,18,18, 19, /* 31dB */
  142505. 19,19,20,21,22,23,24, 25, /* 39dB */
  142506. }},
  142507. /* mode A short */
  142508. {{
  142509. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142510. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142511. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142512. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142513. 11,12,13,14,15,16,17, 18, /* 39dB */
  142514. }},
  142515. /* sub-mode Z long */
  142516. {{
  142517. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142518. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142519. 16,17,18,19,20,21,22, 23, /* 23dB */
  142520. 24,25,26,27,28,29,30, 31, /* 31dB */
  142521. 32,33,34,35,36,37,38, 39, /* 39dB */
  142522. }},
  142523. /* mode_Z nominal long */
  142524. {{
  142525. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142526. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142527. 13,14,14,14,15,15,15, 15, /* 23dB */
  142528. 16,16,17,17,17,18,18, 19, /* 31dB */
  142529. 19,19,20,21,22,23,24, 25, /* 39dB */
  142530. }},
  142531. /* mode A long */
  142532. {{
  142533. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142534. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142535. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142536. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142537. 11,12,13,14,15,16,17, 18, /* 39dB */
  142538. }}
  142539. };
  142540. /* tonal masking curve level adjustments *************************/
  142541. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142542. /* 63 125 250 500 1 2 4 8 16 */
  142543. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142544. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142545. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142546. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142547. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142548. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142549. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142550. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142551. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142552. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142553. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142554. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142555. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142556. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142557. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142558. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142559. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142560. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142561. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142562. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142563. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142564. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142565. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142566. };
  142567. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142568. /* 63 125 250 500 1 2 4 8 16 */
  142569. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142570. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142571. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142572. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142573. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142574. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142575. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142576. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142577. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142578. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142579. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142580. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142581. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142582. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142583. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142584. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142585. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142586. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142587. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142588. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142589. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142590. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142591. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142592. };
  142593. /* noise bias (transition block) */
  142594. static noise3 _psy_noisebias_trans[12]={
  142595. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142596. /* -1 */
  142597. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142598. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142599. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142600. /* 0
  142601. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142602. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142603. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142604. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142605. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142606. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142607. /* 1
  142608. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142609. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142610. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142611. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142612. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142613. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142614. /* 2
  142615. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142616. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142617. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142618. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142619. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142620. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142621. /* 3
  142622. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142623. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142624. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142625. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142626. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142627. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142628. /* 4
  142629. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142630. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142631. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142632. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142633. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142634. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142635. /* 5
  142636. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142637. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142638. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142639. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142640. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142641. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142642. /* 6
  142643. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142644. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142645. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142646. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142647. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142648. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142649. /* 7
  142650. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142651. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142652. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142653. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142654. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142655. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142656. /* 8
  142657. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142658. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142659. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142660. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142661. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142662. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142663. /* 9
  142664. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142665. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142666. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142667. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142668. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142669. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142670. /* 10 */
  142671. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142672. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142673. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142674. };
  142675. /* noise bias (long block) */
  142676. static noise3 _psy_noisebias_long[12]={
  142677. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142678. /* -1 */
  142679. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142680. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142681. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142682. /* 0 */
  142683. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142684. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142685. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142686. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142687. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142688. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142689. /* 1 */
  142690. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142691. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142692. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142693. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142694. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142695. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142696. /* 2 */
  142697. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142698. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142699. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142700. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142701. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142702. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142703. /* 3 */
  142704. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142705. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142706. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142707. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142708. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142709. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142710. /* 4 */
  142711. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142712. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142713. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142714. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142715. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142716. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142717. /* 5 */
  142718. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142719. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142720. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142721. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142722. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142723. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142724. /* 6 */
  142725. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142726. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142727. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142728. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142729. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142730. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142731. /* 7 */
  142732. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142733. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142734. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142735. /* 8 */
  142736. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142737. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142738. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142739. /* 9 */
  142740. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142741. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142742. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142743. /* 10 */
  142744. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142745. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142746. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142747. };
  142748. /* noise bias (impulse block) */
  142749. static noise3 _psy_noisebias_impulse[12]={
  142750. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142751. /* -1 */
  142752. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142753. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142754. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142755. /* 0 */
  142756. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142757. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142758. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142759. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142760. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142761. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142762. /* 1 */
  142763. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142764. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142765. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142766. /* 2 */
  142767. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142768. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142769. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142770. /* 3 */
  142771. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142772. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142773. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142774. /* 4 */
  142775. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142776. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142777. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142778. /* 5 */
  142779. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142780. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142781. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142782. /* 6
  142783. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142784. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142785. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142786. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142787. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142788. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142789. /* 7 */
  142790. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142791. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142792. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142793. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142794. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142795. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142796. /* 8 */
  142797. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142798. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142799. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142800. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142801. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142802. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142803. /* 9 */
  142804. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142805. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142806. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142807. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142808. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142809. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142810. /* 10 */
  142811. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142812. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142813. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142814. };
  142815. /* noise bias (padding block) */
  142816. static noise3 _psy_noisebias_padding[12]={
  142817. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142818. /* -1 */
  142819. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142820. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142821. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142822. /* 0 */
  142823. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142824. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142825. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142826. /* 1 */
  142827. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142828. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142829. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142830. /* 2 */
  142831. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142832. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142833. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142834. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142835. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142836. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142837. /* 3 */
  142838. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142839. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142840. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142841. /* 4 */
  142842. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142843. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142844. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142845. /* 5 */
  142846. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142847. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142848. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142849. /* 6 */
  142850. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142851. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142852. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142853. /* 7 */
  142854. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142855. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142856. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142857. /* 8 */
  142858. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142859. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142860. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142861. /* 9 */
  142862. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142863. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142864. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142865. /* 10 */
  142866. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142867. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142868. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142869. };
  142870. static noiseguard _psy_noiseguards_44[4]={
  142871. {3,3,15},
  142872. {3,3,15},
  142873. {10,10,100},
  142874. {10,10,100},
  142875. };
  142876. static int _psy_tone_suppress[12]={
  142877. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142878. };
  142879. static int _psy_tone_0dB[12]={
  142880. 90,90,95,95,95,95,105,105,105,105,105,105,
  142881. };
  142882. static int _psy_noise_suppress[12]={
  142883. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142884. };
  142885. static vorbis_info_psy _psy_info_template={
  142886. /* blockflag */
  142887. -1,
  142888. /* ath_adjatt, ath_maxatt */
  142889. -140.,-140.,
  142890. /* tonemask att boost/decay,suppr,curves */
  142891. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142892. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142893. 1, -0.f, .5f, .5f, 0,0,0,
  142894. /* noiseoffset*3, noisecompand, max_curve_dB */
  142895. {{-1},{-1},{-1}},{-1},105.f,
  142896. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142897. 0,0,-1,-1,0.,
  142898. };
  142899. /* ath ****************/
  142900. static int _psy_ath_floater[12]={
  142901. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142902. };
  142903. static int _psy_ath_abs[12]={
  142904. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142905. };
  142906. /* stereo setup. These don't map directly to quality level, there's
  142907. an additional indirection as several of the below may be used in a
  142908. single bitmanaged stream
  142909. ****************/
  142910. /* various stereo possibilities */
  142911. /* stereo mode by base quality level */
  142912. static adj_stereo _psy_stereo_modes_44[12]={
  142913. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142914. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142915. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142916. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142917. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142918. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142919. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142920. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142921. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142922. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142923. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142924. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142925. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142926. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142927. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142928. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142929. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142930. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142931. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142932. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142933. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142934. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142935. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142936. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142937. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142938. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142939. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142940. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142941. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142942. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142943. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142944. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142945. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142946. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142947. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142948. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142949. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142950. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142951. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142952. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142953. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142954. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142955. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142956. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142957. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142958. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142959. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142960. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142961. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142962. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142963. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142964. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142965. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142966. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142967. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142968. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142969. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142970. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142971. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142972. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142973. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142974. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142975. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142976. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142977. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142978. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142979. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142980. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142981. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142982. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142983. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142984. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142985. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142986. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142987. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142988. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142989. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142990. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142991. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142992. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142993. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142994. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142995. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142996. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142997. };
  142998. /* tone master attenuation by base quality mode and bitrate tweak */
  142999. static att3 _psy_tone_masteratt_44[12]={
  143000. {{ 35, 21, 9}, 0, 0}, /* -1 */
  143001. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  143002. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  143003. {{ 25, 12, 2}, 0, 0}, /* 1 */
  143004. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  143005. {{ 20, 9, -3}, 0, 0}, /* 2 */
  143006. {{ 20, 9, -4}, 0, 0}, /* 3 */
  143007. {{ 20, 9, -4}, 0, 0}, /* 4 */
  143008. {{ 20, 6, -6}, 0, 0}, /* 5 */
  143009. {{ 20, 3, -10}, 0, 0}, /* 6 */
  143010. {{ 18, 1, -14}, 0, 0}, /* 7 */
  143011. {{ 18, 0, -16}, 0, 0}, /* 8 */
  143012. {{ 18, -2, -16}, 0, 0}, /* 9 */
  143013. {{ 12, -2, -20}, 0, 0}, /* 10 */
  143014. };
  143015. /* lowpass by mode **************/
  143016. static double _psy_lowpass_44[12]={
  143017. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  143018. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  143019. };
  143020. /* noise normalization **********/
  143021. static int _noise_start_short_44[11]={
  143022. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  143023. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  143024. };
  143025. static int _noise_start_long_44[11]={
  143026. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  143027. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  143028. };
  143029. static int _noise_part_short_44[11]={
  143030. 8,8,8,8,8,8,8,8,8,8,8
  143031. };
  143032. static int _noise_part_long_44[11]={
  143033. 32,32,32,32,32,32,32,32,32,32,32
  143034. };
  143035. static double _noise_thresh_44[11]={
  143036. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  143037. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  143038. };
  143039. static double _noise_thresh_5only[2]={
  143040. .5,.5,
  143041. };
  143042. /*** End of inlined file: psych_44.h ***/
  143043. static double rate_mapping_44_stereo[12]={
  143044. 22500.,32000.,40000.,48000.,56000.,64000.,
  143045. 80000.,96000.,112000.,128000.,160000.,250001.
  143046. };
  143047. static double quality_mapping_44[12]={
  143048. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  143049. };
  143050. static int blocksize_short_44[11]={
  143051. 512,256,256,256,256,256,256,256,256,256,256
  143052. };
  143053. static int blocksize_long_44[11]={
  143054. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  143055. };
  143056. static double _psy_compand_short_mapping[12]={
  143057. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  143058. };
  143059. static double _psy_compand_long_mapping[12]={
  143060. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  143061. };
  143062. static double _global_mapping_44[12]={
  143063. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  143064. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  143065. };
  143066. static int _floor_short_mapping_44[11]={
  143067. 1,0,0,2,2,4,5,5,5,5,5
  143068. };
  143069. static int _floor_long_mapping_44[11]={
  143070. 8,7,7,7,7,7,7,7,7,7,7
  143071. };
  143072. ve_setup_data_template ve_setup_44_stereo={
  143073. 11,
  143074. rate_mapping_44_stereo,
  143075. quality_mapping_44,
  143076. 2,
  143077. 40000,
  143078. 50000,
  143079. blocksize_short_44,
  143080. blocksize_long_44,
  143081. _psy_tone_masteratt_44,
  143082. _psy_tone_0dB,
  143083. _psy_tone_suppress,
  143084. _vp_tonemask_adj_otherblock,
  143085. _vp_tonemask_adj_longblock,
  143086. _vp_tonemask_adj_otherblock,
  143087. _psy_noiseguards_44,
  143088. _psy_noisebias_impulse,
  143089. _psy_noisebias_padding,
  143090. _psy_noisebias_trans,
  143091. _psy_noisebias_long,
  143092. _psy_noise_suppress,
  143093. _psy_compand_44,
  143094. _psy_compand_short_mapping,
  143095. _psy_compand_long_mapping,
  143096. {_noise_start_short_44,_noise_start_long_44},
  143097. {_noise_part_short_44,_noise_part_long_44},
  143098. _noise_thresh_44,
  143099. _psy_ath_floater,
  143100. _psy_ath_abs,
  143101. _psy_lowpass_44,
  143102. _psy_global_44,
  143103. _global_mapping_44,
  143104. _psy_stereo_modes_44,
  143105. _floor_books,
  143106. _floor,
  143107. _floor_short_mapping_44,
  143108. _floor_long_mapping_44,
  143109. _mapres_template_44_stereo
  143110. };
  143111. /*** End of inlined file: setup_44.h ***/
  143112. /*** Start of inlined file: setup_44u.h ***/
  143113. /*** Start of inlined file: residue_44u.h ***/
  143114. /*** Start of inlined file: res_books_uncoupled.h ***/
  143115. static long _vq_quantlist__16u0__p1_0[] = {
  143116. 1,
  143117. 0,
  143118. 2,
  143119. };
  143120. static long _vq_lengthlist__16u0__p1_0[] = {
  143121. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  143122. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  143123. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  143124. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  143125. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  143126. 12,
  143127. };
  143128. static float _vq_quantthresh__16u0__p1_0[] = {
  143129. -0.5, 0.5,
  143130. };
  143131. static long _vq_quantmap__16u0__p1_0[] = {
  143132. 1, 0, 2,
  143133. };
  143134. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  143135. _vq_quantthresh__16u0__p1_0,
  143136. _vq_quantmap__16u0__p1_0,
  143137. 3,
  143138. 3
  143139. };
  143140. static static_codebook _16u0__p1_0 = {
  143141. 4, 81,
  143142. _vq_lengthlist__16u0__p1_0,
  143143. 1, -535822336, 1611661312, 2, 0,
  143144. _vq_quantlist__16u0__p1_0,
  143145. NULL,
  143146. &_vq_auxt__16u0__p1_0,
  143147. NULL,
  143148. 0
  143149. };
  143150. static long _vq_quantlist__16u0__p2_0[] = {
  143151. 1,
  143152. 0,
  143153. 2,
  143154. };
  143155. static long _vq_lengthlist__16u0__p2_0[] = {
  143156. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143157. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143158. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143159. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143160. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143161. 8,
  143162. };
  143163. static float _vq_quantthresh__16u0__p2_0[] = {
  143164. -0.5, 0.5,
  143165. };
  143166. static long _vq_quantmap__16u0__p2_0[] = {
  143167. 1, 0, 2,
  143168. };
  143169. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143170. _vq_quantthresh__16u0__p2_0,
  143171. _vq_quantmap__16u0__p2_0,
  143172. 3,
  143173. 3
  143174. };
  143175. static static_codebook _16u0__p2_0 = {
  143176. 4, 81,
  143177. _vq_lengthlist__16u0__p2_0,
  143178. 1, -535822336, 1611661312, 2, 0,
  143179. _vq_quantlist__16u0__p2_0,
  143180. NULL,
  143181. &_vq_auxt__16u0__p2_0,
  143182. NULL,
  143183. 0
  143184. };
  143185. static long _vq_quantlist__16u0__p3_0[] = {
  143186. 2,
  143187. 1,
  143188. 3,
  143189. 0,
  143190. 4,
  143191. };
  143192. static long _vq_lengthlist__16u0__p3_0[] = {
  143193. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143194. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143195. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143196. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143197. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143198. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143199. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143200. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143201. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143202. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143203. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143204. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143205. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143206. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143207. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143208. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143209. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143210. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143211. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143212. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143213. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143214. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143215. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143216. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143217. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143218. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143219. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143220. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143221. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143222. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143223. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143224. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143225. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143226. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143227. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143228. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143229. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143230. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143231. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143232. 18,
  143233. };
  143234. static float _vq_quantthresh__16u0__p3_0[] = {
  143235. -1.5, -0.5, 0.5, 1.5,
  143236. };
  143237. static long _vq_quantmap__16u0__p3_0[] = {
  143238. 3, 1, 0, 2, 4,
  143239. };
  143240. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143241. _vq_quantthresh__16u0__p3_0,
  143242. _vq_quantmap__16u0__p3_0,
  143243. 5,
  143244. 5
  143245. };
  143246. static static_codebook _16u0__p3_0 = {
  143247. 4, 625,
  143248. _vq_lengthlist__16u0__p3_0,
  143249. 1, -533725184, 1611661312, 3, 0,
  143250. _vq_quantlist__16u0__p3_0,
  143251. NULL,
  143252. &_vq_auxt__16u0__p3_0,
  143253. NULL,
  143254. 0
  143255. };
  143256. static long _vq_quantlist__16u0__p4_0[] = {
  143257. 2,
  143258. 1,
  143259. 3,
  143260. 0,
  143261. 4,
  143262. };
  143263. static long _vq_lengthlist__16u0__p4_0[] = {
  143264. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143265. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143266. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143267. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143268. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143269. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143270. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143271. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143272. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143273. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143274. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143275. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143276. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143277. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143278. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143279. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143280. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143281. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143282. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143283. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143284. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143285. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143286. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143287. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143288. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143289. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143290. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143291. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143292. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143293. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143294. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143295. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143296. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143297. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143298. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143299. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143300. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143301. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143302. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143303. 11,
  143304. };
  143305. static float _vq_quantthresh__16u0__p4_0[] = {
  143306. -1.5, -0.5, 0.5, 1.5,
  143307. };
  143308. static long _vq_quantmap__16u0__p4_0[] = {
  143309. 3, 1, 0, 2, 4,
  143310. };
  143311. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143312. _vq_quantthresh__16u0__p4_0,
  143313. _vq_quantmap__16u0__p4_0,
  143314. 5,
  143315. 5
  143316. };
  143317. static static_codebook _16u0__p4_0 = {
  143318. 4, 625,
  143319. _vq_lengthlist__16u0__p4_0,
  143320. 1, -533725184, 1611661312, 3, 0,
  143321. _vq_quantlist__16u0__p4_0,
  143322. NULL,
  143323. &_vq_auxt__16u0__p4_0,
  143324. NULL,
  143325. 0
  143326. };
  143327. static long _vq_quantlist__16u0__p5_0[] = {
  143328. 4,
  143329. 3,
  143330. 5,
  143331. 2,
  143332. 6,
  143333. 1,
  143334. 7,
  143335. 0,
  143336. 8,
  143337. };
  143338. static long _vq_lengthlist__16u0__p5_0[] = {
  143339. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143340. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143341. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143342. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143343. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143344. 12,
  143345. };
  143346. static float _vq_quantthresh__16u0__p5_0[] = {
  143347. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143348. };
  143349. static long _vq_quantmap__16u0__p5_0[] = {
  143350. 7, 5, 3, 1, 0, 2, 4, 6,
  143351. 8,
  143352. };
  143353. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143354. _vq_quantthresh__16u0__p5_0,
  143355. _vq_quantmap__16u0__p5_0,
  143356. 9,
  143357. 9
  143358. };
  143359. static static_codebook _16u0__p5_0 = {
  143360. 2, 81,
  143361. _vq_lengthlist__16u0__p5_0,
  143362. 1, -531628032, 1611661312, 4, 0,
  143363. _vq_quantlist__16u0__p5_0,
  143364. NULL,
  143365. &_vq_auxt__16u0__p5_0,
  143366. NULL,
  143367. 0
  143368. };
  143369. static long _vq_quantlist__16u0__p6_0[] = {
  143370. 6,
  143371. 5,
  143372. 7,
  143373. 4,
  143374. 8,
  143375. 3,
  143376. 9,
  143377. 2,
  143378. 10,
  143379. 1,
  143380. 11,
  143381. 0,
  143382. 12,
  143383. };
  143384. static long _vq_lengthlist__16u0__p6_0[] = {
  143385. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143386. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143387. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143388. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143389. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143390. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143391. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143392. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143393. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143394. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143395. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143396. };
  143397. static float _vq_quantthresh__16u0__p6_0[] = {
  143398. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143399. 12.5, 17.5, 22.5, 27.5,
  143400. };
  143401. static long _vq_quantmap__16u0__p6_0[] = {
  143402. 11, 9, 7, 5, 3, 1, 0, 2,
  143403. 4, 6, 8, 10, 12,
  143404. };
  143405. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143406. _vq_quantthresh__16u0__p6_0,
  143407. _vq_quantmap__16u0__p6_0,
  143408. 13,
  143409. 13
  143410. };
  143411. static static_codebook _16u0__p6_0 = {
  143412. 2, 169,
  143413. _vq_lengthlist__16u0__p6_0,
  143414. 1, -526516224, 1616117760, 4, 0,
  143415. _vq_quantlist__16u0__p6_0,
  143416. NULL,
  143417. &_vq_auxt__16u0__p6_0,
  143418. NULL,
  143419. 0
  143420. };
  143421. static long _vq_quantlist__16u0__p6_1[] = {
  143422. 2,
  143423. 1,
  143424. 3,
  143425. 0,
  143426. 4,
  143427. };
  143428. static long _vq_lengthlist__16u0__p6_1[] = {
  143429. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143430. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143431. };
  143432. static float _vq_quantthresh__16u0__p6_1[] = {
  143433. -1.5, -0.5, 0.5, 1.5,
  143434. };
  143435. static long _vq_quantmap__16u0__p6_1[] = {
  143436. 3, 1, 0, 2, 4,
  143437. };
  143438. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143439. _vq_quantthresh__16u0__p6_1,
  143440. _vq_quantmap__16u0__p6_1,
  143441. 5,
  143442. 5
  143443. };
  143444. static static_codebook _16u0__p6_1 = {
  143445. 2, 25,
  143446. _vq_lengthlist__16u0__p6_1,
  143447. 1, -533725184, 1611661312, 3, 0,
  143448. _vq_quantlist__16u0__p6_1,
  143449. NULL,
  143450. &_vq_auxt__16u0__p6_1,
  143451. NULL,
  143452. 0
  143453. };
  143454. static long _vq_quantlist__16u0__p7_0[] = {
  143455. 1,
  143456. 0,
  143457. 2,
  143458. };
  143459. static long _vq_lengthlist__16u0__p7_0[] = {
  143460. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143461. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143462. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143463. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143464. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143465. 7,
  143466. };
  143467. static float _vq_quantthresh__16u0__p7_0[] = {
  143468. -157.5, 157.5,
  143469. };
  143470. static long _vq_quantmap__16u0__p7_0[] = {
  143471. 1, 0, 2,
  143472. };
  143473. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143474. _vq_quantthresh__16u0__p7_0,
  143475. _vq_quantmap__16u0__p7_0,
  143476. 3,
  143477. 3
  143478. };
  143479. static static_codebook _16u0__p7_0 = {
  143480. 4, 81,
  143481. _vq_lengthlist__16u0__p7_0,
  143482. 1, -518803456, 1628680192, 2, 0,
  143483. _vq_quantlist__16u0__p7_0,
  143484. NULL,
  143485. &_vq_auxt__16u0__p7_0,
  143486. NULL,
  143487. 0
  143488. };
  143489. static long _vq_quantlist__16u0__p7_1[] = {
  143490. 7,
  143491. 6,
  143492. 8,
  143493. 5,
  143494. 9,
  143495. 4,
  143496. 10,
  143497. 3,
  143498. 11,
  143499. 2,
  143500. 12,
  143501. 1,
  143502. 13,
  143503. 0,
  143504. 14,
  143505. };
  143506. static long _vq_lengthlist__16u0__p7_1[] = {
  143507. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143508. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143509. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143510. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143511. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143512. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143513. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143514. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143515. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143516. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143517. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143518. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143519. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143520. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143521. 10,
  143522. };
  143523. static float _vq_quantthresh__16u0__p7_1[] = {
  143524. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143525. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143526. };
  143527. static long _vq_quantmap__16u0__p7_1[] = {
  143528. 13, 11, 9, 7, 5, 3, 1, 0,
  143529. 2, 4, 6, 8, 10, 12, 14,
  143530. };
  143531. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143532. _vq_quantthresh__16u0__p7_1,
  143533. _vq_quantmap__16u0__p7_1,
  143534. 15,
  143535. 15
  143536. };
  143537. static static_codebook _16u0__p7_1 = {
  143538. 2, 225,
  143539. _vq_lengthlist__16u0__p7_1,
  143540. 1, -520986624, 1620377600, 4, 0,
  143541. _vq_quantlist__16u0__p7_1,
  143542. NULL,
  143543. &_vq_auxt__16u0__p7_1,
  143544. NULL,
  143545. 0
  143546. };
  143547. static long _vq_quantlist__16u0__p7_2[] = {
  143548. 10,
  143549. 9,
  143550. 11,
  143551. 8,
  143552. 12,
  143553. 7,
  143554. 13,
  143555. 6,
  143556. 14,
  143557. 5,
  143558. 15,
  143559. 4,
  143560. 16,
  143561. 3,
  143562. 17,
  143563. 2,
  143564. 18,
  143565. 1,
  143566. 19,
  143567. 0,
  143568. 20,
  143569. };
  143570. static long _vq_lengthlist__16u0__p7_2[] = {
  143571. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143572. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143573. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143574. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143575. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143576. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143577. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143578. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143579. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143580. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143581. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143582. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143583. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143584. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143585. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143586. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143587. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143588. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143589. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143590. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143591. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143592. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143593. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143594. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143595. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143596. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143597. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143598. 10,10,12,11,10,11,11,11,10,
  143599. };
  143600. static float _vq_quantthresh__16u0__p7_2[] = {
  143601. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143602. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143603. 6.5, 7.5, 8.5, 9.5,
  143604. };
  143605. static long _vq_quantmap__16u0__p7_2[] = {
  143606. 19, 17, 15, 13, 11, 9, 7, 5,
  143607. 3, 1, 0, 2, 4, 6, 8, 10,
  143608. 12, 14, 16, 18, 20,
  143609. };
  143610. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143611. _vq_quantthresh__16u0__p7_2,
  143612. _vq_quantmap__16u0__p7_2,
  143613. 21,
  143614. 21
  143615. };
  143616. static static_codebook _16u0__p7_2 = {
  143617. 2, 441,
  143618. _vq_lengthlist__16u0__p7_2,
  143619. 1, -529268736, 1611661312, 5, 0,
  143620. _vq_quantlist__16u0__p7_2,
  143621. NULL,
  143622. &_vq_auxt__16u0__p7_2,
  143623. NULL,
  143624. 0
  143625. };
  143626. static long _huff_lengthlist__16u0__single[] = {
  143627. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143628. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143629. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143630. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143631. };
  143632. static static_codebook _huff_book__16u0__single = {
  143633. 2, 64,
  143634. _huff_lengthlist__16u0__single,
  143635. 0, 0, 0, 0, 0,
  143636. NULL,
  143637. NULL,
  143638. NULL,
  143639. NULL,
  143640. 0
  143641. };
  143642. static long _huff_lengthlist__16u1__long[] = {
  143643. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143644. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143645. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143646. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143647. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143648. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143649. 16,13,16,18,
  143650. };
  143651. static static_codebook _huff_book__16u1__long = {
  143652. 2, 100,
  143653. _huff_lengthlist__16u1__long,
  143654. 0, 0, 0, 0, 0,
  143655. NULL,
  143656. NULL,
  143657. NULL,
  143658. NULL,
  143659. 0
  143660. };
  143661. static long _vq_quantlist__16u1__p1_0[] = {
  143662. 1,
  143663. 0,
  143664. 2,
  143665. };
  143666. static long _vq_lengthlist__16u1__p1_0[] = {
  143667. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143668. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143669. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143670. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143671. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143672. 11,
  143673. };
  143674. static float _vq_quantthresh__16u1__p1_0[] = {
  143675. -0.5, 0.5,
  143676. };
  143677. static long _vq_quantmap__16u1__p1_0[] = {
  143678. 1, 0, 2,
  143679. };
  143680. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143681. _vq_quantthresh__16u1__p1_0,
  143682. _vq_quantmap__16u1__p1_0,
  143683. 3,
  143684. 3
  143685. };
  143686. static static_codebook _16u1__p1_0 = {
  143687. 4, 81,
  143688. _vq_lengthlist__16u1__p1_0,
  143689. 1, -535822336, 1611661312, 2, 0,
  143690. _vq_quantlist__16u1__p1_0,
  143691. NULL,
  143692. &_vq_auxt__16u1__p1_0,
  143693. NULL,
  143694. 0
  143695. };
  143696. static long _vq_quantlist__16u1__p2_0[] = {
  143697. 1,
  143698. 0,
  143699. 2,
  143700. };
  143701. static long _vq_lengthlist__16u1__p2_0[] = {
  143702. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143703. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143704. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143705. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143706. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143707. 8,
  143708. };
  143709. static float _vq_quantthresh__16u1__p2_0[] = {
  143710. -0.5, 0.5,
  143711. };
  143712. static long _vq_quantmap__16u1__p2_0[] = {
  143713. 1, 0, 2,
  143714. };
  143715. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143716. _vq_quantthresh__16u1__p2_0,
  143717. _vq_quantmap__16u1__p2_0,
  143718. 3,
  143719. 3
  143720. };
  143721. static static_codebook _16u1__p2_0 = {
  143722. 4, 81,
  143723. _vq_lengthlist__16u1__p2_0,
  143724. 1, -535822336, 1611661312, 2, 0,
  143725. _vq_quantlist__16u1__p2_0,
  143726. NULL,
  143727. &_vq_auxt__16u1__p2_0,
  143728. NULL,
  143729. 0
  143730. };
  143731. static long _vq_quantlist__16u1__p3_0[] = {
  143732. 2,
  143733. 1,
  143734. 3,
  143735. 0,
  143736. 4,
  143737. };
  143738. static long _vq_lengthlist__16u1__p3_0[] = {
  143739. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143740. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143741. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143742. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143743. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143744. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143745. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143746. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143747. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143748. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143749. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143750. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143751. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143752. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143753. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143754. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143755. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143756. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143757. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143758. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143759. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143760. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143761. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143762. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143763. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143764. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143765. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143766. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143767. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143768. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143769. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143770. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143771. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143772. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143773. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143774. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143775. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143776. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143777. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143778. 16,
  143779. };
  143780. static float _vq_quantthresh__16u1__p3_0[] = {
  143781. -1.5, -0.5, 0.5, 1.5,
  143782. };
  143783. static long _vq_quantmap__16u1__p3_0[] = {
  143784. 3, 1, 0, 2, 4,
  143785. };
  143786. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143787. _vq_quantthresh__16u1__p3_0,
  143788. _vq_quantmap__16u1__p3_0,
  143789. 5,
  143790. 5
  143791. };
  143792. static static_codebook _16u1__p3_0 = {
  143793. 4, 625,
  143794. _vq_lengthlist__16u1__p3_0,
  143795. 1, -533725184, 1611661312, 3, 0,
  143796. _vq_quantlist__16u1__p3_0,
  143797. NULL,
  143798. &_vq_auxt__16u1__p3_0,
  143799. NULL,
  143800. 0
  143801. };
  143802. static long _vq_quantlist__16u1__p4_0[] = {
  143803. 2,
  143804. 1,
  143805. 3,
  143806. 0,
  143807. 4,
  143808. };
  143809. static long _vq_lengthlist__16u1__p4_0[] = {
  143810. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143811. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143812. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143813. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143814. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143815. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143816. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143817. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143818. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143819. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143820. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143821. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143822. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143823. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143824. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143825. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143826. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143827. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143828. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143829. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143830. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143831. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143832. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143833. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143834. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143835. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143836. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143837. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143838. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143839. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143840. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143841. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143842. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143843. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143844. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143845. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143846. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143847. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143848. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143849. 11,
  143850. };
  143851. static float _vq_quantthresh__16u1__p4_0[] = {
  143852. -1.5, -0.5, 0.5, 1.5,
  143853. };
  143854. static long _vq_quantmap__16u1__p4_0[] = {
  143855. 3, 1, 0, 2, 4,
  143856. };
  143857. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143858. _vq_quantthresh__16u1__p4_0,
  143859. _vq_quantmap__16u1__p4_0,
  143860. 5,
  143861. 5
  143862. };
  143863. static static_codebook _16u1__p4_0 = {
  143864. 4, 625,
  143865. _vq_lengthlist__16u1__p4_0,
  143866. 1, -533725184, 1611661312, 3, 0,
  143867. _vq_quantlist__16u1__p4_0,
  143868. NULL,
  143869. &_vq_auxt__16u1__p4_0,
  143870. NULL,
  143871. 0
  143872. };
  143873. static long _vq_quantlist__16u1__p5_0[] = {
  143874. 4,
  143875. 3,
  143876. 5,
  143877. 2,
  143878. 6,
  143879. 1,
  143880. 7,
  143881. 0,
  143882. 8,
  143883. };
  143884. static long _vq_lengthlist__16u1__p5_0[] = {
  143885. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143886. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143887. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143888. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143889. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143890. 13,
  143891. };
  143892. static float _vq_quantthresh__16u1__p5_0[] = {
  143893. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143894. };
  143895. static long _vq_quantmap__16u1__p5_0[] = {
  143896. 7, 5, 3, 1, 0, 2, 4, 6,
  143897. 8,
  143898. };
  143899. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143900. _vq_quantthresh__16u1__p5_0,
  143901. _vq_quantmap__16u1__p5_0,
  143902. 9,
  143903. 9
  143904. };
  143905. static static_codebook _16u1__p5_0 = {
  143906. 2, 81,
  143907. _vq_lengthlist__16u1__p5_0,
  143908. 1, -531628032, 1611661312, 4, 0,
  143909. _vq_quantlist__16u1__p5_0,
  143910. NULL,
  143911. &_vq_auxt__16u1__p5_0,
  143912. NULL,
  143913. 0
  143914. };
  143915. static long _vq_quantlist__16u1__p6_0[] = {
  143916. 4,
  143917. 3,
  143918. 5,
  143919. 2,
  143920. 6,
  143921. 1,
  143922. 7,
  143923. 0,
  143924. 8,
  143925. };
  143926. static long _vq_lengthlist__16u1__p6_0[] = {
  143927. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143928. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143929. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143930. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143931. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143932. 11,
  143933. };
  143934. static float _vq_quantthresh__16u1__p6_0[] = {
  143935. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143936. };
  143937. static long _vq_quantmap__16u1__p6_0[] = {
  143938. 7, 5, 3, 1, 0, 2, 4, 6,
  143939. 8,
  143940. };
  143941. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143942. _vq_quantthresh__16u1__p6_0,
  143943. _vq_quantmap__16u1__p6_0,
  143944. 9,
  143945. 9
  143946. };
  143947. static static_codebook _16u1__p6_0 = {
  143948. 2, 81,
  143949. _vq_lengthlist__16u1__p6_0,
  143950. 1, -531628032, 1611661312, 4, 0,
  143951. _vq_quantlist__16u1__p6_0,
  143952. NULL,
  143953. &_vq_auxt__16u1__p6_0,
  143954. NULL,
  143955. 0
  143956. };
  143957. static long _vq_quantlist__16u1__p7_0[] = {
  143958. 1,
  143959. 0,
  143960. 2,
  143961. };
  143962. static long _vq_lengthlist__16u1__p7_0[] = {
  143963. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143964. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143965. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143966. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143967. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143968. 13,
  143969. };
  143970. static float _vq_quantthresh__16u1__p7_0[] = {
  143971. -5.5, 5.5,
  143972. };
  143973. static long _vq_quantmap__16u1__p7_0[] = {
  143974. 1, 0, 2,
  143975. };
  143976. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143977. _vq_quantthresh__16u1__p7_0,
  143978. _vq_quantmap__16u1__p7_0,
  143979. 3,
  143980. 3
  143981. };
  143982. static static_codebook _16u1__p7_0 = {
  143983. 4, 81,
  143984. _vq_lengthlist__16u1__p7_0,
  143985. 1, -529137664, 1618345984, 2, 0,
  143986. _vq_quantlist__16u1__p7_0,
  143987. NULL,
  143988. &_vq_auxt__16u1__p7_0,
  143989. NULL,
  143990. 0
  143991. };
  143992. static long _vq_quantlist__16u1__p7_1[] = {
  143993. 5,
  143994. 4,
  143995. 6,
  143996. 3,
  143997. 7,
  143998. 2,
  143999. 8,
  144000. 1,
  144001. 9,
  144002. 0,
  144003. 10,
  144004. };
  144005. static long _vq_lengthlist__16u1__p7_1[] = {
  144006. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  144007. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  144008. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144009. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  144010. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  144011. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  144012. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  144013. 8, 9, 9,10,10,10,10,10,10,
  144014. };
  144015. static float _vq_quantthresh__16u1__p7_1[] = {
  144016. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144017. 3.5, 4.5,
  144018. };
  144019. static long _vq_quantmap__16u1__p7_1[] = {
  144020. 9, 7, 5, 3, 1, 0, 2, 4,
  144021. 6, 8, 10,
  144022. };
  144023. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  144024. _vq_quantthresh__16u1__p7_1,
  144025. _vq_quantmap__16u1__p7_1,
  144026. 11,
  144027. 11
  144028. };
  144029. static static_codebook _16u1__p7_1 = {
  144030. 2, 121,
  144031. _vq_lengthlist__16u1__p7_1,
  144032. 1, -531365888, 1611661312, 4, 0,
  144033. _vq_quantlist__16u1__p7_1,
  144034. NULL,
  144035. &_vq_auxt__16u1__p7_1,
  144036. NULL,
  144037. 0
  144038. };
  144039. static long _vq_quantlist__16u1__p8_0[] = {
  144040. 5,
  144041. 4,
  144042. 6,
  144043. 3,
  144044. 7,
  144045. 2,
  144046. 8,
  144047. 1,
  144048. 9,
  144049. 0,
  144050. 10,
  144051. };
  144052. static long _vq_lengthlist__16u1__p8_0[] = {
  144053. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  144054. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  144055. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  144056. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  144057. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  144058. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  144059. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  144060. 13,14,14,15,15,16,16,15,16,
  144061. };
  144062. static float _vq_quantthresh__16u1__p8_0[] = {
  144063. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144064. 38.5, 49.5,
  144065. };
  144066. static long _vq_quantmap__16u1__p8_0[] = {
  144067. 9, 7, 5, 3, 1, 0, 2, 4,
  144068. 6, 8, 10,
  144069. };
  144070. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  144071. _vq_quantthresh__16u1__p8_0,
  144072. _vq_quantmap__16u1__p8_0,
  144073. 11,
  144074. 11
  144075. };
  144076. static static_codebook _16u1__p8_0 = {
  144077. 2, 121,
  144078. _vq_lengthlist__16u1__p8_0,
  144079. 1, -524582912, 1618345984, 4, 0,
  144080. _vq_quantlist__16u1__p8_0,
  144081. NULL,
  144082. &_vq_auxt__16u1__p8_0,
  144083. NULL,
  144084. 0
  144085. };
  144086. static long _vq_quantlist__16u1__p8_1[] = {
  144087. 5,
  144088. 4,
  144089. 6,
  144090. 3,
  144091. 7,
  144092. 2,
  144093. 8,
  144094. 1,
  144095. 9,
  144096. 0,
  144097. 10,
  144098. };
  144099. static long _vq_lengthlist__16u1__p8_1[] = {
  144100. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  144101. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144102. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  144103. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144104. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144105. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144106. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144107. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144108. };
  144109. static float _vq_quantthresh__16u1__p8_1[] = {
  144110. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144111. 3.5, 4.5,
  144112. };
  144113. static long _vq_quantmap__16u1__p8_1[] = {
  144114. 9, 7, 5, 3, 1, 0, 2, 4,
  144115. 6, 8, 10,
  144116. };
  144117. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  144118. _vq_quantthresh__16u1__p8_1,
  144119. _vq_quantmap__16u1__p8_1,
  144120. 11,
  144121. 11
  144122. };
  144123. static static_codebook _16u1__p8_1 = {
  144124. 2, 121,
  144125. _vq_lengthlist__16u1__p8_1,
  144126. 1, -531365888, 1611661312, 4, 0,
  144127. _vq_quantlist__16u1__p8_1,
  144128. NULL,
  144129. &_vq_auxt__16u1__p8_1,
  144130. NULL,
  144131. 0
  144132. };
  144133. static long _vq_quantlist__16u1__p9_0[] = {
  144134. 7,
  144135. 6,
  144136. 8,
  144137. 5,
  144138. 9,
  144139. 4,
  144140. 10,
  144141. 3,
  144142. 11,
  144143. 2,
  144144. 12,
  144145. 1,
  144146. 13,
  144147. 0,
  144148. 14,
  144149. };
  144150. static long _vq_lengthlist__16u1__p9_0[] = {
  144151. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144152. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144153. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144154. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144155. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144156. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144157. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144158. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144159. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144160. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144161. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144162. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144163. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144164. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144165. 8,
  144166. };
  144167. static float _vq_quantthresh__16u1__p9_0[] = {
  144168. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144169. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144170. };
  144171. static long _vq_quantmap__16u1__p9_0[] = {
  144172. 13, 11, 9, 7, 5, 3, 1, 0,
  144173. 2, 4, 6, 8, 10, 12, 14,
  144174. };
  144175. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144176. _vq_quantthresh__16u1__p9_0,
  144177. _vq_quantmap__16u1__p9_0,
  144178. 15,
  144179. 15
  144180. };
  144181. static static_codebook _16u1__p9_0 = {
  144182. 2, 225,
  144183. _vq_lengthlist__16u1__p9_0,
  144184. 1, -514071552, 1627381760, 4, 0,
  144185. _vq_quantlist__16u1__p9_0,
  144186. NULL,
  144187. &_vq_auxt__16u1__p9_0,
  144188. NULL,
  144189. 0
  144190. };
  144191. static long _vq_quantlist__16u1__p9_1[] = {
  144192. 7,
  144193. 6,
  144194. 8,
  144195. 5,
  144196. 9,
  144197. 4,
  144198. 10,
  144199. 3,
  144200. 11,
  144201. 2,
  144202. 12,
  144203. 1,
  144204. 13,
  144205. 0,
  144206. 14,
  144207. };
  144208. static long _vq_lengthlist__16u1__p9_1[] = {
  144209. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144210. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144211. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144212. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144213. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144214. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144215. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144216. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144217. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144218. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144219. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144220. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144221. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144222. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144223. 9,
  144224. };
  144225. static float _vq_quantthresh__16u1__p9_1[] = {
  144226. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144227. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144228. };
  144229. static long _vq_quantmap__16u1__p9_1[] = {
  144230. 13, 11, 9, 7, 5, 3, 1, 0,
  144231. 2, 4, 6, 8, 10, 12, 14,
  144232. };
  144233. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144234. _vq_quantthresh__16u1__p9_1,
  144235. _vq_quantmap__16u1__p9_1,
  144236. 15,
  144237. 15
  144238. };
  144239. static static_codebook _16u1__p9_1 = {
  144240. 2, 225,
  144241. _vq_lengthlist__16u1__p9_1,
  144242. 1, -522338304, 1620115456, 4, 0,
  144243. _vq_quantlist__16u1__p9_1,
  144244. NULL,
  144245. &_vq_auxt__16u1__p9_1,
  144246. NULL,
  144247. 0
  144248. };
  144249. static long _vq_quantlist__16u1__p9_2[] = {
  144250. 8,
  144251. 7,
  144252. 9,
  144253. 6,
  144254. 10,
  144255. 5,
  144256. 11,
  144257. 4,
  144258. 12,
  144259. 3,
  144260. 13,
  144261. 2,
  144262. 14,
  144263. 1,
  144264. 15,
  144265. 0,
  144266. 16,
  144267. };
  144268. static long _vq_lengthlist__16u1__p9_2[] = {
  144269. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144270. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144271. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144272. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144273. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144274. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144275. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144276. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144277. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144278. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144279. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144280. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144281. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144282. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144283. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144284. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144285. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144286. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144287. 10,
  144288. };
  144289. static float _vq_quantthresh__16u1__p9_2[] = {
  144290. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144291. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144292. };
  144293. static long _vq_quantmap__16u1__p9_2[] = {
  144294. 15, 13, 11, 9, 7, 5, 3, 1,
  144295. 0, 2, 4, 6, 8, 10, 12, 14,
  144296. 16,
  144297. };
  144298. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144299. _vq_quantthresh__16u1__p9_2,
  144300. _vq_quantmap__16u1__p9_2,
  144301. 17,
  144302. 17
  144303. };
  144304. static static_codebook _16u1__p9_2 = {
  144305. 2, 289,
  144306. _vq_lengthlist__16u1__p9_2,
  144307. 1, -529530880, 1611661312, 5, 0,
  144308. _vq_quantlist__16u1__p9_2,
  144309. NULL,
  144310. &_vq_auxt__16u1__p9_2,
  144311. NULL,
  144312. 0
  144313. };
  144314. static long _huff_lengthlist__16u1__short[] = {
  144315. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144316. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144317. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144318. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144319. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144320. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144321. 16,16,16,16,
  144322. };
  144323. static static_codebook _huff_book__16u1__short = {
  144324. 2, 100,
  144325. _huff_lengthlist__16u1__short,
  144326. 0, 0, 0, 0, 0,
  144327. NULL,
  144328. NULL,
  144329. NULL,
  144330. NULL,
  144331. 0
  144332. };
  144333. static long _huff_lengthlist__16u2__long[] = {
  144334. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144335. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144336. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144337. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144338. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144339. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144340. 13,14,18,18,
  144341. };
  144342. static static_codebook _huff_book__16u2__long = {
  144343. 2, 100,
  144344. _huff_lengthlist__16u2__long,
  144345. 0, 0, 0, 0, 0,
  144346. NULL,
  144347. NULL,
  144348. NULL,
  144349. NULL,
  144350. 0
  144351. };
  144352. static long _huff_lengthlist__16u2__short[] = {
  144353. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144354. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144355. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144356. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144357. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144358. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144359. 16,16,16,16,
  144360. };
  144361. static static_codebook _huff_book__16u2__short = {
  144362. 2, 100,
  144363. _huff_lengthlist__16u2__short,
  144364. 0, 0, 0, 0, 0,
  144365. NULL,
  144366. NULL,
  144367. NULL,
  144368. NULL,
  144369. 0
  144370. };
  144371. static long _vq_quantlist__16u2_p1_0[] = {
  144372. 1,
  144373. 0,
  144374. 2,
  144375. };
  144376. static long _vq_lengthlist__16u2_p1_0[] = {
  144377. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144378. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144379. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144380. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144381. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144382. 10,
  144383. };
  144384. static float _vq_quantthresh__16u2_p1_0[] = {
  144385. -0.5, 0.5,
  144386. };
  144387. static long _vq_quantmap__16u2_p1_0[] = {
  144388. 1, 0, 2,
  144389. };
  144390. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144391. _vq_quantthresh__16u2_p1_0,
  144392. _vq_quantmap__16u2_p1_0,
  144393. 3,
  144394. 3
  144395. };
  144396. static static_codebook _16u2_p1_0 = {
  144397. 4, 81,
  144398. _vq_lengthlist__16u2_p1_0,
  144399. 1, -535822336, 1611661312, 2, 0,
  144400. _vq_quantlist__16u2_p1_0,
  144401. NULL,
  144402. &_vq_auxt__16u2_p1_0,
  144403. NULL,
  144404. 0
  144405. };
  144406. static long _vq_quantlist__16u2_p2_0[] = {
  144407. 2,
  144408. 1,
  144409. 3,
  144410. 0,
  144411. 4,
  144412. };
  144413. static long _vq_lengthlist__16u2_p2_0[] = {
  144414. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144415. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144416. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144417. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144418. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144419. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144420. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144421. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144422. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144423. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144424. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144425. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144426. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144427. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144428. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144429. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144430. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144431. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144432. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144433. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144434. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144435. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144436. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144437. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144438. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144439. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144440. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144441. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144442. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144443. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144444. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144445. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144446. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144447. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144448. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144449. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144450. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144451. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144452. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144453. 13,
  144454. };
  144455. static float _vq_quantthresh__16u2_p2_0[] = {
  144456. -1.5, -0.5, 0.5, 1.5,
  144457. };
  144458. static long _vq_quantmap__16u2_p2_0[] = {
  144459. 3, 1, 0, 2, 4,
  144460. };
  144461. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144462. _vq_quantthresh__16u2_p2_0,
  144463. _vq_quantmap__16u2_p2_0,
  144464. 5,
  144465. 5
  144466. };
  144467. static static_codebook _16u2_p2_0 = {
  144468. 4, 625,
  144469. _vq_lengthlist__16u2_p2_0,
  144470. 1, -533725184, 1611661312, 3, 0,
  144471. _vq_quantlist__16u2_p2_0,
  144472. NULL,
  144473. &_vq_auxt__16u2_p2_0,
  144474. NULL,
  144475. 0
  144476. };
  144477. static long _vq_quantlist__16u2_p3_0[] = {
  144478. 4,
  144479. 3,
  144480. 5,
  144481. 2,
  144482. 6,
  144483. 1,
  144484. 7,
  144485. 0,
  144486. 8,
  144487. };
  144488. static long _vq_lengthlist__16u2_p3_0[] = {
  144489. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144490. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144491. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144492. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144493. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144494. 11,
  144495. };
  144496. static float _vq_quantthresh__16u2_p3_0[] = {
  144497. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144498. };
  144499. static long _vq_quantmap__16u2_p3_0[] = {
  144500. 7, 5, 3, 1, 0, 2, 4, 6,
  144501. 8,
  144502. };
  144503. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144504. _vq_quantthresh__16u2_p3_0,
  144505. _vq_quantmap__16u2_p3_0,
  144506. 9,
  144507. 9
  144508. };
  144509. static static_codebook _16u2_p3_0 = {
  144510. 2, 81,
  144511. _vq_lengthlist__16u2_p3_0,
  144512. 1, -531628032, 1611661312, 4, 0,
  144513. _vq_quantlist__16u2_p3_0,
  144514. NULL,
  144515. &_vq_auxt__16u2_p3_0,
  144516. NULL,
  144517. 0
  144518. };
  144519. static long _vq_quantlist__16u2_p4_0[] = {
  144520. 8,
  144521. 7,
  144522. 9,
  144523. 6,
  144524. 10,
  144525. 5,
  144526. 11,
  144527. 4,
  144528. 12,
  144529. 3,
  144530. 13,
  144531. 2,
  144532. 14,
  144533. 1,
  144534. 15,
  144535. 0,
  144536. 16,
  144537. };
  144538. static long _vq_lengthlist__16u2_p4_0[] = {
  144539. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144540. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144541. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144542. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144543. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144544. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144545. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144546. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144547. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144548. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144549. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144550. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144551. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144552. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144553. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144554. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144555. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144556. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144557. 14,
  144558. };
  144559. static float _vq_quantthresh__16u2_p4_0[] = {
  144560. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144561. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144562. };
  144563. static long _vq_quantmap__16u2_p4_0[] = {
  144564. 15, 13, 11, 9, 7, 5, 3, 1,
  144565. 0, 2, 4, 6, 8, 10, 12, 14,
  144566. 16,
  144567. };
  144568. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144569. _vq_quantthresh__16u2_p4_0,
  144570. _vq_quantmap__16u2_p4_0,
  144571. 17,
  144572. 17
  144573. };
  144574. static static_codebook _16u2_p4_0 = {
  144575. 2, 289,
  144576. _vq_lengthlist__16u2_p4_0,
  144577. 1, -529530880, 1611661312, 5, 0,
  144578. _vq_quantlist__16u2_p4_0,
  144579. NULL,
  144580. &_vq_auxt__16u2_p4_0,
  144581. NULL,
  144582. 0
  144583. };
  144584. static long _vq_quantlist__16u2_p5_0[] = {
  144585. 1,
  144586. 0,
  144587. 2,
  144588. };
  144589. static long _vq_lengthlist__16u2_p5_0[] = {
  144590. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144591. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144592. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144593. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144594. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144595. 10,
  144596. };
  144597. static float _vq_quantthresh__16u2_p5_0[] = {
  144598. -5.5, 5.5,
  144599. };
  144600. static long _vq_quantmap__16u2_p5_0[] = {
  144601. 1, 0, 2,
  144602. };
  144603. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144604. _vq_quantthresh__16u2_p5_0,
  144605. _vq_quantmap__16u2_p5_0,
  144606. 3,
  144607. 3
  144608. };
  144609. static static_codebook _16u2_p5_0 = {
  144610. 4, 81,
  144611. _vq_lengthlist__16u2_p5_0,
  144612. 1, -529137664, 1618345984, 2, 0,
  144613. _vq_quantlist__16u2_p5_0,
  144614. NULL,
  144615. &_vq_auxt__16u2_p5_0,
  144616. NULL,
  144617. 0
  144618. };
  144619. static long _vq_quantlist__16u2_p5_1[] = {
  144620. 5,
  144621. 4,
  144622. 6,
  144623. 3,
  144624. 7,
  144625. 2,
  144626. 8,
  144627. 1,
  144628. 9,
  144629. 0,
  144630. 10,
  144631. };
  144632. static long _vq_lengthlist__16u2_p5_1[] = {
  144633. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144634. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144635. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144636. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144637. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144638. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144639. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144640. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144641. };
  144642. static float _vq_quantthresh__16u2_p5_1[] = {
  144643. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144644. 3.5, 4.5,
  144645. };
  144646. static long _vq_quantmap__16u2_p5_1[] = {
  144647. 9, 7, 5, 3, 1, 0, 2, 4,
  144648. 6, 8, 10,
  144649. };
  144650. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144651. _vq_quantthresh__16u2_p5_1,
  144652. _vq_quantmap__16u2_p5_1,
  144653. 11,
  144654. 11
  144655. };
  144656. static static_codebook _16u2_p5_1 = {
  144657. 2, 121,
  144658. _vq_lengthlist__16u2_p5_1,
  144659. 1, -531365888, 1611661312, 4, 0,
  144660. _vq_quantlist__16u2_p5_1,
  144661. NULL,
  144662. &_vq_auxt__16u2_p5_1,
  144663. NULL,
  144664. 0
  144665. };
  144666. static long _vq_quantlist__16u2_p6_0[] = {
  144667. 6,
  144668. 5,
  144669. 7,
  144670. 4,
  144671. 8,
  144672. 3,
  144673. 9,
  144674. 2,
  144675. 10,
  144676. 1,
  144677. 11,
  144678. 0,
  144679. 12,
  144680. };
  144681. static long _vq_lengthlist__16u2_p6_0[] = {
  144682. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144683. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144684. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144685. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144686. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144687. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144688. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144689. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144690. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144691. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144692. 12,13,13,14,14,14,14,15,15,
  144693. };
  144694. static float _vq_quantthresh__16u2_p6_0[] = {
  144695. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144696. 12.5, 17.5, 22.5, 27.5,
  144697. };
  144698. static long _vq_quantmap__16u2_p6_0[] = {
  144699. 11, 9, 7, 5, 3, 1, 0, 2,
  144700. 4, 6, 8, 10, 12,
  144701. };
  144702. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144703. _vq_quantthresh__16u2_p6_0,
  144704. _vq_quantmap__16u2_p6_0,
  144705. 13,
  144706. 13
  144707. };
  144708. static static_codebook _16u2_p6_0 = {
  144709. 2, 169,
  144710. _vq_lengthlist__16u2_p6_0,
  144711. 1, -526516224, 1616117760, 4, 0,
  144712. _vq_quantlist__16u2_p6_0,
  144713. NULL,
  144714. &_vq_auxt__16u2_p6_0,
  144715. NULL,
  144716. 0
  144717. };
  144718. static long _vq_quantlist__16u2_p6_1[] = {
  144719. 2,
  144720. 1,
  144721. 3,
  144722. 0,
  144723. 4,
  144724. };
  144725. static long _vq_lengthlist__16u2_p6_1[] = {
  144726. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144727. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144728. };
  144729. static float _vq_quantthresh__16u2_p6_1[] = {
  144730. -1.5, -0.5, 0.5, 1.5,
  144731. };
  144732. static long _vq_quantmap__16u2_p6_1[] = {
  144733. 3, 1, 0, 2, 4,
  144734. };
  144735. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144736. _vq_quantthresh__16u2_p6_1,
  144737. _vq_quantmap__16u2_p6_1,
  144738. 5,
  144739. 5
  144740. };
  144741. static static_codebook _16u2_p6_1 = {
  144742. 2, 25,
  144743. _vq_lengthlist__16u2_p6_1,
  144744. 1, -533725184, 1611661312, 3, 0,
  144745. _vq_quantlist__16u2_p6_1,
  144746. NULL,
  144747. &_vq_auxt__16u2_p6_1,
  144748. NULL,
  144749. 0
  144750. };
  144751. static long _vq_quantlist__16u2_p7_0[] = {
  144752. 6,
  144753. 5,
  144754. 7,
  144755. 4,
  144756. 8,
  144757. 3,
  144758. 9,
  144759. 2,
  144760. 10,
  144761. 1,
  144762. 11,
  144763. 0,
  144764. 12,
  144765. };
  144766. static long _vq_lengthlist__16u2_p7_0[] = {
  144767. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144768. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144769. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144770. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144771. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144772. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144773. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144774. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144775. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144776. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144777. 12,13,13,13,14,14,14,15,14,
  144778. };
  144779. static float _vq_quantthresh__16u2_p7_0[] = {
  144780. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144781. 27.5, 38.5, 49.5, 60.5,
  144782. };
  144783. static long _vq_quantmap__16u2_p7_0[] = {
  144784. 11, 9, 7, 5, 3, 1, 0, 2,
  144785. 4, 6, 8, 10, 12,
  144786. };
  144787. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144788. _vq_quantthresh__16u2_p7_0,
  144789. _vq_quantmap__16u2_p7_0,
  144790. 13,
  144791. 13
  144792. };
  144793. static static_codebook _16u2_p7_0 = {
  144794. 2, 169,
  144795. _vq_lengthlist__16u2_p7_0,
  144796. 1, -523206656, 1618345984, 4, 0,
  144797. _vq_quantlist__16u2_p7_0,
  144798. NULL,
  144799. &_vq_auxt__16u2_p7_0,
  144800. NULL,
  144801. 0
  144802. };
  144803. static long _vq_quantlist__16u2_p7_1[] = {
  144804. 5,
  144805. 4,
  144806. 6,
  144807. 3,
  144808. 7,
  144809. 2,
  144810. 8,
  144811. 1,
  144812. 9,
  144813. 0,
  144814. 10,
  144815. };
  144816. static long _vq_lengthlist__16u2_p7_1[] = {
  144817. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144818. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144819. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144820. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144821. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144822. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144823. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144824. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144825. };
  144826. static float _vq_quantthresh__16u2_p7_1[] = {
  144827. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144828. 3.5, 4.5,
  144829. };
  144830. static long _vq_quantmap__16u2_p7_1[] = {
  144831. 9, 7, 5, 3, 1, 0, 2, 4,
  144832. 6, 8, 10,
  144833. };
  144834. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144835. _vq_quantthresh__16u2_p7_1,
  144836. _vq_quantmap__16u2_p7_1,
  144837. 11,
  144838. 11
  144839. };
  144840. static static_codebook _16u2_p7_1 = {
  144841. 2, 121,
  144842. _vq_lengthlist__16u2_p7_1,
  144843. 1, -531365888, 1611661312, 4, 0,
  144844. _vq_quantlist__16u2_p7_1,
  144845. NULL,
  144846. &_vq_auxt__16u2_p7_1,
  144847. NULL,
  144848. 0
  144849. };
  144850. static long _vq_quantlist__16u2_p8_0[] = {
  144851. 7,
  144852. 6,
  144853. 8,
  144854. 5,
  144855. 9,
  144856. 4,
  144857. 10,
  144858. 3,
  144859. 11,
  144860. 2,
  144861. 12,
  144862. 1,
  144863. 13,
  144864. 0,
  144865. 14,
  144866. };
  144867. static long _vq_lengthlist__16u2_p8_0[] = {
  144868. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144869. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144870. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144871. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144872. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144873. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144874. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144875. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144876. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144877. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144878. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144879. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144880. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144881. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144882. 14,
  144883. };
  144884. static float _vq_quantthresh__16u2_p8_0[] = {
  144885. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144886. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144887. };
  144888. static long _vq_quantmap__16u2_p8_0[] = {
  144889. 13, 11, 9, 7, 5, 3, 1, 0,
  144890. 2, 4, 6, 8, 10, 12, 14,
  144891. };
  144892. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144893. _vq_quantthresh__16u2_p8_0,
  144894. _vq_quantmap__16u2_p8_0,
  144895. 15,
  144896. 15
  144897. };
  144898. static static_codebook _16u2_p8_0 = {
  144899. 2, 225,
  144900. _vq_lengthlist__16u2_p8_0,
  144901. 1, -520986624, 1620377600, 4, 0,
  144902. _vq_quantlist__16u2_p8_0,
  144903. NULL,
  144904. &_vq_auxt__16u2_p8_0,
  144905. NULL,
  144906. 0
  144907. };
  144908. static long _vq_quantlist__16u2_p8_1[] = {
  144909. 10,
  144910. 9,
  144911. 11,
  144912. 8,
  144913. 12,
  144914. 7,
  144915. 13,
  144916. 6,
  144917. 14,
  144918. 5,
  144919. 15,
  144920. 4,
  144921. 16,
  144922. 3,
  144923. 17,
  144924. 2,
  144925. 18,
  144926. 1,
  144927. 19,
  144928. 0,
  144929. 20,
  144930. };
  144931. static long _vq_lengthlist__16u2_p8_1[] = {
  144932. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144933. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144934. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144935. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144936. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144937. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144938. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144939. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144940. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144941. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144942. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144943. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144944. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144945. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144946. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144947. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144948. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144949. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144950. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144951. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144952. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144953. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144954. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144955. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144957. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144958. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144959. 11,11,10,11,11,11,10,11,11,
  144960. };
  144961. static float _vq_quantthresh__16u2_p8_1[] = {
  144962. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144963. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144964. 6.5, 7.5, 8.5, 9.5,
  144965. };
  144966. static long _vq_quantmap__16u2_p8_1[] = {
  144967. 19, 17, 15, 13, 11, 9, 7, 5,
  144968. 3, 1, 0, 2, 4, 6, 8, 10,
  144969. 12, 14, 16, 18, 20,
  144970. };
  144971. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144972. _vq_quantthresh__16u2_p8_1,
  144973. _vq_quantmap__16u2_p8_1,
  144974. 21,
  144975. 21
  144976. };
  144977. static static_codebook _16u2_p8_1 = {
  144978. 2, 441,
  144979. _vq_lengthlist__16u2_p8_1,
  144980. 1, -529268736, 1611661312, 5, 0,
  144981. _vq_quantlist__16u2_p8_1,
  144982. NULL,
  144983. &_vq_auxt__16u2_p8_1,
  144984. NULL,
  144985. 0
  144986. };
  144987. static long _vq_quantlist__16u2_p9_0[] = {
  144988. 5586,
  144989. 4655,
  144990. 6517,
  144991. 3724,
  144992. 7448,
  144993. 2793,
  144994. 8379,
  144995. 1862,
  144996. 9310,
  144997. 931,
  144998. 10241,
  144999. 0,
  145000. 11172,
  145001. 5521,
  145002. 5651,
  145003. };
  145004. static long _vq_lengthlist__16u2_p9_0[] = {
  145005. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  145006. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145007. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145008. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145009. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145010. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145011. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145012. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145013. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145014. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145015. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145016. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145017. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  145018. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  145019. 5,
  145020. };
  145021. static float _vq_quantthresh__16u2_p9_0[] = {
  145022. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  145023. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  145024. };
  145025. static long _vq_quantmap__16u2_p9_0[] = {
  145026. 11, 9, 7, 5, 3, 1, 13, 0,
  145027. 14, 2, 4, 6, 8, 10, 12,
  145028. };
  145029. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  145030. _vq_quantthresh__16u2_p9_0,
  145031. _vq_quantmap__16u2_p9_0,
  145032. 15,
  145033. 15
  145034. };
  145035. static static_codebook _16u2_p9_0 = {
  145036. 2, 225,
  145037. _vq_lengthlist__16u2_p9_0,
  145038. 1, -510275072, 1611661312, 14, 0,
  145039. _vq_quantlist__16u2_p9_0,
  145040. NULL,
  145041. &_vq_auxt__16u2_p9_0,
  145042. NULL,
  145043. 0
  145044. };
  145045. static long _vq_quantlist__16u2_p9_1[] = {
  145046. 392,
  145047. 343,
  145048. 441,
  145049. 294,
  145050. 490,
  145051. 245,
  145052. 539,
  145053. 196,
  145054. 588,
  145055. 147,
  145056. 637,
  145057. 98,
  145058. 686,
  145059. 49,
  145060. 735,
  145061. 0,
  145062. 784,
  145063. 388,
  145064. 396,
  145065. };
  145066. static long _vq_lengthlist__16u2_p9_1[] = {
  145067. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  145068. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  145069. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  145070. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  145071. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  145072. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  145073. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145074. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  145075. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  145076. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145077. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145078. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145079. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145080. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145081. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  145082. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145083. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145084. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145085. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145086. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145087. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  145088. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  145089. 11,11,11,11,11,11,11, 5, 4,
  145090. };
  145091. static float _vq_quantthresh__16u2_p9_1[] = {
  145092. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  145093. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  145094. 318.5, 367.5,
  145095. };
  145096. static long _vq_quantmap__16u2_p9_1[] = {
  145097. 15, 13, 11, 9, 7, 5, 3, 1,
  145098. 17, 0, 18, 2, 4, 6, 8, 10,
  145099. 12, 14, 16,
  145100. };
  145101. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  145102. _vq_quantthresh__16u2_p9_1,
  145103. _vq_quantmap__16u2_p9_1,
  145104. 19,
  145105. 19
  145106. };
  145107. static static_codebook _16u2_p9_1 = {
  145108. 2, 361,
  145109. _vq_lengthlist__16u2_p9_1,
  145110. 1, -518488064, 1611661312, 10, 0,
  145111. _vq_quantlist__16u2_p9_1,
  145112. NULL,
  145113. &_vq_auxt__16u2_p9_1,
  145114. NULL,
  145115. 0
  145116. };
  145117. static long _vq_quantlist__16u2_p9_2[] = {
  145118. 24,
  145119. 23,
  145120. 25,
  145121. 22,
  145122. 26,
  145123. 21,
  145124. 27,
  145125. 20,
  145126. 28,
  145127. 19,
  145128. 29,
  145129. 18,
  145130. 30,
  145131. 17,
  145132. 31,
  145133. 16,
  145134. 32,
  145135. 15,
  145136. 33,
  145137. 14,
  145138. 34,
  145139. 13,
  145140. 35,
  145141. 12,
  145142. 36,
  145143. 11,
  145144. 37,
  145145. 10,
  145146. 38,
  145147. 9,
  145148. 39,
  145149. 8,
  145150. 40,
  145151. 7,
  145152. 41,
  145153. 6,
  145154. 42,
  145155. 5,
  145156. 43,
  145157. 4,
  145158. 44,
  145159. 3,
  145160. 45,
  145161. 2,
  145162. 46,
  145163. 1,
  145164. 47,
  145165. 0,
  145166. 48,
  145167. };
  145168. static long _vq_lengthlist__16u2_p9_2[] = {
  145169. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145170. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145171. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145172. 11,
  145173. };
  145174. static float _vq_quantthresh__16u2_p9_2[] = {
  145175. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145176. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145177. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145178. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145179. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145180. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145181. };
  145182. static long _vq_quantmap__16u2_p9_2[] = {
  145183. 47, 45, 43, 41, 39, 37, 35, 33,
  145184. 31, 29, 27, 25, 23, 21, 19, 17,
  145185. 15, 13, 11, 9, 7, 5, 3, 1,
  145186. 0, 2, 4, 6, 8, 10, 12, 14,
  145187. 16, 18, 20, 22, 24, 26, 28, 30,
  145188. 32, 34, 36, 38, 40, 42, 44, 46,
  145189. 48,
  145190. };
  145191. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145192. _vq_quantthresh__16u2_p9_2,
  145193. _vq_quantmap__16u2_p9_2,
  145194. 49,
  145195. 49
  145196. };
  145197. static static_codebook _16u2_p9_2 = {
  145198. 1, 49,
  145199. _vq_lengthlist__16u2_p9_2,
  145200. 1, -526909440, 1611661312, 6, 0,
  145201. _vq_quantlist__16u2_p9_2,
  145202. NULL,
  145203. &_vq_auxt__16u2_p9_2,
  145204. NULL,
  145205. 0
  145206. };
  145207. static long _vq_quantlist__8u0__p1_0[] = {
  145208. 1,
  145209. 0,
  145210. 2,
  145211. };
  145212. static long _vq_lengthlist__8u0__p1_0[] = {
  145213. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145214. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145215. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145216. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145217. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145218. 11,
  145219. };
  145220. static float _vq_quantthresh__8u0__p1_0[] = {
  145221. -0.5, 0.5,
  145222. };
  145223. static long _vq_quantmap__8u0__p1_0[] = {
  145224. 1, 0, 2,
  145225. };
  145226. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145227. _vq_quantthresh__8u0__p1_0,
  145228. _vq_quantmap__8u0__p1_0,
  145229. 3,
  145230. 3
  145231. };
  145232. static static_codebook _8u0__p1_0 = {
  145233. 4, 81,
  145234. _vq_lengthlist__8u0__p1_0,
  145235. 1, -535822336, 1611661312, 2, 0,
  145236. _vq_quantlist__8u0__p1_0,
  145237. NULL,
  145238. &_vq_auxt__8u0__p1_0,
  145239. NULL,
  145240. 0
  145241. };
  145242. static long _vq_quantlist__8u0__p2_0[] = {
  145243. 1,
  145244. 0,
  145245. 2,
  145246. };
  145247. static long _vq_lengthlist__8u0__p2_0[] = {
  145248. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145249. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145250. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145251. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145252. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145253. 8,
  145254. };
  145255. static float _vq_quantthresh__8u0__p2_0[] = {
  145256. -0.5, 0.5,
  145257. };
  145258. static long _vq_quantmap__8u0__p2_0[] = {
  145259. 1, 0, 2,
  145260. };
  145261. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145262. _vq_quantthresh__8u0__p2_0,
  145263. _vq_quantmap__8u0__p2_0,
  145264. 3,
  145265. 3
  145266. };
  145267. static static_codebook _8u0__p2_0 = {
  145268. 4, 81,
  145269. _vq_lengthlist__8u0__p2_0,
  145270. 1, -535822336, 1611661312, 2, 0,
  145271. _vq_quantlist__8u0__p2_0,
  145272. NULL,
  145273. &_vq_auxt__8u0__p2_0,
  145274. NULL,
  145275. 0
  145276. };
  145277. static long _vq_quantlist__8u0__p3_0[] = {
  145278. 2,
  145279. 1,
  145280. 3,
  145281. 0,
  145282. 4,
  145283. };
  145284. static long _vq_lengthlist__8u0__p3_0[] = {
  145285. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145286. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145287. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145288. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145289. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145290. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145291. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145292. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145293. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145294. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145295. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145296. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145297. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145298. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145299. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145300. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145301. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145302. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145303. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145304. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145305. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145306. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145307. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145308. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145309. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145310. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145311. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145312. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145313. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145314. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145315. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145316. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145317. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145318. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145319. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145320. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145321. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145322. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145323. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145324. 16,
  145325. };
  145326. static float _vq_quantthresh__8u0__p3_0[] = {
  145327. -1.5, -0.5, 0.5, 1.5,
  145328. };
  145329. static long _vq_quantmap__8u0__p3_0[] = {
  145330. 3, 1, 0, 2, 4,
  145331. };
  145332. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145333. _vq_quantthresh__8u0__p3_0,
  145334. _vq_quantmap__8u0__p3_0,
  145335. 5,
  145336. 5
  145337. };
  145338. static static_codebook _8u0__p3_0 = {
  145339. 4, 625,
  145340. _vq_lengthlist__8u0__p3_0,
  145341. 1, -533725184, 1611661312, 3, 0,
  145342. _vq_quantlist__8u0__p3_0,
  145343. NULL,
  145344. &_vq_auxt__8u0__p3_0,
  145345. NULL,
  145346. 0
  145347. };
  145348. static long _vq_quantlist__8u0__p4_0[] = {
  145349. 2,
  145350. 1,
  145351. 3,
  145352. 0,
  145353. 4,
  145354. };
  145355. static long _vq_lengthlist__8u0__p4_0[] = {
  145356. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145357. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145358. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145359. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145360. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145361. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145362. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145363. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145364. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145365. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145366. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145367. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145368. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145369. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145370. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145371. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145372. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145373. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145374. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145375. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145376. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145377. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145378. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145379. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145380. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145381. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145382. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145383. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145384. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145385. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145386. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145387. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145388. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145389. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145390. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145391. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145392. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145393. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145394. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145395. 12,
  145396. };
  145397. static float _vq_quantthresh__8u0__p4_0[] = {
  145398. -1.5, -0.5, 0.5, 1.5,
  145399. };
  145400. static long _vq_quantmap__8u0__p4_0[] = {
  145401. 3, 1, 0, 2, 4,
  145402. };
  145403. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145404. _vq_quantthresh__8u0__p4_0,
  145405. _vq_quantmap__8u0__p4_0,
  145406. 5,
  145407. 5
  145408. };
  145409. static static_codebook _8u0__p4_0 = {
  145410. 4, 625,
  145411. _vq_lengthlist__8u0__p4_0,
  145412. 1, -533725184, 1611661312, 3, 0,
  145413. _vq_quantlist__8u0__p4_0,
  145414. NULL,
  145415. &_vq_auxt__8u0__p4_0,
  145416. NULL,
  145417. 0
  145418. };
  145419. static long _vq_quantlist__8u0__p5_0[] = {
  145420. 4,
  145421. 3,
  145422. 5,
  145423. 2,
  145424. 6,
  145425. 1,
  145426. 7,
  145427. 0,
  145428. 8,
  145429. };
  145430. static long _vq_lengthlist__8u0__p5_0[] = {
  145431. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145432. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145433. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145434. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145435. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145436. 12,
  145437. };
  145438. static float _vq_quantthresh__8u0__p5_0[] = {
  145439. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145440. };
  145441. static long _vq_quantmap__8u0__p5_0[] = {
  145442. 7, 5, 3, 1, 0, 2, 4, 6,
  145443. 8,
  145444. };
  145445. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145446. _vq_quantthresh__8u0__p5_0,
  145447. _vq_quantmap__8u0__p5_0,
  145448. 9,
  145449. 9
  145450. };
  145451. static static_codebook _8u0__p5_0 = {
  145452. 2, 81,
  145453. _vq_lengthlist__8u0__p5_0,
  145454. 1, -531628032, 1611661312, 4, 0,
  145455. _vq_quantlist__8u0__p5_0,
  145456. NULL,
  145457. &_vq_auxt__8u0__p5_0,
  145458. NULL,
  145459. 0
  145460. };
  145461. static long _vq_quantlist__8u0__p6_0[] = {
  145462. 6,
  145463. 5,
  145464. 7,
  145465. 4,
  145466. 8,
  145467. 3,
  145468. 9,
  145469. 2,
  145470. 10,
  145471. 1,
  145472. 11,
  145473. 0,
  145474. 12,
  145475. };
  145476. static long _vq_lengthlist__8u0__p6_0[] = {
  145477. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145478. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145479. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145480. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145481. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145482. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145483. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145484. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145485. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145486. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145487. 16, 0,15, 0,17, 0, 0, 0, 0,
  145488. };
  145489. static float _vq_quantthresh__8u0__p6_0[] = {
  145490. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145491. 12.5, 17.5, 22.5, 27.5,
  145492. };
  145493. static long _vq_quantmap__8u0__p6_0[] = {
  145494. 11, 9, 7, 5, 3, 1, 0, 2,
  145495. 4, 6, 8, 10, 12,
  145496. };
  145497. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145498. _vq_quantthresh__8u0__p6_0,
  145499. _vq_quantmap__8u0__p6_0,
  145500. 13,
  145501. 13
  145502. };
  145503. static static_codebook _8u0__p6_0 = {
  145504. 2, 169,
  145505. _vq_lengthlist__8u0__p6_0,
  145506. 1, -526516224, 1616117760, 4, 0,
  145507. _vq_quantlist__8u0__p6_0,
  145508. NULL,
  145509. &_vq_auxt__8u0__p6_0,
  145510. NULL,
  145511. 0
  145512. };
  145513. static long _vq_quantlist__8u0__p6_1[] = {
  145514. 2,
  145515. 1,
  145516. 3,
  145517. 0,
  145518. 4,
  145519. };
  145520. static long _vq_lengthlist__8u0__p6_1[] = {
  145521. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145522. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145523. };
  145524. static float _vq_quantthresh__8u0__p6_1[] = {
  145525. -1.5, -0.5, 0.5, 1.5,
  145526. };
  145527. static long _vq_quantmap__8u0__p6_1[] = {
  145528. 3, 1, 0, 2, 4,
  145529. };
  145530. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145531. _vq_quantthresh__8u0__p6_1,
  145532. _vq_quantmap__8u0__p6_1,
  145533. 5,
  145534. 5
  145535. };
  145536. static static_codebook _8u0__p6_1 = {
  145537. 2, 25,
  145538. _vq_lengthlist__8u0__p6_1,
  145539. 1, -533725184, 1611661312, 3, 0,
  145540. _vq_quantlist__8u0__p6_1,
  145541. NULL,
  145542. &_vq_auxt__8u0__p6_1,
  145543. NULL,
  145544. 0
  145545. };
  145546. static long _vq_quantlist__8u0__p7_0[] = {
  145547. 1,
  145548. 0,
  145549. 2,
  145550. };
  145551. static long _vq_lengthlist__8u0__p7_0[] = {
  145552. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145553. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145554. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145555. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145556. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145557. 7,
  145558. };
  145559. static float _vq_quantthresh__8u0__p7_0[] = {
  145560. -157.5, 157.5,
  145561. };
  145562. static long _vq_quantmap__8u0__p7_0[] = {
  145563. 1, 0, 2,
  145564. };
  145565. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145566. _vq_quantthresh__8u0__p7_0,
  145567. _vq_quantmap__8u0__p7_0,
  145568. 3,
  145569. 3
  145570. };
  145571. static static_codebook _8u0__p7_0 = {
  145572. 4, 81,
  145573. _vq_lengthlist__8u0__p7_0,
  145574. 1, -518803456, 1628680192, 2, 0,
  145575. _vq_quantlist__8u0__p7_0,
  145576. NULL,
  145577. &_vq_auxt__8u0__p7_0,
  145578. NULL,
  145579. 0
  145580. };
  145581. static long _vq_quantlist__8u0__p7_1[] = {
  145582. 7,
  145583. 6,
  145584. 8,
  145585. 5,
  145586. 9,
  145587. 4,
  145588. 10,
  145589. 3,
  145590. 11,
  145591. 2,
  145592. 12,
  145593. 1,
  145594. 13,
  145595. 0,
  145596. 14,
  145597. };
  145598. static long _vq_lengthlist__8u0__p7_1[] = {
  145599. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145600. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145601. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145602. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145603. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145604. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145611. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145612. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145613. 10,
  145614. };
  145615. static float _vq_quantthresh__8u0__p7_1[] = {
  145616. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145617. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145618. };
  145619. static long _vq_quantmap__8u0__p7_1[] = {
  145620. 13, 11, 9, 7, 5, 3, 1, 0,
  145621. 2, 4, 6, 8, 10, 12, 14,
  145622. };
  145623. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145624. _vq_quantthresh__8u0__p7_1,
  145625. _vq_quantmap__8u0__p7_1,
  145626. 15,
  145627. 15
  145628. };
  145629. static static_codebook _8u0__p7_1 = {
  145630. 2, 225,
  145631. _vq_lengthlist__8u0__p7_1,
  145632. 1, -520986624, 1620377600, 4, 0,
  145633. _vq_quantlist__8u0__p7_1,
  145634. NULL,
  145635. &_vq_auxt__8u0__p7_1,
  145636. NULL,
  145637. 0
  145638. };
  145639. static long _vq_quantlist__8u0__p7_2[] = {
  145640. 10,
  145641. 9,
  145642. 11,
  145643. 8,
  145644. 12,
  145645. 7,
  145646. 13,
  145647. 6,
  145648. 14,
  145649. 5,
  145650. 15,
  145651. 4,
  145652. 16,
  145653. 3,
  145654. 17,
  145655. 2,
  145656. 18,
  145657. 1,
  145658. 19,
  145659. 0,
  145660. 20,
  145661. };
  145662. static long _vq_lengthlist__8u0__p7_2[] = {
  145663. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145664. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145665. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145666. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145667. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145668. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145669. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145670. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145671. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145672. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145673. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145674. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145675. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145676. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145677. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145678. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145679. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145680. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145681. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145682. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145683. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145684. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145685. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145686. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145687. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145688. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145689. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145690. 11,12,11,11,11,10,10,11,11,
  145691. };
  145692. static float _vq_quantthresh__8u0__p7_2[] = {
  145693. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145694. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145695. 6.5, 7.5, 8.5, 9.5,
  145696. };
  145697. static long _vq_quantmap__8u0__p7_2[] = {
  145698. 19, 17, 15, 13, 11, 9, 7, 5,
  145699. 3, 1, 0, 2, 4, 6, 8, 10,
  145700. 12, 14, 16, 18, 20,
  145701. };
  145702. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145703. _vq_quantthresh__8u0__p7_2,
  145704. _vq_quantmap__8u0__p7_2,
  145705. 21,
  145706. 21
  145707. };
  145708. static static_codebook _8u0__p7_2 = {
  145709. 2, 441,
  145710. _vq_lengthlist__8u0__p7_2,
  145711. 1, -529268736, 1611661312, 5, 0,
  145712. _vq_quantlist__8u0__p7_2,
  145713. NULL,
  145714. &_vq_auxt__8u0__p7_2,
  145715. NULL,
  145716. 0
  145717. };
  145718. static long _huff_lengthlist__8u0__single[] = {
  145719. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145720. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145721. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145722. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145723. };
  145724. static static_codebook _huff_book__8u0__single = {
  145725. 2, 64,
  145726. _huff_lengthlist__8u0__single,
  145727. 0, 0, 0, 0, 0,
  145728. NULL,
  145729. NULL,
  145730. NULL,
  145731. NULL,
  145732. 0
  145733. };
  145734. static long _vq_quantlist__8u1__p1_0[] = {
  145735. 1,
  145736. 0,
  145737. 2,
  145738. };
  145739. static long _vq_lengthlist__8u1__p1_0[] = {
  145740. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145741. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145742. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145743. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145744. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145745. 10,
  145746. };
  145747. static float _vq_quantthresh__8u1__p1_0[] = {
  145748. -0.5, 0.5,
  145749. };
  145750. static long _vq_quantmap__8u1__p1_0[] = {
  145751. 1, 0, 2,
  145752. };
  145753. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145754. _vq_quantthresh__8u1__p1_0,
  145755. _vq_quantmap__8u1__p1_0,
  145756. 3,
  145757. 3
  145758. };
  145759. static static_codebook _8u1__p1_0 = {
  145760. 4, 81,
  145761. _vq_lengthlist__8u1__p1_0,
  145762. 1, -535822336, 1611661312, 2, 0,
  145763. _vq_quantlist__8u1__p1_0,
  145764. NULL,
  145765. &_vq_auxt__8u1__p1_0,
  145766. NULL,
  145767. 0
  145768. };
  145769. static long _vq_quantlist__8u1__p2_0[] = {
  145770. 1,
  145771. 0,
  145772. 2,
  145773. };
  145774. static long _vq_lengthlist__8u1__p2_0[] = {
  145775. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145776. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145777. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145778. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145779. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145780. 7,
  145781. };
  145782. static float _vq_quantthresh__8u1__p2_0[] = {
  145783. -0.5, 0.5,
  145784. };
  145785. static long _vq_quantmap__8u1__p2_0[] = {
  145786. 1, 0, 2,
  145787. };
  145788. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145789. _vq_quantthresh__8u1__p2_0,
  145790. _vq_quantmap__8u1__p2_0,
  145791. 3,
  145792. 3
  145793. };
  145794. static static_codebook _8u1__p2_0 = {
  145795. 4, 81,
  145796. _vq_lengthlist__8u1__p2_0,
  145797. 1, -535822336, 1611661312, 2, 0,
  145798. _vq_quantlist__8u1__p2_0,
  145799. NULL,
  145800. &_vq_auxt__8u1__p2_0,
  145801. NULL,
  145802. 0
  145803. };
  145804. static long _vq_quantlist__8u1__p3_0[] = {
  145805. 2,
  145806. 1,
  145807. 3,
  145808. 0,
  145809. 4,
  145810. };
  145811. static long _vq_lengthlist__8u1__p3_0[] = {
  145812. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145813. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145814. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145815. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145816. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145817. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145818. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145819. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145820. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145821. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145822. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145823. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145824. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145825. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145826. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145827. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145828. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145829. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145830. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145831. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145832. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145833. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145834. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145835. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145836. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145837. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145838. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145839. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145840. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145841. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145842. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145843. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145844. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145845. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145846. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145847. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145848. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145849. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145850. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145851. 16,
  145852. };
  145853. static float _vq_quantthresh__8u1__p3_0[] = {
  145854. -1.5, -0.5, 0.5, 1.5,
  145855. };
  145856. static long _vq_quantmap__8u1__p3_0[] = {
  145857. 3, 1, 0, 2, 4,
  145858. };
  145859. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145860. _vq_quantthresh__8u1__p3_0,
  145861. _vq_quantmap__8u1__p3_0,
  145862. 5,
  145863. 5
  145864. };
  145865. static static_codebook _8u1__p3_0 = {
  145866. 4, 625,
  145867. _vq_lengthlist__8u1__p3_0,
  145868. 1, -533725184, 1611661312, 3, 0,
  145869. _vq_quantlist__8u1__p3_0,
  145870. NULL,
  145871. &_vq_auxt__8u1__p3_0,
  145872. NULL,
  145873. 0
  145874. };
  145875. static long _vq_quantlist__8u1__p4_0[] = {
  145876. 2,
  145877. 1,
  145878. 3,
  145879. 0,
  145880. 4,
  145881. };
  145882. static long _vq_lengthlist__8u1__p4_0[] = {
  145883. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145884. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145885. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145886. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145887. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145888. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145889. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145890. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145891. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145892. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145893. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145894. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145895. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145896. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145897. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145898. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145899. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145900. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145901. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145902. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145903. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145904. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145905. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145906. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145907. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145908. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145909. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145910. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145911. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145912. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145913. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145914. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145915. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145916. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145917. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145918. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145919. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145920. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145921. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145922. 10,
  145923. };
  145924. static float _vq_quantthresh__8u1__p4_0[] = {
  145925. -1.5, -0.5, 0.5, 1.5,
  145926. };
  145927. static long _vq_quantmap__8u1__p4_0[] = {
  145928. 3, 1, 0, 2, 4,
  145929. };
  145930. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145931. _vq_quantthresh__8u1__p4_0,
  145932. _vq_quantmap__8u1__p4_0,
  145933. 5,
  145934. 5
  145935. };
  145936. static static_codebook _8u1__p4_0 = {
  145937. 4, 625,
  145938. _vq_lengthlist__8u1__p4_0,
  145939. 1, -533725184, 1611661312, 3, 0,
  145940. _vq_quantlist__8u1__p4_0,
  145941. NULL,
  145942. &_vq_auxt__8u1__p4_0,
  145943. NULL,
  145944. 0
  145945. };
  145946. static long _vq_quantlist__8u1__p5_0[] = {
  145947. 4,
  145948. 3,
  145949. 5,
  145950. 2,
  145951. 6,
  145952. 1,
  145953. 7,
  145954. 0,
  145955. 8,
  145956. };
  145957. static long _vq_lengthlist__8u1__p5_0[] = {
  145958. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145959. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145960. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145961. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145962. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145963. 13,
  145964. };
  145965. static float _vq_quantthresh__8u1__p5_0[] = {
  145966. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145967. };
  145968. static long _vq_quantmap__8u1__p5_0[] = {
  145969. 7, 5, 3, 1, 0, 2, 4, 6,
  145970. 8,
  145971. };
  145972. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145973. _vq_quantthresh__8u1__p5_0,
  145974. _vq_quantmap__8u1__p5_0,
  145975. 9,
  145976. 9
  145977. };
  145978. static static_codebook _8u1__p5_0 = {
  145979. 2, 81,
  145980. _vq_lengthlist__8u1__p5_0,
  145981. 1, -531628032, 1611661312, 4, 0,
  145982. _vq_quantlist__8u1__p5_0,
  145983. NULL,
  145984. &_vq_auxt__8u1__p5_0,
  145985. NULL,
  145986. 0
  145987. };
  145988. static long _vq_quantlist__8u1__p6_0[] = {
  145989. 4,
  145990. 3,
  145991. 5,
  145992. 2,
  145993. 6,
  145994. 1,
  145995. 7,
  145996. 0,
  145997. 8,
  145998. };
  145999. static long _vq_lengthlist__8u1__p6_0[] = {
  146000. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  146001. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  146002. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146003. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  146004. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146005. 10,
  146006. };
  146007. static float _vq_quantthresh__8u1__p6_0[] = {
  146008. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146009. };
  146010. static long _vq_quantmap__8u1__p6_0[] = {
  146011. 7, 5, 3, 1, 0, 2, 4, 6,
  146012. 8,
  146013. };
  146014. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  146015. _vq_quantthresh__8u1__p6_0,
  146016. _vq_quantmap__8u1__p6_0,
  146017. 9,
  146018. 9
  146019. };
  146020. static static_codebook _8u1__p6_0 = {
  146021. 2, 81,
  146022. _vq_lengthlist__8u1__p6_0,
  146023. 1, -531628032, 1611661312, 4, 0,
  146024. _vq_quantlist__8u1__p6_0,
  146025. NULL,
  146026. &_vq_auxt__8u1__p6_0,
  146027. NULL,
  146028. 0
  146029. };
  146030. static long _vq_quantlist__8u1__p7_0[] = {
  146031. 1,
  146032. 0,
  146033. 2,
  146034. };
  146035. static long _vq_lengthlist__8u1__p7_0[] = {
  146036. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  146037. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  146038. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  146039. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  146040. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  146041. 11,
  146042. };
  146043. static float _vq_quantthresh__8u1__p7_0[] = {
  146044. -5.5, 5.5,
  146045. };
  146046. static long _vq_quantmap__8u1__p7_0[] = {
  146047. 1, 0, 2,
  146048. };
  146049. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  146050. _vq_quantthresh__8u1__p7_0,
  146051. _vq_quantmap__8u1__p7_0,
  146052. 3,
  146053. 3
  146054. };
  146055. static static_codebook _8u1__p7_0 = {
  146056. 4, 81,
  146057. _vq_lengthlist__8u1__p7_0,
  146058. 1, -529137664, 1618345984, 2, 0,
  146059. _vq_quantlist__8u1__p7_0,
  146060. NULL,
  146061. &_vq_auxt__8u1__p7_0,
  146062. NULL,
  146063. 0
  146064. };
  146065. static long _vq_quantlist__8u1__p7_1[] = {
  146066. 5,
  146067. 4,
  146068. 6,
  146069. 3,
  146070. 7,
  146071. 2,
  146072. 8,
  146073. 1,
  146074. 9,
  146075. 0,
  146076. 10,
  146077. };
  146078. static long _vq_lengthlist__8u1__p7_1[] = {
  146079. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146080. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  146081. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146082. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146083. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146084. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146085. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146086. 9, 9, 9, 9, 9,10,10,10,10,
  146087. };
  146088. static float _vq_quantthresh__8u1__p7_1[] = {
  146089. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146090. 3.5, 4.5,
  146091. };
  146092. static long _vq_quantmap__8u1__p7_1[] = {
  146093. 9, 7, 5, 3, 1, 0, 2, 4,
  146094. 6, 8, 10,
  146095. };
  146096. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  146097. _vq_quantthresh__8u1__p7_1,
  146098. _vq_quantmap__8u1__p7_1,
  146099. 11,
  146100. 11
  146101. };
  146102. static static_codebook _8u1__p7_1 = {
  146103. 2, 121,
  146104. _vq_lengthlist__8u1__p7_1,
  146105. 1, -531365888, 1611661312, 4, 0,
  146106. _vq_quantlist__8u1__p7_1,
  146107. NULL,
  146108. &_vq_auxt__8u1__p7_1,
  146109. NULL,
  146110. 0
  146111. };
  146112. static long _vq_quantlist__8u1__p8_0[] = {
  146113. 5,
  146114. 4,
  146115. 6,
  146116. 3,
  146117. 7,
  146118. 2,
  146119. 8,
  146120. 1,
  146121. 9,
  146122. 0,
  146123. 10,
  146124. };
  146125. static long _vq_lengthlist__8u1__p8_0[] = {
  146126. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146127. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  146128. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  146129. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  146130. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  146131. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  146132. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  146133. 12,13,13,14,14,15,15,15,15,
  146134. };
  146135. static float _vq_quantthresh__8u1__p8_0[] = {
  146136. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146137. 38.5, 49.5,
  146138. };
  146139. static long _vq_quantmap__8u1__p8_0[] = {
  146140. 9, 7, 5, 3, 1, 0, 2, 4,
  146141. 6, 8, 10,
  146142. };
  146143. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146144. _vq_quantthresh__8u1__p8_0,
  146145. _vq_quantmap__8u1__p8_0,
  146146. 11,
  146147. 11
  146148. };
  146149. static static_codebook _8u1__p8_0 = {
  146150. 2, 121,
  146151. _vq_lengthlist__8u1__p8_0,
  146152. 1, -524582912, 1618345984, 4, 0,
  146153. _vq_quantlist__8u1__p8_0,
  146154. NULL,
  146155. &_vq_auxt__8u1__p8_0,
  146156. NULL,
  146157. 0
  146158. };
  146159. static long _vq_quantlist__8u1__p8_1[] = {
  146160. 5,
  146161. 4,
  146162. 6,
  146163. 3,
  146164. 7,
  146165. 2,
  146166. 8,
  146167. 1,
  146168. 9,
  146169. 0,
  146170. 10,
  146171. };
  146172. static long _vq_lengthlist__8u1__p8_1[] = {
  146173. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146174. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146175. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146176. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146177. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146178. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146179. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146180. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146181. };
  146182. static float _vq_quantthresh__8u1__p8_1[] = {
  146183. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146184. 3.5, 4.5,
  146185. };
  146186. static long _vq_quantmap__8u1__p8_1[] = {
  146187. 9, 7, 5, 3, 1, 0, 2, 4,
  146188. 6, 8, 10,
  146189. };
  146190. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146191. _vq_quantthresh__8u1__p8_1,
  146192. _vq_quantmap__8u1__p8_1,
  146193. 11,
  146194. 11
  146195. };
  146196. static static_codebook _8u1__p8_1 = {
  146197. 2, 121,
  146198. _vq_lengthlist__8u1__p8_1,
  146199. 1, -531365888, 1611661312, 4, 0,
  146200. _vq_quantlist__8u1__p8_1,
  146201. NULL,
  146202. &_vq_auxt__8u1__p8_1,
  146203. NULL,
  146204. 0
  146205. };
  146206. static long _vq_quantlist__8u1__p9_0[] = {
  146207. 7,
  146208. 6,
  146209. 8,
  146210. 5,
  146211. 9,
  146212. 4,
  146213. 10,
  146214. 3,
  146215. 11,
  146216. 2,
  146217. 12,
  146218. 1,
  146219. 13,
  146220. 0,
  146221. 14,
  146222. };
  146223. static long _vq_lengthlist__8u1__p9_0[] = {
  146224. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146225. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146226. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146227. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146228. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146229. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146230. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146231. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146232. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146233. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146234. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146235. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146236. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146237. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146238. 10,
  146239. };
  146240. static float _vq_quantthresh__8u1__p9_0[] = {
  146241. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146242. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146243. };
  146244. static long _vq_quantmap__8u1__p9_0[] = {
  146245. 13, 11, 9, 7, 5, 3, 1, 0,
  146246. 2, 4, 6, 8, 10, 12, 14,
  146247. };
  146248. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146249. _vq_quantthresh__8u1__p9_0,
  146250. _vq_quantmap__8u1__p9_0,
  146251. 15,
  146252. 15
  146253. };
  146254. static static_codebook _8u1__p9_0 = {
  146255. 2, 225,
  146256. _vq_lengthlist__8u1__p9_0,
  146257. 1, -514071552, 1627381760, 4, 0,
  146258. _vq_quantlist__8u1__p9_0,
  146259. NULL,
  146260. &_vq_auxt__8u1__p9_0,
  146261. NULL,
  146262. 0
  146263. };
  146264. static long _vq_quantlist__8u1__p9_1[] = {
  146265. 7,
  146266. 6,
  146267. 8,
  146268. 5,
  146269. 9,
  146270. 4,
  146271. 10,
  146272. 3,
  146273. 11,
  146274. 2,
  146275. 12,
  146276. 1,
  146277. 13,
  146278. 0,
  146279. 14,
  146280. };
  146281. static long _vq_lengthlist__8u1__p9_1[] = {
  146282. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146283. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146284. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146285. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146286. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146287. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146288. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146289. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146290. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146291. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146292. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146293. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146294. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146295. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146296. 13,
  146297. };
  146298. static float _vq_quantthresh__8u1__p9_1[] = {
  146299. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146300. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146301. };
  146302. static long _vq_quantmap__8u1__p9_1[] = {
  146303. 13, 11, 9, 7, 5, 3, 1, 0,
  146304. 2, 4, 6, 8, 10, 12, 14,
  146305. };
  146306. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146307. _vq_quantthresh__8u1__p9_1,
  146308. _vq_quantmap__8u1__p9_1,
  146309. 15,
  146310. 15
  146311. };
  146312. static static_codebook _8u1__p9_1 = {
  146313. 2, 225,
  146314. _vq_lengthlist__8u1__p9_1,
  146315. 1, -522338304, 1620115456, 4, 0,
  146316. _vq_quantlist__8u1__p9_1,
  146317. NULL,
  146318. &_vq_auxt__8u1__p9_1,
  146319. NULL,
  146320. 0
  146321. };
  146322. static long _vq_quantlist__8u1__p9_2[] = {
  146323. 8,
  146324. 7,
  146325. 9,
  146326. 6,
  146327. 10,
  146328. 5,
  146329. 11,
  146330. 4,
  146331. 12,
  146332. 3,
  146333. 13,
  146334. 2,
  146335. 14,
  146336. 1,
  146337. 15,
  146338. 0,
  146339. 16,
  146340. };
  146341. static long _vq_lengthlist__8u1__p9_2[] = {
  146342. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146343. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146344. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146345. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146346. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146347. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146348. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146349. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146350. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146351. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146352. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146353. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146354. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146355. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146356. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146357. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146358. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146359. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146360. 10,
  146361. };
  146362. static float _vq_quantthresh__8u1__p9_2[] = {
  146363. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146364. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146365. };
  146366. static long _vq_quantmap__8u1__p9_2[] = {
  146367. 15, 13, 11, 9, 7, 5, 3, 1,
  146368. 0, 2, 4, 6, 8, 10, 12, 14,
  146369. 16,
  146370. };
  146371. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146372. _vq_quantthresh__8u1__p9_2,
  146373. _vq_quantmap__8u1__p9_2,
  146374. 17,
  146375. 17
  146376. };
  146377. static static_codebook _8u1__p9_2 = {
  146378. 2, 289,
  146379. _vq_lengthlist__8u1__p9_2,
  146380. 1, -529530880, 1611661312, 5, 0,
  146381. _vq_quantlist__8u1__p9_2,
  146382. NULL,
  146383. &_vq_auxt__8u1__p9_2,
  146384. NULL,
  146385. 0
  146386. };
  146387. static long _huff_lengthlist__8u1__single[] = {
  146388. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146389. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146390. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146391. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146392. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146393. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146394. 13, 8, 8,15,
  146395. };
  146396. static static_codebook _huff_book__8u1__single = {
  146397. 2, 100,
  146398. _huff_lengthlist__8u1__single,
  146399. 0, 0, 0, 0, 0,
  146400. NULL,
  146401. NULL,
  146402. NULL,
  146403. NULL,
  146404. 0
  146405. };
  146406. static long _huff_lengthlist__44u0__long[] = {
  146407. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146408. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146409. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146410. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146411. };
  146412. static static_codebook _huff_book__44u0__long = {
  146413. 2, 64,
  146414. _huff_lengthlist__44u0__long,
  146415. 0, 0, 0, 0, 0,
  146416. NULL,
  146417. NULL,
  146418. NULL,
  146419. NULL,
  146420. 0
  146421. };
  146422. static long _vq_quantlist__44u0__p1_0[] = {
  146423. 1,
  146424. 0,
  146425. 2,
  146426. };
  146427. static long _vq_lengthlist__44u0__p1_0[] = {
  146428. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146429. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146430. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146431. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146432. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146433. 13,
  146434. };
  146435. static float _vq_quantthresh__44u0__p1_0[] = {
  146436. -0.5, 0.5,
  146437. };
  146438. static long _vq_quantmap__44u0__p1_0[] = {
  146439. 1, 0, 2,
  146440. };
  146441. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146442. _vq_quantthresh__44u0__p1_0,
  146443. _vq_quantmap__44u0__p1_0,
  146444. 3,
  146445. 3
  146446. };
  146447. static static_codebook _44u0__p1_0 = {
  146448. 4, 81,
  146449. _vq_lengthlist__44u0__p1_0,
  146450. 1, -535822336, 1611661312, 2, 0,
  146451. _vq_quantlist__44u0__p1_0,
  146452. NULL,
  146453. &_vq_auxt__44u0__p1_0,
  146454. NULL,
  146455. 0
  146456. };
  146457. static long _vq_quantlist__44u0__p2_0[] = {
  146458. 1,
  146459. 0,
  146460. 2,
  146461. };
  146462. static long _vq_lengthlist__44u0__p2_0[] = {
  146463. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146464. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146465. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146466. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146467. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146468. 9,
  146469. };
  146470. static float _vq_quantthresh__44u0__p2_0[] = {
  146471. -0.5, 0.5,
  146472. };
  146473. static long _vq_quantmap__44u0__p2_0[] = {
  146474. 1, 0, 2,
  146475. };
  146476. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146477. _vq_quantthresh__44u0__p2_0,
  146478. _vq_quantmap__44u0__p2_0,
  146479. 3,
  146480. 3
  146481. };
  146482. static static_codebook _44u0__p2_0 = {
  146483. 4, 81,
  146484. _vq_lengthlist__44u0__p2_0,
  146485. 1, -535822336, 1611661312, 2, 0,
  146486. _vq_quantlist__44u0__p2_0,
  146487. NULL,
  146488. &_vq_auxt__44u0__p2_0,
  146489. NULL,
  146490. 0
  146491. };
  146492. static long _vq_quantlist__44u0__p3_0[] = {
  146493. 2,
  146494. 1,
  146495. 3,
  146496. 0,
  146497. 4,
  146498. };
  146499. static long _vq_lengthlist__44u0__p3_0[] = {
  146500. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146501. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146502. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146503. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146504. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146505. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146506. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146507. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146508. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146509. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146510. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146511. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146512. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146513. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146514. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146515. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146516. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146517. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146518. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146519. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146520. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146521. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146522. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146523. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146524. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146525. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146526. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146527. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146528. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146529. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146530. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146531. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146532. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146533. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146534. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146535. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146536. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146537. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146538. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146539. 19,
  146540. };
  146541. static float _vq_quantthresh__44u0__p3_0[] = {
  146542. -1.5, -0.5, 0.5, 1.5,
  146543. };
  146544. static long _vq_quantmap__44u0__p3_0[] = {
  146545. 3, 1, 0, 2, 4,
  146546. };
  146547. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146548. _vq_quantthresh__44u0__p3_0,
  146549. _vq_quantmap__44u0__p3_0,
  146550. 5,
  146551. 5
  146552. };
  146553. static static_codebook _44u0__p3_0 = {
  146554. 4, 625,
  146555. _vq_lengthlist__44u0__p3_0,
  146556. 1, -533725184, 1611661312, 3, 0,
  146557. _vq_quantlist__44u0__p3_0,
  146558. NULL,
  146559. &_vq_auxt__44u0__p3_0,
  146560. NULL,
  146561. 0
  146562. };
  146563. static long _vq_quantlist__44u0__p4_0[] = {
  146564. 2,
  146565. 1,
  146566. 3,
  146567. 0,
  146568. 4,
  146569. };
  146570. static long _vq_lengthlist__44u0__p4_0[] = {
  146571. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146572. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146573. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146574. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146575. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146576. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146577. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146578. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146579. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146580. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146581. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146582. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146583. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146584. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146585. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146586. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146587. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146588. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146589. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146590. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146591. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146592. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146593. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146594. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146595. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146596. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146597. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146598. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146599. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146600. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146601. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146602. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146603. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146604. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146605. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146606. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146607. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146608. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146609. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146610. 12,
  146611. };
  146612. static float _vq_quantthresh__44u0__p4_0[] = {
  146613. -1.5, -0.5, 0.5, 1.5,
  146614. };
  146615. static long _vq_quantmap__44u0__p4_0[] = {
  146616. 3, 1, 0, 2, 4,
  146617. };
  146618. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146619. _vq_quantthresh__44u0__p4_0,
  146620. _vq_quantmap__44u0__p4_0,
  146621. 5,
  146622. 5
  146623. };
  146624. static static_codebook _44u0__p4_0 = {
  146625. 4, 625,
  146626. _vq_lengthlist__44u0__p4_0,
  146627. 1, -533725184, 1611661312, 3, 0,
  146628. _vq_quantlist__44u0__p4_0,
  146629. NULL,
  146630. &_vq_auxt__44u0__p4_0,
  146631. NULL,
  146632. 0
  146633. };
  146634. static long _vq_quantlist__44u0__p5_0[] = {
  146635. 4,
  146636. 3,
  146637. 5,
  146638. 2,
  146639. 6,
  146640. 1,
  146641. 7,
  146642. 0,
  146643. 8,
  146644. };
  146645. static long _vq_lengthlist__44u0__p5_0[] = {
  146646. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146647. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146648. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146649. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146650. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146651. 12,
  146652. };
  146653. static float _vq_quantthresh__44u0__p5_0[] = {
  146654. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146655. };
  146656. static long _vq_quantmap__44u0__p5_0[] = {
  146657. 7, 5, 3, 1, 0, 2, 4, 6,
  146658. 8,
  146659. };
  146660. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146661. _vq_quantthresh__44u0__p5_0,
  146662. _vq_quantmap__44u0__p5_0,
  146663. 9,
  146664. 9
  146665. };
  146666. static static_codebook _44u0__p5_0 = {
  146667. 2, 81,
  146668. _vq_lengthlist__44u0__p5_0,
  146669. 1, -531628032, 1611661312, 4, 0,
  146670. _vq_quantlist__44u0__p5_0,
  146671. NULL,
  146672. &_vq_auxt__44u0__p5_0,
  146673. NULL,
  146674. 0
  146675. };
  146676. static long _vq_quantlist__44u0__p6_0[] = {
  146677. 6,
  146678. 5,
  146679. 7,
  146680. 4,
  146681. 8,
  146682. 3,
  146683. 9,
  146684. 2,
  146685. 10,
  146686. 1,
  146687. 11,
  146688. 0,
  146689. 12,
  146690. };
  146691. static long _vq_lengthlist__44u0__p6_0[] = {
  146692. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146693. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146694. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146695. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146696. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146697. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146698. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146699. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146700. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146701. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146702. 15,17,16,17,18,17,17,18, 0,
  146703. };
  146704. static float _vq_quantthresh__44u0__p6_0[] = {
  146705. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146706. 12.5, 17.5, 22.5, 27.5,
  146707. };
  146708. static long _vq_quantmap__44u0__p6_0[] = {
  146709. 11, 9, 7, 5, 3, 1, 0, 2,
  146710. 4, 6, 8, 10, 12,
  146711. };
  146712. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146713. _vq_quantthresh__44u0__p6_0,
  146714. _vq_quantmap__44u0__p6_0,
  146715. 13,
  146716. 13
  146717. };
  146718. static static_codebook _44u0__p6_0 = {
  146719. 2, 169,
  146720. _vq_lengthlist__44u0__p6_0,
  146721. 1, -526516224, 1616117760, 4, 0,
  146722. _vq_quantlist__44u0__p6_0,
  146723. NULL,
  146724. &_vq_auxt__44u0__p6_0,
  146725. NULL,
  146726. 0
  146727. };
  146728. static long _vq_quantlist__44u0__p6_1[] = {
  146729. 2,
  146730. 1,
  146731. 3,
  146732. 0,
  146733. 4,
  146734. };
  146735. static long _vq_lengthlist__44u0__p6_1[] = {
  146736. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146737. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146738. };
  146739. static float _vq_quantthresh__44u0__p6_1[] = {
  146740. -1.5, -0.5, 0.5, 1.5,
  146741. };
  146742. static long _vq_quantmap__44u0__p6_1[] = {
  146743. 3, 1, 0, 2, 4,
  146744. };
  146745. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146746. _vq_quantthresh__44u0__p6_1,
  146747. _vq_quantmap__44u0__p6_1,
  146748. 5,
  146749. 5
  146750. };
  146751. static static_codebook _44u0__p6_1 = {
  146752. 2, 25,
  146753. _vq_lengthlist__44u0__p6_1,
  146754. 1, -533725184, 1611661312, 3, 0,
  146755. _vq_quantlist__44u0__p6_1,
  146756. NULL,
  146757. &_vq_auxt__44u0__p6_1,
  146758. NULL,
  146759. 0
  146760. };
  146761. static long _vq_quantlist__44u0__p7_0[] = {
  146762. 2,
  146763. 1,
  146764. 3,
  146765. 0,
  146766. 4,
  146767. };
  146768. static long _vq_lengthlist__44u0__p7_0[] = {
  146769. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146770. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146771. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146772. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146773. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146775. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146776. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146777. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146778. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146779. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146780. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146781. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146787. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146799. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146800. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146801. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146802. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146803. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146804. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146805. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146806. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146807. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146808. 10,
  146809. };
  146810. static float _vq_quantthresh__44u0__p7_0[] = {
  146811. -253.5, -84.5, 84.5, 253.5,
  146812. };
  146813. static long _vq_quantmap__44u0__p7_0[] = {
  146814. 3, 1, 0, 2, 4,
  146815. };
  146816. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146817. _vq_quantthresh__44u0__p7_0,
  146818. _vq_quantmap__44u0__p7_0,
  146819. 5,
  146820. 5
  146821. };
  146822. static static_codebook _44u0__p7_0 = {
  146823. 4, 625,
  146824. _vq_lengthlist__44u0__p7_0,
  146825. 1, -518709248, 1626677248, 3, 0,
  146826. _vq_quantlist__44u0__p7_0,
  146827. NULL,
  146828. &_vq_auxt__44u0__p7_0,
  146829. NULL,
  146830. 0
  146831. };
  146832. static long _vq_quantlist__44u0__p7_1[] = {
  146833. 6,
  146834. 5,
  146835. 7,
  146836. 4,
  146837. 8,
  146838. 3,
  146839. 9,
  146840. 2,
  146841. 10,
  146842. 1,
  146843. 11,
  146844. 0,
  146845. 12,
  146846. };
  146847. static long _vq_lengthlist__44u0__p7_1[] = {
  146848. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146849. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146850. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146851. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146852. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146853. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146854. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146855. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146856. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146857. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146858. 15,15,15,15,15,15,15,15,15,
  146859. };
  146860. static float _vq_quantthresh__44u0__p7_1[] = {
  146861. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146862. 32.5, 45.5, 58.5, 71.5,
  146863. };
  146864. static long _vq_quantmap__44u0__p7_1[] = {
  146865. 11, 9, 7, 5, 3, 1, 0, 2,
  146866. 4, 6, 8, 10, 12,
  146867. };
  146868. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146869. _vq_quantthresh__44u0__p7_1,
  146870. _vq_quantmap__44u0__p7_1,
  146871. 13,
  146872. 13
  146873. };
  146874. static static_codebook _44u0__p7_1 = {
  146875. 2, 169,
  146876. _vq_lengthlist__44u0__p7_1,
  146877. 1, -523010048, 1618608128, 4, 0,
  146878. _vq_quantlist__44u0__p7_1,
  146879. NULL,
  146880. &_vq_auxt__44u0__p7_1,
  146881. NULL,
  146882. 0
  146883. };
  146884. static long _vq_quantlist__44u0__p7_2[] = {
  146885. 6,
  146886. 5,
  146887. 7,
  146888. 4,
  146889. 8,
  146890. 3,
  146891. 9,
  146892. 2,
  146893. 10,
  146894. 1,
  146895. 11,
  146896. 0,
  146897. 12,
  146898. };
  146899. static long _vq_lengthlist__44u0__p7_2[] = {
  146900. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146901. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146902. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146903. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146904. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146905. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146906. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146907. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146908. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146909. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146910. 9, 9, 9,10, 9, 9,10,10, 9,
  146911. };
  146912. static float _vq_quantthresh__44u0__p7_2[] = {
  146913. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146914. 2.5, 3.5, 4.5, 5.5,
  146915. };
  146916. static long _vq_quantmap__44u0__p7_2[] = {
  146917. 11, 9, 7, 5, 3, 1, 0, 2,
  146918. 4, 6, 8, 10, 12,
  146919. };
  146920. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146921. _vq_quantthresh__44u0__p7_2,
  146922. _vq_quantmap__44u0__p7_2,
  146923. 13,
  146924. 13
  146925. };
  146926. static static_codebook _44u0__p7_2 = {
  146927. 2, 169,
  146928. _vq_lengthlist__44u0__p7_2,
  146929. 1, -531103744, 1611661312, 4, 0,
  146930. _vq_quantlist__44u0__p7_2,
  146931. NULL,
  146932. &_vq_auxt__44u0__p7_2,
  146933. NULL,
  146934. 0
  146935. };
  146936. static long _huff_lengthlist__44u0__short[] = {
  146937. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146938. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146939. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146940. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146941. };
  146942. static static_codebook _huff_book__44u0__short = {
  146943. 2, 64,
  146944. _huff_lengthlist__44u0__short,
  146945. 0, 0, 0, 0, 0,
  146946. NULL,
  146947. NULL,
  146948. NULL,
  146949. NULL,
  146950. 0
  146951. };
  146952. static long _huff_lengthlist__44u1__long[] = {
  146953. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146954. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146955. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146956. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146957. };
  146958. static static_codebook _huff_book__44u1__long = {
  146959. 2, 64,
  146960. _huff_lengthlist__44u1__long,
  146961. 0, 0, 0, 0, 0,
  146962. NULL,
  146963. NULL,
  146964. NULL,
  146965. NULL,
  146966. 0
  146967. };
  146968. static long _vq_quantlist__44u1__p1_0[] = {
  146969. 1,
  146970. 0,
  146971. 2,
  146972. };
  146973. static long _vq_lengthlist__44u1__p1_0[] = {
  146974. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146975. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146976. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146977. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146978. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146979. 13,
  146980. };
  146981. static float _vq_quantthresh__44u1__p1_0[] = {
  146982. -0.5, 0.5,
  146983. };
  146984. static long _vq_quantmap__44u1__p1_0[] = {
  146985. 1, 0, 2,
  146986. };
  146987. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146988. _vq_quantthresh__44u1__p1_0,
  146989. _vq_quantmap__44u1__p1_0,
  146990. 3,
  146991. 3
  146992. };
  146993. static static_codebook _44u1__p1_0 = {
  146994. 4, 81,
  146995. _vq_lengthlist__44u1__p1_0,
  146996. 1, -535822336, 1611661312, 2, 0,
  146997. _vq_quantlist__44u1__p1_0,
  146998. NULL,
  146999. &_vq_auxt__44u1__p1_0,
  147000. NULL,
  147001. 0
  147002. };
  147003. static long _vq_quantlist__44u1__p2_0[] = {
  147004. 1,
  147005. 0,
  147006. 2,
  147007. };
  147008. static long _vq_lengthlist__44u1__p2_0[] = {
  147009. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  147010. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  147011. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147012. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  147013. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147014. 9,
  147015. };
  147016. static float _vq_quantthresh__44u1__p2_0[] = {
  147017. -0.5, 0.5,
  147018. };
  147019. static long _vq_quantmap__44u1__p2_0[] = {
  147020. 1, 0, 2,
  147021. };
  147022. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  147023. _vq_quantthresh__44u1__p2_0,
  147024. _vq_quantmap__44u1__p2_0,
  147025. 3,
  147026. 3
  147027. };
  147028. static static_codebook _44u1__p2_0 = {
  147029. 4, 81,
  147030. _vq_lengthlist__44u1__p2_0,
  147031. 1, -535822336, 1611661312, 2, 0,
  147032. _vq_quantlist__44u1__p2_0,
  147033. NULL,
  147034. &_vq_auxt__44u1__p2_0,
  147035. NULL,
  147036. 0
  147037. };
  147038. static long _vq_quantlist__44u1__p3_0[] = {
  147039. 2,
  147040. 1,
  147041. 3,
  147042. 0,
  147043. 4,
  147044. };
  147045. static long _vq_lengthlist__44u1__p3_0[] = {
  147046. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147047. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  147048. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  147049. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  147050. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  147051. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  147052. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  147053. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  147054. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  147055. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  147056. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  147057. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  147058. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  147059. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  147060. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  147061. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  147062. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  147063. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  147064. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  147065. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  147066. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  147067. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  147068. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  147069. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  147070. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  147071. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  147072. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  147073. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  147074. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  147075. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  147076. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  147077. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  147078. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  147079. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  147080. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  147081. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  147082. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  147083. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  147084. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  147085. 19,
  147086. };
  147087. static float _vq_quantthresh__44u1__p3_0[] = {
  147088. -1.5, -0.5, 0.5, 1.5,
  147089. };
  147090. static long _vq_quantmap__44u1__p3_0[] = {
  147091. 3, 1, 0, 2, 4,
  147092. };
  147093. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  147094. _vq_quantthresh__44u1__p3_0,
  147095. _vq_quantmap__44u1__p3_0,
  147096. 5,
  147097. 5
  147098. };
  147099. static static_codebook _44u1__p3_0 = {
  147100. 4, 625,
  147101. _vq_lengthlist__44u1__p3_0,
  147102. 1, -533725184, 1611661312, 3, 0,
  147103. _vq_quantlist__44u1__p3_0,
  147104. NULL,
  147105. &_vq_auxt__44u1__p3_0,
  147106. NULL,
  147107. 0
  147108. };
  147109. static long _vq_quantlist__44u1__p4_0[] = {
  147110. 2,
  147111. 1,
  147112. 3,
  147113. 0,
  147114. 4,
  147115. };
  147116. static long _vq_lengthlist__44u1__p4_0[] = {
  147117. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147118. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147119. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147120. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147121. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147122. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147123. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147124. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147125. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147126. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147127. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147128. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147129. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147130. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147131. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147132. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147133. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147134. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147135. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147136. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147137. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147138. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147139. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147140. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147141. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147142. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147143. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147144. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147145. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147146. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147147. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147148. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147149. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147150. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147151. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147152. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147153. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147154. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147155. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147156. 12,
  147157. };
  147158. static float _vq_quantthresh__44u1__p4_0[] = {
  147159. -1.5, -0.5, 0.5, 1.5,
  147160. };
  147161. static long _vq_quantmap__44u1__p4_0[] = {
  147162. 3, 1, 0, 2, 4,
  147163. };
  147164. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147165. _vq_quantthresh__44u1__p4_0,
  147166. _vq_quantmap__44u1__p4_0,
  147167. 5,
  147168. 5
  147169. };
  147170. static static_codebook _44u1__p4_0 = {
  147171. 4, 625,
  147172. _vq_lengthlist__44u1__p4_0,
  147173. 1, -533725184, 1611661312, 3, 0,
  147174. _vq_quantlist__44u1__p4_0,
  147175. NULL,
  147176. &_vq_auxt__44u1__p4_0,
  147177. NULL,
  147178. 0
  147179. };
  147180. static long _vq_quantlist__44u1__p5_0[] = {
  147181. 4,
  147182. 3,
  147183. 5,
  147184. 2,
  147185. 6,
  147186. 1,
  147187. 7,
  147188. 0,
  147189. 8,
  147190. };
  147191. static long _vq_lengthlist__44u1__p5_0[] = {
  147192. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147193. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147194. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147195. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147196. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147197. 12,
  147198. };
  147199. static float _vq_quantthresh__44u1__p5_0[] = {
  147200. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147201. };
  147202. static long _vq_quantmap__44u1__p5_0[] = {
  147203. 7, 5, 3, 1, 0, 2, 4, 6,
  147204. 8,
  147205. };
  147206. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147207. _vq_quantthresh__44u1__p5_0,
  147208. _vq_quantmap__44u1__p5_0,
  147209. 9,
  147210. 9
  147211. };
  147212. static static_codebook _44u1__p5_0 = {
  147213. 2, 81,
  147214. _vq_lengthlist__44u1__p5_0,
  147215. 1, -531628032, 1611661312, 4, 0,
  147216. _vq_quantlist__44u1__p5_0,
  147217. NULL,
  147218. &_vq_auxt__44u1__p5_0,
  147219. NULL,
  147220. 0
  147221. };
  147222. static long _vq_quantlist__44u1__p6_0[] = {
  147223. 6,
  147224. 5,
  147225. 7,
  147226. 4,
  147227. 8,
  147228. 3,
  147229. 9,
  147230. 2,
  147231. 10,
  147232. 1,
  147233. 11,
  147234. 0,
  147235. 12,
  147236. };
  147237. static long _vq_lengthlist__44u1__p6_0[] = {
  147238. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147239. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147240. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147241. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147242. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147243. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147244. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147245. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147246. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147247. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147248. 15,17,16,17,18,17,17,18, 0,
  147249. };
  147250. static float _vq_quantthresh__44u1__p6_0[] = {
  147251. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147252. 12.5, 17.5, 22.5, 27.5,
  147253. };
  147254. static long _vq_quantmap__44u1__p6_0[] = {
  147255. 11, 9, 7, 5, 3, 1, 0, 2,
  147256. 4, 6, 8, 10, 12,
  147257. };
  147258. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147259. _vq_quantthresh__44u1__p6_0,
  147260. _vq_quantmap__44u1__p6_0,
  147261. 13,
  147262. 13
  147263. };
  147264. static static_codebook _44u1__p6_0 = {
  147265. 2, 169,
  147266. _vq_lengthlist__44u1__p6_0,
  147267. 1, -526516224, 1616117760, 4, 0,
  147268. _vq_quantlist__44u1__p6_0,
  147269. NULL,
  147270. &_vq_auxt__44u1__p6_0,
  147271. NULL,
  147272. 0
  147273. };
  147274. static long _vq_quantlist__44u1__p6_1[] = {
  147275. 2,
  147276. 1,
  147277. 3,
  147278. 0,
  147279. 4,
  147280. };
  147281. static long _vq_lengthlist__44u1__p6_1[] = {
  147282. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147283. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147284. };
  147285. static float _vq_quantthresh__44u1__p6_1[] = {
  147286. -1.5, -0.5, 0.5, 1.5,
  147287. };
  147288. static long _vq_quantmap__44u1__p6_1[] = {
  147289. 3, 1, 0, 2, 4,
  147290. };
  147291. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147292. _vq_quantthresh__44u1__p6_1,
  147293. _vq_quantmap__44u1__p6_1,
  147294. 5,
  147295. 5
  147296. };
  147297. static static_codebook _44u1__p6_1 = {
  147298. 2, 25,
  147299. _vq_lengthlist__44u1__p6_1,
  147300. 1, -533725184, 1611661312, 3, 0,
  147301. _vq_quantlist__44u1__p6_1,
  147302. NULL,
  147303. &_vq_auxt__44u1__p6_1,
  147304. NULL,
  147305. 0
  147306. };
  147307. static long _vq_quantlist__44u1__p7_0[] = {
  147308. 3,
  147309. 2,
  147310. 4,
  147311. 1,
  147312. 5,
  147313. 0,
  147314. 6,
  147315. };
  147316. static long _vq_lengthlist__44u1__p7_0[] = {
  147317. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147318. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147319. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147320. 8,
  147321. };
  147322. static float _vq_quantthresh__44u1__p7_0[] = {
  147323. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147324. };
  147325. static long _vq_quantmap__44u1__p7_0[] = {
  147326. 5, 3, 1, 0, 2, 4, 6,
  147327. };
  147328. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147329. _vq_quantthresh__44u1__p7_0,
  147330. _vq_quantmap__44u1__p7_0,
  147331. 7,
  147332. 7
  147333. };
  147334. static static_codebook _44u1__p7_0 = {
  147335. 2, 49,
  147336. _vq_lengthlist__44u1__p7_0,
  147337. 1, -518017024, 1626677248, 3, 0,
  147338. _vq_quantlist__44u1__p7_0,
  147339. NULL,
  147340. &_vq_auxt__44u1__p7_0,
  147341. NULL,
  147342. 0
  147343. };
  147344. static long _vq_quantlist__44u1__p7_1[] = {
  147345. 6,
  147346. 5,
  147347. 7,
  147348. 4,
  147349. 8,
  147350. 3,
  147351. 9,
  147352. 2,
  147353. 10,
  147354. 1,
  147355. 11,
  147356. 0,
  147357. 12,
  147358. };
  147359. static long _vq_lengthlist__44u1__p7_1[] = {
  147360. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147361. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147362. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147363. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147364. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147365. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147366. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147367. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147368. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147369. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147370. 15,15,15,15,15,15,15,15,15,
  147371. };
  147372. static float _vq_quantthresh__44u1__p7_1[] = {
  147373. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147374. 32.5, 45.5, 58.5, 71.5,
  147375. };
  147376. static long _vq_quantmap__44u1__p7_1[] = {
  147377. 11, 9, 7, 5, 3, 1, 0, 2,
  147378. 4, 6, 8, 10, 12,
  147379. };
  147380. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147381. _vq_quantthresh__44u1__p7_1,
  147382. _vq_quantmap__44u1__p7_1,
  147383. 13,
  147384. 13
  147385. };
  147386. static static_codebook _44u1__p7_1 = {
  147387. 2, 169,
  147388. _vq_lengthlist__44u1__p7_1,
  147389. 1, -523010048, 1618608128, 4, 0,
  147390. _vq_quantlist__44u1__p7_1,
  147391. NULL,
  147392. &_vq_auxt__44u1__p7_1,
  147393. NULL,
  147394. 0
  147395. };
  147396. static long _vq_quantlist__44u1__p7_2[] = {
  147397. 6,
  147398. 5,
  147399. 7,
  147400. 4,
  147401. 8,
  147402. 3,
  147403. 9,
  147404. 2,
  147405. 10,
  147406. 1,
  147407. 11,
  147408. 0,
  147409. 12,
  147410. };
  147411. static long _vq_lengthlist__44u1__p7_2[] = {
  147412. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147413. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147414. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147415. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147416. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147417. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147418. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147419. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147420. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147421. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147422. 9, 9, 9,10, 9, 9,10,10, 9,
  147423. };
  147424. static float _vq_quantthresh__44u1__p7_2[] = {
  147425. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147426. 2.5, 3.5, 4.5, 5.5,
  147427. };
  147428. static long _vq_quantmap__44u1__p7_2[] = {
  147429. 11, 9, 7, 5, 3, 1, 0, 2,
  147430. 4, 6, 8, 10, 12,
  147431. };
  147432. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147433. _vq_quantthresh__44u1__p7_2,
  147434. _vq_quantmap__44u1__p7_2,
  147435. 13,
  147436. 13
  147437. };
  147438. static static_codebook _44u1__p7_2 = {
  147439. 2, 169,
  147440. _vq_lengthlist__44u1__p7_2,
  147441. 1, -531103744, 1611661312, 4, 0,
  147442. _vq_quantlist__44u1__p7_2,
  147443. NULL,
  147444. &_vq_auxt__44u1__p7_2,
  147445. NULL,
  147446. 0
  147447. };
  147448. static long _huff_lengthlist__44u1__short[] = {
  147449. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147450. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147451. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147452. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147453. };
  147454. static static_codebook _huff_book__44u1__short = {
  147455. 2, 64,
  147456. _huff_lengthlist__44u1__short,
  147457. 0, 0, 0, 0, 0,
  147458. NULL,
  147459. NULL,
  147460. NULL,
  147461. NULL,
  147462. 0
  147463. };
  147464. static long _huff_lengthlist__44u2__long[] = {
  147465. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147466. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147467. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147468. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147469. };
  147470. static static_codebook _huff_book__44u2__long = {
  147471. 2, 64,
  147472. _huff_lengthlist__44u2__long,
  147473. 0, 0, 0, 0, 0,
  147474. NULL,
  147475. NULL,
  147476. NULL,
  147477. NULL,
  147478. 0
  147479. };
  147480. static long _vq_quantlist__44u2__p1_0[] = {
  147481. 1,
  147482. 0,
  147483. 2,
  147484. };
  147485. static long _vq_lengthlist__44u2__p1_0[] = {
  147486. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147487. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147488. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147489. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147490. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147491. 13,
  147492. };
  147493. static float _vq_quantthresh__44u2__p1_0[] = {
  147494. -0.5, 0.5,
  147495. };
  147496. static long _vq_quantmap__44u2__p1_0[] = {
  147497. 1, 0, 2,
  147498. };
  147499. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147500. _vq_quantthresh__44u2__p1_0,
  147501. _vq_quantmap__44u2__p1_0,
  147502. 3,
  147503. 3
  147504. };
  147505. static static_codebook _44u2__p1_0 = {
  147506. 4, 81,
  147507. _vq_lengthlist__44u2__p1_0,
  147508. 1, -535822336, 1611661312, 2, 0,
  147509. _vq_quantlist__44u2__p1_0,
  147510. NULL,
  147511. &_vq_auxt__44u2__p1_0,
  147512. NULL,
  147513. 0
  147514. };
  147515. static long _vq_quantlist__44u2__p2_0[] = {
  147516. 1,
  147517. 0,
  147518. 2,
  147519. };
  147520. static long _vq_lengthlist__44u2__p2_0[] = {
  147521. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147522. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147523. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147524. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147525. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147526. 9,
  147527. };
  147528. static float _vq_quantthresh__44u2__p2_0[] = {
  147529. -0.5, 0.5,
  147530. };
  147531. static long _vq_quantmap__44u2__p2_0[] = {
  147532. 1, 0, 2,
  147533. };
  147534. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147535. _vq_quantthresh__44u2__p2_0,
  147536. _vq_quantmap__44u2__p2_0,
  147537. 3,
  147538. 3
  147539. };
  147540. static static_codebook _44u2__p2_0 = {
  147541. 4, 81,
  147542. _vq_lengthlist__44u2__p2_0,
  147543. 1, -535822336, 1611661312, 2, 0,
  147544. _vq_quantlist__44u2__p2_0,
  147545. NULL,
  147546. &_vq_auxt__44u2__p2_0,
  147547. NULL,
  147548. 0
  147549. };
  147550. static long _vq_quantlist__44u2__p3_0[] = {
  147551. 2,
  147552. 1,
  147553. 3,
  147554. 0,
  147555. 4,
  147556. };
  147557. static long _vq_lengthlist__44u2__p3_0[] = {
  147558. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147559. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147560. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147561. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147562. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147563. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147564. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147565. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147566. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147567. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147568. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147569. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147570. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147571. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147572. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147573. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147574. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147575. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147576. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147577. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147578. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147579. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147580. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147581. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147582. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147583. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147584. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147585. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147586. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147587. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147588. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147589. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147590. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147591. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147592. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147593. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147594. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147595. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147596. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147597. 0,
  147598. };
  147599. static float _vq_quantthresh__44u2__p3_0[] = {
  147600. -1.5, -0.5, 0.5, 1.5,
  147601. };
  147602. static long _vq_quantmap__44u2__p3_0[] = {
  147603. 3, 1, 0, 2, 4,
  147604. };
  147605. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147606. _vq_quantthresh__44u2__p3_0,
  147607. _vq_quantmap__44u2__p3_0,
  147608. 5,
  147609. 5
  147610. };
  147611. static static_codebook _44u2__p3_0 = {
  147612. 4, 625,
  147613. _vq_lengthlist__44u2__p3_0,
  147614. 1, -533725184, 1611661312, 3, 0,
  147615. _vq_quantlist__44u2__p3_0,
  147616. NULL,
  147617. &_vq_auxt__44u2__p3_0,
  147618. NULL,
  147619. 0
  147620. };
  147621. static long _vq_quantlist__44u2__p4_0[] = {
  147622. 2,
  147623. 1,
  147624. 3,
  147625. 0,
  147626. 4,
  147627. };
  147628. static long _vq_lengthlist__44u2__p4_0[] = {
  147629. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147630. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147631. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147632. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147633. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147634. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147635. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147636. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147637. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147638. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147639. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147640. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147641. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147642. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147643. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147644. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147645. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147646. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147647. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147648. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147649. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147650. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147651. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147652. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147653. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147654. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147655. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147656. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147657. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147658. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147659. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147660. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147661. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147662. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147663. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147664. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147665. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147666. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147667. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147668. 13,
  147669. };
  147670. static float _vq_quantthresh__44u2__p4_0[] = {
  147671. -1.5, -0.5, 0.5, 1.5,
  147672. };
  147673. static long _vq_quantmap__44u2__p4_0[] = {
  147674. 3, 1, 0, 2, 4,
  147675. };
  147676. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147677. _vq_quantthresh__44u2__p4_0,
  147678. _vq_quantmap__44u2__p4_0,
  147679. 5,
  147680. 5
  147681. };
  147682. static static_codebook _44u2__p4_0 = {
  147683. 4, 625,
  147684. _vq_lengthlist__44u2__p4_0,
  147685. 1, -533725184, 1611661312, 3, 0,
  147686. _vq_quantlist__44u2__p4_0,
  147687. NULL,
  147688. &_vq_auxt__44u2__p4_0,
  147689. NULL,
  147690. 0
  147691. };
  147692. static long _vq_quantlist__44u2__p5_0[] = {
  147693. 4,
  147694. 3,
  147695. 5,
  147696. 2,
  147697. 6,
  147698. 1,
  147699. 7,
  147700. 0,
  147701. 8,
  147702. };
  147703. static long _vq_lengthlist__44u2__p5_0[] = {
  147704. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147705. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147706. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147707. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147708. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147709. 13,
  147710. };
  147711. static float _vq_quantthresh__44u2__p5_0[] = {
  147712. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147713. };
  147714. static long _vq_quantmap__44u2__p5_0[] = {
  147715. 7, 5, 3, 1, 0, 2, 4, 6,
  147716. 8,
  147717. };
  147718. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147719. _vq_quantthresh__44u2__p5_0,
  147720. _vq_quantmap__44u2__p5_0,
  147721. 9,
  147722. 9
  147723. };
  147724. static static_codebook _44u2__p5_0 = {
  147725. 2, 81,
  147726. _vq_lengthlist__44u2__p5_0,
  147727. 1, -531628032, 1611661312, 4, 0,
  147728. _vq_quantlist__44u2__p5_0,
  147729. NULL,
  147730. &_vq_auxt__44u2__p5_0,
  147731. NULL,
  147732. 0
  147733. };
  147734. static long _vq_quantlist__44u2__p6_0[] = {
  147735. 6,
  147736. 5,
  147737. 7,
  147738. 4,
  147739. 8,
  147740. 3,
  147741. 9,
  147742. 2,
  147743. 10,
  147744. 1,
  147745. 11,
  147746. 0,
  147747. 12,
  147748. };
  147749. static long _vq_lengthlist__44u2__p6_0[] = {
  147750. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147751. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147752. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147753. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147754. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147755. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147756. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147757. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147758. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147759. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147760. 15,17,17,16,18,17,18, 0, 0,
  147761. };
  147762. static float _vq_quantthresh__44u2__p6_0[] = {
  147763. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147764. 12.5, 17.5, 22.5, 27.5,
  147765. };
  147766. static long _vq_quantmap__44u2__p6_0[] = {
  147767. 11, 9, 7, 5, 3, 1, 0, 2,
  147768. 4, 6, 8, 10, 12,
  147769. };
  147770. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147771. _vq_quantthresh__44u2__p6_0,
  147772. _vq_quantmap__44u2__p6_0,
  147773. 13,
  147774. 13
  147775. };
  147776. static static_codebook _44u2__p6_0 = {
  147777. 2, 169,
  147778. _vq_lengthlist__44u2__p6_0,
  147779. 1, -526516224, 1616117760, 4, 0,
  147780. _vq_quantlist__44u2__p6_0,
  147781. NULL,
  147782. &_vq_auxt__44u2__p6_0,
  147783. NULL,
  147784. 0
  147785. };
  147786. static long _vq_quantlist__44u2__p6_1[] = {
  147787. 2,
  147788. 1,
  147789. 3,
  147790. 0,
  147791. 4,
  147792. };
  147793. static long _vq_lengthlist__44u2__p6_1[] = {
  147794. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147795. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147796. };
  147797. static float _vq_quantthresh__44u2__p6_1[] = {
  147798. -1.5, -0.5, 0.5, 1.5,
  147799. };
  147800. static long _vq_quantmap__44u2__p6_1[] = {
  147801. 3, 1, 0, 2, 4,
  147802. };
  147803. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147804. _vq_quantthresh__44u2__p6_1,
  147805. _vq_quantmap__44u2__p6_1,
  147806. 5,
  147807. 5
  147808. };
  147809. static static_codebook _44u2__p6_1 = {
  147810. 2, 25,
  147811. _vq_lengthlist__44u2__p6_1,
  147812. 1, -533725184, 1611661312, 3, 0,
  147813. _vq_quantlist__44u2__p6_1,
  147814. NULL,
  147815. &_vq_auxt__44u2__p6_1,
  147816. NULL,
  147817. 0
  147818. };
  147819. static long _vq_quantlist__44u2__p7_0[] = {
  147820. 4,
  147821. 3,
  147822. 5,
  147823. 2,
  147824. 6,
  147825. 1,
  147826. 7,
  147827. 0,
  147828. 8,
  147829. };
  147830. static long _vq_lengthlist__44u2__p7_0[] = {
  147831. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147832. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147833. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147834. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147836. 11,
  147837. };
  147838. static float _vq_quantthresh__44u2__p7_0[] = {
  147839. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147840. };
  147841. static long _vq_quantmap__44u2__p7_0[] = {
  147842. 7, 5, 3, 1, 0, 2, 4, 6,
  147843. 8,
  147844. };
  147845. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147846. _vq_quantthresh__44u2__p7_0,
  147847. _vq_quantmap__44u2__p7_0,
  147848. 9,
  147849. 9
  147850. };
  147851. static static_codebook _44u2__p7_0 = {
  147852. 2, 81,
  147853. _vq_lengthlist__44u2__p7_0,
  147854. 1, -516612096, 1626677248, 4, 0,
  147855. _vq_quantlist__44u2__p7_0,
  147856. NULL,
  147857. &_vq_auxt__44u2__p7_0,
  147858. NULL,
  147859. 0
  147860. };
  147861. static long _vq_quantlist__44u2__p7_1[] = {
  147862. 6,
  147863. 5,
  147864. 7,
  147865. 4,
  147866. 8,
  147867. 3,
  147868. 9,
  147869. 2,
  147870. 10,
  147871. 1,
  147872. 11,
  147873. 0,
  147874. 12,
  147875. };
  147876. static long _vq_lengthlist__44u2__p7_1[] = {
  147877. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147878. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147879. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147880. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147881. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147882. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147883. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147884. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147885. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147886. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147887. 14,14,14,17,15,17,17,17,17,
  147888. };
  147889. static float _vq_quantthresh__44u2__p7_1[] = {
  147890. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147891. 32.5, 45.5, 58.5, 71.5,
  147892. };
  147893. static long _vq_quantmap__44u2__p7_1[] = {
  147894. 11, 9, 7, 5, 3, 1, 0, 2,
  147895. 4, 6, 8, 10, 12,
  147896. };
  147897. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147898. _vq_quantthresh__44u2__p7_1,
  147899. _vq_quantmap__44u2__p7_1,
  147900. 13,
  147901. 13
  147902. };
  147903. static static_codebook _44u2__p7_1 = {
  147904. 2, 169,
  147905. _vq_lengthlist__44u2__p7_1,
  147906. 1, -523010048, 1618608128, 4, 0,
  147907. _vq_quantlist__44u2__p7_1,
  147908. NULL,
  147909. &_vq_auxt__44u2__p7_1,
  147910. NULL,
  147911. 0
  147912. };
  147913. static long _vq_quantlist__44u2__p7_2[] = {
  147914. 6,
  147915. 5,
  147916. 7,
  147917. 4,
  147918. 8,
  147919. 3,
  147920. 9,
  147921. 2,
  147922. 10,
  147923. 1,
  147924. 11,
  147925. 0,
  147926. 12,
  147927. };
  147928. static long _vq_lengthlist__44u2__p7_2[] = {
  147929. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147930. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147931. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147932. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147933. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147934. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147935. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147936. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147937. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147938. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147939. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147940. };
  147941. static float _vq_quantthresh__44u2__p7_2[] = {
  147942. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147943. 2.5, 3.5, 4.5, 5.5,
  147944. };
  147945. static long _vq_quantmap__44u2__p7_2[] = {
  147946. 11, 9, 7, 5, 3, 1, 0, 2,
  147947. 4, 6, 8, 10, 12,
  147948. };
  147949. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147950. _vq_quantthresh__44u2__p7_2,
  147951. _vq_quantmap__44u2__p7_2,
  147952. 13,
  147953. 13
  147954. };
  147955. static static_codebook _44u2__p7_2 = {
  147956. 2, 169,
  147957. _vq_lengthlist__44u2__p7_2,
  147958. 1, -531103744, 1611661312, 4, 0,
  147959. _vq_quantlist__44u2__p7_2,
  147960. NULL,
  147961. &_vq_auxt__44u2__p7_2,
  147962. NULL,
  147963. 0
  147964. };
  147965. static long _huff_lengthlist__44u2__short[] = {
  147966. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147967. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147968. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147969. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147970. };
  147971. static static_codebook _huff_book__44u2__short = {
  147972. 2, 64,
  147973. _huff_lengthlist__44u2__short,
  147974. 0, 0, 0, 0, 0,
  147975. NULL,
  147976. NULL,
  147977. NULL,
  147978. NULL,
  147979. 0
  147980. };
  147981. static long _huff_lengthlist__44u3__long[] = {
  147982. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147983. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147984. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147985. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147986. };
  147987. static static_codebook _huff_book__44u3__long = {
  147988. 2, 64,
  147989. _huff_lengthlist__44u3__long,
  147990. 0, 0, 0, 0, 0,
  147991. NULL,
  147992. NULL,
  147993. NULL,
  147994. NULL,
  147995. 0
  147996. };
  147997. static long _vq_quantlist__44u3__p1_0[] = {
  147998. 1,
  147999. 0,
  148000. 2,
  148001. };
  148002. static long _vq_lengthlist__44u3__p1_0[] = {
  148003. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148004. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148005. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  148006. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148007. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  148008. 13,
  148009. };
  148010. static float _vq_quantthresh__44u3__p1_0[] = {
  148011. -0.5, 0.5,
  148012. };
  148013. static long _vq_quantmap__44u3__p1_0[] = {
  148014. 1, 0, 2,
  148015. };
  148016. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  148017. _vq_quantthresh__44u3__p1_0,
  148018. _vq_quantmap__44u3__p1_0,
  148019. 3,
  148020. 3
  148021. };
  148022. static static_codebook _44u3__p1_0 = {
  148023. 4, 81,
  148024. _vq_lengthlist__44u3__p1_0,
  148025. 1, -535822336, 1611661312, 2, 0,
  148026. _vq_quantlist__44u3__p1_0,
  148027. NULL,
  148028. &_vq_auxt__44u3__p1_0,
  148029. NULL,
  148030. 0
  148031. };
  148032. static long _vq_quantlist__44u3__p2_0[] = {
  148033. 1,
  148034. 0,
  148035. 2,
  148036. };
  148037. static long _vq_lengthlist__44u3__p2_0[] = {
  148038. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148039. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  148040. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148041. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  148042. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  148043. 9,
  148044. };
  148045. static float _vq_quantthresh__44u3__p2_0[] = {
  148046. -0.5, 0.5,
  148047. };
  148048. static long _vq_quantmap__44u3__p2_0[] = {
  148049. 1, 0, 2,
  148050. };
  148051. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  148052. _vq_quantthresh__44u3__p2_0,
  148053. _vq_quantmap__44u3__p2_0,
  148054. 3,
  148055. 3
  148056. };
  148057. static static_codebook _44u3__p2_0 = {
  148058. 4, 81,
  148059. _vq_lengthlist__44u3__p2_0,
  148060. 1, -535822336, 1611661312, 2, 0,
  148061. _vq_quantlist__44u3__p2_0,
  148062. NULL,
  148063. &_vq_auxt__44u3__p2_0,
  148064. NULL,
  148065. 0
  148066. };
  148067. static long _vq_quantlist__44u3__p3_0[] = {
  148068. 2,
  148069. 1,
  148070. 3,
  148071. 0,
  148072. 4,
  148073. };
  148074. static long _vq_lengthlist__44u3__p3_0[] = {
  148075. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148076. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  148077. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  148078. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  148079. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  148080. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  148081. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  148082. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  148083. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  148084. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  148085. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  148086. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  148087. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  148088. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  148089. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  148090. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  148091. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  148092. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  148093. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  148094. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  148095. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  148096. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  148097. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  148098. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  148099. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  148100. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  148101. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  148102. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  148103. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  148104. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  148105. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  148106. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  148107. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  148108. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  148109. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  148110. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  148111. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  148112. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  148113. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  148114. 0,
  148115. };
  148116. static float _vq_quantthresh__44u3__p3_0[] = {
  148117. -1.5, -0.5, 0.5, 1.5,
  148118. };
  148119. static long _vq_quantmap__44u3__p3_0[] = {
  148120. 3, 1, 0, 2, 4,
  148121. };
  148122. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  148123. _vq_quantthresh__44u3__p3_0,
  148124. _vq_quantmap__44u3__p3_0,
  148125. 5,
  148126. 5
  148127. };
  148128. static static_codebook _44u3__p3_0 = {
  148129. 4, 625,
  148130. _vq_lengthlist__44u3__p3_0,
  148131. 1, -533725184, 1611661312, 3, 0,
  148132. _vq_quantlist__44u3__p3_0,
  148133. NULL,
  148134. &_vq_auxt__44u3__p3_0,
  148135. NULL,
  148136. 0
  148137. };
  148138. static long _vq_quantlist__44u3__p4_0[] = {
  148139. 2,
  148140. 1,
  148141. 3,
  148142. 0,
  148143. 4,
  148144. };
  148145. static long _vq_lengthlist__44u3__p4_0[] = {
  148146. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148147. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148148. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148149. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148150. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148151. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148152. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148153. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148154. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148155. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148156. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148157. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148158. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148159. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148160. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148161. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148162. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148163. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148164. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148165. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148166. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148167. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148168. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148169. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148170. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148171. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148172. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148173. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148174. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148175. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148176. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148177. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148178. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148179. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148180. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148181. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148182. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148183. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148184. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148185. 13,
  148186. };
  148187. static float _vq_quantthresh__44u3__p4_0[] = {
  148188. -1.5, -0.5, 0.5, 1.5,
  148189. };
  148190. static long _vq_quantmap__44u3__p4_0[] = {
  148191. 3, 1, 0, 2, 4,
  148192. };
  148193. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148194. _vq_quantthresh__44u3__p4_0,
  148195. _vq_quantmap__44u3__p4_0,
  148196. 5,
  148197. 5
  148198. };
  148199. static static_codebook _44u3__p4_0 = {
  148200. 4, 625,
  148201. _vq_lengthlist__44u3__p4_0,
  148202. 1, -533725184, 1611661312, 3, 0,
  148203. _vq_quantlist__44u3__p4_0,
  148204. NULL,
  148205. &_vq_auxt__44u3__p4_0,
  148206. NULL,
  148207. 0
  148208. };
  148209. static long _vq_quantlist__44u3__p5_0[] = {
  148210. 4,
  148211. 3,
  148212. 5,
  148213. 2,
  148214. 6,
  148215. 1,
  148216. 7,
  148217. 0,
  148218. 8,
  148219. };
  148220. static long _vq_lengthlist__44u3__p5_0[] = {
  148221. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148222. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148223. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148224. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148225. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148226. 12,
  148227. };
  148228. static float _vq_quantthresh__44u3__p5_0[] = {
  148229. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148230. };
  148231. static long _vq_quantmap__44u3__p5_0[] = {
  148232. 7, 5, 3, 1, 0, 2, 4, 6,
  148233. 8,
  148234. };
  148235. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148236. _vq_quantthresh__44u3__p5_0,
  148237. _vq_quantmap__44u3__p5_0,
  148238. 9,
  148239. 9
  148240. };
  148241. static static_codebook _44u3__p5_0 = {
  148242. 2, 81,
  148243. _vq_lengthlist__44u3__p5_0,
  148244. 1, -531628032, 1611661312, 4, 0,
  148245. _vq_quantlist__44u3__p5_0,
  148246. NULL,
  148247. &_vq_auxt__44u3__p5_0,
  148248. NULL,
  148249. 0
  148250. };
  148251. static long _vq_quantlist__44u3__p6_0[] = {
  148252. 6,
  148253. 5,
  148254. 7,
  148255. 4,
  148256. 8,
  148257. 3,
  148258. 9,
  148259. 2,
  148260. 10,
  148261. 1,
  148262. 11,
  148263. 0,
  148264. 12,
  148265. };
  148266. static long _vq_lengthlist__44u3__p6_0[] = {
  148267. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148268. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148269. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148270. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148271. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148272. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148273. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148274. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148275. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148276. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148277. 15,16,16,16,17,18,16,20,18,
  148278. };
  148279. static float _vq_quantthresh__44u3__p6_0[] = {
  148280. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148281. 12.5, 17.5, 22.5, 27.5,
  148282. };
  148283. static long _vq_quantmap__44u3__p6_0[] = {
  148284. 11, 9, 7, 5, 3, 1, 0, 2,
  148285. 4, 6, 8, 10, 12,
  148286. };
  148287. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148288. _vq_quantthresh__44u3__p6_0,
  148289. _vq_quantmap__44u3__p6_0,
  148290. 13,
  148291. 13
  148292. };
  148293. static static_codebook _44u3__p6_0 = {
  148294. 2, 169,
  148295. _vq_lengthlist__44u3__p6_0,
  148296. 1, -526516224, 1616117760, 4, 0,
  148297. _vq_quantlist__44u3__p6_0,
  148298. NULL,
  148299. &_vq_auxt__44u3__p6_0,
  148300. NULL,
  148301. 0
  148302. };
  148303. static long _vq_quantlist__44u3__p6_1[] = {
  148304. 2,
  148305. 1,
  148306. 3,
  148307. 0,
  148308. 4,
  148309. };
  148310. static long _vq_lengthlist__44u3__p6_1[] = {
  148311. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148312. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148313. };
  148314. static float _vq_quantthresh__44u3__p6_1[] = {
  148315. -1.5, -0.5, 0.5, 1.5,
  148316. };
  148317. static long _vq_quantmap__44u3__p6_1[] = {
  148318. 3, 1, 0, 2, 4,
  148319. };
  148320. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148321. _vq_quantthresh__44u3__p6_1,
  148322. _vq_quantmap__44u3__p6_1,
  148323. 5,
  148324. 5
  148325. };
  148326. static static_codebook _44u3__p6_1 = {
  148327. 2, 25,
  148328. _vq_lengthlist__44u3__p6_1,
  148329. 1, -533725184, 1611661312, 3, 0,
  148330. _vq_quantlist__44u3__p6_1,
  148331. NULL,
  148332. &_vq_auxt__44u3__p6_1,
  148333. NULL,
  148334. 0
  148335. };
  148336. static long _vq_quantlist__44u3__p7_0[] = {
  148337. 4,
  148338. 3,
  148339. 5,
  148340. 2,
  148341. 6,
  148342. 1,
  148343. 7,
  148344. 0,
  148345. 8,
  148346. };
  148347. static long _vq_lengthlist__44u3__p7_0[] = {
  148348. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148349. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148350. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148351. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148352. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148353. 9,
  148354. };
  148355. static float _vq_quantthresh__44u3__p7_0[] = {
  148356. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148357. };
  148358. static long _vq_quantmap__44u3__p7_0[] = {
  148359. 7, 5, 3, 1, 0, 2, 4, 6,
  148360. 8,
  148361. };
  148362. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148363. _vq_quantthresh__44u3__p7_0,
  148364. _vq_quantmap__44u3__p7_0,
  148365. 9,
  148366. 9
  148367. };
  148368. static static_codebook _44u3__p7_0 = {
  148369. 2, 81,
  148370. _vq_lengthlist__44u3__p7_0,
  148371. 1, -515907584, 1627381760, 4, 0,
  148372. _vq_quantlist__44u3__p7_0,
  148373. NULL,
  148374. &_vq_auxt__44u3__p7_0,
  148375. NULL,
  148376. 0
  148377. };
  148378. static long _vq_quantlist__44u3__p7_1[] = {
  148379. 7,
  148380. 6,
  148381. 8,
  148382. 5,
  148383. 9,
  148384. 4,
  148385. 10,
  148386. 3,
  148387. 11,
  148388. 2,
  148389. 12,
  148390. 1,
  148391. 13,
  148392. 0,
  148393. 14,
  148394. };
  148395. static long _vq_lengthlist__44u3__p7_1[] = {
  148396. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148397. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148398. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148399. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148400. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148401. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148402. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148403. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148404. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148405. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148406. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148407. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148408. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148409. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148410. 17,
  148411. };
  148412. static float _vq_quantthresh__44u3__p7_1[] = {
  148413. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148414. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148415. };
  148416. static long _vq_quantmap__44u3__p7_1[] = {
  148417. 13, 11, 9, 7, 5, 3, 1, 0,
  148418. 2, 4, 6, 8, 10, 12, 14,
  148419. };
  148420. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148421. _vq_quantthresh__44u3__p7_1,
  148422. _vq_quantmap__44u3__p7_1,
  148423. 15,
  148424. 15
  148425. };
  148426. static static_codebook _44u3__p7_1 = {
  148427. 2, 225,
  148428. _vq_lengthlist__44u3__p7_1,
  148429. 1, -522338304, 1620115456, 4, 0,
  148430. _vq_quantlist__44u3__p7_1,
  148431. NULL,
  148432. &_vq_auxt__44u3__p7_1,
  148433. NULL,
  148434. 0
  148435. };
  148436. static long _vq_quantlist__44u3__p7_2[] = {
  148437. 8,
  148438. 7,
  148439. 9,
  148440. 6,
  148441. 10,
  148442. 5,
  148443. 11,
  148444. 4,
  148445. 12,
  148446. 3,
  148447. 13,
  148448. 2,
  148449. 14,
  148450. 1,
  148451. 15,
  148452. 0,
  148453. 16,
  148454. };
  148455. static long _vq_lengthlist__44u3__p7_2[] = {
  148456. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148457. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148458. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148459. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148460. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148461. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148462. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148463. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148464. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148465. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148466. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148467. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148468. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148469. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148470. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148471. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148472. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148473. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148474. 11,
  148475. };
  148476. static float _vq_quantthresh__44u3__p7_2[] = {
  148477. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148478. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148479. };
  148480. static long _vq_quantmap__44u3__p7_2[] = {
  148481. 15, 13, 11, 9, 7, 5, 3, 1,
  148482. 0, 2, 4, 6, 8, 10, 12, 14,
  148483. 16,
  148484. };
  148485. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148486. _vq_quantthresh__44u3__p7_2,
  148487. _vq_quantmap__44u3__p7_2,
  148488. 17,
  148489. 17
  148490. };
  148491. static static_codebook _44u3__p7_2 = {
  148492. 2, 289,
  148493. _vq_lengthlist__44u3__p7_2,
  148494. 1, -529530880, 1611661312, 5, 0,
  148495. _vq_quantlist__44u3__p7_2,
  148496. NULL,
  148497. &_vq_auxt__44u3__p7_2,
  148498. NULL,
  148499. 0
  148500. };
  148501. static long _huff_lengthlist__44u3__short[] = {
  148502. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148503. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148504. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148505. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148506. };
  148507. static static_codebook _huff_book__44u3__short = {
  148508. 2, 64,
  148509. _huff_lengthlist__44u3__short,
  148510. 0, 0, 0, 0, 0,
  148511. NULL,
  148512. NULL,
  148513. NULL,
  148514. NULL,
  148515. 0
  148516. };
  148517. static long _huff_lengthlist__44u4__long[] = {
  148518. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148519. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148520. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148521. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148522. };
  148523. static static_codebook _huff_book__44u4__long = {
  148524. 2, 64,
  148525. _huff_lengthlist__44u4__long,
  148526. 0, 0, 0, 0, 0,
  148527. NULL,
  148528. NULL,
  148529. NULL,
  148530. NULL,
  148531. 0
  148532. };
  148533. static long _vq_quantlist__44u4__p1_0[] = {
  148534. 1,
  148535. 0,
  148536. 2,
  148537. };
  148538. static long _vq_lengthlist__44u4__p1_0[] = {
  148539. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148540. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148541. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148542. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148543. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148544. 13,
  148545. };
  148546. static float _vq_quantthresh__44u4__p1_0[] = {
  148547. -0.5, 0.5,
  148548. };
  148549. static long _vq_quantmap__44u4__p1_0[] = {
  148550. 1, 0, 2,
  148551. };
  148552. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148553. _vq_quantthresh__44u4__p1_0,
  148554. _vq_quantmap__44u4__p1_0,
  148555. 3,
  148556. 3
  148557. };
  148558. static static_codebook _44u4__p1_0 = {
  148559. 4, 81,
  148560. _vq_lengthlist__44u4__p1_0,
  148561. 1, -535822336, 1611661312, 2, 0,
  148562. _vq_quantlist__44u4__p1_0,
  148563. NULL,
  148564. &_vq_auxt__44u4__p1_0,
  148565. NULL,
  148566. 0
  148567. };
  148568. static long _vq_quantlist__44u4__p2_0[] = {
  148569. 1,
  148570. 0,
  148571. 2,
  148572. };
  148573. static long _vq_lengthlist__44u4__p2_0[] = {
  148574. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148575. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148576. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148577. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148578. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148579. 9,
  148580. };
  148581. static float _vq_quantthresh__44u4__p2_0[] = {
  148582. -0.5, 0.5,
  148583. };
  148584. static long _vq_quantmap__44u4__p2_0[] = {
  148585. 1, 0, 2,
  148586. };
  148587. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148588. _vq_quantthresh__44u4__p2_0,
  148589. _vq_quantmap__44u4__p2_0,
  148590. 3,
  148591. 3
  148592. };
  148593. static static_codebook _44u4__p2_0 = {
  148594. 4, 81,
  148595. _vq_lengthlist__44u4__p2_0,
  148596. 1, -535822336, 1611661312, 2, 0,
  148597. _vq_quantlist__44u4__p2_0,
  148598. NULL,
  148599. &_vq_auxt__44u4__p2_0,
  148600. NULL,
  148601. 0
  148602. };
  148603. static long _vq_quantlist__44u4__p3_0[] = {
  148604. 2,
  148605. 1,
  148606. 3,
  148607. 0,
  148608. 4,
  148609. };
  148610. static long _vq_lengthlist__44u4__p3_0[] = {
  148611. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148612. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148613. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148614. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148615. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148616. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148617. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148618. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148619. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148620. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148621. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148622. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148623. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148624. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148625. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148626. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148627. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148628. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148629. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148630. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148631. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148632. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148633. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148634. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148635. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148636. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148637. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148638. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148639. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148640. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148641. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148642. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148643. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148644. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148645. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148646. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148647. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148648. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148649. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148650. 0,
  148651. };
  148652. static float _vq_quantthresh__44u4__p3_0[] = {
  148653. -1.5, -0.5, 0.5, 1.5,
  148654. };
  148655. static long _vq_quantmap__44u4__p3_0[] = {
  148656. 3, 1, 0, 2, 4,
  148657. };
  148658. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148659. _vq_quantthresh__44u4__p3_0,
  148660. _vq_quantmap__44u4__p3_0,
  148661. 5,
  148662. 5
  148663. };
  148664. static static_codebook _44u4__p3_0 = {
  148665. 4, 625,
  148666. _vq_lengthlist__44u4__p3_0,
  148667. 1, -533725184, 1611661312, 3, 0,
  148668. _vq_quantlist__44u4__p3_0,
  148669. NULL,
  148670. &_vq_auxt__44u4__p3_0,
  148671. NULL,
  148672. 0
  148673. };
  148674. static long _vq_quantlist__44u4__p4_0[] = {
  148675. 2,
  148676. 1,
  148677. 3,
  148678. 0,
  148679. 4,
  148680. };
  148681. static long _vq_lengthlist__44u4__p4_0[] = {
  148682. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148683. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148684. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148685. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148686. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148687. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148688. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148689. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148690. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148691. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148692. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148693. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148694. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148695. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148696. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148697. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148698. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148699. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148700. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148701. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148702. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148703. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148704. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148705. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148706. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148707. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148708. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148709. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148710. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148711. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148712. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148713. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148714. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148715. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148716. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148717. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148718. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148719. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148720. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148721. 13,
  148722. };
  148723. static float _vq_quantthresh__44u4__p4_0[] = {
  148724. -1.5, -0.5, 0.5, 1.5,
  148725. };
  148726. static long _vq_quantmap__44u4__p4_0[] = {
  148727. 3, 1, 0, 2, 4,
  148728. };
  148729. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148730. _vq_quantthresh__44u4__p4_0,
  148731. _vq_quantmap__44u4__p4_0,
  148732. 5,
  148733. 5
  148734. };
  148735. static static_codebook _44u4__p4_0 = {
  148736. 4, 625,
  148737. _vq_lengthlist__44u4__p4_0,
  148738. 1, -533725184, 1611661312, 3, 0,
  148739. _vq_quantlist__44u4__p4_0,
  148740. NULL,
  148741. &_vq_auxt__44u4__p4_0,
  148742. NULL,
  148743. 0
  148744. };
  148745. static long _vq_quantlist__44u4__p5_0[] = {
  148746. 4,
  148747. 3,
  148748. 5,
  148749. 2,
  148750. 6,
  148751. 1,
  148752. 7,
  148753. 0,
  148754. 8,
  148755. };
  148756. static long _vq_lengthlist__44u4__p5_0[] = {
  148757. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148758. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148759. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148760. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148761. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148762. 12,
  148763. };
  148764. static float _vq_quantthresh__44u4__p5_0[] = {
  148765. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148766. };
  148767. static long _vq_quantmap__44u4__p5_0[] = {
  148768. 7, 5, 3, 1, 0, 2, 4, 6,
  148769. 8,
  148770. };
  148771. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148772. _vq_quantthresh__44u4__p5_0,
  148773. _vq_quantmap__44u4__p5_0,
  148774. 9,
  148775. 9
  148776. };
  148777. static static_codebook _44u4__p5_0 = {
  148778. 2, 81,
  148779. _vq_lengthlist__44u4__p5_0,
  148780. 1, -531628032, 1611661312, 4, 0,
  148781. _vq_quantlist__44u4__p5_0,
  148782. NULL,
  148783. &_vq_auxt__44u4__p5_0,
  148784. NULL,
  148785. 0
  148786. };
  148787. static long _vq_quantlist__44u4__p6_0[] = {
  148788. 6,
  148789. 5,
  148790. 7,
  148791. 4,
  148792. 8,
  148793. 3,
  148794. 9,
  148795. 2,
  148796. 10,
  148797. 1,
  148798. 11,
  148799. 0,
  148800. 12,
  148801. };
  148802. static long _vq_lengthlist__44u4__p6_0[] = {
  148803. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148804. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148805. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148806. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148807. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148808. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148809. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148810. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148811. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148812. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148813. 16,16,16,17,17,18,17,20,21,
  148814. };
  148815. static float _vq_quantthresh__44u4__p6_0[] = {
  148816. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148817. 12.5, 17.5, 22.5, 27.5,
  148818. };
  148819. static long _vq_quantmap__44u4__p6_0[] = {
  148820. 11, 9, 7, 5, 3, 1, 0, 2,
  148821. 4, 6, 8, 10, 12,
  148822. };
  148823. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148824. _vq_quantthresh__44u4__p6_0,
  148825. _vq_quantmap__44u4__p6_0,
  148826. 13,
  148827. 13
  148828. };
  148829. static static_codebook _44u4__p6_0 = {
  148830. 2, 169,
  148831. _vq_lengthlist__44u4__p6_0,
  148832. 1, -526516224, 1616117760, 4, 0,
  148833. _vq_quantlist__44u4__p6_0,
  148834. NULL,
  148835. &_vq_auxt__44u4__p6_0,
  148836. NULL,
  148837. 0
  148838. };
  148839. static long _vq_quantlist__44u4__p6_1[] = {
  148840. 2,
  148841. 1,
  148842. 3,
  148843. 0,
  148844. 4,
  148845. };
  148846. static long _vq_lengthlist__44u4__p6_1[] = {
  148847. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148848. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148849. };
  148850. static float _vq_quantthresh__44u4__p6_1[] = {
  148851. -1.5, -0.5, 0.5, 1.5,
  148852. };
  148853. static long _vq_quantmap__44u4__p6_1[] = {
  148854. 3, 1, 0, 2, 4,
  148855. };
  148856. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148857. _vq_quantthresh__44u4__p6_1,
  148858. _vq_quantmap__44u4__p6_1,
  148859. 5,
  148860. 5
  148861. };
  148862. static static_codebook _44u4__p6_1 = {
  148863. 2, 25,
  148864. _vq_lengthlist__44u4__p6_1,
  148865. 1, -533725184, 1611661312, 3, 0,
  148866. _vq_quantlist__44u4__p6_1,
  148867. NULL,
  148868. &_vq_auxt__44u4__p6_1,
  148869. NULL,
  148870. 0
  148871. };
  148872. static long _vq_quantlist__44u4__p7_0[] = {
  148873. 6,
  148874. 5,
  148875. 7,
  148876. 4,
  148877. 8,
  148878. 3,
  148879. 9,
  148880. 2,
  148881. 10,
  148882. 1,
  148883. 11,
  148884. 0,
  148885. 12,
  148886. };
  148887. static long _vq_lengthlist__44u4__p7_0[] = {
  148888. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148889. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148890. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148891. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148892. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148893. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148895. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148896. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148897. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148898. 11,11,11,11,11,11,11,11,11,
  148899. };
  148900. static float _vq_quantthresh__44u4__p7_0[] = {
  148901. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148902. 637.5, 892.5, 1147.5, 1402.5,
  148903. };
  148904. static long _vq_quantmap__44u4__p7_0[] = {
  148905. 11, 9, 7, 5, 3, 1, 0, 2,
  148906. 4, 6, 8, 10, 12,
  148907. };
  148908. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148909. _vq_quantthresh__44u4__p7_0,
  148910. _vq_quantmap__44u4__p7_0,
  148911. 13,
  148912. 13
  148913. };
  148914. static static_codebook _44u4__p7_0 = {
  148915. 2, 169,
  148916. _vq_lengthlist__44u4__p7_0,
  148917. 1, -514332672, 1627381760, 4, 0,
  148918. _vq_quantlist__44u4__p7_0,
  148919. NULL,
  148920. &_vq_auxt__44u4__p7_0,
  148921. NULL,
  148922. 0
  148923. };
  148924. static long _vq_quantlist__44u4__p7_1[] = {
  148925. 7,
  148926. 6,
  148927. 8,
  148928. 5,
  148929. 9,
  148930. 4,
  148931. 10,
  148932. 3,
  148933. 11,
  148934. 2,
  148935. 12,
  148936. 1,
  148937. 13,
  148938. 0,
  148939. 14,
  148940. };
  148941. static long _vq_lengthlist__44u4__p7_1[] = {
  148942. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148943. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148944. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148945. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148946. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148947. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148948. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148949. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148950. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148951. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148952. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148953. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148954. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148955. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148956. 16,
  148957. };
  148958. static float _vq_quantthresh__44u4__p7_1[] = {
  148959. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148960. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148961. };
  148962. static long _vq_quantmap__44u4__p7_1[] = {
  148963. 13, 11, 9, 7, 5, 3, 1, 0,
  148964. 2, 4, 6, 8, 10, 12, 14,
  148965. };
  148966. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148967. _vq_quantthresh__44u4__p7_1,
  148968. _vq_quantmap__44u4__p7_1,
  148969. 15,
  148970. 15
  148971. };
  148972. static static_codebook _44u4__p7_1 = {
  148973. 2, 225,
  148974. _vq_lengthlist__44u4__p7_1,
  148975. 1, -522338304, 1620115456, 4, 0,
  148976. _vq_quantlist__44u4__p7_1,
  148977. NULL,
  148978. &_vq_auxt__44u4__p7_1,
  148979. NULL,
  148980. 0
  148981. };
  148982. static long _vq_quantlist__44u4__p7_2[] = {
  148983. 8,
  148984. 7,
  148985. 9,
  148986. 6,
  148987. 10,
  148988. 5,
  148989. 11,
  148990. 4,
  148991. 12,
  148992. 3,
  148993. 13,
  148994. 2,
  148995. 14,
  148996. 1,
  148997. 15,
  148998. 0,
  148999. 16,
  149000. };
  149001. static long _vq_lengthlist__44u4__p7_2[] = {
  149002. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149003. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149004. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149005. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149006. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  149007. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149008. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149009. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149010. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  149011. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  149012. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  149013. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  149014. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149015. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  149016. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149017. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149018. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149019. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  149020. 10,
  149021. };
  149022. static float _vq_quantthresh__44u4__p7_2[] = {
  149023. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149024. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149025. };
  149026. static long _vq_quantmap__44u4__p7_2[] = {
  149027. 15, 13, 11, 9, 7, 5, 3, 1,
  149028. 0, 2, 4, 6, 8, 10, 12, 14,
  149029. 16,
  149030. };
  149031. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  149032. _vq_quantthresh__44u4__p7_2,
  149033. _vq_quantmap__44u4__p7_2,
  149034. 17,
  149035. 17
  149036. };
  149037. static static_codebook _44u4__p7_2 = {
  149038. 2, 289,
  149039. _vq_lengthlist__44u4__p7_2,
  149040. 1, -529530880, 1611661312, 5, 0,
  149041. _vq_quantlist__44u4__p7_2,
  149042. NULL,
  149043. &_vq_auxt__44u4__p7_2,
  149044. NULL,
  149045. 0
  149046. };
  149047. static long _huff_lengthlist__44u4__short[] = {
  149048. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  149049. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  149050. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  149051. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  149052. };
  149053. static static_codebook _huff_book__44u4__short = {
  149054. 2, 64,
  149055. _huff_lengthlist__44u4__short,
  149056. 0, 0, 0, 0, 0,
  149057. NULL,
  149058. NULL,
  149059. NULL,
  149060. NULL,
  149061. 0
  149062. };
  149063. static long _huff_lengthlist__44u5__long[] = {
  149064. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  149065. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  149066. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  149067. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  149068. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  149069. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  149070. 14, 8, 7, 8,
  149071. };
  149072. static static_codebook _huff_book__44u5__long = {
  149073. 2, 100,
  149074. _huff_lengthlist__44u5__long,
  149075. 0, 0, 0, 0, 0,
  149076. NULL,
  149077. NULL,
  149078. NULL,
  149079. NULL,
  149080. 0
  149081. };
  149082. static long _vq_quantlist__44u5__p1_0[] = {
  149083. 1,
  149084. 0,
  149085. 2,
  149086. };
  149087. static long _vq_lengthlist__44u5__p1_0[] = {
  149088. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149089. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149090. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149091. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  149092. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149093. 12,
  149094. };
  149095. static float _vq_quantthresh__44u5__p1_0[] = {
  149096. -0.5, 0.5,
  149097. };
  149098. static long _vq_quantmap__44u5__p1_0[] = {
  149099. 1, 0, 2,
  149100. };
  149101. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  149102. _vq_quantthresh__44u5__p1_0,
  149103. _vq_quantmap__44u5__p1_0,
  149104. 3,
  149105. 3
  149106. };
  149107. static static_codebook _44u5__p1_0 = {
  149108. 4, 81,
  149109. _vq_lengthlist__44u5__p1_0,
  149110. 1, -535822336, 1611661312, 2, 0,
  149111. _vq_quantlist__44u5__p1_0,
  149112. NULL,
  149113. &_vq_auxt__44u5__p1_0,
  149114. NULL,
  149115. 0
  149116. };
  149117. static long _vq_quantlist__44u5__p2_0[] = {
  149118. 1,
  149119. 0,
  149120. 2,
  149121. };
  149122. static long _vq_lengthlist__44u5__p2_0[] = {
  149123. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149124. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149125. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149126. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149127. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149128. 9,
  149129. };
  149130. static float _vq_quantthresh__44u5__p2_0[] = {
  149131. -0.5, 0.5,
  149132. };
  149133. static long _vq_quantmap__44u5__p2_0[] = {
  149134. 1, 0, 2,
  149135. };
  149136. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  149137. _vq_quantthresh__44u5__p2_0,
  149138. _vq_quantmap__44u5__p2_0,
  149139. 3,
  149140. 3
  149141. };
  149142. static static_codebook _44u5__p2_0 = {
  149143. 4, 81,
  149144. _vq_lengthlist__44u5__p2_0,
  149145. 1, -535822336, 1611661312, 2, 0,
  149146. _vq_quantlist__44u5__p2_0,
  149147. NULL,
  149148. &_vq_auxt__44u5__p2_0,
  149149. NULL,
  149150. 0
  149151. };
  149152. static long _vq_quantlist__44u5__p3_0[] = {
  149153. 2,
  149154. 1,
  149155. 3,
  149156. 0,
  149157. 4,
  149158. };
  149159. static long _vq_lengthlist__44u5__p3_0[] = {
  149160. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149161. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149162. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149163. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149164. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149165. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149166. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149167. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149168. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149169. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149170. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149171. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149172. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149173. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149174. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149175. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149176. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149177. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149178. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149179. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149180. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149181. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149182. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149183. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149184. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149185. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149186. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149187. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149188. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149189. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149190. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149191. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149192. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149193. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149194. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149195. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149196. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149197. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149198. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149199. 0,
  149200. };
  149201. static float _vq_quantthresh__44u5__p3_0[] = {
  149202. -1.5, -0.5, 0.5, 1.5,
  149203. };
  149204. static long _vq_quantmap__44u5__p3_0[] = {
  149205. 3, 1, 0, 2, 4,
  149206. };
  149207. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149208. _vq_quantthresh__44u5__p3_0,
  149209. _vq_quantmap__44u5__p3_0,
  149210. 5,
  149211. 5
  149212. };
  149213. static static_codebook _44u5__p3_0 = {
  149214. 4, 625,
  149215. _vq_lengthlist__44u5__p3_0,
  149216. 1, -533725184, 1611661312, 3, 0,
  149217. _vq_quantlist__44u5__p3_0,
  149218. NULL,
  149219. &_vq_auxt__44u5__p3_0,
  149220. NULL,
  149221. 0
  149222. };
  149223. static long _vq_quantlist__44u5__p4_0[] = {
  149224. 2,
  149225. 1,
  149226. 3,
  149227. 0,
  149228. 4,
  149229. };
  149230. static long _vq_lengthlist__44u5__p4_0[] = {
  149231. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149232. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149233. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149234. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149235. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149236. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149237. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149238. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149239. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149240. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149241. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149242. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149243. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149244. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149245. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149246. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149247. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149248. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149249. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149250. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149251. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149252. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149253. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149254. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149255. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149256. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149257. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149258. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149259. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149260. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149261. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149262. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149263. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149264. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149265. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149266. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149267. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149268. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149269. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149270. 12,
  149271. };
  149272. static float _vq_quantthresh__44u5__p4_0[] = {
  149273. -1.5, -0.5, 0.5, 1.5,
  149274. };
  149275. static long _vq_quantmap__44u5__p4_0[] = {
  149276. 3, 1, 0, 2, 4,
  149277. };
  149278. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149279. _vq_quantthresh__44u5__p4_0,
  149280. _vq_quantmap__44u5__p4_0,
  149281. 5,
  149282. 5
  149283. };
  149284. static static_codebook _44u5__p4_0 = {
  149285. 4, 625,
  149286. _vq_lengthlist__44u5__p4_0,
  149287. 1, -533725184, 1611661312, 3, 0,
  149288. _vq_quantlist__44u5__p4_0,
  149289. NULL,
  149290. &_vq_auxt__44u5__p4_0,
  149291. NULL,
  149292. 0
  149293. };
  149294. static long _vq_quantlist__44u5__p5_0[] = {
  149295. 4,
  149296. 3,
  149297. 5,
  149298. 2,
  149299. 6,
  149300. 1,
  149301. 7,
  149302. 0,
  149303. 8,
  149304. };
  149305. static long _vq_lengthlist__44u5__p5_0[] = {
  149306. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149307. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149308. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149309. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149310. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149311. 14,
  149312. };
  149313. static float _vq_quantthresh__44u5__p5_0[] = {
  149314. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149315. };
  149316. static long _vq_quantmap__44u5__p5_0[] = {
  149317. 7, 5, 3, 1, 0, 2, 4, 6,
  149318. 8,
  149319. };
  149320. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149321. _vq_quantthresh__44u5__p5_0,
  149322. _vq_quantmap__44u5__p5_0,
  149323. 9,
  149324. 9
  149325. };
  149326. static static_codebook _44u5__p5_0 = {
  149327. 2, 81,
  149328. _vq_lengthlist__44u5__p5_0,
  149329. 1, -531628032, 1611661312, 4, 0,
  149330. _vq_quantlist__44u5__p5_0,
  149331. NULL,
  149332. &_vq_auxt__44u5__p5_0,
  149333. NULL,
  149334. 0
  149335. };
  149336. static long _vq_quantlist__44u5__p6_0[] = {
  149337. 4,
  149338. 3,
  149339. 5,
  149340. 2,
  149341. 6,
  149342. 1,
  149343. 7,
  149344. 0,
  149345. 8,
  149346. };
  149347. static long _vq_lengthlist__44u5__p6_0[] = {
  149348. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149349. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149350. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149351. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149352. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149353. 11,
  149354. };
  149355. static float _vq_quantthresh__44u5__p6_0[] = {
  149356. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149357. };
  149358. static long _vq_quantmap__44u5__p6_0[] = {
  149359. 7, 5, 3, 1, 0, 2, 4, 6,
  149360. 8,
  149361. };
  149362. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149363. _vq_quantthresh__44u5__p6_0,
  149364. _vq_quantmap__44u5__p6_0,
  149365. 9,
  149366. 9
  149367. };
  149368. static static_codebook _44u5__p6_0 = {
  149369. 2, 81,
  149370. _vq_lengthlist__44u5__p6_0,
  149371. 1, -531628032, 1611661312, 4, 0,
  149372. _vq_quantlist__44u5__p6_0,
  149373. NULL,
  149374. &_vq_auxt__44u5__p6_0,
  149375. NULL,
  149376. 0
  149377. };
  149378. static long _vq_quantlist__44u5__p7_0[] = {
  149379. 1,
  149380. 0,
  149381. 2,
  149382. };
  149383. static long _vq_lengthlist__44u5__p7_0[] = {
  149384. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149385. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149386. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149387. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149388. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149389. 12,
  149390. };
  149391. static float _vq_quantthresh__44u5__p7_0[] = {
  149392. -5.5, 5.5,
  149393. };
  149394. static long _vq_quantmap__44u5__p7_0[] = {
  149395. 1, 0, 2,
  149396. };
  149397. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149398. _vq_quantthresh__44u5__p7_0,
  149399. _vq_quantmap__44u5__p7_0,
  149400. 3,
  149401. 3
  149402. };
  149403. static static_codebook _44u5__p7_0 = {
  149404. 4, 81,
  149405. _vq_lengthlist__44u5__p7_0,
  149406. 1, -529137664, 1618345984, 2, 0,
  149407. _vq_quantlist__44u5__p7_0,
  149408. NULL,
  149409. &_vq_auxt__44u5__p7_0,
  149410. NULL,
  149411. 0
  149412. };
  149413. static long _vq_quantlist__44u5__p7_1[] = {
  149414. 5,
  149415. 4,
  149416. 6,
  149417. 3,
  149418. 7,
  149419. 2,
  149420. 8,
  149421. 1,
  149422. 9,
  149423. 0,
  149424. 10,
  149425. };
  149426. static long _vq_lengthlist__44u5__p7_1[] = {
  149427. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149428. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149429. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149430. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149431. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149432. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149433. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149434. 9, 9, 9, 9, 9,10,10,10,10,
  149435. };
  149436. static float _vq_quantthresh__44u5__p7_1[] = {
  149437. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149438. 3.5, 4.5,
  149439. };
  149440. static long _vq_quantmap__44u5__p7_1[] = {
  149441. 9, 7, 5, 3, 1, 0, 2, 4,
  149442. 6, 8, 10,
  149443. };
  149444. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149445. _vq_quantthresh__44u5__p7_1,
  149446. _vq_quantmap__44u5__p7_1,
  149447. 11,
  149448. 11
  149449. };
  149450. static static_codebook _44u5__p7_1 = {
  149451. 2, 121,
  149452. _vq_lengthlist__44u5__p7_1,
  149453. 1, -531365888, 1611661312, 4, 0,
  149454. _vq_quantlist__44u5__p7_1,
  149455. NULL,
  149456. &_vq_auxt__44u5__p7_1,
  149457. NULL,
  149458. 0
  149459. };
  149460. static long _vq_quantlist__44u5__p8_0[] = {
  149461. 5,
  149462. 4,
  149463. 6,
  149464. 3,
  149465. 7,
  149466. 2,
  149467. 8,
  149468. 1,
  149469. 9,
  149470. 0,
  149471. 10,
  149472. };
  149473. static long _vq_lengthlist__44u5__p8_0[] = {
  149474. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149475. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149476. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149477. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149478. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149479. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149480. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149481. 12,13,13,14,14,14,14,15,15,
  149482. };
  149483. static float _vq_quantthresh__44u5__p8_0[] = {
  149484. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149485. 38.5, 49.5,
  149486. };
  149487. static long _vq_quantmap__44u5__p8_0[] = {
  149488. 9, 7, 5, 3, 1, 0, 2, 4,
  149489. 6, 8, 10,
  149490. };
  149491. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149492. _vq_quantthresh__44u5__p8_0,
  149493. _vq_quantmap__44u5__p8_0,
  149494. 11,
  149495. 11
  149496. };
  149497. static static_codebook _44u5__p8_0 = {
  149498. 2, 121,
  149499. _vq_lengthlist__44u5__p8_0,
  149500. 1, -524582912, 1618345984, 4, 0,
  149501. _vq_quantlist__44u5__p8_0,
  149502. NULL,
  149503. &_vq_auxt__44u5__p8_0,
  149504. NULL,
  149505. 0
  149506. };
  149507. static long _vq_quantlist__44u5__p8_1[] = {
  149508. 5,
  149509. 4,
  149510. 6,
  149511. 3,
  149512. 7,
  149513. 2,
  149514. 8,
  149515. 1,
  149516. 9,
  149517. 0,
  149518. 10,
  149519. };
  149520. static long _vq_lengthlist__44u5__p8_1[] = {
  149521. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149522. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149523. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149524. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149525. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149526. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149527. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149528. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149529. };
  149530. static float _vq_quantthresh__44u5__p8_1[] = {
  149531. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149532. 3.5, 4.5,
  149533. };
  149534. static long _vq_quantmap__44u5__p8_1[] = {
  149535. 9, 7, 5, 3, 1, 0, 2, 4,
  149536. 6, 8, 10,
  149537. };
  149538. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149539. _vq_quantthresh__44u5__p8_1,
  149540. _vq_quantmap__44u5__p8_1,
  149541. 11,
  149542. 11
  149543. };
  149544. static static_codebook _44u5__p8_1 = {
  149545. 2, 121,
  149546. _vq_lengthlist__44u5__p8_1,
  149547. 1, -531365888, 1611661312, 4, 0,
  149548. _vq_quantlist__44u5__p8_1,
  149549. NULL,
  149550. &_vq_auxt__44u5__p8_1,
  149551. NULL,
  149552. 0
  149553. };
  149554. static long _vq_quantlist__44u5__p9_0[] = {
  149555. 6,
  149556. 5,
  149557. 7,
  149558. 4,
  149559. 8,
  149560. 3,
  149561. 9,
  149562. 2,
  149563. 10,
  149564. 1,
  149565. 11,
  149566. 0,
  149567. 12,
  149568. };
  149569. static long _vq_lengthlist__44u5__p9_0[] = {
  149570. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149571. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149572. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149573. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149574. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149575. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149576. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149577. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149578. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149579. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149580. 12,12,12,12,12,12,12,12,12,
  149581. };
  149582. static float _vq_quantthresh__44u5__p9_0[] = {
  149583. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149584. 637.5, 892.5, 1147.5, 1402.5,
  149585. };
  149586. static long _vq_quantmap__44u5__p9_0[] = {
  149587. 11, 9, 7, 5, 3, 1, 0, 2,
  149588. 4, 6, 8, 10, 12,
  149589. };
  149590. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149591. _vq_quantthresh__44u5__p9_0,
  149592. _vq_quantmap__44u5__p9_0,
  149593. 13,
  149594. 13
  149595. };
  149596. static static_codebook _44u5__p9_0 = {
  149597. 2, 169,
  149598. _vq_lengthlist__44u5__p9_0,
  149599. 1, -514332672, 1627381760, 4, 0,
  149600. _vq_quantlist__44u5__p9_0,
  149601. NULL,
  149602. &_vq_auxt__44u5__p9_0,
  149603. NULL,
  149604. 0
  149605. };
  149606. static long _vq_quantlist__44u5__p9_1[] = {
  149607. 7,
  149608. 6,
  149609. 8,
  149610. 5,
  149611. 9,
  149612. 4,
  149613. 10,
  149614. 3,
  149615. 11,
  149616. 2,
  149617. 12,
  149618. 1,
  149619. 13,
  149620. 0,
  149621. 14,
  149622. };
  149623. static long _vq_lengthlist__44u5__p9_1[] = {
  149624. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149625. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149626. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149627. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149628. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149629. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149630. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149631. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149632. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149633. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149634. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149635. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149636. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149637. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149638. 14,
  149639. };
  149640. static float _vq_quantthresh__44u5__p9_1[] = {
  149641. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149642. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149643. };
  149644. static long _vq_quantmap__44u5__p9_1[] = {
  149645. 13, 11, 9, 7, 5, 3, 1, 0,
  149646. 2, 4, 6, 8, 10, 12, 14,
  149647. };
  149648. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149649. _vq_quantthresh__44u5__p9_1,
  149650. _vq_quantmap__44u5__p9_1,
  149651. 15,
  149652. 15
  149653. };
  149654. static static_codebook _44u5__p9_1 = {
  149655. 2, 225,
  149656. _vq_lengthlist__44u5__p9_1,
  149657. 1, -522338304, 1620115456, 4, 0,
  149658. _vq_quantlist__44u5__p9_1,
  149659. NULL,
  149660. &_vq_auxt__44u5__p9_1,
  149661. NULL,
  149662. 0
  149663. };
  149664. static long _vq_quantlist__44u5__p9_2[] = {
  149665. 8,
  149666. 7,
  149667. 9,
  149668. 6,
  149669. 10,
  149670. 5,
  149671. 11,
  149672. 4,
  149673. 12,
  149674. 3,
  149675. 13,
  149676. 2,
  149677. 14,
  149678. 1,
  149679. 15,
  149680. 0,
  149681. 16,
  149682. };
  149683. static long _vq_lengthlist__44u5__p9_2[] = {
  149684. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149685. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149686. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149687. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149688. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149689. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149690. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149691. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149692. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149693. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149694. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149695. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149696. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149697. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149698. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149699. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149700. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149701. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149702. 10,
  149703. };
  149704. static float _vq_quantthresh__44u5__p9_2[] = {
  149705. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149706. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149707. };
  149708. static long _vq_quantmap__44u5__p9_2[] = {
  149709. 15, 13, 11, 9, 7, 5, 3, 1,
  149710. 0, 2, 4, 6, 8, 10, 12, 14,
  149711. 16,
  149712. };
  149713. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149714. _vq_quantthresh__44u5__p9_2,
  149715. _vq_quantmap__44u5__p9_2,
  149716. 17,
  149717. 17
  149718. };
  149719. static static_codebook _44u5__p9_2 = {
  149720. 2, 289,
  149721. _vq_lengthlist__44u5__p9_2,
  149722. 1, -529530880, 1611661312, 5, 0,
  149723. _vq_quantlist__44u5__p9_2,
  149724. NULL,
  149725. &_vq_auxt__44u5__p9_2,
  149726. NULL,
  149727. 0
  149728. };
  149729. static long _huff_lengthlist__44u5__short[] = {
  149730. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149731. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149732. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149733. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149734. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149735. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149736. 6, 8,15,17,
  149737. };
  149738. static static_codebook _huff_book__44u5__short = {
  149739. 2, 100,
  149740. _huff_lengthlist__44u5__short,
  149741. 0, 0, 0, 0, 0,
  149742. NULL,
  149743. NULL,
  149744. NULL,
  149745. NULL,
  149746. 0
  149747. };
  149748. static long _huff_lengthlist__44u6__long[] = {
  149749. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149750. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149751. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149752. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149753. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149754. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149755. 13, 8, 7, 7,
  149756. };
  149757. static static_codebook _huff_book__44u6__long = {
  149758. 2, 100,
  149759. _huff_lengthlist__44u6__long,
  149760. 0, 0, 0, 0, 0,
  149761. NULL,
  149762. NULL,
  149763. NULL,
  149764. NULL,
  149765. 0
  149766. };
  149767. static long _vq_quantlist__44u6__p1_0[] = {
  149768. 1,
  149769. 0,
  149770. 2,
  149771. };
  149772. static long _vq_lengthlist__44u6__p1_0[] = {
  149773. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149774. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149775. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149776. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149777. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149778. 12,
  149779. };
  149780. static float _vq_quantthresh__44u6__p1_0[] = {
  149781. -0.5, 0.5,
  149782. };
  149783. static long _vq_quantmap__44u6__p1_0[] = {
  149784. 1, 0, 2,
  149785. };
  149786. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149787. _vq_quantthresh__44u6__p1_0,
  149788. _vq_quantmap__44u6__p1_0,
  149789. 3,
  149790. 3
  149791. };
  149792. static static_codebook _44u6__p1_0 = {
  149793. 4, 81,
  149794. _vq_lengthlist__44u6__p1_0,
  149795. 1, -535822336, 1611661312, 2, 0,
  149796. _vq_quantlist__44u6__p1_0,
  149797. NULL,
  149798. &_vq_auxt__44u6__p1_0,
  149799. NULL,
  149800. 0
  149801. };
  149802. static long _vq_quantlist__44u6__p2_0[] = {
  149803. 1,
  149804. 0,
  149805. 2,
  149806. };
  149807. static long _vq_lengthlist__44u6__p2_0[] = {
  149808. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149809. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149810. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149811. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149812. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149813. 9,
  149814. };
  149815. static float _vq_quantthresh__44u6__p2_0[] = {
  149816. -0.5, 0.5,
  149817. };
  149818. static long _vq_quantmap__44u6__p2_0[] = {
  149819. 1, 0, 2,
  149820. };
  149821. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149822. _vq_quantthresh__44u6__p2_0,
  149823. _vq_quantmap__44u6__p2_0,
  149824. 3,
  149825. 3
  149826. };
  149827. static static_codebook _44u6__p2_0 = {
  149828. 4, 81,
  149829. _vq_lengthlist__44u6__p2_0,
  149830. 1, -535822336, 1611661312, 2, 0,
  149831. _vq_quantlist__44u6__p2_0,
  149832. NULL,
  149833. &_vq_auxt__44u6__p2_0,
  149834. NULL,
  149835. 0
  149836. };
  149837. static long _vq_quantlist__44u6__p3_0[] = {
  149838. 2,
  149839. 1,
  149840. 3,
  149841. 0,
  149842. 4,
  149843. };
  149844. static long _vq_lengthlist__44u6__p3_0[] = {
  149845. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149846. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149847. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149848. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149849. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149850. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149851. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149852. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149853. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149854. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149855. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149856. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149857. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149858. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149859. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149860. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149861. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149862. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149863. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149864. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149865. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149866. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149867. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149868. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149869. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149870. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149871. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149872. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149873. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149874. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149875. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149876. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149877. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149878. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149879. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149880. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149881. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149882. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149883. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149884. 19,
  149885. };
  149886. static float _vq_quantthresh__44u6__p3_0[] = {
  149887. -1.5, -0.5, 0.5, 1.5,
  149888. };
  149889. static long _vq_quantmap__44u6__p3_0[] = {
  149890. 3, 1, 0, 2, 4,
  149891. };
  149892. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149893. _vq_quantthresh__44u6__p3_0,
  149894. _vq_quantmap__44u6__p3_0,
  149895. 5,
  149896. 5
  149897. };
  149898. static static_codebook _44u6__p3_0 = {
  149899. 4, 625,
  149900. _vq_lengthlist__44u6__p3_0,
  149901. 1, -533725184, 1611661312, 3, 0,
  149902. _vq_quantlist__44u6__p3_0,
  149903. NULL,
  149904. &_vq_auxt__44u6__p3_0,
  149905. NULL,
  149906. 0
  149907. };
  149908. static long _vq_quantlist__44u6__p4_0[] = {
  149909. 2,
  149910. 1,
  149911. 3,
  149912. 0,
  149913. 4,
  149914. };
  149915. static long _vq_lengthlist__44u6__p4_0[] = {
  149916. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149917. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149918. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149919. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149920. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149921. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149922. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149923. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149924. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149925. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149926. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149927. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149928. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149929. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149930. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149931. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149932. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149933. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149934. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149935. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149936. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149937. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149938. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149939. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149940. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149941. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149942. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149943. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149944. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149945. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149946. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149947. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149948. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149949. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149950. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149951. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149952. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149953. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149954. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149955. 13,
  149956. };
  149957. static float _vq_quantthresh__44u6__p4_0[] = {
  149958. -1.5, -0.5, 0.5, 1.5,
  149959. };
  149960. static long _vq_quantmap__44u6__p4_0[] = {
  149961. 3, 1, 0, 2, 4,
  149962. };
  149963. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149964. _vq_quantthresh__44u6__p4_0,
  149965. _vq_quantmap__44u6__p4_0,
  149966. 5,
  149967. 5
  149968. };
  149969. static static_codebook _44u6__p4_0 = {
  149970. 4, 625,
  149971. _vq_lengthlist__44u6__p4_0,
  149972. 1, -533725184, 1611661312, 3, 0,
  149973. _vq_quantlist__44u6__p4_0,
  149974. NULL,
  149975. &_vq_auxt__44u6__p4_0,
  149976. NULL,
  149977. 0
  149978. };
  149979. static long _vq_quantlist__44u6__p5_0[] = {
  149980. 4,
  149981. 3,
  149982. 5,
  149983. 2,
  149984. 6,
  149985. 1,
  149986. 7,
  149987. 0,
  149988. 8,
  149989. };
  149990. static long _vq_lengthlist__44u6__p5_0[] = {
  149991. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149992. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149993. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149994. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149995. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149996. 14,
  149997. };
  149998. static float _vq_quantthresh__44u6__p5_0[] = {
  149999. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150000. };
  150001. static long _vq_quantmap__44u6__p5_0[] = {
  150002. 7, 5, 3, 1, 0, 2, 4, 6,
  150003. 8,
  150004. };
  150005. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  150006. _vq_quantthresh__44u6__p5_0,
  150007. _vq_quantmap__44u6__p5_0,
  150008. 9,
  150009. 9
  150010. };
  150011. static static_codebook _44u6__p5_0 = {
  150012. 2, 81,
  150013. _vq_lengthlist__44u6__p5_0,
  150014. 1, -531628032, 1611661312, 4, 0,
  150015. _vq_quantlist__44u6__p5_0,
  150016. NULL,
  150017. &_vq_auxt__44u6__p5_0,
  150018. NULL,
  150019. 0
  150020. };
  150021. static long _vq_quantlist__44u6__p6_0[] = {
  150022. 4,
  150023. 3,
  150024. 5,
  150025. 2,
  150026. 6,
  150027. 1,
  150028. 7,
  150029. 0,
  150030. 8,
  150031. };
  150032. static long _vq_lengthlist__44u6__p6_0[] = {
  150033. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150034. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  150035. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150036. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  150037. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  150038. 12,
  150039. };
  150040. static float _vq_quantthresh__44u6__p6_0[] = {
  150041. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150042. };
  150043. static long _vq_quantmap__44u6__p6_0[] = {
  150044. 7, 5, 3, 1, 0, 2, 4, 6,
  150045. 8,
  150046. };
  150047. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  150048. _vq_quantthresh__44u6__p6_0,
  150049. _vq_quantmap__44u6__p6_0,
  150050. 9,
  150051. 9
  150052. };
  150053. static static_codebook _44u6__p6_0 = {
  150054. 2, 81,
  150055. _vq_lengthlist__44u6__p6_0,
  150056. 1, -531628032, 1611661312, 4, 0,
  150057. _vq_quantlist__44u6__p6_0,
  150058. NULL,
  150059. &_vq_auxt__44u6__p6_0,
  150060. NULL,
  150061. 0
  150062. };
  150063. static long _vq_quantlist__44u6__p7_0[] = {
  150064. 1,
  150065. 0,
  150066. 2,
  150067. };
  150068. static long _vq_lengthlist__44u6__p7_0[] = {
  150069. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  150070. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  150071. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  150072. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  150073. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  150074. 10,
  150075. };
  150076. static float _vq_quantthresh__44u6__p7_0[] = {
  150077. -5.5, 5.5,
  150078. };
  150079. static long _vq_quantmap__44u6__p7_0[] = {
  150080. 1, 0, 2,
  150081. };
  150082. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  150083. _vq_quantthresh__44u6__p7_0,
  150084. _vq_quantmap__44u6__p7_0,
  150085. 3,
  150086. 3
  150087. };
  150088. static static_codebook _44u6__p7_0 = {
  150089. 4, 81,
  150090. _vq_lengthlist__44u6__p7_0,
  150091. 1, -529137664, 1618345984, 2, 0,
  150092. _vq_quantlist__44u6__p7_0,
  150093. NULL,
  150094. &_vq_auxt__44u6__p7_0,
  150095. NULL,
  150096. 0
  150097. };
  150098. static long _vq_quantlist__44u6__p7_1[] = {
  150099. 5,
  150100. 4,
  150101. 6,
  150102. 3,
  150103. 7,
  150104. 2,
  150105. 8,
  150106. 1,
  150107. 9,
  150108. 0,
  150109. 10,
  150110. };
  150111. static long _vq_lengthlist__44u6__p7_1[] = {
  150112. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  150113. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  150114. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  150115. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  150116. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  150117. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  150118. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  150119. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150120. };
  150121. static float _vq_quantthresh__44u6__p7_1[] = {
  150122. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150123. 3.5, 4.5,
  150124. };
  150125. static long _vq_quantmap__44u6__p7_1[] = {
  150126. 9, 7, 5, 3, 1, 0, 2, 4,
  150127. 6, 8, 10,
  150128. };
  150129. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  150130. _vq_quantthresh__44u6__p7_1,
  150131. _vq_quantmap__44u6__p7_1,
  150132. 11,
  150133. 11
  150134. };
  150135. static static_codebook _44u6__p7_1 = {
  150136. 2, 121,
  150137. _vq_lengthlist__44u6__p7_1,
  150138. 1, -531365888, 1611661312, 4, 0,
  150139. _vq_quantlist__44u6__p7_1,
  150140. NULL,
  150141. &_vq_auxt__44u6__p7_1,
  150142. NULL,
  150143. 0
  150144. };
  150145. static long _vq_quantlist__44u6__p8_0[] = {
  150146. 5,
  150147. 4,
  150148. 6,
  150149. 3,
  150150. 7,
  150151. 2,
  150152. 8,
  150153. 1,
  150154. 9,
  150155. 0,
  150156. 10,
  150157. };
  150158. static long _vq_lengthlist__44u6__p8_0[] = {
  150159. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150160. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150161. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150162. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150163. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150164. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150165. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150166. 12,13,13,14,14,14,15,15,15,
  150167. };
  150168. static float _vq_quantthresh__44u6__p8_0[] = {
  150169. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150170. 38.5, 49.5,
  150171. };
  150172. static long _vq_quantmap__44u6__p8_0[] = {
  150173. 9, 7, 5, 3, 1, 0, 2, 4,
  150174. 6, 8, 10,
  150175. };
  150176. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150177. _vq_quantthresh__44u6__p8_0,
  150178. _vq_quantmap__44u6__p8_0,
  150179. 11,
  150180. 11
  150181. };
  150182. static static_codebook _44u6__p8_0 = {
  150183. 2, 121,
  150184. _vq_lengthlist__44u6__p8_0,
  150185. 1, -524582912, 1618345984, 4, 0,
  150186. _vq_quantlist__44u6__p8_0,
  150187. NULL,
  150188. &_vq_auxt__44u6__p8_0,
  150189. NULL,
  150190. 0
  150191. };
  150192. static long _vq_quantlist__44u6__p8_1[] = {
  150193. 5,
  150194. 4,
  150195. 6,
  150196. 3,
  150197. 7,
  150198. 2,
  150199. 8,
  150200. 1,
  150201. 9,
  150202. 0,
  150203. 10,
  150204. };
  150205. static long _vq_lengthlist__44u6__p8_1[] = {
  150206. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150207. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150208. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150209. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150210. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150211. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150212. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150213. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150214. };
  150215. static float _vq_quantthresh__44u6__p8_1[] = {
  150216. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150217. 3.5, 4.5,
  150218. };
  150219. static long _vq_quantmap__44u6__p8_1[] = {
  150220. 9, 7, 5, 3, 1, 0, 2, 4,
  150221. 6, 8, 10,
  150222. };
  150223. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150224. _vq_quantthresh__44u6__p8_1,
  150225. _vq_quantmap__44u6__p8_1,
  150226. 11,
  150227. 11
  150228. };
  150229. static static_codebook _44u6__p8_1 = {
  150230. 2, 121,
  150231. _vq_lengthlist__44u6__p8_1,
  150232. 1, -531365888, 1611661312, 4, 0,
  150233. _vq_quantlist__44u6__p8_1,
  150234. NULL,
  150235. &_vq_auxt__44u6__p8_1,
  150236. NULL,
  150237. 0
  150238. };
  150239. static long _vq_quantlist__44u6__p9_0[] = {
  150240. 7,
  150241. 6,
  150242. 8,
  150243. 5,
  150244. 9,
  150245. 4,
  150246. 10,
  150247. 3,
  150248. 11,
  150249. 2,
  150250. 12,
  150251. 1,
  150252. 13,
  150253. 0,
  150254. 14,
  150255. };
  150256. static long _vq_lengthlist__44u6__p9_0[] = {
  150257. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150258. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150259. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150260. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150261. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150262. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150263. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150264. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150265. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150266. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150267. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150268. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150269. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150270. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150271. 14,
  150272. };
  150273. static float _vq_quantthresh__44u6__p9_0[] = {
  150274. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150275. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150276. };
  150277. static long _vq_quantmap__44u6__p9_0[] = {
  150278. 13, 11, 9, 7, 5, 3, 1, 0,
  150279. 2, 4, 6, 8, 10, 12, 14,
  150280. };
  150281. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150282. _vq_quantthresh__44u6__p9_0,
  150283. _vq_quantmap__44u6__p9_0,
  150284. 15,
  150285. 15
  150286. };
  150287. static static_codebook _44u6__p9_0 = {
  150288. 2, 225,
  150289. _vq_lengthlist__44u6__p9_0,
  150290. 1, -514071552, 1627381760, 4, 0,
  150291. _vq_quantlist__44u6__p9_0,
  150292. NULL,
  150293. &_vq_auxt__44u6__p9_0,
  150294. NULL,
  150295. 0
  150296. };
  150297. static long _vq_quantlist__44u6__p9_1[] = {
  150298. 7,
  150299. 6,
  150300. 8,
  150301. 5,
  150302. 9,
  150303. 4,
  150304. 10,
  150305. 3,
  150306. 11,
  150307. 2,
  150308. 12,
  150309. 1,
  150310. 13,
  150311. 0,
  150312. 14,
  150313. };
  150314. static long _vq_lengthlist__44u6__p9_1[] = {
  150315. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150316. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150317. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150318. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150319. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150320. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150321. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150322. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150323. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150324. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150325. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150326. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150327. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150328. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150329. 13,
  150330. };
  150331. static float _vq_quantthresh__44u6__p9_1[] = {
  150332. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150333. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150334. };
  150335. static long _vq_quantmap__44u6__p9_1[] = {
  150336. 13, 11, 9, 7, 5, 3, 1, 0,
  150337. 2, 4, 6, 8, 10, 12, 14,
  150338. };
  150339. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150340. _vq_quantthresh__44u6__p9_1,
  150341. _vq_quantmap__44u6__p9_1,
  150342. 15,
  150343. 15
  150344. };
  150345. static static_codebook _44u6__p9_1 = {
  150346. 2, 225,
  150347. _vq_lengthlist__44u6__p9_1,
  150348. 1, -522338304, 1620115456, 4, 0,
  150349. _vq_quantlist__44u6__p9_1,
  150350. NULL,
  150351. &_vq_auxt__44u6__p9_1,
  150352. NULL,
  150353. 0
  150354. };
  150355. static long _vq_quantlist__44u6__p9_2[] = {
  150356. 8,
  150357. 7,
  150358. 9,
  150359. 6,
  150360. 10,
  150361. 5,
  150362. 11,
  150363. 4,
  150364. 12,
  150365. 3,
  150366. 13,
  150367. 2,
  150368. 14,
  150369. 1,
  150370. 15,
  150371. 0,
  150372. 16,
  150373. };
  150374. static long _vq_lengthlist__44u6__p9_2[] = {
  150375. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150376. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150377. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150378. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150379. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150380. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150381. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150382. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150383. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150384. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150385. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150386. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150387. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150388. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150389. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150390. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150391. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150392. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150393. 10,
  150394. };
  150395. static float _vq_quantthresh__44u6__p9_2[] = {
  150396. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150397. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150398. };
  150399. static long _vq_quantmap__44u6__p9_2[] = {
  150400. 15, 13, 11, 9, 7, 5, 3, 1,
  150401. 0, 2, 4, 6, 8, 10, 12, 14,
  150402. 16,
  150403. };
  150404. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150405. _vq_quantthresh__44u6__p9_2,
  150406. _vq_quantmap__44u6__p9_2,
  150407. 17,
  150408. 17
  150409. };
  150410. static static_codebook _44u6__p9_2 = {
  150411. 2, 289,
  150412. _vq_lengthlist__44u6__p9_2,
  150413. 1, -529530880, 1611661312, 5, 0,
  150414. _vq_quantlist__44u6__p9_2,
  150415. NULL,
  150416. &_vq_auxt__44u6__p9_2,
  150417. NULL,
  150418. 0
  150419. };
  150420. static long _huff_lengthlist__44u6__short[] = {
  150421. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150422. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150423. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150424. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150425. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150426. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150427. 7, 6, 9,16,
  150428. };
  150429. static static_codebook _huff_book__44u6__short = {
  150430. 2, 100,
  150431. _huff_lengthlist__44u6__short,
  150432. 0, 0, 0, 0, 0,
  150433. NULL,
  150434. NULL,
  150435. NULL,
  150436. NULL,
  150437. 0
  150438. };
  150439. static long _huff_lengthlist__44u7__long[] = {
  150440. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150441. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150442. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150443. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150444. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150445. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150446. 12, 8, 6, 7,
  150447. };
  150448. static static_codebook _huff_book__44u7__long = {
  150449. 2, 100,
  150450. _huff_lengthlist__44u7__long,
  150451. 0, 0, 0, 0, 0,
  150452. NULL,
  150453. NULL,
  150454. NULL,
  150455. NULL,
  150456. 0
  150457. };
  150458. static long _vq_quantlist__44u7__p1_0[] = {
  150459. 1,
  150460. 0,
  150461. 2,
  150462. };
  150463. static long _vq_lengthlist__44u7__p1_0[] = {
  150464. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150465. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150466. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150467. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150468. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150469. 12,
  150470. };
  150471. static float _vq_quantthresh__44u7__p1_0[] = {
  150472. -0.5, 0.5,
  150473. };
  150474. static long _vq_quantmap__44u7__p1_0[] = {
  150475. 1, 0, 2,
  150476. };
  150477. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150478. _vq_quantthresh__44u7__p1_0,
  150479. _vq_quantmap__44u7__p1_0,
  150480. 3,
  150481. 3
  150482. };
  150483. static static_codebook _44u7__p1_0 = {
  150484. 4, 81,
  150485. _vq_lengthlist__44u7__p1_0,
  150486. 1, -535822336, 1611661312, 2, 0,
  150487. _vq_quantlist__44u7__p1_0,
  150488. NULL,
  150489. &_vq_auxt__44u7__p1_0,
  150490. NULL,
  150491. 0
  150492. };
  150493. static long _vq_quantlist__44u7__p2_0[] = {
  150494. 1,
  150495. 0,
  150496. 2,
  150497. };
  150498. static long _vq_lengthlist__44u7__p2_0[] = {
  150499. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150500. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150501. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150502. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150503. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150504. 9,
  150505. };
  150506. static float _vq_quantthresh__44u7__p2_0[] = {
  150507. -0.5, 0.5,
  150508. };
  150509. static long _vq_quantmap__44u7__p2_0[] = {
  150510. 1, 0, 2,
  150511. };
  150512. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150513. _vq_quantthresh__44u7__p2_0,
  150514. _vq_quantmap__44u7__p2_0,
  150515. 3,
  150516. 3
  150517. };
  150518. static static_codebook _44u7__p2_0 = {
  150519. 4, 81,
  150520. _vq_lengthlist__44u7__p2_0,
  150521. 1, -535822336, 1611661312, 2, 0,
  150522. _vq_quantlist__44u7__p2_0,
  150523. NULL,
  150524. &_vq_auxt__44u7__p2_0,
  150525. NULL,
  150526. 0
  150527. };
  150528. static long _vq_quantlist__44u7__p3_0[] = {
  150529. 2,
  150530. 1,
  150531. 3,
  150532. 0,
  150533. 4,
  150534. };
  150535. static long _vq_lengthlist__44u7__p3_0[] = {
  150536. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150537. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150538. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150539. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150540. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150541. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150542. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150543. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150544. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150545. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150546. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150547. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150548. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150549. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150550. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150551. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150552. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150553. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150554. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150555. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150556. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150557. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150558. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150559. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150560. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150561. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150562. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150563. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150564. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150565. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150566. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150567. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150568. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150569. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150570. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150571. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150572. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150573. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150574. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150575. 0,
  150576. };
  150577. static float _vq_quantthresh__44u7__p3_0[] = {
  150578. -1.5, -0.5, 0.5, 1.5,
  150579. };
  150580. static long _vq_quantmap__44u7__p3_0[] = {
  150581. 3, 1, 0, 2, 4,
  150582. };
  150583. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150584. _vq_quantthresh__44u7__p3_0,
  150585. _vq_quantmap__44u7__p3_0,
  150586. 5,
  150587. 5
  150588. };
  150589. static static_codebook _44u7__p3_0 = {
  150590. 4, 625,
  150591. _vq_lengthlist__44u7__p3_0,
  150592. 1, -533725184, 1611661312, 3, 0,
  150593. _vq_quantlist__44u7__p3_0,
  150594. NULL,
  150595. &_vq_auxt__44u7__p3_0,
  150596. NULL,
  150597. 0
  150598. };
  150599. static long _vq_quantlist__44u7__p4_0[] = {
  150600. 2,
  150601. 1,
  150602. 3,
  150603. 0,
  150604. 4,
  150605. };
  150606. static long _vq_lengthlist__44u7__p4_0[] = {
  150607. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150608. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150609. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150610. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150611. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150612. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150613. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150614. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150615. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150616. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150617. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150618. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150619. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150620. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150621. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150622. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150623. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150624. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150625. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150626. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150627. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150628. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150629. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150630. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150631. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150632. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150633. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150634. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150635. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150636. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150637. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150638. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150639. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150640. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150641. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150642. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150643. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150644. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150645. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150646. 14,
  150647. };
  150648. static float _vq_quantthresh__44u7__p4_0[] = {
  150649. -1.5, -0.5, 0.5, 1.5,
  150650. };
  150651. static long _vq_quantmap__44u7__p4_0[] = {
  150652. 3, 1, 0, 2, 4,
  150653. };
  150654. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150655. _vq_quantthresh__44u7__p4_0,
  150656. _vq_quantmap__44u7__p4_0,
  150657. 5,
  150658. 5
  150659. };
  150660. static static_codebook _44u7__p4_0 = {
  150661. 4, 625,
  150662. _vq_lengthlist__44u7__p4_0,
  150663. 1, -533725184, 1611661312, 3, 0,
  150664. _vq_quantlist__44u7__p4_0,
  150665. NULL,
  150666. &_vq_auxt__44u7__p4_0,
  150667. NULL,
  150668. 0
  150669. };
  150670. static long _vq_quantlist__44u7__p5_0[] = {
  150671. 4,
  150672. 3,
  150673. 5,
  150674. 2,
  150675. 6,
  150676. 1,
  150677. 7,
  150678. 0,
  150679. 8,
  150680. };
  150681. static long _vq_lengthlist__44u7__p5_0[] = {
  150682. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150683. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150684. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150685. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150686. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150687. 14,
  150688. };
  150689. static float _vq_quantthresh__44u7__p5_0[] = {
  150690. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150691. };
  150692. static long _vq_quantmap__44u7__p5_0[] = {
  150693. 7, 5, 3, 1, 0, 2, 4, 6,
  150694. 8,
  150695. };
  150696. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150697. _vq_quantthresh__44u7__p5_0,
  150698. _vq_quantmap__44u7__p5_0,
  150699. 9,
  150700. 9
  150701. };
  150702. static static_codebook _44u7__p5_0 = {
  150703. 2, 81,
  150704. _vq_lengthlist__44u7__p5_0,
  150705. 1, -531628032, 1611661312, 4, 0,
  150706. _vq_quantlist__44u7__p5_0,
  150707. NULL,
  150708. &_vq_auxt__44u7__p5_0,
  150709. NULL,
  150710. 0
  150711. };
  150712. static long _vq_quantlist__44u7__p6_0[] = {
  150713. 4,
  150714. 3,
  150715. 5,
  150716. 2,
  150717. 6,
  150718. 1,
  150719. 7,
  150720. 0,
  150721. 8,
  150722. };
  150723. static long _vq_lengthlist__44u7__p6_0[] = {
  150724. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150725. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150726. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150727. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150728. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150729. 12,
  150730. };
  150731. static float _vq_quantthresh__44u7__p6_0[] = {
  150732. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150733. };
  150734. static long _vq_quantmap__44u7__p6_0[] = {
  150735. 7, 5, 3, 1, 0, 2, 4, 6,
  150736. 8,
  150737. };
  150738. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150739. _vq_quantthresh__44u7__p6_0,
  150740. _vq_quantmap__44u7__p6_0,
  150741. 9,
  150742. 9
  150743. };
  150744. static static_codebook _44u7__p6_0 = {
  150745. 2, 81,
  150746. _vq_lengthlist__44u7__p6_0,
  150747. 1, -531628032, 1611661312, 4, 0,
  150748. _vq_quantlist__44u7__p6_0,
  150749. NULL,
  150750. &_vq_auxt__44u7__p6_0,
  150751. NULL,
  150752. 0
  150753. };
  150754. static long _vq_quantlist__44u7__p7_0[] = {
  150755. 1,
  150756. 0,
  150757. 2,
  150758. };
  150759. static long _vq_lengthlist__44u7__p7_0[] = {
  150760. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150761. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150762. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150763. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150764. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150765. 10,
  150766. };
  150767. static float _vq_quantthresh__44u7__p7_0[] = {
  150768. -5.5, 5.5,
  150769. };
  150770. static long _vq_quantmap__44u7__p7_0[] = {
  150771. 1, 0, 2,
  150772. };
  150773. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150774. _vq_quantthresh__44u7__p7_0,
  150775. _vq_quantmap__44u7__p7_0,
  150776. 3,
  150777. 3
  150778. };
  150779. static static_codebook _44u7__p7_0 = {
  150780. 4, 81,
  150781. _vq_lengthlist__44u7__p7_0,
  150782. 1, -529137664, 1618345984, 2, 0,
  150783. _vq_quantlist__44u7__p7_0,
  150784. NULL,
  150785. &_vq_auxt__44u7__p7_0,
  150786. NULL,
  150787. 0
  150788. };
  150789. static long _vq_quantlist__44u7__p7_1[] = {
  150790. 5,
  150791. 4,
  150792. 6,
  150793. 3,
  150794. 7,
  150795. 2,
  150796. 8,
  150797. 1,
  150798. 9,
  150799. 0,
  150800. 10,
  150801. };
  150802. static long _vq_lengthlist__44u7__p7_1[] = {
  150803. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150804. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150805. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150806. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150807. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150808. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150809. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150810. 8, 9, 9, 9, 9, 9,10,10,10,
  150811. };
  150812. static float _vq_quantthresh__44u7__p7_1[] = {
  150813. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150814. 3.5, 4.5,
  150815. };
  150816. static long _vq_quantmap__44u7__p7_1[] = {
  150817. 9, 7, 5, 3, 1, 0, 2, 4,
  150818. 6, 8, 10,
  150819. };
  150820. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150821. _vq_quantthresh__44u7__p7_1,
  150822. _vq_quantmap__44u7__p7_1,
  150823. 11,
  150824. 11
  150825. };
  150826. static static_codebook _44u7__p7_1 = {
  150827. 2, 121,
  150828. _vq_lengthlist__44u7__p7_1,
  150829. 1, -531365888, 1611661312, 4, 0,
  150830. _vq_quantlist__44u7__p7_1,
  150831. NULL,
  150832. &_vq_auxt__44u7__p7_1,
  150833. NULL,
  150834. 0
  150835. };
  150836. static long _vq_quantlist__44u7__p8_0[] = {
  150837. 5,
  150838. 4,
  150839. 6,
  150840. 3,
  150841. 7,
  150842. 2,
  150843. 8,
  150844. 1,
  150845. 9,
  150846. 0,
  150847. 10,
  150848. };
  150849. static long _vq_lengthlist__44u7__p8_0[] = {
  150850. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150851. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150852. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150853. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150854. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150855. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150856. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150857. 12,13,13,14,14,15,15,15,16,
  150858. };
  150859. static float _vq_quantthresh__44u7__p8_0[] = {
  150860. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150861. 38.5, 49.5,
  150862. };
  150863. static long _vq_quantmap__44u7__p8_0[] = {
  150864. 9, 7, 5, 3, 1, 0, 2, 4,
  150865. 6, 8, 10,
  150866. };
  150867. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150868. _vq_quantthresh__44u7__p8_0,
  150869. _vq_quantmap__44u7__p8_0,
  150870. 11,
  150871. 11
  150872. };
  150873. static static_codebook _44u7__p8_0 = {
  150874. 2, 121,
  150875. _vq_lengthlist__44u7__p8_0,
  150876. 1, -524582912, 1618345984, 4, 0,
  150877. _vq_quantlist__44u7__p8_0,
  150878. NULL,
  150879. &_vq_auxt__44u7__p8_0,
  150880. NULL,
  150881. 0
  150882. };
  150883. static long _vq_quantlist__44u7__p8_1[] = {
  150884. 5,
  150885. 4,
  150886. 6,
  150887. 3,
  150888. 7,
  150889. 2,
  150890. 8,
  150891. 1,
  150892. 9,
  150893. 0,
  150894. 10,
  150895. };
  150896. static long _vq_lengthlist__44u7__p8_1[] = {
  150897. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150898. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150899. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150900. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150901. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150902. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150903. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150904. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150905. };
  150906. static float _vq_quantthresh__44u7__p8_1[] = {
  150907. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150908. 3.5, 4.5,
  150909. };
  150910. static long _vq_quantmap__44u7__p8_1[] = {
  150911. 9, 7, 5, 3, 1, 0, 2, 4,
  150912. 6, 8, 10,
  150913. };
  150914. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150915. _vq_quantthresh__44u7__p8_1,
  150916. _vq_quantmap__44u7__p8_1,
  150917. 11,
  150918. 11
  150919. };
  150920. static static_codebook _44u7__p8_1 = {
  150921. 2, 121,
  150922. _vq_lengthlist__44u7__p8_1,
  150923. 1, -531365888, 1611661312, 4, 0,
  150924. _vq_quantlist__44u7__p8_1,
  150925. NULL,
  150926. &_vq_auxt__44u7__p8_1,
  150927. NULL,
  150928. 0
  150929. };
  150930. static long _vq_quantlist__44u7__p9_0[] = {
  150931. 5,
  150932. 4,
  150933. 6,
  150934. 3,
  150935. 7,
  150936. 2,
  150937. 8,
  150938. 1,
  150939. 9,
  150940. 0,
  150941. 10,
  150942. };
  150943. static long _vq_lengthlist__44u7__p9_0[] = {
  150944. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150945. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150946. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150947. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150948. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150949. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150950. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150951. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150952. };
  150953. static float _vq_quantthresh__44u7__p9_0[] = {
  150954. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150955. 2229.5, 2866.5,
  150956. };
  150957. static long _vq_quantmap__44u7__p9_0[] = {
  150958. 9, 7, 5, 3, 1, 0, 2, 4,
  150959. 6, 8, 10,
  150960. };
  150961. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150962. _vq_quantthresh__44u7__p9_0,
  150963. _vq_quantmap__44u7__p9_0,
  150964. 11,
  150965. 11
  150966. };
  150967. static static_codebook _44u7__p9_0 = {
  150968. 2, 121,
  150969. _vq_lengthlist__44u7__p9_0,
  150970. 1, -512171520, 1630791680, 4, 0,
  150971. _vq_quantlist__44u7__p9_0,
  150972. NULL,
  150973. &_vq_auxt__44u7__p9_0,
  150974. NULL,
  150975. 0
  150976. };
  150977. static long _vq_quantlist__44u7__p9_1[] = {
  150978. 6,
  150979. 5,
  150980. 7,
  150981. 4,
  150982. 8,
  150983. 3,
  150984. 9,
  150985. 2,
  150986. 10,
  150987. 1,
  150988. 11,
  150989. 0,
  150990. 12,
  150991. };
  150992. static long _vq_lengthlist__44u7__p9_1[] = {
  150993. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150994. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150995. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150996. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150997. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150998. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150999. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  151000. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  151001. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  151002. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  151003. 15,15,15,15,17,17,16,17,16,
  151004. };
  151005. static float _vq_quantthresh__44u7__p9_1[] = {
  151006. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  151007. 122.5, 171.5, 220.5, 269.5,
  151008. };
  151009. static long _vq_quantmap__44u7__p9_1[] = {
  151010. 11, 9, 7, 5, 3, 1, 0, 2,
  151011. 4, 6, 8, 10, 12,
  151012. };
  151013. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  151014. _vq_quantthresh__44u7__p9_1,
  151015. _vq_quantmap__44u7__p9_1,
  151016. 13,
  151017. 13
  151018. };
  151019. static static_codebook _44u7__p9_1 = {
  151020. 2, 169,
  151021. _vq_lengthlist__44u7__p9_1,
  151022. 1, -518889472, 1622704128, 4, 0,
  151023. _vq_quantlist__44u7__p9_1,
  151024. NULL,
  151025. &_vq_auxt__44u7__p9_1,
  151026. NULL,
  151027. 0
  151028. };
  151029. static long _vq_quantlist__44u7__p9_2[] = {
  151030. 24,
  151031. 23,
  151032. 25,
  151033. 22,
  151034. 26,
  151035. 21,
  151036. 27,
  151037. 20,
  151038. 28,
  151039. 19,
  151040. 29,
  151041. 18,
  151042. 30,
  151043. 17,
  151044. 31,
  151045. 16,
  151046. 32,
  151047. 15,
  151048. 33,
  151049. 14,
  151050. 34,
  151051. 13,
  151052. 35,
  151053. 12,
  151054. 36,
  151055. 11,
  151056. 37,
  151057. 10,
  151058. 38,
  151059. 9,
  151060. 39,
  151061. 8,
  151062. 40,
  151063. 7,
  151064. 41,
  151065. 6,
  151066. 42,
  151067. 5,
  151068. 43,
  151069. 4,
  151070. 44,
  151071. 3,
  151072. 45,
  151073. 2,
  151074. 46,
  151075. 1,
  151076. 47,
  151077. 0,
  151078. 48,
  151079. };
  151080. static long _vq_lengthlist__44u7__p9_2[] = {
  151081. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151082. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151083. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  151084. 8,
  151085. };
  151086. static float _vq_quantthresh__44u7__p9_2[] = {
  151087. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151088. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151089. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151090. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151091. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151092. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151093. };
  151094. static long _vq_quantmap__44u7__p9_2[] = {
  151095. 47, 45, 43, 41, 39, 37, 35, 33,
  151096. 31, 29, 27, 25, 23, 21, 19, 17,
  151097. 15, 13, 11, 9, 7, 5, 3, 1,
  151098. 0, 2, 4, 6, 8, 10, 12, 14,
  151099. 16, 18, 20, 22, 24, 26, 28, 30,
  151100. 32, 34, 36, 38, 40, 42, 44, 46,
  151101. 48,
  151102. };
  151103. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  151104. _vq_quantthresh__44u7__p9_2,
  151105. _vq_quantmap__44u7__p9_2,
  151106. 49,
  151107. 49
  151108. };
  151109. static static_codebook _44u7__p9_2 = {
  151110. 1, 49,
  151111. _vq_lengthlist__44u7__p9_2,
  151112. 1, -526909440, 1611661312, 6, 0,
  151113. _vq_quantlist__44u7__p9_2,
  151114. NULL,
  151115. &_vq_auxt__44u7__p9_2,
  151116. NULL,
  151117. 0
  151118. };
  151119. static long _huff_lengthlist__44u7__short[] = {
  151120. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  151121. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  151122. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  151123. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  151124. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  151125. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  151126. 6, 8, 5, 9,
  151127. };
  151128. static static_codebook _huff_book__44u7__short = {
  151129. 2, 100,
  151130. _huff_lengthlist__44u7__short,
  151131. 0, 0, 0, 0, 0,
  151132. NULL,
  151133. NULL,
  151134. NULL,
  151135. NULL,
  151136. 0
  151137. };
  151138. static long _huff_lengthlist__44u8__long[] = {
  151139. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151140. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151141. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151142. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151143. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151144. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151145. 10, 8, 8, 9,
  151146. };
  151147. static static_codebook _huff_book__44u8__long = {
  151148. 2, 100,
  151149. _huff_lengthlist__44u8__long,
  151150. 0, 0, 0, 0, 0,
  151151. NULL,
  151152. NULL,
  151153. NULL,
  151154. NULL,
  151155. 0
  151156. };
  151157. static long _huff_lengthlist__44u8__short[] = {
  151158. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151159. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151160. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151161. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151162. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151163. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151164. 10,10,15,17,
  151165. };
  151166. static static_codebook _huff_book__44u8__short = {
  151167. 2, 100,
  151168. _huff_lengthlist__44u8__short,
  151169. 0, 0, 0, 0, 0,
  151170. NULL,
  151171. NULL,
  151172. NULL,
  151173. NULL,
  151174. 0
  151175. };
  151176. static long _vq_quantlist__44u8_p1_0[] = {
  151177. 1,
  151178. 0,
  151179. 2,
  151180. };
  151181. static long _vq_lengthlist__44u8_p1_0[] = {
  151182. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151183. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151184. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151185. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151186. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151187. 10,
  151188. };
  151189. static float _vq_quantthresh__44u8_p1_0[] = {
  151190. -0.5, 0.5,
  151191. };
  151192. static long _vq_quantmap__44u8_p1_0[] = {
  151193. 1, 0, 2,
  151194. };
  151195. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151196. _vq_quantthresh__44u8_p1_0,
  151197. _vq_quantmap__44u8_p1_0,
  151198. 3,
  151199. 3
  151200. };
  151201. static static_codebook _44u8_p1_0 = {
  151202. 4, 81,
  151203. _vq_lengthlist__44u8_p1_0,
  151204. 1, -535822336, 1611661312, 2, 0,
  151205. _vq_quantlist__44u8_p1_0,
  151206. NULL,
  151207. &_vq_auxt__44u8_p1_0,
  151208. NULL,
  151209. 0
  151210. };
  151211. static long _vq_quantlist__44u8_p2_0[] = {
  151212. 2,
  151213. 1,
  151214. 3,
  151215. 0,
  151216. 4,
  151217. };
  151218. static long _vq_lengthlist__44u8_p2_0[] = {
  151219. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151220. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151221. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151222. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151223. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151224. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151225. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151226. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151227. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151228. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151229. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151230. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151231. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151232. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151233. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151234. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151235. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151236. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151237. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151238. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151239. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151240. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151241. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151242. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151243. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151244. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151245. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151246. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151247. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151248. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151249. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151250. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151251. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151252. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151253. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151254. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151255. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151256. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151257. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151258. 14,
  151259. };
  151260. static float _vq_quantthresh__44u8_p2_0[] = {
  151261. -1.5, -0.5, 0.5, 1.5,
  151262. };
  151263. static long _vq_quantmap__44u8_p2_0[] = {
  151264. 3, 1, 0, 2, 4,
  151265. };
  151266. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151267. _vq_quantthresh__44u8_p2_0,
  151268. _vq_quantmap__44u8_p2_0,
  151269. 5,
  151270. 5
  151271. };
  151272. static static_codebook _44u8_p2_0 = {
  151273. 4, 625,
  151274. _vq_lengthlist__44u8_p2_0,
  151275. 1, -533725184, 1611661312, 3, 0,
  151276. _vq_quantlist__44u8_p2_0,
  151277. NULL,
  151278. &_vq_auxt__44u8_p2_0,
  151279. NULL,
  151280. 0
  151281. };
  151282. static long _vq_quantlist__44u8_p3_0[] = {
  151283. 4,
  151284. 3,
  151285. 5,
  151286. 2,
  151287. 6,
  151288. 1,
  151289. 7,
  151290. 0,
  151291. 8,
  151292. };
  151293. static long _vq_lengthlist__44u8_p3_0[] = {
  151294. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151295. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151296. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151297. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151298. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151299. 12,
  151300. };
  151301. static float _vq_quantthresh__44u8_p3_0[] = {
  151302. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151303. };
  151304. static long _vq_quantmap__44u8_p3_0[] = {
  151305. 7, 5, 3, 1, 0, 2, 4, 6,
  151306. 8,
  151307. };
  151308. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151309. _vq_quantthresh__44u8_p3_0,
  151310. _vq_quantmap__44u8_p3_0,
  151311. 9,
  151312. 9
  151313. };
  151314. static static_codebook _44u8_p3_0 = {
  151315. 2, 81,
  151316. _vq_lengthlist__44u8_p3_0,
  151317. 1, -531628032, 1611661312, 4, 0,
  151318. _vq_quantlist__44u8_p3_0,
  151319. NULL,
  151320. &_vq_auxt__44u8_p3_0,
  151321. NULL,
  151322. 0
  151323. };
  151324. static long _vq_quantlist__44u8_p4_0[] = {
  151325. 8,
  151326. 7,
  151327. 9,
  151328. 6,
  151329. 10,
  151330. 5,
  151331. 11,
  151332. 4,
  151333. 12,
  151334. 3,
  151335. 13,
  151336. 2,
  151337. 14,
  151338. 1,
  151339. 15,
  151340. 0,
  151341. 16,
  151342. };
  151343. static long _vq_lengthlist__44u8_p4_0[] = {
  151344. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151345. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151346. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151347. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151348. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151349. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151350. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151351. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151352. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151353. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151354. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151355. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151356. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151357. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151358. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151359. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151360. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151361. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151362. 14,
  151363. };
  151364. static float _vq_quantthresh__44u8_p4_0[] = {
  151365. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151366. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151367. };
  151368. static long _vq_quantmap__44u8_p4_0[] = {
  151369. 15, 13, 11, 9, 7, 5, 3, 1,
  151370. 0, 2, 4, 6, 8, 10, 12, 14,
  151371. 16,
  151372. };
  151373. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151374. _vq_quantthresh__44u8_p4_0,
  151375. _vq_quantmap__44u8_p4_0,
  151376. 17,
  151377. 17
  151378. };
  151379. static static_codebook _44u8_p4_0 = {
  151380. 2, 289,
  151381. _vq_lengthlist__44u8_p4_0,
  151382. 1, -529530880, 1611661312, 5, 0,
  151383. _vq_quantlist__44u8_p4_0,
  151384. NULL,
  151385. &_vq_auxt__44u8_p4_0,
  151386. NULL,
  151387. 0
  151388. };
  151389. static long _vq_quantlist__44u8_p5_0[] = {
  151390. 1,
  151391. 0,
  151392. 2,
  151393. };
  151394. static long _vq_lengthlist__44u8_p5_0[] = {
  151395. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151396. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151397. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151398. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151399. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151400. 10,
  151401. };
  151402. static float _vq_quantthresh__44u8_p5_0[] = {
  151403. -5.5, 5.5,
  151404. };
  151405. static long _vq_quantmap__44u8_p5_0[] = {
  151406. 1, 0, 2,
  151407. };
  151408. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151409. _vq_quantthresh__44u8_p5_0,
  151410. _vq_quantmap__44u8_p5_0,
  151411. 3,
  151412. 3
  151413. };
  151414. static static_codebook _44u8_p5_0 = {
  151415. 4, 81,
  151416. _vq_lengthlist__44u8_p5_0,
  151417. 1, -529137664, 1618345984, 2, 0,
  151418. _vq_quantlist__44u8_p5_0,
  151419. NULL,
  151420. &_vq_auxt__44u8_p5_0,
  151421. NULL,
  151422. 0
  151423. };
  151424. static long _vq_quantlist__44u8_p5_1[] = {
  151425. 5,
  151426. 4,
  151427. 6,
  151428. 3,
  151429. 7,
  151430. 2,
  151431. 8,
  151432. 1,
  151433. 9,
  151434. 0,
  151435. 10,
  151436. };
  151437. static long _vq_lengthlist__44u8_p5_1[] = {
  151438. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151439. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151440. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151441. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151442. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151443. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151444. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151445. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151446. };
  151447. static float _vq_quantthresh__44u8_p5_1[] = {
  151448. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151449. 3.5, 4.5,
  151450. };
  151451. static long _vq_quantmap__44u8_p5_1[] = {
  151452. 9, 7, 5, 3, 1, 0, 2, 4,
  151453. 6, 8, 10,
  151454. };
  151455. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151456. _vq_quantthresh__44u8_p5_1,
  151457. _vq_quantmap__44u8_p5_1,
  151458. 11,
  151459. 11
  151460. };
  151461. static static_codebook _44u8_p5_1 = {
  151462. 2, 121,
  151463. _vq_lengthlist__44u8_p5_1,
  151464. 1, -531365888, 1611661312, 4, 0,
  151465. _vq_quantlist__44u8_p5_1,
  151466. NULL,
  151467. &_vq_auxt__44u8_p5_1,
  151468. NULL,
  151469. 0
  151470. };
  151471. static long _vq_quantlist__44u8_p6_0[] = {
  151472. 6,
  151473. 5,
  151474. 7,
  151475. 4,
  151476. 8,
  151477. 3,
  151478. 9,
  151479. 2,
  151480. 10,
  151481. 1,
  151482. 11,
  151483. 0,
  151484. 12,
  151485. };
  151486. static long _vq_lengthlist__44u8_p6_0[] = {
  151487. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151488. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151489. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151490. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151491. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151492. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151493. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151494. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151495. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151496. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151497. 11,11,11,11,11,12,11,12,12,
  151498. };
  151499. static float _vq_quantthresh__44u8_p6_0[] = {
  151500. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151501. 12.5, 17.5, 22.5, 27.5,
  151502. };
  151503. static long _vq_quantmap__44u8_p6_0[] = {
  151504. 11, 9, 7, 5, 3, 1, 0, 2,
  151505. 4, 6, 8, 10, 12,
  151506. };
  151507. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151508. _vq_quantthresh__44u8_p6_0,
  151509. _vq_quantmap__44u8_p6_0,
  151510. 13,
  151511. 13
  151512. };
  151513. static static_codebook _44u8_p6_0 = {
  151514. 2, 169,
  151515. _vq_lengthlist__44u8_p6_0,
  151516. 1, -526516224, 1616117760, 4, 0,
  151517. _vq_quantlist__44u8_p6_0,
  151518. NULL,
  151519. &_vq_auxt__44u8_p6_0,
  151520. NULL,
  151521. 0
  151522. };
  151523. static long _vq_quantlist__44u8_p6_1[] = {
  151524. 2,
  151525. 1,
  151526. 3,
  151527. 0,
  151528. 4,
  151529. };
  151530. static long _vq_lengthlist__44u8_p6_1[] = {
  151531. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151532. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151533. };
  151534. static float _vq_quantthresh__44u8_p6_1[] = {
  151535. -1.5, -0.5, 0.5, 1.5,
  151536. };
  151537. static long _vq_quantmap__44u8_p6_1[] = {
  151538. 3, 1, 0, 2, 4,
  151539. };
  151540. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151541. _vq_quantthresh__44u8_p6_1,
  151542. _vq_quantmap__44u8_p6_1,
  151543. 5,
  151544. 5
  151545. };
  151546. static static_codebook _44u8_p6_1 = {
  151547. 2, 25,
  151548. _vq_lengthlist__44u8_p6_1,
  151549. 1, -533725184, 1611661312, 3, 0,
  151550. _vq_quantlist__44u8_p6_1,
  151551. NULL,
  151552. &_vq_auxt__44u8_p6_1,
  151553. NULL,
  151554. 0
  151555. };
  151556. static long _vq_quantlist__44u8_p7_0[] = {
  151557. 6,
  151558. 5,
  151559. 7,
  151560. 4,
  151561. 8,
  151562. 3,
  151563. 9,
  151564. 2,
  151565. 10,
  151566. 1,
  151567. 11,
  151568. 0,
  151569. 12,
  151570. };
  151571. static long _vq_lengthlist__44u8_p7_0[] = {
  151572. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151573. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151574. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151575. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151576. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151577. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151578. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151579. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151580. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151581. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151582. 13,13,14,14,14,15,15,15,16,
  151583. };
  151584. static float _vq_quantthresh__44u8_p7_0[] = {
  151585. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151586. 27.5, 38.5, 49.5, 60.5,
  151587. };
  151588. static long _vq_quantmap__44u8_p7_0[] = {
  151589. 11, 9, 7, 5, 3, 1, 0, 2,
  151590. 4, 6, 8, 10, 12,
  151591. };
  151592. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151593. _vq_quantthresh__44u8_p7_0,
  151594. _vq_quantmap__44u8_p7_0,
  151595. 13,
  151596. 13
  151597. };
  151598. static static_codebook _44u8_p7_0 = {
  151599. 2, 169,
  151600. _vq_lengthlist__44u8_p7_0,
  151601. 1, -523206656, 1618345984, 4, 0,
  151602. _vq_quantlist__44u8_p7_0,
  151603. NULL,
  151604. &_vq_auxt__44u8_p7_0,
  151605. NULL,
  151606. 0
  151607. };
  151608. static long _vq_quantlist__44u8_p7_1[] = {
  151609. 5,
  151610. 4,
  151611. 6,
  151612. 3,
  151613. 7,
  151614. 2,
  151615. 8,
  151616. 1,
  151617. 9,
  151618. 0,
  151619. 10,
  151620. };
  151621. static long _vq_lengthlist__44u8_p7_1[] = {
  151622. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151623. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151624. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151625. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151626. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151627. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151628. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151629. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151630. };
  151631. static float _vq_quantthresh__44u8_p7_1[] = {
  151632. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151633. 3.5, 4.5,
  151634. };
  151635. static long _vq_quantmap__44u8_p7_1[] = {
  151636. 9, 7, 5, 3, 1, 0, 2, 4,
  151637. 6, 8, 10,
  151638. };
  151639. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151640. _vq_quantthresh__44u8_p7_1,
  151641. _vq_quantmap__44u8_p7_1,
  151642. 11,
  151643. 11
  151644. };
  151645. static static_codebook _44u8_p7_1 = {
  151646. 2, 121,
  151647. _vq_lengthlist__44u8_p7_1,
  151648. 1, -531365888, 1611661312, 4, 0,
  151649. _vq_quantlist__44u8_p7_1,
  151650. NULL,
  151651. &_vq_auxt__44u8_p7_1,
  151652. NULL,
  151653. 0
  151654. };
  151655. static long _vq_quantlist__44u8_p8_0[] = {
  151656. 7,
  151657. 6,
  151658. 8,
  151659. 5,
  151660. 9,
  151661. 4,
  151662. 10,
  151663. 3,
  151664. 11,
  151665. 2,
  151666. 12,
  151667. 1,
  151668. 13,
  151669. 0,
  151670. 14,
  151671. };
  151672. static long _vq_lengthlist__44u8_p8_0[] = {
  151673. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151674. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151675. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151676. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151677. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151678. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151679. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151680. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151681. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151682. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151683. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151684. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151685. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151686. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151687. 17,
  151688. };
  151689. static float _vq_quantthresh__44u8_p8_0[] = {
  151690. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151691. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151692. };
  151693. static long _vq_quantmap__44u8_p8_0[] = {
  151694. 13, 11, 9, 7, 5, 3, 1, 0,
  151695. 2, 4, 6, 8, 10, 12, 14,
  151696. };
  151697. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151698. _vq_quantthresh__44u8_p8_0,
  151699. _vq_quantmap__44u8_p8_0,
  151700. 15,
  151701. 15
  151702. };
  151703. static static_codebook _44u8_p8_0 = {
  151704. 2, 225,
  151705. _vq_lengthlist__44u8_p8_0,
  151706. 1, -520986624, 1620377600, 4, 0,
  151707. _vq_quantlist__44u8_p8_0,
  151708. NULL,
  151709. &_vq_auxt__44u8_p8_0,
  151710. NULL,
  151711. 0
  151712. };
  151713. static long _vq_quantlist__44u8_p8_1[] = {
  151714. 10,
  151715. 9,
  151716. 11,
  151717. 8,
  151718. 12,
  151719. 7,
  151720. 13,
  151721. 6,
  151722. 14,
  151723. 5,
  151724. 15,
  151725. 4,
  151726. 16,
  151727. 3,
  151728. 17,
  151729. 2,
  151730. 18,
  151731. 1,
  151732. 19,
  151733. 0,
  151734. 20,
  151735. };
  151736. static long _vq_lengthlist__44u8_p8_1[] = {
  151737. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151738. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151739. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151740. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151741. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151742. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151743. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151744. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151745. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151746. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151747. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151748. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151749. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151750. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151751. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151752. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151753. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151754. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151755. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151756. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151757. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151758. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151759. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151760. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151761. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151762. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151763. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151764. 10,10,10,10,10,10,10,10,10,
  151765. };
  151766. static float _vq_quantthresh__44u8_p8_1[] = {
  151767. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151768. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151769. 6.5, 7.5, 8.5, 9.5,
  151770. };
  151771. static long _vq_quantmap__44u8_p8_1[] = {
  151772. 19, 17, 15, 13, 11, 9, 7, 5,
  151773. 3, 1, 0, 2, 4, 6, 8, 10,
  151774. 12, 14, 16, 18, 20,
  151775. };
  151776. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151777. _vq_quantthresh__44u8_p8_1,
  151778. _vq_quantmap__44u8_p8_1,
  151779. 21,
  151780. 21
  151781. };
  151782. static static_codebook _44u8_p8_1 = {
  151783. 2, 441,
  151784. _vq_lengthlist__44u8_p8_1,
  151785. 1, -529268736, 1611661312, 5, 0,
  151786. _vq_quantlist__44u8_p8_1,
  151787. NULL,
  151788. &_vq_auxt__44u8_p8_1,
  151789. NULL,
  151790. 0
  151791. };
  151792. static long _vq_quantlist__44u8_p9_0[] = {
  151793. 4,
  151794. 3,
  151795. 5,
  151796. 2,
  151797. 6,
  151798. 1,
  151799. 7,
  151800. 0,
  151801. 8,
  151802. };
  151803. static long _vq_lengthlist__44u8_p9_0[] = {
  151804. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151805. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151806. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151807. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151808. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151809. 8,
  151810. };
  151811. static float _vq_quantthresh__44u8_p9_0[] = {
  151812. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151813. };
  151814. static long _vq_quantmap__44u8_p9_0[] = {
  151815. 7, 5, 3, 1, 0, 2, 4, 6,
  151816. 8,
  151817. };
  151818. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151819. _vq_quantthresh__44u8_p9_0,
  151820. _vq_quantmap__44u8_p9_0,
  151821. 9,
  151822. 9
  151823. };
  151824. static static_codebook _44u8_p9_0 = {
  151825. 2, 81,
  151826. _vq_lengthlist__44u8_p9_0,
  151827. 1, -511895552, 1631393792, 4, 0,
  151828. _vq_quantlist__44u8_p9_0,
  151829. NULL,
  151830. &_vq_auxt__44u8_p9_0,
  151831. NULL,
  151832. 0
  151833. };
  151834. static long _vq_quantlist__44u8_p9_1[] = {
  151835. 9,
  151836. 8,
  151837. 10,
  151838. 7,
  151839. 11,
  151840. 6,
  151841. 12,
  151842. 5,
  151843. 13,
  151844. 4,
  151845. 14,
  151846. 3,
  151847. 15,
  151848. 2,
  151849. 16,
  151850. 1,
  151851. 17,
  151852. 0,
  151853. 18,
  151854. };
  151855. static long _vq_lengthlist__44u8_p9_1[] = {
  151856. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151857. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151858. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151859. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151860. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151861. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151862. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151863. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151864. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151865. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151866. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151867. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151868. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151869. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151870. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151871. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151872. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151873. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151874. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151875. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151876. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151877. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151878. 16,15,16,16,16,16,16,16,16,
  151879. };
  151880. static float _vq_quantthresh__44u8_p9_1[] = {
  151881. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151882. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151883. 367.5, 416.5,
  151884. };
  151885. static long _vq_quantmap__44u8_p9_1[] = {
  151886. 17, 15, 13, 11, 9, 7, 5, 3,
  151887. 1, 0, 2, 4, 6, 8, 10, 12,
  151888. 14, 16, 18,
  151889. };
  151890. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151891. _vq_quantthresh__44u8_p9_1,
  151892. _vq_quantmap__44u8_p9_1,
  151893. 19,
  151894. 19
  151895. };
  151896. static static_codebook _44u8_p9_1 = {
  151897. 2, 361,
  151898. _vq_lengthlist__44u8_p9_1,
  151899. 1, -518287360, 1622704128, 5, 0,
  151900. _vq_quantlist__44u8_p9_1,
  151901. NULL,
  151902. &_vq_auxt__44u8_p9_1,
  151903. NULL,
  151904. 0
  151905. };
  151906. static long _vq_quantlist__44u8_p9_2[] = {
  151907. 24,
  151908. 23,
  151909. 25,
  151910. 22,
  151911. 26,
  151912. 21,
  151913. 27,
  151914. 20,
  151915. 28,
  151916. 19,
  151917. 29,
  151918. 18,
  151919. 30,
  151920. 17,
  151921. 31,
  151922. 16,
  151923. 32,
  151924. 15,
  151925. 33,
  151926. 14,
  151927. 34,
  151928. 13,
  151929. 35,
  151930. 12,
  151931. 36,
  151932. 11,
  151933. 37,
  151934. 10,
  151935. 38,
  151936. 9,
  151937. 39,
  151938. 8,
  151939. 40,
  151940. 7,
  151941. 41,
  151942. 6,
  151943. 42,
  151944. 5,
  151945. 43,
  151946. 4,
  151947. 44,
  151948. 3,
  151949. 45,
  151950. 2,
  151951. 46,
  151952. 1,
  151953. 47,
  151954. 0,
  151955. 48,
  151956. };
  151957. static long _vq_lengthlist__44u8_p9_2[] = {
  151958. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151959. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151960. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151961. 7,
  151962. };
  151963. static float _vq_quantthresh__44u8_p9_2[] = {
  151964. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151965. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151966. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151967. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151968. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151969. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151970. };
  151971. static long _vq_quantmap__44u8_p9_2[] = {
  151972. 47, 45, 43, 41, 39, 37, 35, 33,
  151973. 31, 29, 27, 25, 23, 21, 19, 17,
  151974. 15, 13, 11, 9, 7, 5, 3, 1,
  151975. 0, 2, 4, 6, 8, 10, 12, 14,
  151976. 16, 18, 20, 22, 24, 26, 28, 30,
  151977. 32, 34, 36, 38, 40, 42, 44, 46,
  151978. 48,
  151979. };
  151980. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151981. _vq_quantthresh__44u8_p9_2,
  151982. _vq_quantmap__44u8_p9_2,
  151983. 49,
  151984. 49
  151985. };
  151986. static static_codebook _44u8_p9_2 = {
  151987. 1, 49,
  151988. _vq_lengthlist__44u8_p9_2,
  151989. 1, -526909440, 1611661312, 6, 0,
  151990. _vq_quantlist__44u8_p9_2,
  151991. NULL,
  151992. &_vq_auxt__44u8_p9_2,
  151993. NULL,
  151994. 0
  151995. };
  151996. static long _huff_lengthlist__44u9__long[] = {
  151997. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151998. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151999. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  152000. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  152001. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  152002. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  152003. 10, 8, 8, 9,
  152004. };
  152005. static static_codebook _huff_book__44u9__long = {
  152006. 2, 100,
  152007. _huff_lengthlist__44u9__long,
  152008. 0, 0, 0, 0, 0,
  152009. NULL,
  152010. NULL,
  152011. NULL,
  152012. NULL,
  152013. 0
  152014. };
  152015. static long _huff_lengthlist__44u9__short[] = {
  152016. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  152017. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  152018. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  152019. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  152020. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  152021. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  152022. 9, 9,12,15,
  152023. };
  152024. static static_codebook _huff_book__44u9__short = {
  152025. 2, 100,
  152026. _huff_lengthlist__44u9__short,
  152027. 0, 0, 0, 0, 0,
  152028. NULL,
  152029. NULL,
  152030. NULL,
  152031. NULL,
  152032. 0
  152033. };
  152034. static long _vq_quantlist__44u9_p1_0[] = {
  152035. 1,
  152036. 0,
  152037. 2,
  152038. };
  152039. static long _vq_lengthlist__44u9_p1_0[] = {
  152040. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  152041. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  152042. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  152043. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  152044. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  152045. 10,
  152046. };
  152047. static float _vq_quantthresh__44u9_p1_0[] = {
  152048. -0.5, 0.5,
  152049. };
  152050. static long _vq_quantmap__44u9_p1_0[] = {
  152051. 1, 0, 2,
  152052. };
  152053. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  152054. _vq_quantthresh__44u9_p1_0,
  152055. _vq_quantmap__44u9_p1_0,
  152056. 3,
  152057. 3
  152058. };
  152059. static static_codebook _44u9_p1_0 = {
  152060. 4, 81,
  152061. _vq_lengthlist__44u9_p1_0,
  152062. 1, -535822336, 1611661312, 2, 0,
  152063. _vq_quantlist__44u9_p1_0,
  152064. NULL,
  152065. &_vq_auxt__44u9_p1_0,
  152066. NULL,
  152067. 0
  152068. };
  152069. static long _vq_quantlist__44u9_p2_0[] = {
  152070. 2,
  152071. 1,
  152072. 3,
  152073. 0,
  152074. 4,
  152075. };
  152076. static long _vq_lengthlist__44u9_p2_0[] = {
  152077. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  152078. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  152079. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  152080. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  152081. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  152082. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  152083. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  152084. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  152085. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  152086. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  152087. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  152088. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  152089. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  152090. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  152091. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  152092. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  152093. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  152094. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  152095. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  152096. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  152097. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  152098. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  152099. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  152100. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  152101. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  152102. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  152103. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  152104. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  152105. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  152106. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  152107. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  152108. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  152109. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  152110. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  152111. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  152112. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  152113. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  152114. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  152115. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  152116. 14,
  152117. };
  152118. static float _vq_quantthresh__44u9_p2_0[] = {
  152119. -1.5, -0.5, 0.5, 1.5,
  152120. };
  152121. static long _vq_quantmap__44u9_p2_0[] = {
  152122. 3, 1, 0, 2, 4,
  152123. };
  152124. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  152125. _vq_quantthresh__44u9_p2_0,
  152126. _vq_quantmap__44u9_p2_0,
  152127. 5,
  152128. 5
  152129. };
  152130. static static_codebook _44u9_p2_0 = {
  152131. 4, 625,
  152132. _vq_lengthlist__44u9_p2_0,
  152133. 1, -533725184, 1611661312, 3, 0,
  152134. _vq_quantlist__44u9_p2_0,
  152135. NULL,
  152136. &_vq_auxt__44u9_p2_0,
  152137. NULL,
  152138. 0
  152139. };
  152140. static long _vq_quantlist__44u9_p3_0[] = {
  152141. 4,
  152142. 3,
  152143. 5,
  152144. 2,
  152145. 6,
  152146. 1,
  152147. 7,
  152148. 0,
  152149. 8,
  152150. };
  152151. static long _vq_lengthlist__44u9_p3_0[] = {
  152152. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152153. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152154. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152155. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152156. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152157. 11,
  152158. };
  152159. static float _vq_quantthresh__44u9_p3_0[] = {
  152160. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152161. };
  152162. static long _vq_quantmap__44u9_p3_0[] = {
  152163. 7, 5, 3, 1, 0, 2, 4, 6,
  152164. 8,
  152165. };
  152166. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152167. _vq_quantthresh__44u9_p3_0,
  152168. _vq_quantmap__44u9_p3_0,
  152169. 9,
  152170. 9
  152171. };
  152172. static static_codebook _44u9_p3_0 = {
  152173. 2, 81,
  152174. _vq_lengthlist__44u9_p3_0,
  152175. 1, -531628032, 1611661312, 4, 0,
  152176. _vq_quantlist__44u9_p3_0,
  152177. NULL,
  152178. &_vq_auxt__44u9_p3_0,
  152179. NULL,
  152180. 0
  152181. };
  152182. static long _vq_quantlist__44u9_p4_0[] = {
  152183. 8,
  152184. 7,
  152185. 9,
  152186. 6,
  152187. 10,
  152188. 5,
  152189. 11,
  152190. 4,
  152191. 12,
  152192. 3,
  152193. 13,
  152194. 2,
  152195. 14,
  152196. 1,
  152197. 15,
  152198. 0,
  152199. 16,
  152200. };
  152201. static long _vq_lengthlist__44u9_p4_0[] = {
  152202. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152203. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152204. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152205. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152206. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152207. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152208. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152209. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152210. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152211. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152212. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152213. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152214. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152215. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152216. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152217. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152218. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152219. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152220. 14,
  152221. };
  152222. static float _vq_quantthresh__44u9_p4_0[] = {
  152223. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152224. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152225. };
  152226. static long _vq_quantmap__44u9_p4_0[] = {
  152227. 15, 13, 11, 9, 7, 5, 3, 1,
  152228. 0, 2, 4, 6, 8, 10, 12, 14,
  152229. 16,
  152230. };
  152231. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152232. _vq_quantthresh__44u9_p4_0,
  152233. _vq_quantmap__44u9_p4_0,
  152234. 17,
  152235. 17
  152236. };
  152237. static static_codebook _44u9_p4_0 = {
  152238. 2, 289,
  152239. _vq_lengthlist__44u9_p4_0,
  152240. 1, -529530880, 1611661312, 5, 0,
  152241. _vq_quantlist__44u9_p4_0,
  152242. NULL,
  152243. &_vq_auxt__44u9_p4_0,
  152244. NULL,
  152245. 0
  152246. };
  152247. static long _vq_quantlist__44u9_p5_0[] = {
  152248. 1,
  152249. 0,
  152250. 2,
  152251. };
  152252. static long _vq_lengthlist__44u9_p5_0[] = {
  152253. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152254. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152255. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152256. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152257. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152258. 10,
  152259. };
  152260. static float _vq_quantthresh__44u9_p5_0[] = {
  152261. -5.5, 5.5,
  152262. };
  152263. static long _vq_quantmap__44u9_p5_0[] = {
  152264. 1, 0, 2,
  152265. };
  152266. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152267. _vq_quantthresh__44u9_p5_0,
  152268. _vq_quantmap__44u9_p5_0,
  152269. 3,
  152270. 3
  152271. };
  152272. static static_codebook _44u9_p5_0 = {
  152273. 4, 81,
  152274. _vq_lengthlist__44u9_p5_0,
  152275. 1, -529137664, 1618345984, 2, 0,
  152276. _vq_quantlist__44u9_p5_0,
  152277. NULL,
  152278. &_vq_auxt__44u9_p5_0,
  152279. NULL,
  152280. 0
  152281. };
  152282. static long _vq_quantlist__44u9_p5_1[] = {
  152283. 5,
  152284. 4,
  152285. 6,
  152286. 3,
  152287. 7,
  152288. 2,
  152289. 8,
  152290. 1,
  152291. 9,
  152292. 0,
  152293. 10,
  152294. };
  152295. static long _vq_lengthlist__44u9_p5_1[] = {
  152296. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152297. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152298. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152299. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152300. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152301. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152302. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152303. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152304. };
  152305. static float _vq_quantthresh__44u9_p5_1[] = {
  152306. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152307. 3.5, 4.5,
  152308. };
  152309. static long _vq_quantmap__44u9_p5_1[] = {
  152310. 9, 7, 5, 3, 1, 0, 2, 4,
  152311. 6, 8, 10,
  152312. };
  152313. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152314. _vq_quantthresh__44u9_p5_1,
  152315. _vq_quantmap__44u9_p5_1,
  152316. 11,
  152317. 11
  152318. };
  152319. static static_codebook _44u9_p5_1 = {
  152320. 2, 121,
  152321. _vq_lengthlist__44u9_p5_1,
  152322. 1, -531365888, 1611661312, 4, 0,
  152323. _vq_quantlist__44u9_p5_1,
  152324. NULL,
  152325. &_vq_auxt__44u9_p5_1,
  152326. NULL,
  152327. 0
  152328. };
  152329. static long _vq_quantlist__44u9_p6_0[] = {
  152330. 6,
  152331. 5,
  152332. 7,
  152333. 4,
  152334. 8,
  152335. 3,
  152336. 9,
  152337. 2,
  152338. 10,
  152339. 1,
  152340. 11,
  152341. 0,
  152342. 12,
  152343. };
  152344. static long _vq_lengthlist__44u9_p6_0[] = {
  152345. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152346. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152347. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152348. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152349. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152350. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152351. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152352. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152353. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152354. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152355. 10,11,11,11,11,12,11,12,12,
  152356. };
  152357. static float _vq_quantthresh__44u9_p6_0[] = {
  152358. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152359. 12.5, 17.5, 22.5, 27.5,
  152360. };
  152361. static long _vq_quantmap__44u9_p6_0[] = {
  152362. 11, 9, 7, 5, 3, 1, 0, 2,
  152363. 4, 6, 8, 10, 12,
  152364. };
  152365. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152366. _vq_quantthresh__44u9_p6_0,
  152367. _vq_quantmap__44u9_p6_0,
  152368. 13,
  152369. 13
  152370. };
  152371. static static_codebook _44u9_p6_0 = {
  152372. 2, 169,
  152373. _vq_lengthlist__44u9_p6_0,
  152374. 1, -526516224, 1616117760, 4, 0,
  152375. _vq_quantlist__44u9_p6_0,
  152376. NULL,
  152377. &_vq_auxt__44u9_p6_0,
  152378. NULL,
  152379. 0
  152380. };
  152381. static long _vq_quantlist__44u9_p6_1[] = {
  152382. 2,
  152383. 1,
  152384. 3,
  152385. 0,
  152386. 4,
  152387. };
  152388. static long _vq_lengthlist__44u9_p6_1[] = {
  152389. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152390. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152391. };
  152392. static float _vq_quantthresh__44u9_p6_1[] = {
  152393. -1.5, -0.5, 0.5, 1.5,
  152394. };
  152395. static long _vq_quantmap__44u9_p6_1[] = {
  152396. 3, 1, 0, 2, 4,
  152397. };
  152398. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152399. _vq_quantthresh__44u9_p6_1,
  152400. _vq_quantmap__44u9_p6_1,
  152401. 5,
  152402. 5
  152403. };
  152404. static static_codebook _44u9_p6_1 = {
  152405. 2, 25,
  152406. _vq_lengthlist__44u9_p6_1,
  152407. 1, -533725184, 1611661312, 3, 0,
  152408. _vq_quantlist__44u9_p6_1,
  152409. NULL,
  152410. &_vq_auxt__44u9_p6_1,
  152411. NULL,
  152412. 0
  152413. };
  152414. static long _vq_quantlist__44u9_p7_0[] = {
  152415. 6,
  152416. 5,
  152417. 7,
  152418. 4,
  152419. 8,
  152420. 3,
  152421. 9,
  152422. 2,
  152423. 10,
  152424. 1,
  152425. 11,
  152426. 0,
  152427. 12,
  152428. };
  152429. static long _vq_lengthlist__44u9_p7_0[] = {
  152430. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152431. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152432. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152433. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152434. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152435. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152436. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152437. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152438. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152439. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152440. 12,13,13,14,14,14,15,15,15,
  152441. };
  152442. static float _vq_quantthresh__44u9_p7_0[] = {
  152443. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152444. 27.5, 38.5, 49.5, 60.5,
  152445. };
  152446. static long _vq_quantmap__44u9_p7_0[] = {
  152447. 11, 9, 7, 5, 3, 1, 0, 2,
  152448. 4, 6, 8, 10, 12,
  152449. };
  152450. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152451. _vq_quantthresh__44u9_p7_0,
  152452. _vq_quantmap__44u9_p7_0,
  152453. 13,
  152454. 13
  152455. };
  152456. static static_codebook _44u9_p7_0 = {
  152457. 2, 169,
  152458. _vq_lengthlist__44u9_p7_0,
  152459. 1, -523206656, 1618345984, 4, 0,
  152460. _vq_quantlist__44u9_p7_0,
  152461. NULL,
  152462. &_vq_auxt__44u9_p7_0,
  152463. NULL,
  152464. 0
  152465. };
  152466. static long _vq_quantlist__44u9_p7_1[] = {
  152467. 5,
  152468. 4,
  152469. 6,
  152470. 3,
  152471. 7,
  152472. 2,
  152473. 8,
  152474. 1,
  152475. 9,
  152476. 0,
  152477. 10,
  152478. };
  152479. static long _vq_lengthlist__44u9_p7_1[] = {
  152480. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152481. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152482. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152483. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152484. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152485. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152486. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152487. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152488. };
  152489. static float _vq_quantthresh__44u9_p7_1[] = {
  152490. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152491. 3.5, 4.5,
  152492. };
  152493. static long _vq_quantmap__44u9_p7_1[] = {
  152494. 9, 7, 5, 3, 1, 0, 2, 4,
  152495. 6, 8, 10,
  152496. };
  152497. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152498. _vq_quantthresh__44u9_p7_1,
  152499. _vq_quantmap__44u9_p7_1,
  152500. 11,
  152501. 11
  152502. };
  152503. static static_codebook _44u9_p7_1 = {
  152504. 2, 121,
  152505. _vq_lengthlist__44u9_p7_1,
  152506. 1, -531365888, 1611661312, 4, 0,
  152507. _vq_quantlist__44u9_p7_1,
  152508. NULL,
  152509. &_vq_auxt__44u9_p7_1,
  152510. NULL,
  152511. 0
  152512. };
  152513. static long _vq_quantlist__44u9_p8_0[] = {
  152514. 7,
  152515. 6,
  152516. 8,
  152517. 5,
  152518. 9,
  152519. 4,
  152520. 10,
  152521. 3,
  152522. 11,
  152523. 2,
  152524. 12,
  152525. 1,
  152526. 13,
  152527. 0,
  152528. 14,
  152529. };
  152530. static long _vq_lengthlist__44u9_p8_0[] = {
  152531. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152532. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152533. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152534. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152535. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152536. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152537. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152538. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152539. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152540. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152541. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152542. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152543. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152544. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152545. 15,
  152546. };
  152547. static float _vq_quantthresh__44u9_p8_0[] = {
  152548. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152549. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152550. };
  152551. static long _vq_quantmap__44u9_p8_0[] = {
  152552. 13, 11, 9, 7, 5, 3, 1, 0,
  152553. 2, 4, 6, 8, 10, 12, 14,
  152554. };
  152555. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152556. _vq_quantthresh__44u9_p8_0,
  152557. _vq_quantmap__44u9_p8_0,
  152558. 15,
  152559. 15
  152560. };
  152561. static static_codebook _44u9_p8_0 = {
  152562. 2, 225,
  152563. _vq_lengthlist__44u9_p8_0,
  152564. 1, -520986624, 1620377600, 4, 0,
  152565. _vq_quantlist__44u9_p8_0,
  152566. NULL,
  152567. &_vq_auxt__44u9_p8_0,
  152568. NULL,
  152569. 0
  152570. };
  152571. static long _vq_quantlist__44u9_p8_1[] = {
  152572. 10,
  152573. 9,
  152574. 11,
  152575. 8,
  152576. 12,
  152577. 7,
  152578. 13,
  152579. 6,
  152580. 14,
  152581. 5,
  152582. 15,
  152583. 4,
  152584. 16,
  152585. 3,
  152586. 17,
  152587. 2,
  152588. 18,
  152589. 1,
  152590. 19,
  152591. 0,
  152592. 20,
  152593. };
  152594. static long _vq_lengthlist__44u9_p8_1[] = {
  152595. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152596. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152597. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152598. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152599. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152600. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152601. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152602. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152603. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152604. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152605. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152606. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152607. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152608. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152609. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152610. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152611. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152612. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152613. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152614. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152615. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152616. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152617. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152618. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152619. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152620. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152621. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152622. 10,10,10,10,10,10,10,10,10,
  152623. };
  152624. static float _vq_quantthresh__44u9_p8_1[] = {
  152625. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152626. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152627. 6.5, 7.5, 8.5, 9.5,
  152628. };
  152629. static long _vq_quantmap__44u9_p8_1[] = {
  152630. 19, 17, 15, 13, 11, 9, 7, 5,
  152631. 3, 1, 0, 2, 4, 6, 8, 10,
  152632. 12, 14, 16, 18, 20,
  152633. };
  152634. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152635. _vq_quantthresh__44u9_p8_1,
  152636. _vq_quantmap__44u9_p8_1,
  152637. 21,
  152638. 21
  152639. };
  152640. static static_codebook _44u9_p8_1 = {
  152641. 2, 441,
  152642. _vq_lengthlist__44u9_p8_1,
  152643. 1, -529268736, 1611661312, 5, 0,
  152644. _vq_quantlist__44u9_p8_1,
  152645. NULL,
  152646. &_vq_auxt__44u9_p8_1,
  152647. NULL,
  152648. 0
  152649. };
  152650. static long _vq_quantlist__44u9_p9_0[] = {
  152651. 7,
  152652. 6,
  152653. 8,
  152654. 5,
  152655. 9,
  152656. 4,
  152657. 10,
  152658. 3,
  152659. 11,
  152660. 2,
  152661. 12,
  152662. 1,
  152663. 13,
  152664. 0,
  152665. 14,
  152666. };
  152667. static long _vq_lengthlist__44u9_p9_0[] = {
  152668. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152669. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152670. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152671. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152672. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152673. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152674. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152675. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152676. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152680. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152681. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152682. 10,
  152683. };
  152684. static float _vq_quantthresh__44u9_p9_0[] = {
  152685. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152686. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152687. };
  152688. static long _vq_quantmap__44u9_p9_0[] = {
  152689. 13, 11, 9, 7, 5, 3, 1, 0,
  152690. 2, 4, 6, 8, 10, 12, 14,
  152691. };
  152692. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152693. _vq_quantthresh__44u9_p9_0,
  152694. _vq_quantmap__44u9_p9_0,
  152695. 15,
  152696. 15
  152697. };
  152698. static static_codebook _44u9_p9_0 = {
  152699. 2, 225,
  152700. _vq_lengthlist__44u9_p9_0,
  152701. 1, -510036736, 1631393792, 4, 0,
  152702. _vq_quantlist__44u9_p9_0,
  152703. NULL,
  152704. &_vq_auxt__44u9_p9_0,
  152705. NULL,
  152706. 0
  152707. };
  152708. static long _vq_quantlist__44u9_p9_1[] = {
  152709. 9,
  152710. 8,
  152711. 10,
  152712. 7,
  152713. 11,
  152714. 6,
  152715. 12,
  152716. 5,
  152717. 13,
  152718. 4,
  152719. 14,
  152720. 3,
  152721. 15,
  152722. 2,
  152723. 16,
  152724. 1,
  152725. 17,
  152726. 0,
  152727. 18,
  152728. };
  152729. static long _vq_lengthlist__44u9_p9_1[] = {
  152730. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152731. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152732. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152733. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152734. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152735. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152736. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152737. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152738. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152739. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152740. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152741. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152742. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152743. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152744. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152745. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152746. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152747. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152748. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152749. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152750. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152751. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152752. 17,17,15,17,15,17,16,16,17,
  152753. };
  152754. static float _vq_quantthresh__44u9_p9_1[] = {
  152755. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152756. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152757. 367.5, 416.5,
  152758. };
  152759. static long _vq_quantmap__44u9_p9_1[] = {
  152760. 17, 15, 13, 11, 9, 7, 5, 3,
  152761. 1, 0, 2, 4, 6, 8, 10, 12,
  152762. 14, 16, 18,
  152763. };
  152764. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152765. _vq_quantthresh__44u9_p9_1,
  152766. _vq_quantmap__44u9_p9_1,
  152767. 19,
  152768. 19
  152769. };
  152770. static static_codebook _44u9_p9_1 = {
  152771. 2, 361,
  152772. _vq_lengthlist__44u9_p9_1,
  152773. 1, -518287360, 1622704128, 5, 0,
  152774. _vq_quantlist__44u9_p9_1,
  152775. NULL,
  152776. &_vq_auxt__44u9_p9_1,
  152777. NULL,
  152778. 0
  152779. };
  152780. static long _vq_quantlist__44u9_p9_2[] = {
  152781. 24,
  152782. 23,
  152783. 25,
  152784. 22,
  152785. 26,
  152786. 21,
  152787. 27,
  152788. 20,
  152789. 28,
  152790. 19,
  152791. 29,
  152792. 18,
  152793. 30,
  152794. 17,
  152795. 31,
  152796. 16,
  152797. 32,
  152798. 15,
  152799. 33,
  152800. 14,
  152801. 34,
  152802. 13,
  152803. 35,
  152804. 12,
  152805. 36,
  152806. 11,
  152807. 37,
  152808. 10,
  152809. 38,
  152810. 9,
  152811. 39,
  152812. 8,
  152813. 40,
  152814. 7,
  152815. 41,
  152816. 6,
  152817. 42,
  152818. 5,
  152819. 43,
  152820. 4,
  152821. 44,
  152822. 3,
  152823. 45,
  152824. 2,
  152825. 46,
  152826. 1,
  152827. 47,
  152828. 0,
  152829. 48,
  152830. };
  152831. static long _vq_lengthlist__44u9_p9_2[] = {
  152832. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152833. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152834. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152835. 7,
  152836. };
  152837. static float _vq_quantthresh__44u9_p9_2[] = {
  152838. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152839. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152840. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152841. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152842. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152843. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152844. };
  152845. static long _vq_quantmap__44u9_p9_2[] = {
  152846. 47, 45, 43, 41, 39, 37, 35, 33,
  152847. 31, 29, 27, 25, 23, 21, 19, 17,
  152848. 15, 13, 11, 9, 7, 5, 3, 1,
  152849. 0, 2, 4, 6, 8, 10, 12, 14,
  152850. 16, 18, 20, 22, 24, 26, 28, 30,
  152851. 32, 34, 36, 38, 40, 42, 44, 46,
  152852. 48,
  152853. };
  152854. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152855. _vq_quantthresh__44u9_p9_2,
  152856. _vq_quantmap__44u9_p9_2,
  152857. 49,
  152858. 49
  152859. };
  152860. static static_codebook _44u9_p9_2 = {
  152861. 1, 49,
  152862. _vq_lengthlist__44u9_p9_2,
  152863. 1, -526909440, 1611661312, 6, 0,
  152864. _vq_quantlist__44u9_p9_2,
  152865. NULL,
  152866. &_vq_auxt__44u9_p9_2,
  152867. NULL,
  152868. 0
  152869. };
  152870. static long _huff_lengthlist__44un1__long[] = {
  152871. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152872. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152873. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152874. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152875. };
  152876. static static_codebook _huff_book__44un1__long = {
  152877. 2, 64,
  152878. _huff_lengthlist__44un1__long,
  152879. 0, 0, 0, 0, 0,
  152880. NULL,
  152881. NULL,
  152882. NULL,
  152883. NULL,
  152884. 0
  152885. };
  152886. static long _vq_quantlist__44un1__p1_0[] = {
  152887. 1,
  152888. 0,
  152889. 2,
  152890. };
  152891. static long _vq_lengthlist__44un1__p1_0[] = {
  152892. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152893. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152894. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152895. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152896. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152897. 12,
  152898. };
  152899. static float _vq_quantthresh__44un1__p1_0[] = {
  152900. -0.5, 0.5,
  152901. };
  152902. static long _vq_quantmap__44un1__p1_0[] = {
  152903. 1, 0, 2,
  152904. };
  152905. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152906. _vq_quantthresh__44un1__p1_0,
  152907. _vq_quantmap__44un1__p1_0,
  152908. 3,
  152909. 3
  152910. };
  152911. static static_codebook _44un1__p1_0 = {
  152912. 4, 81,
  152913. _vq_lengthlist__44un1__p1_0,
  152914. 1, -535822336, 1611661312, 2, 0,
  152915. _vq_quantlist__44un1__p1_0,
  152916. NULL,
  152917. &_vq_auxt__44un1__p1_0,
  152918. NULL,
  152919. 0
  152920. };
  152921. static long _vq_quantlist__44un1__p2_0[] = {
  152922. 1,
  152923. 0,
  152924. 2,
  152925. };
  152926. static long _vq_lengthlist__44un1__p2_0[] = {
  152927. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152928. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152929. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152930. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152931. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152932. 8,
  152933. };
  152934. static float _vq_quantthresh__44un1__p2_0[] = {
  152935. -0.5, 0.5,
  152936. };
  152937. static long _vq_quantmap__44un1__p2_0[] = {
  152938. 1, 0, 2,
  152939. };
  152940. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152941. _vq_quantthresh__44un1__p2_0,
  152942. _vq_quantmap__44un1__p2_0,
  152943. 3,
  152944. 3
  152945. };
  152946. static static_codebook _44un1__p2_0 = {
  152947. 4, 81,
  152948. _vq_lengthlist__44un1__p2_0,
  152949. 1, -535822336, 1611661312, 2, 0,
  152950. _vq_quantlist__44un1__p2_0,
  152951. NULL,
  152952. &_vq_auxt__44un1__p2_0,
  152953. NULL,
  152954. 0
  152955. };
  152956. static long _vq_quantlist__44un1__p3_0[] = {
  152957. 2,
  152958. 1,
  152959. 3,
  152960. 0,
  152961. 4,
  152962. };
  152963. static long _vq_lengthlist__44un1__p3_0[] = {
  152964. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152965. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152966. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152967. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152968. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152969. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152970. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152971. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152972. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152973. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152974. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152975. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152976. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152977. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152978. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152979. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152980. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152981. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152982. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152983. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152984. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152985. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152986. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152987. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152988. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152989. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152990. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152991. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152992. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152993. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152994. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152995. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152996. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152997. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152998. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152999. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  153000. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  153001. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  153002. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  153003. 17,
  153004. };
  153005. static float _vq_quantthresh__44un1__p3_0[] = {
  153006. -1.5, -0.5, 0.5, 1.5,
  153007. };
  153008. static long _vq_quantmap__44un1__p3_0[] = {
  153009. 3, 1, 0, 2, 4,
  153010. };
  153011. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  153012. _vq_quantthresh__44un1__p3_0,
  153013. _vq_quantmap__44un1__p3_0,
  153014. 5,
  153015. 5
  153016. };
  153017. static static_codebook _44un1__p3_0 = {
  153018. 4, 625,
  153019. _vq_lengthlist__44un1__p3_0,
  153020. 1, -533725184, 1611661312, 3, 0,
  153021. _vq_quantlist__44un1__p3_0,
  153022. NULL,
  153023. &_vq_auxt__44un1__p3_0,
  153024. NULL,
  153025. 0
  153026. };
  153027. static long _vq_quantlist__44un1__p4_0[] = {
  153028. 2,
  153029. 1,
  153030. 3,
  153031. 0,
  153032. 4,
  153033. };
  153034. static long _vq_lengthlist__44un1__p4_0[] = {
  153035. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  153036. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  153037. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  153038. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  153039. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  153040. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  153041. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  153042. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  153043. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  153044. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  153045. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  153046. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  153047. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  153048. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  153049. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  153050. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  153051. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  153052. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  153053. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  153054. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  153055. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  153056. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  153057. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  153058. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  153059. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  153060. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  153061. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  153062. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  153063. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  153064. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  153065. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  153066. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  153067. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  153068. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  153069. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  153070. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  153071. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  153072. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  153073. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  153074. 12,
  153075. };
  153076. static float _vq_quantthresh__44un1__p4_0[] = {
  153077. -1.5, -0.5, 0.5, 1.5,
  153078. };
  153079. static long _vq_quantmap__44un1__p4_0[] = {
  153080. 3, 1, 0, 2, 4,
  153081. };
  153082. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  153083. _vq_quantthresh__44un1__p4_0,
  153084. _vq_quantmap__44un1__p4_0,
  153085. 5,
  153086. 5
  153087. };
  153088. static static_codebook _44un1__p4_0 = {
  153089. 4, 625,
  153090. _vq_lengthlist__44un1__p4_0,
  153091. 1, -533725184, 1611661312, 3, 0,
  153092. _vq_quantlist__44un1__p4_0,
  153093. NULL,
  153094. &_vq_auxt__44un1__p4_0,
  153095. NULL,
  153096. 0
  153097. };
  153098. static long _vq_quantlist__44un1__p5_0[] = {
  153099. 4,
  153100. 3,
  153101. 5,
  153102. 2,
  153103. 6,
  153104. 1,
  153105. 7,
  153106. 0,
  153107. 8,
  153108. };
  153109. static long _vq_lengthlist__44un1__p5_0[] = {
  153110. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  153111. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  153112. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  153113. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  153114. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  153115. 12,
  153116. };
  153117. static float _vq_quantthresh__44un1__p5_0[] = {
  153118. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  153119. };
  153120. static long _vq_quantmap__44un1__p5_0[] = {
  153121. 7, 5, 3, 1, 0, 2, 4, 6,
  153122. 8,
  153123. };
  153124. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  153125. _vq_quantthresh__44un1__p5_0,
  153126. _vq_quantmap__44un1__p5_0,
  153127. 9,
  153128. 9
  153129. };
  153130. static static_codebook _44un1__p5_0 = {
  153131. 2, 81,
  153132. _vq_lengthlist__44un1__p5_0,
  153133. 1, -531628032, 1611661312, 4, 0,
  153134. _vq_quantlist__44un1__p5_0,
  153135. NULL,
  153136. &_vq_auxt__44un1__p5_0,
  153137. NULL,
  153138. 0
  153139. };
  153140. static long _vq_quantlist__44un1__p6_0[] = {
  153141. 6,
  153142. 5,
  153143. 7,
  153144. 4,
  153145. 8,
  153146. 3,
  153147. 9,
  153148. 2,
  153149. 10,
  153150. 1,
  153151. 11,
  153152. 0,
  153153. 12,
  153154. };
  153155. static long _vq_lengthlist__44un1__p6_0[] = {
  153156. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153157. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153158. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153159. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153160. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153161. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153162. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153163. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153164. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153165. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153166. 16, 0,15,18,18, 0,16, 0, 0,
  153167. };
  153168. static float _vq_quantthresh__44un1__p6_0[] = {
  153169. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153170. 12.5, 17.5, 22.5, 27.5,
  153171. };
  153172. static long _vq_quantmap__44un1__p6_0[] = {
  153173. 11, 9, 7, 5, 3, 1, 0, 2,
  153174. 4, 6, 8, 10, 12,
  153175. };
  153176. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153177. _vq_quantthresh__44un1__p6_0,
  153178. _vq_quantmap__44un1__p6_0,
  153179. 13,
  153180. 13
  153181. };
  153182. static static_codebook _44un1__p6_0 = {
  153183. 2, 169,
  153184. _vq_lengthlist__44un1__p6_0,
  153185. 1, -526516224, 1616117760, 4, 0,
  153186. _vq_quantlist__44un1__p6_0,
  153187. NULL,
  153188. &_vq_auxt__44un1__p6_0,
  153189. NULL,
  153190. 0
  153191. };
  153192. static long _vq_quantlist__44un1__p6_1[] = {
  153193. 2,
  153194. 1,
  153195. 3,
  153196. 0,
  153197. 4,
  153198. };
  153199. static long _vq_lengthlist__44un1__p6_1[] = {
  153200. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153201. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153202. };
  153203. static float _vq_quantthresh__44un1__p6_1[] = {
  153204. -1.5, -0.5, 0.5, 1.5,
  153205. };
  153206. static long _vq_quantmap__44un1__p6_1[] = {
  153207. 3, 1, 0, 2, 4,
  153208. };
  153209. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153210. _vq_quantthresh__44un1__p6_1,
  153211. _vq_quantmap__44un1__p6_1,
  153212. 5,
  153213. 5
  153214. };
  153215. static static_codebook _44un1__p6_1 = {
  153216. 2, 25,
  153217. _vq_lengthlist__44un1__p6_1,
  153218. 1, -533725184, 1611661312, 3, 0,
  153219. _vq_quantlist__44un1__p6_1,
  153220. NULL,
  153221. &_vq_auxt__44un1__p6_1,
  153222. NULL,
  153223. 0
  153224. };
  153225. static long _vq_quantlist__44un1__p7_0[] = {
  153226. 2,
  153227. 1,
  153228. 3,
  153229. 0,
  153230. 4,
  153231. };
  153232. static long _vq_lengthlist__44un1__p7_0[] = {
  153233. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153234. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153235. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153236. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153237. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153238. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153239. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153240. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153241. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153242. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153243. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153244. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153245. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153246. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153247. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153248. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153249. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153250. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153254. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153256. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153257. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153258. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153259. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153269. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153270. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153271. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153272. 10,
  153273. };
  153274. static float _vq_quantthresh__44un1__p7_0[] = {
  153275. -253.5, -84.5, 84.5, 253.5,
  153276. };
  153277. static long _vq_quantmap__44un1__p7_0[] = {
  153278. 3, 1, 0, 2, 4,
  153279. };
  153280. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153281. _vq_quantthresh__44un1__p7_0,
  153282. _vq_quantmap__44un1__p7_0,
  153283. 5,
  153284. 5
  153285. };
  153286. static static_codebook _44un1__p7_0 = {
  153287. 4, 625,
  153288. _vq_lengthlist__44un1__p7_0,
  153289. 1, -518709248, 1626677248, 3, 0,
  153290. _vq_quantlist__44un1__p7_0,
  153291. NULL,
  153292. &_vq_auxt__44un1__p7_0,
  153293. NULL,
  153294. 0
  153295. };
  153296. static long _vq_quantlist__44un1__p7_1[] = {
  153297. 6,
  153298. 5,
  153299. 7,
  153300. 4,
  153301. 8,
  153302. 3,
  153303. 9,
  153304. 2,
  153305. 10,
  153306. 1,
  153307. 11,
  153308. 0,
  153309. 12,
  153310. };
  153311. static long _vq_lengthlist__44un1__p7_1[] = {
  153312. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153313. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153314. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153315. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153316. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153317. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153318. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153319. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153320. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153321. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153322. 12,13,13,12,13,13,14,14,14,
  153323. };
  153324. static float _vq_quantthresh__44un1__p7_1[] = {
  153325. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153326. 32.5, 45.5, 58.5, 71.5,
  153327. };
  153328. static long _vq_quantmap__44un1__p7_1[] = {
  153329. 11, 9, 7, 5, 3, 1, 0, 2,
  153330. 4, 6, 8, 10, 12,
  153331. };
  153332. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153333. _vq_quantthresh__44un1__p7_1,
  153334. _vq_quantmap__44un1__p7_1,
  153335. 13,
  153336. 13
  153337. };
  153338. static static_codebook _44un1__p7_1 = {
  153339. 2, 169,
  153340. _vq_lengthlist__44un1__p7_1,
  153341. 1, -523010048, 1618608128, 4, 0,
  153342. _vq_quantlist__44un1__p7_1,
  153343. NULL,
  153344. &_vq_auxt__44un1__p7_1,
  153345. NULL,
  153346. 0
  153347. };
  153348. static long _vq_quantlist__44un1__p7_2[] = {
  153349. 6,
  153350. 5,
  153351. 7,
  153352. 4,
  153353. 8,
  153354. 3,
  153355. 9,
  153356. 2,
  153357. 10,
  153358. 1,
  153359. 11,
  153360. 0,
  153361. 12,
  153362. };
  153363. static long _vq_lengthlist__44un1__p7_2[] = {
  153364. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153365. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153366. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153367. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153368. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153369. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153370. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153371. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153372. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153373. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153374. 9, 9, 9,10,10,10,10,10,10,
  153375. };
  153376. static float _vq_quantthresh__44un1__p7_2[] = {
  153377. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153378. 2.5, 3.5, 4.5, 5.5,
  153379. };
  153380. static long _vq_quantmap__44un1__p7_2[] = {
  153381. 11, 9, 7, 5, 3, 1, 0, 2,
  153382. 4, 6, 8, 10, 12,
  153383. };
  153384. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153385. _vq_quantthresh__44un1__p7_2,
  153386. _vq_quantmap__44un1__p7_2,
  153387. 13,
  153388. 13
  153389. };
  153390. static static_codebook _44un1__p7_2 = {
  153391. 2, 169,
  153392. _vq_lengthlist__44un1__p7_2,
  153393. 1, -531103744, 1611661312, 4, 0,
  153394. _vq_quantlist__44un1__p7_2,
  153395. NULL,
  153396. &_vq_auxt__44un1__p7_2,
  153397. NULL,
  153398. 0
  153399. };
  153400. static long _huff_lengthlist__44un1__short[] = {
  153401. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153402. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153403. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153404. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153405. };
  153406. static static_codebook _huff_book__44un1__short = {
  153407. 2, 64,
  153408. _huff_lengthlist__44un1__short,
  153409. 0, 0, 0, 0, 0,
  153410. NULL,
  153411. NULL,
  153412. NULL,
  153413. NULL,
  153414. 0
  153415. };
  153416. /*** End of inlined file: res_books_uncoupled.h ***/
  153417. /***** residue backends *********************************************/
  153418. static vorbis_info_residue0 _residue_44_low_un={
  153419. 0,-1, -1, 8,-1,
  153420. {0},
  153421. {-1},
  153422. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153423. { -1, 25, -1, 45, -1, -1, -1}
  153424. };
  153425. static vorbis_info_residue0 _residue_44_mid_un={
  153426. 0,-1, -1, 10,-1,
  153427. /* 0 1 2 3 4 5 6 7 8 9 */
  153428. {0},
  153429. {-1},
  153430. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153431. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153432. };
  153433. static vorbis_info_residue0 _residue_44_hi_un={
  153434. 0,-1, -1, 10,-1,
  153435. /* 0 1 2 3 4 5 6 7 8 9 */
  153436. {0},
  153437. {-1},
  153438. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153439. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153440. };
  153441. /* mapping conventions:
  153442. only one submap (this would change for efficient 5.1 support for example)*/
  153443. /* Four psychoacoustic profiles are used, one for each blocktype */
  153444. static vorbis_info_mapping0 _map_nominal_u[2]={
  153445. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153446. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153447. };
  153448. static static_bookblock _resbook_44u_n1={
  153449. {
  153450. {0},
  153451. {0,0,&_44un1__p1_0},
  153452. {0,0,&_44un1__p2_0},
  153453. {0,0,&_44un1__p3_0},
  153454. {0,0,&_44un1__p4_0},
  153455. {0,0,&_44un1__p5_0},
  153456. {&_44un1__p6_0,&_44un1__p6_1},
  153457. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153458. }
  153459. };
  153460. static static_bookblock _resbook_44u_0={
  153461. {
  153462. {0},
  153463. {0,0,&_44u0__p1_0},
  153464. {0,0,&_44u0__p2_0},
  153465. {0,0,&_44u0__p3_0},
  153466. {0,0,&_44u0__p4_0},
  153467. {0,0,&_44u0__p5_0},
  153468. {&_44u0__p6_0,&_44u0__p6_1},
  153469. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153470. }
  153471. };
  153472. static static_bookblock _resbook_44u_1={
  153473. {
  153474. {0},
  153475. {0,0,&_44u1__p1_0},
  153476. {0,0,&_44u1__p2_0},
  153477. {0,0,&_44u1__p3_0},
  153478. {0,0,&_44u1__p4_0},
  153479. {0,0,&_44u1__p5_0},
  153480. {&_44u1__p6_0,&_44u1__p6_1},
  153481. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153482. }
  153483. };
  153484. static static_bookblock _resbook_44u_2={
  153485. {
  153486. {0},
  153487. {0,0,&_44u2__p1_0},
  153488. {0,0,&_44u2__p2_0},
  153489. {0,0,&_44u2__p3_0},
  153490. {0,0,&_44u2__p4_0},
  153491. {0,0,&_44u2__p5_0},
  153492. {&_44u2__p6_0,&_44u2__p6_1},
  153493. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153494. }
  153495. };
  153496. static static_bookblock _resbook_44u_3={
  153497. {
  153498. {0},
  153499. {0,0,&_44u3__p1_0},
  153500. {0,0,&_44u3__p2_0},
  153501. {0,0,&_44u3__p3_0},
  153502. {0,0,&_44u3__p4_0},
  153503. {0,0,&_44u3__p5_0},
  153504. {&_44u3__p6_0,&_44u3__p6_1},
  153505. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153506. }
  153507. };
  153508. static static_bookblock _resbook_44u_4={
  153509. {
  153510. {0},
  153511. {0,0,&_44u4__p1_0},
  153512. {0,0,&_44u4__p2_0},
  153513. {0,0,&_44u4__p3_0},
  153514. {0,0,&_44u4__p4_0},
  153515. {0,0,&_44u4__p5_0},
  153516. {&_44u4__p6_0,&_44u4__p6_1},
  153517. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153518. }
  153519. };
  153520. static static_bookblock _resbook_44u_5={
  153521. {
  153522. {0},
  153523. {0,0,&_44u5__p1_0},
  153524. {0,0,&_44u5__p2_0},
  153525. {0,0,&_44u5__p3_0},
  153526. {0,0,&_44u5__p4_0},
  153527. {0,0,&_44u5__p5_0},
  153528. {0,0,&_44u5__p6_0},
  153529. {&_44u5__p7_0,&_44u5__p7_1},
  153530. {&_44u5__p8_0,&_44u5__p8_1},
  153531. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153532. }
  153533. };
  153534. static static_bookblock _resbook_44u_6={
  153535. {
  153536. {0},
  153537. {0,0,&_44u6__p1_0},
  153538. {0,0,&_44u6__p2_0},
  153539. {0,0,&_44u6__p3_0},
  153540. {0,0,&_44u6__p4_0},
  153541. {0,0,&_44u6__p5_0},
  153542. {0,0,&_44u6__p6_0},
  153543. {&_44u6__p7_0,&_44u6__p7_1},
  153544. {&_44u6__p8_0,&_44u6__p8_1},
  153545. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153546. }
  153547. };
  153548. static static_bookblock _resbook_44u_7={
  153549. {
  153550. {0},
  153551. {0,0,&_44u7__p1_0},
  153552. {0,0,&_44u7__p2_0},
  153553. {0,0,&_44u7__p3_0},
  153554. {0,0,&_44u7__p4_0},
  153555. {0,0,&_44u7__p5_0},
  153556. {0,0,&_44u7__p6_0},
  153557. {&_44u7__p7_0,&_44u7__p7_1},
  153558. {&_44u7__p8_0,&_44u7__p8_1},
  153559. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153560. }
  153561. };
  153562. static static_bookblock _resbook_44u_8={
  153563. {
  153564. {0},
  153565. {0,0,&_44u8_p1_0},
  153566. {0,0,&_44u8_p2_0},
  153567. {0,0,&_44u8_p3_0},
  153568. {0,0,&_44u8_p4_0},
  153569. {&_44u8_p5_0,&_44u8_p5_1},
  153570. {&_44u8_p6_0,&_44u8_p6_1},
  153571. {&_44u8_p7_0,&_44u8_p7_1},
  153572. {&_44u8_p8_0,&_44u8_p8_1},
  153573. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153574. }
  153575. };
  153576. static static_bookblock _resbook_44u_9={
  153577. {
  153578. {0},
  153579. {0,0,&_44u9_p1_0},
  153580. {0,0,&_44u9_p2_0},
  153581. {0,0,&_44u9_p3_0},
  153582. {0,0,&_44u9_p4_0},
  153583. {&_44u9_p5_0,&_44u9_p5_1},
  153584. {&_44u9_p6_0,&_44u9_p6_1},
  153585. {&_44u9_p7_0,&_44u9_p7_1},
  153586. {&_44u9_p8_0,&_44u9_p8_1},
  153587. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153588. }
  153589. };
  153590. static vorbis_residue_template _res_44u_n1[]={
  153591. {1,0, &_residue_44_low_un,
  153592. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153593. &_resbook_44u_n1,&_resbook_44u_n1},
  153594. {1,0, &_residue_44_low_un,
  153595. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153596. &_resbook_44u_n1,&_resbook_44u_n1}
  153597. };
  153598. static vorbis_residue_template _res_44u_0[]={
  153599. {1,0, &_residue_44_low_un,
  153600. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153601. &_resbook_44u_0,&_resbook_44u_0},
  153602. {1,0, &_residue_44_low_un,
  153603. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153604. &_resbook_44u_0,&_resbook_44u_0}
  153605. };
  153606. static vorbis_residue_template _res_44u_1[]={
  153607. {1,0, &_residue_44_low_un,
  153608. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153609. &_resbook_44u_1,&_resbook_44u_1},
  153610. {1,0, &_residue_44_low_un,
  153611. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153612. &_resbook_44u_1,&_resbook_44u_1}
  153613. };
  153614. static vorbis_residue_template _res_44u_2[]={
  153615. {1,0, &_residue_44_low_un,
  153616. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153617. &_resbook_44u_2,&_resbook_44u_2},
  153618. {1,0, &_residue_44_low_un,
  153619. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153620. &_resbook_44u_2,&_resbook_44u_2}
  153621. };
  153622. static vorbis_residue_template _res_44u_3[]={
  153623. {1,0, &_residue_44_low_un,
  153624. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153625. &_resbook_44u_3,&_resbook_44u_3},
  153626. {1,0, &_residue_44_low_un,
  153627. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153628. &_resbook_44u_3,&_resbook_44u_3}
  153629. };
  153630. static vorbis_residue_template _res_44u_4[]={
  153631. {1,0, &_residue_44_low_un,
  153632. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153633. &_resbook_44u_4,&_resbook_44u_4},
  153634. {1,0, &_residue_44_low_un,
  153635. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153636. &_resbook_44u_4,&_resbook_44u_4}
  153637. };
  153638. static vorbis_residue_template _res_44u_5[]={
  153639. {1,0, &_residue_44_mid_un,
  153640. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153641. &_resbook_44u_5,&_resbook_44u_5},
  153642. {1,0, &_residue_44_mid_un,
  153643. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153644. &_resbook_44u_5,&_resbook_44u_5}
  153645. };
  153646. static vorbis_residue_template _res_44u_6[]={
  153647. {1,0, &_residue_44_mid_un,
  153648. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153649. &_resbook_44u_6,&_resbook_44u_6},
  153650. {1,0, &_residue_44_mid_un,
  153651. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153652. &_resbook_44u_6,&_resbook_44u_6}
  153653. };
  153654. static vorbis_residue_template _res_44u_7[]={
  153655. {1,0, &_residue_44_mid_un,
  153656. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153657. &_resbook_44u_7,&_resbook_44u_7},
  153658. {1,0, &_residue_44_mid_un,
  153659. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153660. &_resbook_44u_7,&_resbook_44u_7}
  153661. };
  153662. static vorbis_residue_template _res_44u_8[]={
  153663. {1,0, &_residue_44_hi_un,
  153664. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153665. &_resbook_44u_8,&_resbook_44u_8},
  153666. {1,0, &_residue_44_hi_un,
  153667. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153668. &_resbook_44u_8,&_resbook_44u_8}
  153669. };
  153670. static vorbis_residue_template _res_44u_9[]={
  153671. {1,0, &_residue_44_hi_un,
  153672. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153673. &_resbook_44u_9,&_resbook_44u_9},
  153674. {1,0, &_residue_44_hi_un,
  153675. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153676. &_resbook_44u_9,&_resbook_44u_9}
  153677. };
  153678. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153679. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153680. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153681. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153682. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153683. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153684. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153685. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153686. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153687. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153688. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153689. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153690. };
  153691. /*** End of inlined file: residue_44u.h ***/
  153692. static double rate_mapping_44_un[12]={
  153693. 32000.,48000.,60000.,70000.,80000.,86000.,
  153694. 96000.,110000.,120000.,140000.,160000.,240001.
  153695. };
  153696. ve_setup_data_template ve_setup_44_uncoupled={
  153697. 11,
  153698. rate_mapping_44_un,
  153699. quality_mapping_44,
  153700. -1,
  153701. 40000,
  153702. 50000,
  153703. blocksize_short_44,
  153704. blocksize_long_44,
  153705. _psy_tone_masteratt_44,
  153706. _psy_tone_0dB,
  153707. _psy_tone_suppress,
  153708. _vp_tonemask_adj_otherblock,
  153709. _vp_tonemask_adj_longblock,
  153710. _vp_tonemask_adj_otherblock,
  153711. _psy_noiseguards_44,
  153712. _psy_noisebias_impulse,
  153713. _psy_noisebias_padding,
  153714. _psy_noisebias_trans,
  153715. _psy_noisebias_long,
  153716. _psy_noise_suppress,
  153717. _psy_compand_44,
  153718. _psy_compand_short_mapping,
  153719. _psy_compand_long_mapping,
  153720. {_noise_start_short_44,_noise_start_long_44},
  153721. {_noise_part_short_44,_noise_part_long_44},
  153722. _noise_thresh_44,
  153723. _psy_ath_floater,
  153724. _psy_ath_abs,
  153725. _psy_lowpass_44,
  153726. _psy_global_44,
  153727. _global_mapping_44,
  153728. NULL,
  153729. _floor_books,
  153730. _floor,
  153731. _floor_short_mapping_44,
  153732. _floor_long_mapping_44,
  153733. _mapres_template_44_uncoupled
  153734. };
  153735. /*** End of inlined file: setup_44u.h ***/
  153736. /*** Start of inlined file: setup_32.h ***/
  153737. static double rate_mapping_32[12]={
  153738. 18000.,28000.,35000.,45000.,56000.,60000.,
  153739. 75000.,90000.,100000.,115000.,150000.,190000.,
  153740. };
  153741. static double rate_mapping_32_un[12]={
  153742. 30000.,42000.,52000.,64000.,72000.,78000.,
  153743. 86000.,92000.,110000.,120000.,140000.,190000.,
  153744. };
  153745. static double _psy_lowpass_32[12]={
  153746. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153747. };
  153748. ve_setup_data_template ve_setup_32_stereo={
  153749. 11,
  153750. rate_mapping_32,
  153751. quality_mapping_44,
  153752. 2,
  153753. 26000,
  153754. 40000,
  153755. blocksize_short_44,
  153756. blocksize_long_44,
  153757. _psy_tone_masteratt_44,
  153758. _psy_tone_0dB,
  153759. _psy_tone_suppress,
  153760. _vp_tonemask_adj_otherblock,
  153761. _vp_tonemask_adj_longblock,
  153762. _vp_tonemask_adj_otherblock,
  153763. _psy_noiseguards_44,
  153764. _psy_noisebias_impulse,
  153765. _psy_noisebias_padding,
  153766. _psy_noisebias_trans,
  153767. _psy_noisebias_long,
  153768. _psy_noise_suppress,
  153769. _psy_compand_44,
  153770. _psy_compand_short_mapping,
  153771. _psy_compand_long_mapping,
  153772. {_noise_start_short_44,_noise_start_long_44},
  153773. {_noise_part_short_44,_noise_part_long_44},
  153774. _noise_thresh_44,
  153775. _psy_ath_floater,
  153776. _psy_ath_abs,
  153777. _psy_lowpass_32,
  153778. _psy_global_44,
  153779. _global_mapping_44,
  153780. _psy_stereo_modes_44,
  153781. _floor_books,
  153782. _floor,
  153783. _floor_short_mapping_44,
  153784. _floor_long_mapping_44,
  153785. _mapres_template_44_stereo
  153786. };
  153787. ve_setup_data_template ve_setup_32_uncoupled={
  153788. 11,
  153789. rate_mapping_32_un,
  153790. quality_mapping_44,
  153791. -1,
  153792. 26000,
  153793. 40000,
  153794. blocksize_short_44,
  153795. blocksize_long_44,
  153796. _psy_tone_masteratt_44,
  153797. _psy_tone_0dB,
  153798. _psy_tone_suppress,
  153799. _vp_tonemask_adj_otherblock,
  153800. _vp_tonemask_adj_longblock,
  153801. _vp_tonemask_adj_otherblock,
  153802. _psy_noiseguards_44,
  153803. _psy_noisebias_impulse,
  153804. _psy_noisebias_padding,
  153805. _psy_noisebias_trans,
  153806. _psy_noisebias_long,
  153807. _psy_noise_suppress,
  153808. _psy_compand_44,
  153809. _psy_compand_short_mapping,
  153810. _psy_compand_long_mapping,
  153811. {_noise_start_short_44,_noise_start_long_44},
  153812. {_noise_part_short_44,_noise_part_long_44},
  153813. _noise_thresh_44,
  153814. _psy_ath_floater,
  153815. _psy_ath_abs,
  153816. _psy_lowpass_32,
  153817. _psy_global_44,
  153818. _global_mapping_44,
  153819. NULL,
  153820. _floor_books,
  153821. _floor,
  153822. _floor_short_mapping_44,
  153823. _floor_long_mapping_44,
  153824. _mapres_template_44_uncoupled
  153825. };
  153826. /*** End of inlined file: setup_32.h ***/
  153827. /*** Start of inlined file: setup_8.h ***/
  153828. /*** Start of inlined file: psych_8.h ***/
  153829. static att3 _psy_tone_masteratt_8[3]={
  153830. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153831. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153832. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153833. };
  153834. static vp_adjblock _vp_tonemask_adj_8[3]={
  153835. /* adjust for mode zero */
  153836. /* 63 125 250 500 1 2 4 8 16 */
  153837. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153838. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153839. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153840. };
  153841. static noise3 _psy_noisebias_8[3]={
  153842. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153843. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153844. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153845. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153846. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153847. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153848. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153849. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153850. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153851. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153852. };
  153853. /* stereo mode by base quality level */
  153854. static adj_stereo _psy_stereo_modes_8[3]={
  153855. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153856. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153857. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153858. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153859. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153860. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153861. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153862. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153863. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153864. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153865. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153866. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153867. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153868. };
  153869. static noiseguard _psy_noiseguards_8[2]={
  153870. {10,10,-1},
  153871. {10,10,-1},
  153872. };
  153873. static compandblock _psy_compand_8[2]={
  153874. {{
  153875. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153876. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153877. 12,12,13,13,14,14,15, 15, /* 23dB */
  153878. 16,16,17,17,17,18,18, 19, /* 31dB */
  153879. 19,19,20,21,22,23,24, 25, /* 39dB */
  153880. }},
  153881. {{
  153882. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153883. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153884. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153885. 9,10,11,12,13,14,15, 16, /* 31dB */
  153886. 17,18,19,20,21,22,23, 24, /* 39dB */
  153887. }},
  153888. };
  153889. static double _psy_lowpass_8[3]={3.,4.,4.};
  153890. static int _noise_start_8[2]={
  153891. 64,64,
  153892. };
  153893. static int _noise_part_8[2]={
  153894. 8,8,
  153895. };
  153896. static int _psy_ath_floater_8[3]={
  153897. -100,-100,-105,
  153898. };
  153899. static int _psy_ath_abs_8[3]={
  153900. -130,-130,-140,
  153901. };
  153902. /*** End of inlined file: psych_8.h ***/
  153903. /*** Start of inlined file: residue_8.h ***/
  153904. /***** residue backends *********************************************/
  153905. static static_bookblock _resbook_8s_0={
  153906. {
  153907. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153908. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153909. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153910. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153911. }
  153912. };
  153913. static static_bookblock _resbook_8s_1={
  153914. {
  153915. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153916. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153917. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153918. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153919. }
  153920. };
  153921. static vorbis_residue_template _res_8s_0[]={
  153922. {2,0, &_residue_44_mid,
  153923. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153924. &_resbook_8s_0,&_resbook_8s_0},
  153925. };
  153926. static vorbis_residue_template _res_8s_1[]={
  153927. {2,0, &_residue_44_mid,
  153928. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153929. &_resbook_8s_1,&_resbook_8s_1},
  153930. };
  153931. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153932. { _map_nominal, _res_8s_0 }, /* 0 */
  153933. { _map_nominal, _res_8s_1 }, /* 1 */
  153934. };
  153935. static static_bookblock _resbook_8u_0={
  153936. {
  153937. {0},
  153938. {0,0,&_8u0__p1_0},
  153939. {0,0,&_8u0__p2_0},
  153940. {0,0,&_8u0__p3_0},
  153941. {0,0,&_8u0__p4_0},
  153942. {0,0,&_8u0__p5_0},
  153943. {&_8u0__p6_0,&_8u0__p6_1},
  153944. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153945. }
  153946. };
  153947. static static_bookblock _resbook_8u_1={
  153948. {
  153949. {0},
  153950. {0,0,&_8u1__p1_0},
  153951. {0,0,&_8u1__p2_0},
  153952. {0,0,&_8u1__p3_0},
  153953. {0,0,&_8u1__p4_0},
  153954. {0,0,&_8u1__p5_0},
  153955. {0,0,&_8u1__p6_0},
  153956. {&_8u1__p7_0,&_8u1__p7_1},
  153957. {&_8u1__p8_0,&_8u1__p8_1},
  153958. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153959. }
  153960. };
  153961. static vorbis_residue_template _res_8u_0[]={
  153962. {1,0, &_residue_44_low_un,
  153963. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153964. &_resbook_8u_0,&_resbook_8u_0},
  153965. };
  153966. static vorbis_residue_template _res_8u_1[]={
  153967. {1,0, &_residue_44_mid_un,
  153968. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153969. &_resbook_8u_1,&_resbook_8u_1},
  153970. };
  153971. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153972. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153973. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153974. };
  153975. /*** End of inlined file: residue_8.h ***/
  153976. static int blocksize_8[2]={
  153977. 512,512
  153978. };
  153979. static int _floor_mapping_8[2]={
  153980. 6,6,
  153981. };
  153982. static double rate_mapping_8[3]={
  153983. 6000.,9000.,32000.,
  153984. };
  153985. static double rate_mapping_8_uncoupled[3]={
  153986. 8000.,14000.,42000.,
  153987. };
  153988. static double quality_mapping_8[3]={
  153989. -.1,.0,1.
  153990. };
  153991. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153992. static double _global_mapping_8[3]={ 1., 2., 3. };
  153993. ve_setup_data_template ve_setup_8_stereo={
  153994. 2,
  153995. rate_mapping_8,
  153996. quality_mapping_8,
  153997. 2,
  153998. 8000,
  153999. 9000,
  154000. blocksize_8,
  154001. blocksize_8,
  154002. _psy_tone_masteratt_8,
  154003. _psy_tone_0dB,
  154004. _psy_tone_suppress,
  154005. _vp_tonemask_adj_8,
  154006. NULL,
  154007. _vp_tonemask_adj_8,
  154008. _psy_noiseguards_8,
  154009. _psy_noisebias_8,
  154010. _psy_noisebias_8,
  154011. NULL,
  154012. NULL,
  154013. _psy_noise_suppress,
  154014. _psy_compand_8,
  154015. _psy_compand_8_mapping,
  154016. NULL,
  154017. {_noise_start_8,_noise_start_8},
  154018. {_noise_part_8,_noise_part_8},
  154019. _noise_thresh_5only,
  154020. _psy_ath_floater_8,
  154021. _psy_ath_abs_8,
  154022. _psy_lowpass_8,
  154023. _psy_global_44,
  154024. _global_mapping_8,
  154025. _psy_stereo_modes_8,
  154026. _floor_books,
  154027. _floor,
  154028. _floor_mapping_8,
  154029. NULL,
  154030. _mapres_template_8_stereo
  154031. };
  154032. ve_setup_data_template ve_setup_8_uncoupled={
  154033. 2,
  154034. rate_mapping_8_uncoupled,
  154035. quality_mapping_8,
  154036. -1,
  154037. 8000,
  154038. 9000,
  154039. blocksize_8,
  154040. blocksize_8,
  154041. _psy_tone_masteratt_8,
  154042. _psy_tone_0dB,
  154043. _psy_tone_suppress,
  154044. _vp_tonemask_adj_8,
  154045. NULL,
  154046. _vp_tonemask_adj_8,
  154047. _psy_noiseguards_8,
  154048. _psy_noisebias_8,
  154049. _psy_noisebias_8,
  154050. NULL,
  154051. NULL,
  154052. _psy_noise_suppress,
  154053. _psy_compand_8,
  154054. _psy_compand_8_mapping,
  154055. NULL,
  154056. {_noise_start_8,_noise_start_8},
  154057. {_noise_part_8,_noise_part_8},
  154058. _noise_thresh_5only,
  154059. _psy_ath_floater_8,
  154060. _psy_ath_abs_8,
  154061. _psy_lowpass_8,
  154062. _psy_global_44,
  154063. _global_mapping_8,
  154064. _psy_stereo_modes_8,
  154065. _floor_books,
  154066. _floor,
  154067. _floor_mapping_8,
  154068. NULL,
  154069. _mapres_template_8_uncoupled
  154070. };
  154071. /*** End of inlined file: setup_8.h ***/
  154072. /*** Start of inlined file: setup_11.h ***/
  154073. /*** Start of inlined file: psych_11.h ***/
  154074. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  154075. static att3 _psy_tone_masteratt_11[3]={
  154076. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154077. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154078. {{ 20, 0, -14}, 0, 0}, /* 0 */
  154079. };
  154080. static vp_adjblock _vp_tonemask_adj_11[3]={
  154081. /* adjust for mode zero */
  154082. /* 63 125 250 500 1 2 4 8 16 */
  154083. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  154084. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  154085. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  154086. };
  154087. static noise3 _psy_noisebias_11[3]={
  154088. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154089. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154090. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  154091. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154092. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154093. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  154094. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154095. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  154096. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  154097. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  154098. };
  154099. static double _noise_thresh_11[3]={ .3,.5,.5 };
  154100. /*** End of inlined file: psych_11.h ***/
  154101. static int blocksize_11[2]={
  154102. 512,512
  154103. };
  154104. static int _floor_mapping_11[2]={
  154105. 6,6,
  154106. };
  154107. static double rate_mapping_11[3]={
  154108. 8000.,13000.,44000.,
  154109. };
  154110. static double rate_mapping_11_uncoupled[3]={
  154111. 12000.,20000.,50000.,
  154112. };
  154113. static double quality_mapping_11[3]={
  154114. -.1,.0,1.
  154115. };
  154116. ve_setup_data_template ve_setup_11_stereo={
  154117. 2,
  154118. rate_mapping_11,
  154119. quality_mapping_11,
  154120. 2,
  154121. 9000,
  154122. 15000,
  154123. blocksize_11,
  154124. blocksize_11,
  154125. _psy_tone_masteratt_11,
  154126. _psy_tone_0dB,
  154127. _psy_tone_suppress,
  154128. _vp_tonemask_adj_11,
  154129. NULL,
  154130. _vp_tonemask_adj_11,
  154131. _psy_noiseguards_8,
  154132. _psy_noisebias_11,
  154133. _psy_noisebias_11,
  154134. NULL,
  154135. NULL,
  154136. _psy_noise_suppress,
  154137. _psy_compand_8,
  154138. _psy_compand_8_mapping,
  154139. NULL,
  154140. {_noise_start_8,_noise_start_8},
  154141. {_noise_part_8,_noise_part_8},
  154142. _noise_thresh_11,
  154143. _psy_ath_floater_8,
  154144. _psy_ath_abs_8,
  154145. _psy_lowpass_11,
  154146. _psy_global_44,
  154147. _global_mapping_8,
  154148. _psy_stereo_modes_8,
  154149. _floor_books,
  154150. _floor,
  154151. _floor_mapping_11,
  154152. NULL,
  154153. _mapres_template_8_stereo
  154154. };
  154155. ve_setup_data_template ve_setup_11_uncoupled={
  154156. 2,
  154157. rate_mapping_11_uncoupled,
  154158. quality_mapping_11,
  154159. -1,
  154160. 9000,
  154161. 15000,
  154162. blocksize_11,
  154163. blocksize_11,
  154164. _psy_tone_masteratt_11,
  154165. _psy_tone_0dB,
  154166. _psy_tone_suppress,
  154167. _vp_tonemask_adj_11,
  154168. NULL,
  154169. _vp_tonemask_adj_11,
  154170. _psy_noiseguards_8,
  154171. _psy_noisebias_11,
  154172. _psy_noisebias_11,
  154173. NULL,
  154174. NULL,
  154175. _psy_noise_suppress,
  154176. _psy_compand_8,
  154177. _psy_compand_8_mapping,
  154178. NULL,
  154179. {_noise_start_8,_noise_start_8},
  154180. {_noise_part_8,_noise_part_8},
  154181. _noise_thresh_11,
  154182. _psy_ath_floater_8,
  154183. _psy_ath_abs_8,
  154184. _psy_lowpass_11,
  154185. _psy_global_44,
  154186. _global_mapping_8,
  154187. _psy_stereo_modes_8,
  154188. _floor_books,
  154189. _floor,
  154190. _floor_mapping_11,
  154191. NULL,
  154192. _mapres_template_8_uncoupled
  154193. };
  154194. /*** End of inlined file: setup_11.h ***/
  154195. /*** Start of inlined file: setup_16.h ***/
  154196. /*** Start of inlined file: psych_16.h ***/
  154197. /* stereo mode by base quality level */
  154198. static adj_stereo _psy_stereo_modes_16[4]={
  154199. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154200. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154201. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154202. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154203. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154204. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154205. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154206. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154207. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154208. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154209. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154210. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154211. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154212. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154213. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154214. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154215. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154216. };
  154217. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154218. static att3 _psy_tone_masteratt_16[4]={
  154219. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154220. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154221. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154222. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154223. };
  154224. static vp_adjblock _vp_tonemask_adj_16[4]={
  154225. /* adjust for mode zero */
  154226. /* 63 125 250 500 1 2 4 8 16 */
  154227. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154228. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154229. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154230. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154231. };
  154232. static noise3 _psy_noisebias_16_short[4]={
  154233. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154234. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154235. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154236. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154237. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154238. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154239. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154240. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154241. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154242. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154243. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154244. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154245. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154246. };
  154247. static noise3 _psy_noisebias_16_impulse[4]={
  154248. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154249. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154250. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154251. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154252. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154253. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154254. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154255. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154256. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154257. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154258. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154259. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154260. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154261. };
  154262. static noise3 _psy_noisebias_16[4]={
  154263. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154264. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154265. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154266. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154267. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154268. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154269. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154270. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154271. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154272. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154273. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154274. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154275. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154276. };
  154277. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154278. static int _noise_start_16[3]={ 256,256,9999 };
  154279. static int _noise_part_16[4]={ 8,8,8,8 };
  154280. static int _psy_ath_floater_16[4]={
  154281. -100,-100,-100,-105,
  154282. };
  154283. static int _psy_ath_abs_16[4]={
  154284. -130,-130,-130,-140,
  154285. };
  154286. /*** End of inlined file: psych_16.h ***/
  154287. /*** Start of inlined file: residue_16.h ***/
  154288. /***** residue backends *********************************************/
  154289. static static_bookblock _resbook_16s_0={
  154290. {
  154291. {0},
  154292. {0,0,&_16c0_s_p1_0},
  154293. {0,0,&_16c0_s_p2_0},
  154294. {0,0,&_16c0_s_p3_0},
  154295. {0,0,&_16c0_s_p4_0},
  154296. {0,0,&_16c0_s_p5_0},
  154297. {0,0,&_16c0_s_p6_0},
  154298. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154299. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154300. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154301. }
  154302. };
  154303. static static_bookblock _resbook_16s_1={
  154304. {
  154305. {0},
  154306. {0,0,&_16c1_s_p1_0},
  154307. {0,0,&_16c1_s_p2_0},
  154308. {0,0,&_16c1_s_p3_0},
  154309. {0,0,&_16c1_s_p4_0},
  154310. {0,0,&_16c1_s_p5_0},
  154311. {0,0,&_16c1_s_p6_0},
  154312. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154313. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154314. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154315. }
  154316. };
  154317. static static_bookblock _resbook_16s_2={
  154318. {
  154319. {0},
  154320. {0,0,&_16c2_s_p1_0},
  154321. {0,0,&_16c2_s_p2_0},
  154322. {0,0,&_16c2_s_p3_0},
  154323. {0,0,&_16c2_s_p4_0},
  154324. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154325. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154326. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154327. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154328. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154329. }
  154330. };
  154331. static vorbis_residue_template _res_16s_0[]={
  154332. {2,0, &_residue_44_mid,
  154333. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154334. &_resbook_16s_0,&_resbook_16s_0},
  154335. };
  154336. static vorbis_residue_template _res_16s_1[]={
  154337. {2,0, &_residue_44_mid,
  154338. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154339. &_resbook_16s_1,&_resbook_16s_1},
  154340. {2,0, &_residue_44_mid,
  154341. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154342. &_resbook_16s_1,&_resbook_16s_1}
  154343. };
  154344. static vorbis_residue_template _res_16s_2[]={
  154345. {2,0, &_residue_44_high,
  154346. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154347. &_resbook_16s_2,&_resbook_16s_2},
  154348. {2,0, &_residue_44_high,
  154349. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154350. &_resbook_16s_2,&_resbook_16s_2}
  154351. };
  154352. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154353. { _map_nominal, _res_16s_0 }, /* 0 */
  154354. { _map_nominal, _res_16s_1 }, /* 1 */
  154355. { _map_nominal, _res_16s_2 }, /* 2 */
  154356. };
  154357. static static_bookblock _resbook_16u_0={
  154358. {
  154359. {0},
  154360. {0,0,&_16u0__p1_0},
  154361. {0,0,&_16u0__p2_0},
  154362. {0,0,&_16u0__p3_0},
  154363. {0,0,&_16u0__p4_0},
  154364. {0,0,&_16u0__p5_0},
  154365. {&_16u0__p6_0,&_16u0__p6_1},
  154366. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154367. }
  154368. };
  154369. static static_bookblock _resbook_16u_1={
  154370. {
  154371. {0},
  154372. {0,0,&_16u1__p1_0},
  154373. {0,0,&_16u1__p2_0},
  154374. {0,0,&_16u1__p3_0},
  154375. {0,0,&_16u1__p4_0},
  154376. {0,0,&_16u1__p5_0},
  154377. {0,0,&_16u1__p6_0},
  154378. {&_16u1__p7_0,&_16u1__p7_1},
  154379. {&_16u1__p8_0,&_16u1__p8_1},
  154380. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154381. }
  154382. };
  154383. static static_bookblock _resbook_16u_2={
  154384. {
  154385. {0},
  154386. {0,0,&_16u2_p1_0},
  154387. {0,0,&_16u2_p2_0},
  154388. {0,0,&_16u2_p3_0},
  154389. {0,0,&_16u2_p4_0},
  154390. {&_16u2_p5_0,&_16u2_p5_1},
  154391. {&_16u2_p6_0,&_16u2_p6_1},
  154392. {&_16u2_p7_0,&_16u2_p7_1},
  154393. {&_16u2_p8_0,&_16u2_p8_1},
  154394. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154395. }
  154396. };
  154397. static vorbis_residue_template _res_16u_0[]={
  154398. {1,0, &_residue_44_low_un,
  154399. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154400. &_resbook_16u_0,&_resbook_16u_0},
  154401. };
  154402. static vorbis_residue_template _res_16u_1[]={
  154403. {1,0, &_residue_44_mid_un,
  154404. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154405. &_resbook_16u_1,&_resbook_16u_1},
  154406. {1,0, &_residue_44_mid_un,
  154407. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154408. &_resbook_16u_1,&_resbook_16u_1}
  154409. };
  154410. static vorbis_residue_template _res_16u_2[]={
  154411. {1,0, &_residue_44_hi_un,
  154412. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154413. &_resbook_16u_2,&_resbook_16u_2},
  154414. {1,0, &_residue_44_hi_un,
  154415. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154416. &_resbook_16u_2,&_resbook_16u_2}
  154417. };
  154418. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154419. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154420. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154421. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154422. };
  154423. /*** End of inlined file: residue_16.h ***/
  154424. static int blocksize_16_short[3]={
  154425. 1024,512,512
  154426. };
  154427. static int blocksize_16_long[3]={
  154428. 1024,1024,1024
  154429. };
  154430. static int _floor_mapping_16_short[3]={
  154431. 9,3,3
  154432. };
  154433. static int _floor_mapping_16[3]={
  154434. 9,9,9
  154435. };
  154436. static double rate_mapping_16[4]={
  154437. 12000.,20000.,44000.,86000.
  154438. };
  154439. static double rate_mapping_16_uncoupled[4]={
  154440. 16000.,28000.,64000.,100000.
  154441. };
  154442. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154443. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154444. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154445. ve_setup_data_template ve_setup_16_stereo={
  154446. 3,
  154447. rate_mapping_16,
  154448. quality_mapping_16,
  154449. 2,
  154450. 15000,
  154451. 19000,
  154452. blocksize_16_short,
  154453. blocksize_16_long,
  154454. _psy_tone_masteratt_16,
  154455. _psy_tone_0dB,
  154456. _psy_tone_suppress,
  154457. _vp_tonemask_adj_16,
  154458. _vp_tonemask_adj_16,
  154459. _vp_tonemask_adj_16,
  154460. _psy_noiseguards_8,
  154461. _psy_noisebias_16_impulse,
  154462. _psy_noisebias_16_short,
  154463. _psy_noisebias_16_short,
  154464. _psy_noisebias_16,
  154465. _psy_noise_suppress,
  154466. _psy_compand_8,
  154467. _psy_compand_16_mapping,
  154468. _psy_compand_16_mapping,
  154469. {_noise_start_16,_noise_start_16},
  154470. { _noise_part_16, _noise_part_16},
  154471. _noise_thresh_16,
  154472. _psy_ath_floater_16,
  154473. _psy_ath_abs_16,
  154474. _psy_lowpass_16,
  154475. _psy_global_44,
  154476. _global_mapping_16,
  154477. _psy_stereo_modes_16,
  154478. _floor_books,
  154479. _floor,
  154480. _floor_mapping_16_short,
  154481. _floor_mapping_16,
  154482. _mapres_template_16_stereo
  154483. };
  154484. ve_setup_data_template ve_setup_16_uncoupled={
  154485. 3,
  154486. rate_mapping_16_uncoupled,
  154487. quality_mapping_16,
  154488. -1,
  154489. 15000,
  154490. 19000,
  154491. blocksize_16_short,
  154492. blocksize_16_long,
  154493. _psy_tone_masteratt_16,
  154494. _psy_tone_0dB,
  154495. _psy_tone_suppress,
  154496. _vp_tonemask_adj_16,
  154497. _vp_tonemask_adj_16,
  154498. _vp_tonemask_adj_16,
  154499. _psy_noiseguards_8,
  154500. _psy_noisebias_16_impulse,
  154501. _psy_noisebias_16_short,
  154502. _psy_noisebias_16_short,
  154503. _psy_noisebias_16,
  154504. _psy_noise_suppress,
  154505. _psy_compand_8,
  154506. _psy_compand_16_mapping,
  154507. _psy_compand_16_mapping,
  154508. {_noise_start_16,_noise_start_16},
  154509. { _noise_part_16, _noise_part_16},
  154510. _noise_thresh_16,
  154511. _psy_ath_floater_16,
  154512. _psy_ath_abs_16,
  154513. _psy_lowpass_16,
  154514. _psy_global_44,
  154515. _global_mapping_16,
  154516. _psy_stereo_modes_16,
  154517. _floor_books,
  154518. _floor,
  154519. _floor_mapping_16_short,
  154520. _floor_mapping_16,
  154521. _mapres_template_16_uncoupled
  154522. };
  154523. /*** End of inlined file: setup_16.h ***/
  154524. /*** Start of inlined file: setup_22.h ***/
  154525. static double rate_mapping_22[4]={
  154526. 15000.,20000.,44000.,86000.
  154527. };
  154528. static double rate_mapping_22_uncoupled[4]={
  154529. 16000.,28000.,50000.,90000.
  154530. };
  154531. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154532. ve_setup_data_template ve_setup_22_stereo={
  154533. 3,
  154534. rate_mapping_22,
  154535. quality_mapping_16,
  154536. 2,
  154537. 19000,
  154538. 26000,
  154539. blocksize_16_short,
  154540. blocksize_16_long,
  154541. _psy_tone_masteratt_16,
  154542. _psy_tone_0dB,
  154543. _psy_tone_suppress,
  154544. _vp_tonemask_adj_16,
  154545. _vp_tonemask_adj_16,
  154546. _vp_tonemask_adj_16,
  154547. _psy_noiseguards_8,
  154548. _psy_noisebias_16_impulse,
  154549. _psy_noisebias_16_short,
  154550. _psy_noisebias_16_short,
  154551. _psy_noisebias_16,
  154552. _psy_noise_suppress,
  154553. _psy_compand_8,
  154554. _psy_compand_8_mapping,
  154555. _psy_compand_8_mapping,
  154556. {_noise_start_16,_noise_start_16},
  154557. { _noise_part_16, _noise_part_16},
  154558. _noise_thresh_16,
  154559. _psy_ath_floater_16,
  154560. _psy_ath_abs_16,
  154561. _psy_lowpass_22,
  154562. _psy_global_44,
  154563. _global_mapping_16,
  154564. _psy_stereo_modes_16,
  154565. _floor_books,
  154566. _floor,
  154567. _floor_mapping_16_short,
  154568. _floor_mapping_16,
  154569. _mapres_template_16_stereo
  154570. };
  154571. ve_setup_data_template ve_setup_22_uncoupled={
  154572. 3,
  154573. rate_mapping_22_uncoupled,
  154574. quality_mapping_16,
  154575. -1,
  154576. 19000,
  154577. 26000,
  154578. blocksize_16_short,
  154579. blocksize_16_long,
  154580. _psy_tone_masteratt_16,
  154581. _psy_tone_0dB,
  154582. _psy_tone_suppress,
  154583. _vp_tonemask_adj_16,
  154584. _vp_tonemask_adj_16,
  154585. _vp_tonemask_adj_16,
  154586. _psy_noiseguards_8,
  154587. _psy_noisebias_16_impulse,
  154588. _psy_noisebias_16_short,
  154589. _psy_noisebias_16_short,
  154590. _psy_noisebias_16,
  154591. _psy_noise_suppress,
  154592. _psy_compand_8,
  154593. _psy_compand_8_mapping,
  154594. _psy_compand_8_mapping,
  154595. {_noise_start_16,_noise_start_16},
  154596. { _noise_part_16, _noise_part_16},
  154597. _noise_thresh_16,
  154598. _psy_ath_floater_16,
  154599. _psy_ath_abs_16,
  154600. _psy_lowpass_22,
  154601. _psy_global_44,
  154602. _global_mapping_16,
  154603. _psy_stereo_modes_16,
  154604. _floor_books,
  154605. _floor,
  154606. _floor_mapping_16_short,
  154607. _floor_mapping_16,
  154608. _mapres_template_16_uncoupled
  154609. };
  154610. /*** End of inlined file: setup_22.h ***/
  154611. /*** Start of inlined file: setup_X.h ***/
  154612. static double rate_mapping_X[12]={
  154613. -1.,-1.,-1.,-1.,-1.,-1.,
  154614. -1.,-1.,-1.,-1.,-1.,-1.
  154615. };
  154616. ve_setup_data_template ve_setup_X_stereo={
  154617. 11,
  154618. rate_mapping_X,
  154619. quality_mapping_44,
  154620. 2,
  154621. 50000,
  154622. 200000,
  154623. blocksize_short_44,
  154624. blocksize_long_44,
  154625. _psy_tone_masteratt_44,
  154626. _psy_tone_0dB,
  154627. _psy_tone_suppress,
  154628. _vp_tonemask_adj_otherblock,
  154629. _vp_tonemask_adj_longblock,
  154630. _vp_tonemask_adj_otherblock,
  154631. _psy_noiseguards_44,
  154632. _psy_noisebias_impulse,
  154633. _psy_noisebias_padding,
  154634. _psy_noisebias_trans,
  154635. _psy_noisebias_long,
  154636. _psy_noise_suppress,
  154637. _psy_compand_44,
  154638. _psy_compand_short_mapping,
  154639. _psy_compand_long_mapping,
  154640. {_noise_start_short_44,_noise_start_long_44},
  154641. {_noise_part_short_44,_noise_part_long_44},
  154642. _noise_thresh_44,
  154643. _psy_ath_floater,
  154644. _psy_ath_abs,
  154645. _psy_lowpass_44,
  154646. _psy_global_44,
  154647. _global_mapping_44,
  154648. _psy_stereo_modes_44,
  154649. _floor_books,
  154650. _floor,
  154651. _floor_short_mapping_44,
  154652. _floor_long_mapping_44,
  154653. _mapres_template_44_stereo
  154654. };
  154655. ve_setup_data_template ve_setup_X_uncoupled={
  154656. 11,
  154657. rate_mapping_X,
  154658. quality_mapping_44,
  154659. -1,
  154660. 50000,
  154661. 200000,
  154662. blocksize_short_44,
  154663. blocksize_long_44,
  154664. _psy_tone_masteratt_44,
  154665. _psy_tone_0dB,
  154666. _psy_tone_suppress,
  154667. _vp_tonemask_adj_otherblock,
  154668. _vp_tonemask_adj_longblock,
  154669. _vp_tonemask_adj_otherblock,
  154670. _psy_noiseguards_44,
  154671. _psy_noisebias_impulse,
  154672. _psy_noisebias_padding,
  154673. _psy_noisebias_trans,
  154674. _psy_noisebias_long,
  154675. _psy_noise_suppress,
  154676. _psy_compand_44,
  154677. _psy_compand_short_mapping,
  154678. _psy_compand_long_mapping,
  154679. {_noise_start_short_44,_noise_start_long_44},
  154680. {_noise_part_short_44,_noise_part_long_44},
  154681. _noise_thresh_44,
  154682. _psy_ath_floater,
  154683. _psy_ath_abs,
  154684. _psy_lowpass_44,
  154685. _psy_global_44,
  154686. _global_mapping_44,
  154687. NULL,
  154688. _floor_books,
  154689. _floor,
  154690. _floor_short_mapping_44,
  154691. _floor_long_mapping_44,
  154692. _mapres_template_44_uncoupled
  154693. };
  154694. ve_setup_data_template ve_setup_XX_stereo={
  154695. 2,
  154696. rate_mapping_X,
  154697. quality_mapping_8,
  154698. 2,
  154699. 0,
  154700. 8000,
  154701. blocksize_8,
  154702. blocksize_8,
  154703. _psy_tone_masteratt_8,
  154704. _psy_tone_0dB,
  154705. _psy_tone_suppress,
  154706. _vp_tonemask_adj_8,
  154707. NULL,
  154708. _vp_tonemask_adj_8,
  154709. _psy_noiseguards_8,
  154710. _psy_noisebias_8,
  154711. _psy_noisebias_8,
  154712. NULL,
  154713. NULL,
  154714. _psy_noise_suppress,
  154715. _psy_compand_8,
  154716. _psy_compand_8_mapping,
  154717. NULL,
  154718. {_noise_start_8,_noise_start_8},
  154719. {_noise_part_8,_noise_part_8},
  154720. _noise_thresh_5only,
  154721. _psy_ath_floater_8,
  154722. _psy_ath_abs_8,
  154723. _psy_lowpass_8,
  154724. _psy_global_44,
  154725. _global_mapping_8,
  154726. _psy_stereo_modes_8,
  154727. _floor_books,
  154728. _floor,
  154729. _floor_mapping_8,
  154730. NULL,
  154731. _mapres_template_8_stereo
  154732. };
  154733. ve_setup_data_template ve_setup_XX_uncoupled={
  154734. 2,
  154735. rate_mapping_X,
  154736. quality_mapping_8,
  154737. -1,
  154738. 0,
  154739. 8000,
  154740. blocksize_8,
  154741. blocksize_8,
  154742. _psy_tone_masteratt_8,
  154743. _psy_tone_0dB,
  154744. _psy_tone_suppress,
  154745. _vp_tonemask_adj_8,
  154746. NULL,
  154747. _vp_tonemask_adj_8,
  154748. _psy_noiseguards_8,
  154749. _psy_noisebias_8,
  154750. _psy_noisebias_8,
  154751. NULL,
  154752. NULL,
  154753. _psy_noise_suppress,
  154754. _psy_compand_8,
  154755. _psy_compand_8_mapping,
  154756. NULL,
  154757. {_noise_start_8,_noise_start_8},
  154758. {_noise_part_8,_noise_part_8},
  154759. _noise_thresh_5only,
  154760. _psy_ath_floater_8,
  154761. _psy_ath_abs_8,
  154762. _psy_lowpass_8,
  154763. _psy_global_44,
  154764. _global_mapping_8,
  154765. _psy_stereo_modes_8,
  154766. _floor_books,
  154767. _floor,
  154768. _floor_mapping_8,
  154769. NULL,
  154770. _mapres_template_8_uncoupled
  154771. };
  154772. /*** End of inlined file: setup_X.h ***/
  154773. static ve_setup_data_template *setup_list[]={
  154774. &ve_setup_44_stereo,
  154775. &ve_setup_44_uncoupled,
  154776. &ve_setup_32_stereo,
  154777. &ve_setup_32_uncoupled,
  154778. &ve_setup_22_stereo,
  154779. &ve_setup_22_uncoupled,
  154780. &ve_setup_16_stereo,
  154781. &ve_setup_16_uncoupled,
  154782. &ve_setup_11_stereo,
  154783. &ve_setup_11_uncoupled,
  154784. &ve_setup_8_stereo,
  154785. &ve_setup_8_uncoupled,
  154786. &ve_setup_X_stereo,
  154787. &ve_setup_X_uncoupled,
  154788. &ve_setup_XX_stereo,
  154789. &ve_setup_XX_uncoupled,
  154790. 0
  154791. };
  154792. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154793. if(vi && vi->codec_setup){
  154794. vi->version=0;
  154795. vi->channels=ch;
  154796. vi->rate=rate;
  154797. return(0);
  154798. }
  154799. return(OV_EINVAL);
  154800. }
  154801. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154802. static_codebook ***books,
  154803. vorbis_info_floor1 *in,
  154804. int *x){
  154805. int i,k,is=s;
  154806. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154807. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154808. memcpy(f,in+x[is],sizeof(*f));
  154809. /* fill in the lowpass field, even if it's temporary */
  154810. f->n=ci->blocksizes[block]>>1;
  154811. /* books */
  154812. {
  154813. int partitions=f->partitions;
  154814. int maxclass=-1;
  154815. int maxbook=-1;
  154816. for(i=0;i<partitions;i++)
  154817. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154818. for(i=0;i<=maxclass;i++){
  154819. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154820. f->class_book[i]+=ci->books;
  154821. for(k=0;k<(1<<f->class_subs[i]);k++){
  154822. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154823. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154824. }
  154825. }
  154826. for(i=0;i<=maxbook;i++)
  154827. ci->book_param[ci->books++]=books[x[is]][i];
  154828. }
  154829. /* for now, we're only using floor 1 */
  154830. ci->floor_type[ci->floors]=1;
  154831. ci->floor_param[ci->floors]=f;
  154832. ci->floors++;
  154833. return;
  154834. }
  154835. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154836. vorbis_info_psy_global *in,
  154837. double *x){
  154838. int i,is=s;
  154839. double ds=s-is;
  154840. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154841. vorbis_info_psy_global *g=&ci->psy_g_param;
  154842. memcpy(g,in+(int)x[is],sizeof(*g));
  154843. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154844. is=(int)ds;
  154845. ds-=is;
  154846. if(ds==0 && is>0){
  154847. is--;
  154848. ds=1.;
  154849. }
  154850. /* interpolate the trigger threshholds */
  154851. for(i=0;i<4;i++){
  154852. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154853. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154854. }
  154855. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154856. return;
  154857. }
  154858. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154859. highlevel_encode_setup *hi,
  154860. adj_stereo *p){
  154861. float s=hi->stereo_point_setting;
  154862. int i,is=s;
  154863. double ds=s-is;
  154864. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154865. vorbis_info_psy_global *g=&ci->psy_g_param;
  154866. if(p){
  154867. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154868. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154869. if(hi->managed){
  154870. /* interpolate the kHz threshholds */
  154871. for(i=0;i<PACKETBLOBS;i++){
  154872. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154873. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154874. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154875. g->coupling_pkHz[i]=kHz;
  154876. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154877. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154878. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154879. }
  154880. }else{
  154881. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154882. for(i=0;i<PACKETBLOBS;i++){
  154883. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154884. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154885. g->coupling_pkHz[i]=kHz;
  154886. }
  154887. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154888. for(i=0;i<PACKETBLOBS;i++){
  154889. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154890. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154891. }
  154892. }
  154893. }else{
  154894. for(i=0;i<PACKETBLOBS;i++){
  154895. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154896. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154897. }
  154898. }
  154899. return;
  154900. }
  154901. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154902. int *nn_start,
  154903. int *nn_partition,
  154904. double *nn_thresh,
  154905. int block){
  154906. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154907. vorbis_info_psy *p=ci->psy_param[block];
  154908. highlevel_encode_setup *hi=&ci->hi;
  154909. int is=s;
  154910. if(block>=ci->psys)
  154911. ci->psys=block+1;
  154912. if(!p){
  154913. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154914. ci->psy_param[block]=p;
  154915. }
  154916. memcpy(p,&_psy_info_template,sizeof(*p));
  154917. p->blockflag=block>>1;
  154918. if(hi->noise_normalize_p){
  154919. p->normal_channel_p=1;
  154920. p->normal_point_p=1;
  154921. p->normal_start=nn_start[is];
  154922. p->normal_partition=nn_partition[is];
  154923. p->normal_thresh=nn_thresh[is];
  154924. }
  154925. return;
  154926. }
  154927. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154928. att3 *att,
  154929. int *max,
  154930. vp_adjblock *in){
  154931. int i,is=s;
  154932. double ds=s-is;
  154933. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154934. vorbis_info_psy *p=ci->psy_param[block];
  154935. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154936. filling the values in here */
  154937. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154938. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154939. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154940. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154941. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154942. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154943. for(i=0;i<P_BANDS;i++)
  154944. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154945. return;
  154946. }
  154947. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154948. compandblock *in, double *x){
  154949. int i,is=s;
  154950. double ds=s-is;
  154951. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154952. vorbis_info_psy *p=ci->psy_param[block];
  154953. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154954. is=(int)ds;
  154955. ds-=is;
  154956. if(ds==0 && is>0){
  154957. is--;
  154958. ds=1.;
  154959. }
  154960. /* interpolate the compander settings */
  154961. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154962. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154963. return;
  154964. }
  154965. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154966. int *suppress){
  154967. int is=s;
  154968. double ds=s-is;
  154969. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154970. vorbis_info_psy *p=ci->psy_param[block];
  154971. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154972. return;
  154973. }
  154974. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154975. int *suppress,
  154976. noise3 *in,
  154977. noiseguard *guard,
  154978. double userbias){
  154979. int i,is=s,j;
  154980. double ds=s-is;
  154981. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154982. vorbis_info_psy *p=ci->psy_param[block];
  154983. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154984. p->noisewindowlomin=guard[block].lo;
  154985. p->noisewindowhimin=guard[block].hi;
  154986. p->noisewindowfixed=guard[block].fixed;
  154987. for(j=0;j<P_NOISECURVES;j++)
  154988. for(i=0;i<P_BANDS;i++)
  154989. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154990. /* impulse blocks may take a user specified bias to boost the
  154991. nominal/high noise encoding depth */
  154992. for(j=0;j<P_NOISECURVES;j++){
  154993. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154994. for(i=0;i<P_BANDS;i++){
  154995. p->noiseoff[j][i]+=userbias;
  154996. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154997. }
  154998. }
  154999. return;
  155000. }
  155001. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  155002. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155003. vorbis_info_psy *p=ci->psy_param[block];
  155004. p->ath_adjatt=ci->hi.ath_floating_dB;
  155005. p->ath_maxatt=ci->hi.ath_absolute_dB;
  155006. return;
  155007. }
  155008. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  155009. int i;
  155010. for(i=0;i<ci->books;i++)
  155011. if(ci->book_param[i]==book)return(i);
  155012. return(ci->books++);
  155013. }
  155014. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  155015. int *shortb,int *longb){
  155016. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155017. int is=s;
  155018. int blockshort=shortb[is];
  155019. int blocklong=longb[is];
  155020. ci->blocksizes[0]=blockshort;
  155021. ci->blocksizes[1]=blocklong;
  155022. }
  155023. static void vorbis_encode_residue_setup(vorbis_info *vi,
  155024. int number, int block,
  155025. vorbis_residue_template *res){
  155026. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155027. int i,n;
  155028. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  155029. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  155030. memcpy(r,res->res,sizeof(*r));
  155031. if(ci->residues<=number)ci->residues=number+1;
  155032. switch(ci->blocksizes[block]){
  155033. case 64:case 128:case 256:
  155034. r->grouping=16;
  155035. break;
  155036. default:
  155037. r->grouping=32;
  155038. break;
  155039. }
  155040. ci->residue_type[number]=res->res_type;
  155041. /* to be adjusted by lowpass/pointlimit later */
  155042. n=r->end=ci->blocksizes[block]>>1;
  155043. if(res->res_type==2)
  155044. n=r->end*=vi->channels;
  155045. /* fill in all the books */
  155046. {
  155047. int booklist=0,k;
  155048. if(ci->hi.managed){
  155049. for(i=0;i<r->partitions;i++)
  155050. for(k=0;k<3;k++)
  155051. if(res->books_base_managed->books[i][k])
  155052. r->secondstages[i]|=(1<<k);
  155053. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  155054. ci->book_param[r->groupbook]=res->book_aux_managed;
  155055. for(i=0;i<r->partitions;i++){
  155056. for(k=0;k<3;k++){
  155057. if(res->books_base_managed->books[i][k]){
  155058. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  155059. r->booklist[booklist++]=bookid;
  155060. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  155061. }
  155062. }
  155063. }
  155064. }else{
  155065. for(i=0;i<r->partitions;i++)
  155066. for(k=0;k<3;k++)
  155067. if(res->books_base->books[i][k])
  155068. r->secondstages[i]|=(1<<k);
  155069. r->groupbook=book_dup_or_new(ci,res->book_aux);
  155070. ci->book_param[r->groupbook]=res->book_aux;
  155071. for(i=0;i<r->partitions;i++){
  155072. for(k=0;k<3;k++){
  155073. if(res->books_base->books[i][k]){
  155074. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  155075. r->booklist[booklist++]=bookid;
  155076. ci->book_param[bookid]=res->books_base->books[i][k];
  155077. }
  155078. }
  155079. }
  155080. }
  155081. }
  155082. /* lowpass setup/pointlimit */
  155083. {
  155084. double freq=ci->hi.lowpass_kHz*1000.;
  155085. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  155086. double nyq=vi->rate/2.;
  155087. long blocksize=ci->blocksizes[block]>>1;
  155088. /* lowpass needs to be set in the floor and the residue. */
  155089. if(freq>nyq)freq=nyq;
  155090. /* in the floor, the granularity can be very fine; it doesn't alter
  155091. the encoding structure, only the samples used to fit the floor
  155092. approximation */
  155093. f->n=freq/nyq*blocksize;
  155094. /* this res may by limited by the maximum pointlimit of the mode,
  155095. not the lowpass. the floor is always lowpass limited. */
  155096. if(res->limit_type){
  155097. if(ci->hi.managed)
  155098. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  155099. else
  155100. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  155101. if(freq>nyq)freq=nyq;
  155102. }
  155103. /* in the residue, we're constrained, physically, by partition
  155104. boundaries. We still lowpass 'wherever', but we have to round up
  155105. here to next boundary, or the vorbis spec will round it *down* to
  155106. previous boundary in encode/decode */
  155107. if(ci->residue_type[block]==2)
  155108. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  155109. r->grouping;
  155110. else
  155111. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  155112. r->grouping;
  155113. }
  155114. }
  155115. /* we assume two maps in this encoder */
  155116. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  155117. vorbis_mapping_template *maps){
  155118. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155119. int i,j,is=s,modes=2;
  155120. vorbis_info_mapping0 *map=maps[is].map;
  155121. vorbis_info_mode *mode=_mode_template;
  155122. vorbis_residue_template *res=maps[is].res;
  155123. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  155124. for(i=0;i<modes;i++){
  155125. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  155126. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  155127. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  155128. if(i>=ci->modes)ci->modes=i+1;
  155129. ci->map_type[i]=0;
  155130. memcpy(ci->map_param[i],map+i,sizeof(*map));
  155131. if(i>=ci->maps)ci->maps=i+1;
  155132. for(j=0;j<map[i].submaps;j++)
  155133. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  155134. ,res+map[i].residuesubmap[j]);
  155135. }
  155136. }
  155137. static double setting_to_approx_bitrate(vorbis_info *vi){
  155138. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155139. highlevel_encode_setup *hi=&ci->hi;
  155140. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155141. int is=hi->base_setting;
  155142. double ds=hi->base_setting-is;
  155143. int ch=vi->channels;
  155144. double *r=setup->rate_mapping;
  155145. if(r==NULL)
  155146. return(-1);
  155147. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155148. }
  155149. static void get_setup_template(vorbis_info *vi,
  155150. long ch,long srate,
  155151. double req,int q_or_bitrate){
  155152. int i=0,j;
  155153. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155154. highlevel_encode_setup *hi=&ci->hi;
  155155. if(q_or_bitrate)req/=ch;
  155156. while(setup_list[i]){
  155157. if(setup_list[i]->coupling_restriction==-1 ||
  155158. setup_list[i]->coupling_restriction==ch){
  155159. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155160. srate<=setup_list[i]->samplerate_max_restriction){
  155161. int mappings=setup_list[i]->mappings;
  155162. double *map=(q_or_bitrate?
  155163. setup_list[i]->rate_mapping:
  155164. setup_list[i]->quality_mapping);
  155165. /* the template matches. Does the requested quality mode
  155166. fall within this template's modes? */
  155167. if(req<map[0]){++i;continue;}
  155168. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155169. for(j=0;j<mappings;j++)
  155170. if(req>=map[j] && req<map[j+1])break;
  155171. /* an all-points match */
  155172. hi->setup=setup_list[i];
  155173. if(j==mappings)
  155174. hi->base_setting=j-.001;
  155175. else{
  155176. float low=map[j];
  155177. float high=map[j+1];
  155178. float del=(req-low)/(high-low);
  155179. hi->base_setting=j+del;
  155180. }
  155181. return;
  155182. }
  155183. }
  155184. i++;
  155185. }
  155186. hi->setup=NULL;
  155187. }
  155188. /* encoders will need to use vorbis_info_init beforehand and call
  155189. vorbis_info clear when all done */
  155190. /* two interfaces; this, more detailed one, and later a convenience
  155191. layer on top */
  155192. /* the final setup call */
  155193. int vorbis_encode_setup_init(vorbis_info *vi){
  155194. int i0=0,singleblock=0;
  155195. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155196. ve_setup_data_template *setup=NULL;
  155197. highlevel_encode_setup *hi=&ci->hi;
  155198. if(ci==NULL)return(OV_EINVAL);
  155199. if(!hi->impulse_block_p)i0=1;
  155200. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155201. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155202. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155203. /* again, bound this to avoid the app shooting itself int he foot
  155204. too badly */
  155205. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155206. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155207. /* get the appropriate setup template; matches the fetch in previous
  155208. stages */
  155209. setup=(ve_setup_data_template *)hi->setup;
  155210. if(setup==NULL)return(OV_EINVAL);
  155211. hi->set_in_stone=1;
  155212. /* choose block sizes from configured sizes as well as paying
  155213. attention to long_block_p and short_block_p. If the configured
  155214. short and long blocks are the same length, we set long_block_p
  155215. and unset short_block_p */
  155216. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155217. setup->blocksize_short,
  155218. setup->blocksize_long);
  155219. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155220. /* floor setup; choose proper floor params. Allocated on the floor
  155221. stack in order; if we alloc only long floor, it's 0 */
  155222. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155223. setup->floor_books,
  155224. setup->floor_params,
  155225. setup->floor_short_mapping);
  155226. if(!singleblock)
  155227. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155228. setup->floor_books,
  155229. setup->floor_params,
  155230. setup->floor_long_mapping);
  155231. /* setup of [mostly] short block detection and stereo*/
  155232. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155233. setup->global_params,
  155234. setup->global_mapping);
  155235. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155236. /* basic psych setup and noise normalization */
  155237. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155238. setup->psy_noise_normal_start[0],
  155239. setup->psy_noise_normal_partition[0],
  155240. setup->psy_noise_normal_thresh,
  155241. 0);
  155242. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155243. setup->psy_noise_normal_start[0],
  155244. setup->psy_noise_normal_partition[0],
  155245. setup->psy_noise_normal_thresh,
  155246. 1);
  155247. if(!singleblock){
  155248. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155249. setup->psy_noise_normal_start[1],
  155250. setup->psy_noise_normal_partition[1],
  155251. setup->psy_noise_normal_thresh,
  155252. 2);
  155253. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155254. setup->psy_noise_normal_start[1],
  155255. setup->psy_noise_normal_partition[1],
  155256. setup->psy_noise_normal_thresh,
  155257. 3);
  155258. }
  155259. /* tone masking setup */
  155260. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155261. setup->psy_tone_masteratt,
  155262. setup->psy_tone_0dB,
  155263. setup->psy_tone_adj_impulse);
  155264. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155265. setup->psy_tone_masteratt,
  155266. setup->psy_tone_0dB,
  155267. setup->psy_tone_adj_other);
  155268. if(!singleblock){
  155269. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155270. setup->psy_tone_masteratt,
  155271. setup->psy_tone_0dB,
  155272. setup->psy_tone_adj_other);
  155273. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155274. setup->psy_tone_masteratt,
  155275. setup->psy_tone_0dB,
  155276. setup->psy_tone_adj_long);
  155277. }
  155278. /* noise companding setup */
  155279. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155280. setup->psy_noise_compand,
  155281. setup->psy_noise_compand_short_mapping);
  155282. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155283. setup->psy_noise_compand,
  155284. setup->psy_noise_compand_short_mapping);
  155285. if(!singleblock){
  155286. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155287. setup->psy_noise_compand,
  155288. setup->psy_noise_compand_long_mapping);
  155289. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155290. setup->psy_noise_compand,
  155291. setup->psy_noise_compand_long_mapping);
  155292. }
  155293. /* peak guarding setup */
  155294. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155295. setup->psy_tone_dBsuppress);
  155296. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155297. setup->psy_tone_dBsuppress);
  155298. if(!singleblock){
  155299. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155300. setup->psy_tone_dBsuppress);
  155301. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155302. setup->psy_tone_dBsuppress);
  155303. }
  155304. /* noise bias setup */
  155305. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155306. setup->psy_noise_dBsuppress,
  155307. setup->psy_noise_bias_impulse,
  155308. setup->psy_noiseguards,
  155309. (i0==0?hi->impulse_noisetune:0.));
  155310. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155311. setup->psy_noise_dBsuppress,
  155312. setup->psy_noise_bias_padding,
  155313. setup->psy_noiseguards,0.);
  155314. if(!singleblock){
  155315. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155316. setup->psy_noise_dBsuppress,
  155317. setup->psy_noise_bias_trans,
  155318. setup->psy_noiseguards,0.);
  155319. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155320. setup->psy_noise_dBsuppress,
  155321. setup->psy_noise_bias_long,
  155322. setup->psy_noiseguards,0.);
  155323. }
  155324. vorbis_encode_ath_setup(vi,0);
  155325. vorbis_encode_ath_setup(vi,1);
  155326. if(!singleblock){
  155327. vorbis_encode_ath_setup(vi,2);
  155328. vorbis_encode_ath_setup(vi,3);
  155329. }
  155330. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155331. /* set bitrate readonlies and management */
  155332. if(hi->bitrate_av>0)
  155333. vi->bitrate_nominal=hi->bitrate_av;
  155334. else{
  155335. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155336. }
  155337. vi->bitrate_lower=hi->bitrate_min;
  155338. vi->bitrate_upper=hi->bitrate_max;
  155339. if(hi->bitrate_av)
  155340. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155341. else
  155342. vi->bitrate_window=0.;
  155343. if(hi->managed){
  155344. ci->bi.avg_rate=hi->bitrate_av;
  155345. ci->bi.min_rate=hi->bitrate_min;
  155346. ci->bi.max_rate=hi->bitrate_max;
  155347. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155348. ci->bi.reservoir_bias=
  155349. hi->bitrate_reservoir_bias;
  155350. ci->bi.slew_damp=hi->bitrate_av_damp;
  155351. }
  155352. return(0);
  155353. }
  155354. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155355. long channels,
  155356. long rate){
  155357. int ret=0,i,is;
  155358. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155359. highlevel_encode_setup *hi=&ci->hi;
  155360. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155361. double ds;
  155362. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155363. if(ret)return(ret);
  155364. is=hi->base_setting;
  155365. ds=hi->base_setting-is;
  155366. hi->short_setting=hi->base_setting;
  155367. hi->long_setting=hi->base_setting;
  155368. hi->managed=0;
  155369. hi->impulse_block_p=1;
  155370. hi->noise_normalize_p=1;
  155371. hi->stereo_point_setting=hi->base_setting;
  155372. hi->lowpass_kHz=
  155373. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155374. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155375. setup->psy_ath_float[is+1]*ds;
  155376. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155377. setup->psy_ath_abs[is+1]*ds;
  155378. hi->amplitude_track_dBpersec=-6.;
  155379. hi->trigger_setting=hi->base_setting;
  155380. for(i=0;i<4;i++){
  155381. hi->block[i].tone_mask_setting=hi->base_setting;
  155382. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155383. hi->block[i].noise_bias_setting=hi->base_setting;
  155384. hi->block[i].noise_compand_setting=hi->base_setting;
  155385. }
  155386. return(ret);
  155387. }
  155388. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155389. long channels,
  155390. long rate,
  155391. float quality){
  155392. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155393. highlevel_encode_setup *hi=&ci->hi;
  155394. quality+=.0000001;
  155395. if(quality>=1.)quality=.9999;
  155396. get_setup_template(vi,channels,rate,quality,0);
  155397. if(!hi->setup)return OV_EIMPL;
  155398. return vorbis_encode_setup_setting(vi,channels,rate);
  155399. }
  155400. int vorbis_encode_init_vbr(vorbis_info *vi,
  155401. long channels,
  155402. long rate,
  155403. float base_quality /* 0. to 1. */
  155404. ){
  155405. int ret=0;
  155406. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155407. if(ret){
  155408. vorbis_info_clear(vi);
  155409. return ret;
  155410. }
  155411. ret=vorbis_encode_setup_init(vi);
  155412. if(ret)
  155413. vorbis_info_clear(vi);
  155414. return(ret);
  155415. }
  155416. int vorbis_encode_setup_managed(vorbis_info *vi,
  155417. long channels,
  155418. long rate,
  155419. long max_bitrate,
  155420. long nominal_bitrate,
  155421. long min_bitrate){
  155422. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155423. highlevel_encode_setup *hi=&ci->hi;
  155424. double tnominal=nominal_bitrate;
  155425. int ret=0;
  155426. if(nominal_bitrate<=0.){
  155427. if(max_bitrate>0.){
  155428. if(min_bitrate>0.)
  155429. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155430. else
  155431. nominal_bitrate=max_bitrate*.875;
  155432. }else{
  155433. if(min_bitrate>0.){
  155434. nominal_bitrate=min_bitrate;
  155435. }else{
  155436. return(OV_EINVAL);
  155437. }
  155438. }
  155439. }
  155440. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155441. if(!hi->setup)return OV_EIMPL;
  155442. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155443. if(ret){
  155444. vorbis_info_clear(vi);
  155445. return ret;
  155446. }
  155447. /* initialize management with sane defaults */
  155448. hi->managed=1;
  155449. hi->bitrate_min=min_bitrate;
  155450. hi->bitrate_max=max_bitrate;
  155451. hi->bitrate_av=tnominal;
  155452. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155453. hi->bitrate_reservoir=nominal_bitrate*2;
  155454. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155455. return(ret);
  155456. }
  155457. int vorbis_encode_init(vorbis_info *vi,
  155458. long channels,
  155459. long rate,
  155460. long max_bitrate,
  155461. long nominal_bitrate,
  155462. long min_bitrate){
  155463. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155464. max_bitrate,
  155465. nominal_bitrate,
  155466. min_bitrate);
  155467. if(ret){
  155468. vorbis_info_clear(vi);
  155469. return(ret);
  155470. }
  155471. ret=vorbis_encode_setup_init(vi);
  155472. if(ret)
  155473. vorbis_info_clear(vi);
  155474. return(ret);
  155475. }
  155476. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155477. if(vi){
  155478. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155479. highlevel_encode_setup *hi=&ci->hi;
  155480. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155481. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155482. switch(number){
  155483. /* now deprecated *****************/
  155484. case OV_ECTL_RATEMANAGE_GET:
  155485. {
  155486. struct ovectl_ratemanage_arg *ai=
  155487. (struct ovectl_ratemanage_arg *)arg;
  155488. ai->management_active=hi->managed;
  155489. ai->bitrate_hard_window=ai->bitrate_av_window=
  155490. (double)hi->bitrate_reservoir/vi->rate;
  155491. ai->bitrate_av_window_center=1.;
  155492. ai->bitrate_hard_min=hi->bitrate_min;
  155493. ai->bitrate_hard_max=hi->bitrate_max;
  155494. ai->bitrate_av_lo=hi->bitrate_av;
  155495. ai->bitrate_av_hi=hi->bitrate_av;
  155496. }
  155497. return(0);
  155498. /* now deprecated *****************/
  155499. case OV_ECTL_RATEMANAGE_SET:
  155500. {
  155501. struct ovectl_ratemanage_arg *ai=
  155502. (struct ovectl_ratemanage_arg *)arg;
  155503. if(ai==NULL){
  155504. hi->managed=0;
  155505. }else{
  155506. hi->managed=ai->management_active;
  155507. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155508. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155509. }
  155510. }
  155511. return 0;
  155512. /* now deprecated *****************/
  155513. case OV_ECTL_RATEMANAGE_AVG:
  155514. {
  155515. struct ovectl_ratemanage_arg *ai=
  155516. (struct ovectl_ratemanage_arg *)arg;
  155517. if(ai==NULL){
  155518. hi->bitrate_av=0;
  155519. }else{
  155520. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155521. }
  155522. }
  155523. return(0);
  155524. /* now deprecated *****************/
  155525. case OV_ECTL_RATEMANAGE_HARD:
  155526. {
  155527. struct ovectl_ratemanage_arg *ai=
  155528. (struct ovectl_ratemanage_arg *)arg;
  155529. if(ai==NULL){
  155530. hi->bitrate_min=0;
  155531. hi->bitrate_max=0;
  155532. }else{
  155533. hi->bitrate_min=ai->bitrate_hard_min;
  155534. hi->bitrate_max=ai->bitrate_hard_max;
  155535. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155536. (hi->bitrate_max+hi->bitrate_min)*.5;
  155537. }
  155538. if(hi->bitrate_reservoir<128.)
  155539. hi->bitrate_reservoir=128.;
  155540. }
  155541. return(0);
  155542. /* replacement ratemanage interface */
  155543. case OV_ECTL_RATEMANAGE2_GET:
  155544. {
  155545. struct ovectl_ratemanage2_arg *ai=
  155546. (struct ovectl_ratemanage2_arg *)arg;
  155547. if(ai==NULL)return OV_EINVAL;
  155548. ai->management_active=hi->managed;
  155549. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155550. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155551. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155552. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155553. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155554. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155555. }
  155556. return (0);
  155557. case OV_ECTL_RATEMANAGE2_SET:
  155558. {
  155559. struct ovectl_ratemanage2_arg *ai=
  155560. (struct ovectl_ratemanage2_arg *)arg;
  155561. if(ai==NULL){
  155562. hi->managed=0;
  155563. }else{
  155564. /* sanity check; only catch invariant violations */
  155565. if(ai->bitrate_limit_min_kbps>0 &&
  155566. ai->bitrate_average_kbps>0 &&
  155567. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155568. return OV_EINVAL;
  155569. if(ai->bitrate_limit_max_kbps>0 &&
  155570. ai->bitrate_average_kbps>0 &&
  155571. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155572. return OV_EINVAL;
  155573. if(ai->bitrate_limit_min_kbps>0 &&
  155574. ai->bitrate_limit_max_kbps>0 &&
  155575. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155576. return OV_EINVAL;
  155577. if(ai->bitrate_average_damping <= 0.)
  155578. return OV_EINVAL;
  155579. if(ai->bitrate_limit_reservoir_bits < 0)
  155580. return OV_EINVAL;
  155581. if(ai->bitrate_limit_reservoir_bias < 0.)
  155582. return OV_EINVAL;
  155583. if(ai->bitrate_limit_reservoir_bias > 1.)
  155584. return OV_EINVAL;
  155585. hi->managed=ai->management_active;
  155586. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155587. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155588. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155589. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155590. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155591. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155592. }
  155593. }
  155594. return 0;
  155595. case OV_ECTL_LOWPASS_GET:
  155596. {
  155597. double *farg=(double *)arg;
  155598. *farg=hi->lowpass_kHz;
  155599. }
  155600. return(0);
  155601. case OV_ECTL_LOWPASS_SET:
  155602. {
  155603. double *farg=(double *)arg;
  155604. hi->lowpass_kHz=*farg;
  155605. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155606. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155607. }
  155608. return(0);
  155609. case OV_ECTL_IBLOCK_GET:
  155610. {
  155611. double *farg=(double *)arg;
  155612. *farg=hi->impulse_noisetune;
  155613. }
  155614. return(0);
  155615. case OV_ECTL_IBLOCK_SET:
  155616. {
  155617. double *farg=(double *)arg;
  155618. hi->impulse_noisetune=*farg;
  155619. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155620. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155621. }
  155622. return(0);
  155623. }
  155624. return(OV_EIMPL);
  155625. }
  155626. return(OV_EINVAL);
  155627. }
  155628. #endif
  155629. /*** End of inlined file: vorbisenc.c ***/
  155630. /*** Start of inlined file: vorbisfile.c ***/
  155631. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155632. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155633. // tasks..
  155634. #if JUCE_MSVC
  155635. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155636. #endif
  155637. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155638. #if JUCE_USE_OGGVORBIS
  155639. #include <stdlib.h>
  155640. #include <stdio.h>
  155641. #include <errno.h>
  155642. #include <string.h>
  155643. #include <math.h>
  155644. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155645. one logical bitstream arranged end to end (the only form of Ogg
  155646. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155647. multiplexing] is not allowed in Vorbis) */
  155648. /* A Vorbis file can be played beginning to end (streamed) without
  155649. worrying ahead of time about chaining (see decoder_example.c). If
  155650. we have the whole file, however, and want random access
  155651. (seeking/scrubbing) or desire to know the total length/time of a
  155652. file, we need to account for the possibility of chaining. */
  155653. /* We can handle things a number of ways; we can determine the entire
  155654. bitstream structure right off the bat, or find pieces on demand.
  155655. This example determines and caches structure for the entire
  155656. bitstream, but builds a virtual decoder on the fly when moving
  155657. between links in the chain. */
  155658. /* There are also different ways to implement seeking. Enough
  155659. information exists in an Ogg bitstream to seek to
  155660. sample-granularity positions in the output. Or, one can seek by
  155661. picking some portion of the stream roughly in the desired area if
  155662. we only want coarse navigation through the stream. */
  155663. /*************************************************************************
  155664. * Many, many internal helpers. The intention is not to be confusing;
  155665. * rampant duplication and monolithic function implementation would be
  155666. * harder to understand anyway. The high level functions are last. Begin
  155667. * grokking near the end of the file */
  155668. /* read a little more data from the file/pipe into the ogg_sync framer
  155669. */
  155670. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155671. over 8k gets what they deserve */
  155672. static long _get_data(OggVorbis_File *vf){
  155673. errno=0;
  155674. if(vf->datasource){
  155675. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155676. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155677. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155678. if(bytes==0 && errno)return(-1);
  155679. return(bytes);
  155680. }else
  155681. return(0);
  155682. }
  155683. /* save a tiny smidge of verbosity to make the code more readable */
  155684. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155685. if(vf->datasource){
  155686. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155687. vf->offset=offset;
  155688. ogg_sync_reset(&vf->oy);
  155689. }else{
  155690. /* shouldn't happen unless someone writes a broken callback */
  155691. return;
  155692. }
  155693. }
  155694. /* The read/seek functions track absolute position within the stream */
  155695. /* from the head of the stream, get the next page. boundary specifies
  155696. if the function is allowed to fetch more data from the stream (and
  155697. how much) or only use internally buffered data.
  155698. boundary: -1) unbounded search
  155699. 0) read no additional data; use cached only
  155700. n) search for a new page beginning for n bytes
  155701. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155702. n) found a page at absolute offset n */
  155703. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155704. ogg_int64_t boundary){
  155705. if(boundary>0)boundary+=vf->offset;
  155706. while(1){
  155707. long more;
  155708. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155709. more=ogg_sync_pageseek(&vf->oy,og);
  155710. if(more<0){
  155711. /* skipped n bytes */
  155712. vf->offset-=more;
  155713. }else{
  155714. if(more==0){
  155715. /* send more paramedics */
  155716. if(!boundary)return(OV_FALSE);
  155717. {
  155718. long ret=_get_data(vf);
  155719. if(ret==0)return(OV_EOF);
  155720. if(ret<0)return(OV_EREAD);
  155721. }
  155722. }else{
  155723. /* got a page. Return the offset at the page beginning,
  155724. advance the internal offset past the page end */
  155725. ogg_int64_t ret=vf->offset;
  155726. vf->offset+=more;
  155727. return(ret);
  155728. }
  155729. }
  155730. }
  155731. }
  155732. /* find the latest page beginning before the current stream cursor
  155733. position. Much dirtier than the above as Ogg doesn't have any
  155734. backward search linkage. no 'readp' as it will certainly have to
  155735. read. */
  155736. /* returns offset or OV_EREAD, OV_FAULT */
  155737. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155738. ogg_int64_t begin=vf->offset;
  155739. ogg_int64_t end=begin;
  155740. ogg_int64_t ret;
  155741. ogg_int64_t offset=-1;
  155742. while(offset==-1){
  155743. begin-=CHUNKSIZE;
  155744. if(begin<0)
  155745. begin=0;
  155746. _seek_helper(vf,begin);
  155747. while(vf->offset<end){
  155748. ret=_get_next_page(vf,og,end-vf->offset);
  155749. if(ret==OV_EREAD)return(OV_EREAD);
  155750. if(ret<0){
  155751. break;
  155752. }else{
  155753. offset=ret;
  155754. }
  155755. }
  155756. }
  155757. /* we have the offset. Actually snork and hold the page now */
  155758. _seek_helper(vf,offset);
  155759. ret=_get_next_page(vf,og,CHUNKSIZE);
  155760. if(ret<0)
  155761. /* this shouldn't be possible */
  155762. return(OV_EFAULT);
  155763. return(offset);
  155764. }
  155765. /* finds each bitstream link one at a time using a bisection search
  155766. (has to begin by knowing the offset of the lb's initial page).
  155767. Recurses for each link so it can alloc the link storage after
  155768. finding them all, then unroll and fill the cache at the same time */
  155769. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155770. ogg_int64_t begin,
  155771. ogg_int64_t searched,
  155772. ogg_int64_t end,
  155773. long currentno,
  155774. long m){
  155775. ogg_int64_t endsearched=end;
  155776. ogg_int64_t next=end;
  155777. ogg_page og;
  155778. ogg_int64_t ret;
  155779. /* the below guards against garbage seperating the last and
  155780. first pages of two links. */
  155781. while(searched<endsearched){
  155782. ogg_int64_t bisect;
  155783. if(endsearched-searched<CHUNKSIZE){
  155784. bisect=searched;
  155785. }else{
  155786. bisect=(searched+endsearched)/2;
  155787. }
  155788. _seek_helper(vf,bisect);
  155789. ret=_get_next_page(vf,&og,-1);
  155790. if(ret==OV_EREAD)return(OV_EREAD);
  155791. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155792. endsearched=bisect;
  155793. if(ret>=0)next=ret;
  155794. }else{
  155795. searched=ret+og.header_len+og.body_len;
  155796. }
  155797. }
  155798. _seek_helper(vf,next);
  155799. ret=_get_next_page(vf,&og,-1);
  155800. if(ret==OV_EREAD)return(OV_EREAD);
  155801. if(searched>=end || ret<0){
  155802. vf->links=m+1;
  155803. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155804. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155805. vf->offsets[m+1]=searched;
  155806. }else{
  155807. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155808. end,ogg_page_serialno(&og),m+1);
  155809. if(ret==OV_EREAD)return(OV_EREAD);
  155810. }
  155811. vf->offsets[m]=begin;
  155812. vf->serialnos[m]=currentno;
  155813. return(0);
  155814. }
  155815. /* uses the local ogg_stream storage in vf; this is important for
  155816. non-streaming input sources */
  155817. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155818. long *serialno,ogg_page *og_ptr){
  155819. ogg_page og;
  155820. ogg_packet op;
  155821. int i,ret;
  155822. if(!og_ptr){
  155823. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155824. if(llret==OV_EREAD)return(OV_EREAD);
  155825. if(llret<0)return OV_ENOTVORBIS;
  155826. og_ptr=&og;
  155827. }
  155828. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155829. if(serialno)*serialno=vf->os.serialno;
  155830. vf->ready_state=STREAMSET;
  155831. /* extract the initial header from the first page and verify that the
  155832. Ogg bitstream is in fact Vorbis data */
  155833. vorbis_info_init(vi);
  155834. vorbis_comment_init(vc);
  155835. i=0;
  155836. while(i<3){
  155837. ogg_stream_pagein(&vf->os,og_ptr);
  155838. while(i<3){
  155839. int result=ogg_stream_packetout(&vf->os,&op);
  155840. if(result==0)break;
  155841. if(result==-1){
  155842. ret=OV_EBADHEADER;
  155843. goto bail_header;
  155844. }
  155845. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155846. goto bail_header;
  155847. }
  155848. i++;
  155849. }
  155850. if(i<3)
  155851. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155852. ret=OV_EBADHEADER;
  155853. goto bail_header;
  155854. }
  155855. }
  155856. return 0;
  155857. bail_header:
  155858. vorbis_info_clear(vi);
  155859. vorbis_comment_clear(vc);
  155860. vf->ready_state=OPENED;
  155861. return ret;
  155862. }
  155863. /* last step of the OggVorbis_File initialization; get all the
  155864. vorbis_info structs and PCM positions. Only called by the seekable
  155865. initialization (local stream storage is hacked slightly; pay
  155866. attention to how that's done) */
  155867. /* this is void and does not propogate errors up because we want to be
  155868. able to open and use damaged bitstreams as well as we can. Just
  155869. watch out for missing information for links in the OggVorbis_File
  155870. struct */
  155871. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155872. ogg_page og;
  155873. int i;
  155874. ogg_int64_t ret;
  155875. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155876. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155877. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155878. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155879. for(i=0;i<vf->links;i++){
  155880. if(i==0){
  155881. /* we already grabbed the initial header earlier. Just set the offset */
  155882. vf->dataoffsets[i]=dataoffset;
  155883. _seek_helper(vf,dataoffset);
  155884. }else{
  155885. /* seek to the location of the initial header */
  155886. _seek_helper(vf,vf->offsets[i]);
  155887. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155888. vf->dataoffsets[i]=-1;
  155889. }else{
  155890. vf->dataoffsets[i]=vf->offset;
  155891. }
  155892. }
  155893. /* fetch beginning PCM offset */
  155894. if(vf->dataoffsets[i]!=-1){
  155895. ogg_int64_t accumulated=0;
  155896. long lastblock=-1;
  155897. int result;
  155898. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155899. while(1){
  155900. ogg_packet op;
  155901. ret=_get_next_page(vf,&og,-1);
  155902. if(ret<0)
  155903. /* this should not be possible unless the file is
  155904. truncated/mangled */
  155905. break;
  155906. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155907. break;
  155908. /* count blocksizes of all frames in the page */
  155909. ogg_stream_pagein(&vf->os,&og);
  155910. while((result=ogg_stream_packetout(&vf->os,&op))){
  155911. if(result>0){ /* ignore holes */
  155912. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155913. if(lastblock!=-1)
  155914. accumulated+=(lastblock+thisblock)>>2;
  155915. lastblock=thisblock;
  155916. }
  155917. }
  155918. if(ogg_page_granulepos(&og)!=-1){
  155919. /* pcm offset of last packet on the first audio page */
  155920. accumulated= ogg_page_granulepos(&og)-accumulated;
  155921. break;
  155922. }
  155923. }
  155924. /* less than zero? This is a stream with samples trimmed off
  155925. the beginning, a normal occurrence; set the offset to zero */
  155926. if(accumulated<0)accumulated=0;
  155927. vf->pcmlengths[i*2]=accumulated;
  155928. }
  155929. /* get the PCM length of this link. To do this,
  155930. get the last page of the stream */
  155931. {
  155932. ogg_int64_t end=vf->offsets[i+1];
  155933. _seek_helper(vf,end);
  155934. while(1){
  155935. ret=_get_prev_page(vf,&og);
  155936. if(ret<0){
  155937. /* this should not be possible */
  155938. vorbis_info_clear(vf->vi+i);
  155939. vorbis_comment_clear(vf->vc+i);
  155940. break;
  155941. }
  155942. if(ogg_page_granulepos(&og)!=-1){
  155943. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155944. break;
  155945. }
  155946. vf->offset=ret;
  155947. }
  155948. }
  155949. }
  155950. }
  155951. static int _make_decode_ready(OggVorbis_File *vf){
  155952. if(vf->ready_state>STREAMSET)return 0;
  155953. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155954. if(vf->seekable){
  155955. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155956. return OV_EBADLINK;
  155957. }else{
  155958. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155959. return OV_EBADLINK;
  155960. }
  155961. vorbis_block_init(&vf->vd,&vf->vb);
  155962. vf->ready_state=INITSET;
  155963. vf->bittrack=0.f;
  155964. vf->samptrack=0.f;
  155965. return 0;
  155966. }
  155967. static int _open_seekable2(OggVorbis_File *vf){
  155968. long serialno=vf->current_serialno;
  155969. ogg_int64_t dataoffset=vf->offset, end;
  155970. ogg_page og;
  155971. /* we're partially open and have a first link header state in
  155972. storage in vf */
  155973. /* we can seek, so set out learning all about this file */
  155974. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155975. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155976. /* We get the offset for the last page of the physical bitstream.
  155977. Most OggVorbis files will contain a single logical bitstream */
  155978. end=_get_prev_page(vf,&og);
  155979. if(end<0)return(end);
  155980. /* more than one logical bitstream? */
  155981. if(ogg_page_serialno(&og)!=serialno){
  155982. /* Chained bitstream. Bisect-search each logical bitstream
  155983. section. Do so based on serial number only */
  155984. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155985. }else{
  155986. /* Only one logical bitstream */
  155987. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155988. }
  155989. /* the initial header memory is referenced by vf after; don't free it */
  155990. _prefetch_all_headers(vf,dataoffset);
  155991. return(ov_raw_seek(vf,0));
  155992. }
  155993. /* clear out the current logical bitstream decoder */
  155994. static void _decode_clear(OggVorbis_File *vf){
  155995. vorbis_dsp_clear(&vf->vd);
  155996. vorbis_block_clear(&vf->vb);
  155997. vf->ready_state=OPENED;
  155998. }
  155999. /* fetch and process a packet. Handles the case where we're at a
  156000. bitstream boundary and dumps the decoding machine. If the decoding
  156001. machine is unloaded, it loads it. It also keeps pcm_offset up to
  156002. date (seek and read both use this. seek uses a special hack with
  156003. readp).
  156004. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  156005. 0) need more data (only if readp==0)
  156006. 1) got a packet
  156007. */
  156008. static int _fetch_and_process_packet(OggVorbis_File *vf,
  156009. ogg_packet *op_in,
  156010. int readp,
  156011. int spanp){
  156012. ogg_page og;
  156013. /* handle one packet. Try to fetch it from current stream state */
  156014. /* extract packets from page */
  156015. while(1){
  156016. /* process a packet if we can. If the machine isn't loaded,
  156017. neither is a page */
  156018. if(vf->ready_state==INITSET){
  156019. while(1) {
  156020. ogg_packet op;
  156021. ogg_packet *op_ptr=(op_in?op_in:&op);
  156022. int result=ogg_stream_packetout(&vf->os,op_ptr);
  156023. ogg_int64_t granulepos;
  156024. op_in=NULL;
  156025. if(result==-1)return(OV_HOLE); /* hole in the data. */
  156026. if(result>0){
  156027. /* got a packet. process it */
  156028. granulepos=op_ptr->granulepos;
  156029. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  156030. header handling. The
  156031. header packets aren't
  156032. audio, so if/when we
  156033. submit them,
  156034. vorbis_synthesis will
  156035. reject them */
  156036. /* suck in the synthesis data and track bitrate */
  156037. {
  156038. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156039. /* for proper use of libvorbis within libvorbisfile,
  156040. oldsamples will always be zero. */
  156041. if(oldsamples)return(OV_EFAULT);
  156042. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156043. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  156044. vf->bittrack+=op_ptr->bytes*8;
  156045. }
  156046. /* update the pcm offset. */
  156047. if(granulepos!=-1 && !op_ptr->e_o_s){
  156048. int link=(vf->seekable?vf->current_link:0);
  156049. int i,samples;
  156050. /* this packet has a pcm_offset on it (the last packet
  156051. completed on a page carries the offset) After processing
  156052. (above), we know the pcm position of the *last* sample
  156053. ready to be returned. Find the offset of the *first*
  156054. As an aside, this trick is inaccurate if we begin
  156055. reading anew right at the last page; the end-of-stream
  156056. granulepos declares the last frame in the stream, and the
  156057. last packet of the last page may be a partial frame.
  156058. So, we need a previous granulepos from an in-sequence page
  156059. to have a reference point. Thus the !op_ptr->e_o_s clause
  156060. above */
  156061. if(vf->seekable && link>0)
  156062. granulepos-=vf->pcmlengths[link*2];
  156063. if(granulepos<0)granulepos=0; /* actually, this
  156064. shouldn't be possible
  156065. here unless the stream
  156066. is very broken */
  156067. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156068. granulepos-=samples;
  156069. for(i=0;i<link;i++)
  156070. granulepos+=vf->pcmlengths[i*2+1];
  156071. vf->pcm_offset=granulepos;
  156072. }
  156073. return(1);
  156074. }
  156075. }
  156076. else
  156077. break;
  156078. }
  156079. }
  156080. if(vf->ready_state>=OPENED){
  156081. ogg_int64_t ret;
  156082. if(!readp)return(0);
  156083. if((ret=_get_next_page(vf,&og,-1))<0){
  156084. return(OV_EOF); /* eof.
  156085. leave unitialized */
  156086. }
  156087. /* bitrate tracking; add the header's bytes here, the body bytes
  156088. are done by packet above */
  156089. vf->bittrack+=og.header_len*8;
  156090. /* has our decoding just traversed a bitstream boundary? */
  156091. if(vf->ready_state==INITSET){
  156092. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156093. if(!spanp)
  156094. return(OV_EOF);
  156095. _decode_clear(vf);
  156096. if(!vf->seekable){
  156097. vorbis_info_clear(vf->vi);
  156098. vorbis_comment_clear(vf->vc);
  156099. }
  156100. }
  156101. }
  156102. }
  156103. /* Do we need to load a new machine before submitting the page? */
  156104. /* This is different in the seekable and non-seekable cases.
  156105. In the seekable case, we already have all the header
  156106. information loaded and cached; we just initialize the machine
  156107. with it and continue on our merry way.
  156108. In the non-seekable (streaming) case, we'll only be at a
  156109. boundary if we just left the previous logical bitstream and
  156110. we're now nominally at the header of the next bitstream
  156111. */
  156112. if(vf->ready_state!=INITSET){
  156113. int link;
  156114. if(vf->ready_state<STREAMSET){
  156115. if(vf->seekable){
  156116. vf->current_serialno=ogg_page_serialno(&og);
  156117. /* match the serialno to bitstream section. We use this rather than
  156118. offset positions to avoid problems near logical bitstream
  156119. boundaries */
  156120. for(link=0;link<vf->links;link++)
  156121. if(vf->serialnos[link]==vf->current_serialno)break;
  156122. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  156123. stream. error out,
  156124. leave machine
  156125. uninitialized */
  156126. vf->current_link=link;
  156127. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156128. vf->ready_state=STREAMSET;
  156129. }else{
  156130. /* we're streaming */
  156131. /* fetch the three header packets, build the info struct */
  156132. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  156133. if(ret)return(ret);
  156134. vf->current_link++;
  156135. link=0;
  156136. }
  156137. }
  156138. {
  156139. int ret=_make_decode_ready(vf);
  156140. if(ret<0)return ret;
  156141. }
  156142. }
  156143. ogg_stream_pagein(&vf->os,&og);
  156144. }
  156145. }
  156146. /* if, eg, 64 bit stdio is configured by default, this will build with
  156147. fseek64 */
  156148. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156149. if(f==NULL)return(-1);
  156150. return fseek(f,off,whence);
  156151. }
  156152. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156153. long ibytes, ov_callbacks callbacks){
  156154. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156155. int ret;
  156156. memset(vf,0,sizeof(*vf));
  156157. vf->datasource=f;
  156158. vf->callbacks = callbacks;
  156159. /* init the framing state */
  156160. ogg_sync_init(&vf->oy);
  156161. /* perhaps some data was previously read into a buffer for testing
  156162. against other stream types. Allow initialization from this
  156163. previously read data (as we may be reading from a non-seekable
  156164. stream) */
  156165. if(initial){
  156166. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156167. memcpy(buffer,initial,ibytes);
  156168. ogg_sync_wrote(&vf->oy,ibytes);
  156169. }
  156170. /* can we seek? Stevens suggests the seek test was portable */
  156171. if(offsettest!=-1)vf->seekable=1;
  156172. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156173. entry for partial open */
  156174. vf->links=1;
  156175. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156176. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156177. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156178. /* Try to fetch the headers, maintaining all the storage */
  156179. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156180. vf->datasource=NULL;
  156181. ov_clear(vf);
  156182. }else
  156183. vf->ready_state=PARTOPEN;
  156184. return(ret);
  156185. }
  156186. static int _ov_open2(OggVorbis_File *vf){
  156187. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156188. vf->ready_state=OPENED;
  156189. if(vf->seekable){
  156190. int ret=_open_seekable2(vf);
  156191. if(ret){
  156192. vf->datasource=NULL;
  156193. ov_clear(vf);
  156194. }
  156195. return(ret);
  156196. }else
  156197. vf->ready_state=STREAMSET;
  156198. return 0;
  156199. }
  156200. /* clear out the OggVorbis_File struct */
  156201. int ov_clear(OggVorbis_File *vf){
  156202. if(vf){
  156203. vorbis_block_clear(&vf->vb);
  156204. vorbis_dsp_clear(&vf->vd);
  156205. ogg_stream_clear(&vf->os);
  156206. if(vf->vi && vf->links){
  156207. int i;
  156208. for(i=0;i<vf->links;i++){
  156209. vorbis_info_clear(vf->vi+i);
  156210. vorbis_comment_clear(vf->vc+i);
  156211. }
  156212. _ogg_free(vf->vi);
  156213. _ogg_free(vf->vc);
  156214. }
  156215. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156216. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156217. if(vf->serialnos)_ogg_free(vf->serialnos);
  156218. if(vf->offsets)_ogg_free(vf->offsets);
  156219. ogg_sync_clear(&vf->oy);
  156220. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156221. memset(vf,0,sizeof(*vf));
  156222. }
  156223. #ifdef DEBUG_LEAKS
  156224. _VDBG_dump();
  156225. #endif
  156226. return(0);
  156227. }
  156228. /* inspects the OggVorbis file and finds/documents all the logical
  156229. bitstreams contained in it. Tries to be tolerant of logical
  156230. bitstream sections that are truncated/woogie.
  156231. return: -1) error
  156232. 0) OK
  156233. */
  156234. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156235. ov_callbacks callbacks){
  156236. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156237. if(ret)return ret;
  156238. return _ov_open2(vf);
  156239. }
  156240. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156241. ov_callbacks callbacks = {
  156242. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156243. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156244. (int (*)(void *)) fclose,
  156245. (long (*)(void *)) ftell
  156246. };
  156247. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156248. }
  156249. /* cheap hack for game usage where downsampling is desirable; there's
  156250. no need for SRC as we can just do it cheaply in libvorbis. */
  156251. int ov_halfrate(OggVorbis_File *vf,int flag){
  156252. int i;
  156253. if(vf->vi==NULL)return OV_EINVAL;
  156254. if(!vf->seekable)return OV_EINVAL;
  156255. if(vf->ready_state>=STREAMSET)
  156256. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156257. will be able to swap this on the fly, but
  156258. for now dumping the decode machine is needed
  156259. to reinit the MDCT lookups. 1.1 libvorbis
  156260. is planned to be able to switch on the fly */
  156261. for(i=0;i<vf->links;i++){
  156262. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156263. ov_halfrate(vf,0);
  156264. return OV_EINVAL;
  156265. }
  156266. }
  156267. return 0;
  156268. }
  156269. int ov_halfrate_p(OggVorbis_File *vf){
  156270. if(vf->vi==NULL)return OV_EINVAL;
  156271. return vorbis_synthesis_halfrate_p(vf->vi);
  156272. }
  156273. /* Only partially open the vorbis file; test for Vorbisness, and load
  156274. the headers for the first chain. Do not seek (although test for
  156275. seekability). Use ov_test_open to finish opening the file, else
  156276. ov_clear to close/free it. Same return codes as open. */
  156277. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156278. ov_callbacks callbacks)
  156279. {
  156280. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156281. }
  156282. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156283. ov_callbacks callbacks = {
  156284. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156285. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156286. (int (*)(void *)) fclose,
  156287. (long (*)(void *)) ftell
  156288. };
  156289. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156290. }
  156291. int ov_test_open(OggVorbis_File *vf){
  156292. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156293. return _ov_open2(vf);
  156294. }
  156295. /* How many logical bitstreams in this physical bitstream? */
  156296. long ov_streams(OggVorbis_File *vf){
  156297. return vf->links;
  156298. }
  156299. /* Is the FILE * associated with vf seekable? */
  156300. long ov_seekable(OggVorbis_File *vf){
  156301. return vf->seekable;
  156302. }
  156303. /* returns the bitrate for a given logical bitstream or the entire
  156304. physical bitstream. If the file is open for random access, it will
  156305. find the *actual* average bitrate. If the file is streaming, it
  156306. returns the nominal bitrate (if set) else the average of the
  156307. upper/lower bounds (if set) else -1 (unset).
  156308. If you want the actual bitrate field settings, get them from the
  156309. vorbis_info structs */
  156310. long ov_bitrate(OggVorbis_File *vf,int i){
  156311. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156312. if(i>=vf->links)return(OV_EINVAL);
  156313. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156314. if(i<0){
  156315. ogg_int64_t bits=0;
  156316. int i;
  156317. float br;
  156318. for(i=0;i<vf->links;i++)
  156319. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156320. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156321. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156322. * so this is slightly transformed to make it work.
  156323. */
  156324. br = bits/ov_time_total(vf,-1);
  156325. return(rint(br));
  156326. }else{
  156327. if(vf->seekable){
  156328. /* return the actual bitrate */
  156329. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156330. }else{
  156331. /* return nominal if set */
  156332. if(vf->vi[i].bitrate_nominal>0){
  156333. return vf->vi[i].bitrate_nominal;
  156334. }else{
  156335. if(vf->vi[i].bitrate_upper>0){
  156336. if(vf->vi[i].bitrate_lower>0){
  156337. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156338. }else{
  156339. return vf->vi[i].bitrate_upper;
  156340. }
  156341. }
  156342. return(OV_FALSE);
  156343. }
  156344. }
  156345. }
  156346. }
  156347. /* returns the actual bitrate since last call. returns -1 if no
  156348. additional data to offer since last call (or at beginning of stream),
  156349. EINVAL if stream is only partially open
  156350. */
  156351. long ov_bitrate_instant(OggVorbis_File *vf){
  156352. int link=(vf->seekable?vf->current_link:0);
  156353. long ret;
  156354. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156355. if(vf->samptrack==0)return(OV_FALSE);
  156356. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156357. vf->bittrack=0.f;
  156358. vf->samptrack=0.f;
  156359. return(ret);
  156360. }
  156361. /* Guess */
  156362. long ov_serialnumber(OggVorbis_File *vf,int i){
  156363. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156364. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156365. if(i<0){
  156366. return(vf->current_serialno);
  156367. }else{
  156368. return(vf->serialnos[i]);
  156369. }
  156370. }
  156371. /* returns: total raw (compressed) length of content if i==-1
  156372. raw (compressed) length of that logical bitstream for i==0 to n
  156373. OV_EINVAL if the stream is not seekable (we can't know the length)
  156374. or if stream is only partially open
  156375. */
  156376. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156377. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156378. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156379. if(i<0){
  156380. ogg_int64_t acc=0;
  156381. int i;
  156382. for(i=0;i<vf->links;i++)
  156383. acc+=ov_raw_total(vf,i);
  156384. return(acc);
  156385. }else{
  156386. return(vf->offsets[i+1]-vf->offsets[i]);
  156387. }
  156388. }
  156389. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156390. (samples) of that logical bitstream for i==0 to n
  156391. OV_EINVAL if the stream is not seekable (we can't know the
  156392. length) or only partially open
  156393. */
  156394. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156395. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156396. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156397. if(i<0){
  156398. ogg_int64_t acc=0;
  156399. int i;
  156400. for(i=0;i<vf->links;i++)
  156401. acc+=ov_pcm_total(vf,i);
  156402. return(acc);
  156403. }else{
  156404. return(vf->pcmlengths[i*2+1]);
  156405. }
  156406. }
  156407. /* returns: total seconds of content if i==-1
  156408. seconds in that logical bitstream for i==0 to n
  156409. OV_EINVAL if the stream is not seekable (we can't know the
  156410. length) or only partially open
  156411. */
  156412. double ov_time_total(OggVorbis_File *vf,int i){
  156413. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156414. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156415. if(i<0){
  156416. double acc=0;
  156417. int i;
  156418. for(i=0;i<vf->links;i++)
  156419. acc+=ov_time_total(vf,i);
  156420. return(acc);
  156421. }else{
  156422. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156423. }
  156424. }
  156425. /* seek to an offset relative to the *compressed* data. This also
  156426. scans packets to update the PCM cursor. It will cross a logical
  156427. bitstream boundary, but only if it can't get any packets out of the
  156428. tail of the bitstream we seek to (so no surprises).
  156429. returns zero on success, nonzero on failure */
  156430. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156431. ogg_stream_state work_os;
  156432. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156433. if(!vf->seekable)
  156434. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156435. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156436. /* don't yet clear out decoding machine (if it's initialized), in
  156437. the case we're in the same link. Restart the decode lapping, and
  156438. let _fetch_and_process_packet deal with a potential bitstream
  156439. boundary */
  156440. vf->pcm_offset=-1;
  156441. ogg_stream_reset_serialno(&vf->os,
  156442. vf->current_serialno); /* must set serialno */
  156443. vorbis_synthesis_restart(&vf->vd);
  156444. _seek_helper(vf,pos);
  156445. /* we need to make sure the pcm_offset is set, but we don't want to
  156446. advance the raw cursor past good packets just to get to the first
  156447. with a granulepos. That's not equivalent behavior to beginning
  156448. decoding as immediately after the seek position as possible.
  156449. So, a hack. We use two stream states; a local scratch state and
  156450. the shared vf->os stream state. We use the local state to
  156451. scan, and the shared state as a buffer for later decode.
  156452. Unfortuantely, on the last page we still advance to last packet
  156453. because the granulepos on the last page is not necessarily on a
  156454. packet boundary, and we need to make sure the granpos is
  156455. correct.
  156456. */
  156457. {
  156458. ogg_page og;
  156459. ogg_packet op;
  156460. int lastblock=0;
  156461. int accblock=0;
  156462. int thisblock;
  156463. int eosflag;
  156464. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156465. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156466. return from not necessarily
  156467. starting from the beginning */
  156468. while(1){
  156469. if(vf->ready_state>=STREAMSET){
  156470. /* snarf/scan a packet if we can */
  156471. int result=ogg_stream_packetout(&work_os,&op);
  156472. if(result>0){
  156473. if(vf->vi[vf->current_link].codec_setup){
  156474. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156475. if(thisblock<0){
  156476. ogg_stream_packetout(&vf->os,NULL);
  156477. thisblock=0;
  156478. }else{
  156479. if(eosflag)
  156480. ogg_stream_packetout(&vf->os,NULL);
  156481. else
  156482. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156483. }
  156484. if(op.granulepos!=-1){
  156485. int i,link=vf->current_link;
  156486. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156487. if(granulepos<0)granulepos=0;
  156488. for(i=0;i<link;i++)
  156489. granulepos+=vf->pcmlengths[i*2+1];
  156490. vf->pcm_offset=granulepos-accblock;
  156491. break;
  156492. }
  156493. lastblock=thisblock;
  156494. continue;
  156495. }else
  156496. ogg_stream_packetout(&vf->os,NULL);
  156497. }
  156498. }
  156499. if(!lastblock){
  156500. if(_get_next_page(vf,&og,-1)<0){
  156501. vf->pcm_offset=ov_pcm_total(vf,-1);
  156502. break;
  156503. }
  156504. }else{
  156505. /* huh? Bogus stream with packets but no granulepos */
  156506. vf->pcm_offset=-1;
  156507. break;
  156508. }
  156509. /* has our decoding just traversed a bitstream boundary? */
  156510. if(vf->ready_state>=STREAMSET)
  156511. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156512. _decode_clear(vf); /* clear out stream state */
  156513. ogg_stream_clear(&work_os);
  156514. }
  156515. if(vf->ready_state<STREAMSET){
  156516. int link;
  156517. vf->current_serialno=ogg_page_serialno(&og);
  156518. for(link=0;link<vf->links;link++)
  156519. if(vf->serialnos[link]==vf->current_serialno)break;
  156520. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156521. error out, leave
  156522. machine uninitialized */
  156523. vf->current_link=link;
  156524. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156525. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156526. vf->ready_state=STREAMSET;
  156527. }
  156528. ogg_stream_pagein(&vf->os,&og);
  156529. ogg_stream_pagein(&work_os,&og);
  156530. eosflag=ogg_page_eos(&og);
  156531. }
  156532. }
  156533. ogg_stream_clear(&work_os);
  156534. vf->bittrack=0.f;
  156535. vf->samptrack=0.f;
  156536. return(0);
  156537. seek_error:
  156538. /* dump the machine so we're in a known state */
  156539. vf->pcm_offset=-1;
  156540. ogg_stream_clear(&work_os);
  156541. _decode_clear(vf);
  156542. return OV_EBADLINK;
  156543. }
  156544. /* Page granularity seek (faster than sample granularity because we
  156545. don't do the last bit of decode to find a specific sample).
  156546. Seek to the last [granule marked] page preceeding the specified pos
  156547. location, such that decoding past the returned point will quickly
  156548. arrive at the requested position. */
  156549. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156550. int link=-1;
  156551. ogg_int64_t result=0;
  156552. ogg_int64_t total=ov_pcm_total(vf,-1);
  156553. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156554. if(!vf->seekable)return(OV_ENOSEEK);
  156555. if(pos<0 || pos>total)return(OV_EINVAL);
  156556. /* which bitstream section does this pcm offset occur in? */
  156557. for(link=vf->links-1;link>=0;link--){
  156558. total-=vf->pcmlengths[link*2+1];
  156559. if(pos>=total)break;
  156560. }
  156561. /* search within the logical bitstream for the page with the highest
  156562. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156563. missing pages or incorrect frame number information in the
  156564. bitstream could make our task impossible. Account for that (it
  156565. would be an error condition) */
  156566. /* new search algorithm by HB (Nicholas Vinen) */
  156567. {
  156568. ogg_int64_t end=vf->offsets[link+1];
  156569. ogg_int64_t begin=vf->offsets[link];
  156570. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156571. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156572. ogg_int64_t target=pos-total+begintime;
  156573. ogg_int64_t best=begin;
  156574. ogg_page og;
  156575. while(begin<end){
  156576. ogg_int64_t bisect;
  156577. if(end-begin<CHUNKSIZE){
  156578. bisect=begin;
  156579. }else{
  156580. /* take a (pretty decent) guess. */
  156581. bisect=begin +
  156582. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156583. if(bisect<=begin)
  156584. bisect=begin+1;
  156585. }
  156586. _seek_helper(vf,bisect);
  156587. while(begin<end){
  156588. result=_get_next_page(vf,&og,end-vf->offset);
  156589. if(result==OV_EREAD) goto seek_error;
  156590. if(result<0){
  156591. if(bisect<=begin+1)
  156592. end=begin; /* found it */
  156593. else{
  156594. if(bisect==0) goto seek_error;
  156595. bisect-=CHUNKSIZE;
  156596. if(bisect<=begin)bisect=begin+1;
  156597. _seek_helper(vf,bisect);
  156598. }
  156599. }else{
  156600. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156601. if(granulepos==-1)continue;
  156602. if(granulepos<target){
  156603. best=result; /* raw offset of packet with granulepos */
  156604. begin=vf->offset; /* raw offset of next page */
  156605. begintime=granulepos;
  156606. if(target-begintime>44100)break;
  156607. bisect=begin; /* *not* begin + 1 */
  156608. }else{
  156609. if(bisect<=begin+1)
  156610. end=begin; /* found it */
  156611. else{
  156612. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156613. end=result;
  156614. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156615. if(bisect<=begin)bisect=begin+1;
  156616. _seek_helper(vf,bisect);
  156617. }else{
  156618. end=result;
  156619. endtime=granulepos;
  156620. break;
  156621. }
  156622. }
  156623. }
  156624. }
  156625. }
  156626. }
  156627. /* found our page. seek to it, update pcm offset. Easier case than
  156628. raw_seek, don't keep packets preceeding granulepos. */
  156629. {
  156630. ogg_page og;
  156631. ogg_packet op;
  156632. /* seek */
  156633. _seek_helper(vf,best);
  156634. vf->pcm_offset=-1;
  156635. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156636. if(link!=vf->current_link){
  156637. /* Different link; dump entire decode machine */
  156638. _decode_clear(vf);
  156639. vf->current_link=link;
  156640. vf->current_serialno=ogg_page_serialno(&og);
  156641. vf->ready_state=STREAMSET;
  156642. }else{
  156643. vorbis_synthesis_restart(&vf->vd);
  156644. }
  156645. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156646. ogg_stream_pagein(&vf->os,&og);
  156647. /* pull out all but last packet; the one with granulepos */
  156648. while(1){
  156649. result=ogg_stream_packetpeek(&vf->os,&op);
  156650. if(result==0){
  156651. /* !!! the packet finishing this page originated on a
  156652. preceeding page. Keep fetching previous pages until we
  156653. get one with a granulepos or without the 'continued' flag
  156654. set. Then just use raw_seek for simplicity. */
  156655. _seek_helper(vf,best);
  156656. while(1){
  156657. result=_get_prev_page(vf,&og);
  156658. if(result<0) goto seek_error;
  156659. if(ogg_page_granulepos(&og)>-1 ||
  156660. !ogg_page_continued(&og)){
  156661. return ov_raw_seek(vf,result);
  156662. }
  156663. vf->offset=result;
  156664. }
  156665. }
  156666. if(result<0){
  156667. result = OV_EBADPACKET;
  156668. goto seek_error;
  156669. }
  156670. if(op.granulepos!=-1){
  156671. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156672. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156673. vf->pcm_offset+=total;
  156674. break;
  156675. }else
  156676. result=ogg_stream_packetout(&vf->os,NULL);
  156677. }
  156678. }
  156679. }
  156680. /* verify result */
  156681. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156682. result=OV_EFAULT;
  156683. goto seek_error;
  156684. }
  156685. vf->bittrack=0.f;
  156686. vf->samptrack=0.f;
  156687. return(0);
  156688. seek_error:
  156689. /* dump machine so we're in a known state */
  156690. vf->pcm_offset=-1;
  156691. _decode_clear(vf);
  156692. return (int)result;
  156693. }
  156694. /* seek to a sample offset relative to the decompressed pcm stream
  156695. returns zero on success, nonzero on failure */
  156696. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156697. int thisblock,lastblock=0;
  156698. int ret=ov_pcm_seek_page(vf,pos);
  156699. if(ret<0)return(ret);
  156700. if((ret=_make_decode_ready(vf)))return ret;
  156701. /* discard leading packets we don't need for the lapping of the
  156702. position we want; don't decode them */
  156703. while(1){
  156704. ogg_packet op;
  156705. ogg_page og;
  156706. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156707. if(ret>0){
  156708. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156709. if(thisblock<0){
  156710. ogg_stream_packetout(&vf->os,NULL);
  156711. continue; /* non audio packet */
  156712. }
  156713. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156714. if(vf->pcm_offset+((thisblock+
  156715. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156716. /* remove the packet from packet queue and track its granulepos */
  156717. ogg_stream_packetout(&vf->os,NULL);
  156718. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156719. only tracking, no
  156720. pcm_decode */
  156721. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156722. /* end of logical stream case is hard, especially with exact
  156723. length positioning. */
  156724. if(op.granulepos>-1){
  156725. int i;
  156726. /* always believe the stream markers */
  156727. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156728. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156729. for(i=0;i<vf->current_link;i++)
  156730. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156731. }
  156732. lastblock=thisblock;
  156733. }else{
  156734. if(ret<0 && ret!=OV_HOLE)break;
  156735. /* suck in a new page */
  156736. if(_get_next_page(vf,&og,-1)<0)break;
  156737. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156738. if(vf->ready_state<STREAMSET){
  156739. int link;
  156740. vf->current_serialno=ogg_page_serialno(&og);
  156741. for(link=0;link<vf->links;link++)
  156742. if(vf->serialnos[link]==vf->current_serialno)break;
  156743. if(link==vf->links)return(OV_EBADLINK);
  156744. vf->current_link=link;
  156745. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156746. vf->ready_state=STREAMSET;
  156747. ret=_make_decode_ready(vf);
  156748. if(ret)return ret;
  156749. lastblock=0;
  156750. }
  156751. ogg_stream_pagein(&vf->os,&og);
  156752. }
  156753. }
  156754. vf->bittrack=0.f;
  156755. vf->samptrack=0.f;
  156756. /* discard samples until we reach the desired position. Crossing a
  156757. logical bitstream boundary with abandon is OK. */
  156758. while(vf->pcm_offset<pos){
  156759. ogg_int64_t target=pos-vf->pcm_offset;
  156760. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156761. if(samples>target)samples=target;
  156762. vorbis_synthesis_read(&vf->vd,samples);
  156763. vf->pcm_offset+=samples;
  156764. if(samples<target)
  156765. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156766. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156767. }
  156768. return 0;
  156769. }
  156770. /* seek to a playback time relative to the decompressed pcm stream
  156771. returns zero on success, nonzero on failure */
  156772. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156773. /* translate time to PCM position and call ov_pcm_seek */
  156774. int link=-1;
  156775. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156776. double time_total=ov_time_total(vf,-1);
  156777. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156778. if(!vf->seekable)return(OV_ENOSEEK);
  156779. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156780. /* which bitstream section does this time offset occur in? */
  156781. for(link=vf->links-1;link>=0;link--){
  156782. pcm_total-=vf->pcmlengths[link*2+1];
  156783. time_total-=ov_time_total(vf,link);
  156784. if(seconds>=time_total)break;
  156785. }
  156786. /* enough information to convert time offset to pcm offset */
  156787. {
  156788. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156789. return(ov_pcm_seek(vf,target));
  156790. }
  156791. }
  156792. /* page-granularity version of ov_time_seek
  156793. returns zero on success, nonzero on failure */
  156794. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156795. /* translate time to PCM position and call ov_pcm_seek */
  156796. int link=-1;
  156797. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156798. double time_total=ov_time_total(vf,-1);
  156799. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156800. if(!vf->seekable)return(OV_ENOSEEK);
  156801. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156802. /* which bitstream section does this time offset occur in? */
  156803. for(link=vf->links-1;link>=0;link--){
  156804. pcm_total-=vf->pcmlengths[link*2+1];
  156805. time_total-=ov_time_total(vf,link);
  156806. if(seconds>=time_total)break;
  156807. }
  156808. /* enough information to convert time offset to pcm offset */
  156809. {
  156810. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156811. return(ov_pcm_seek_page(vf,target));
  156812. }
  156813. }
  156814. /* tell the current stream offset cursor. Note that seek followed by
  156815. tell will likely not give the set offset due to caching */
  156816. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156817. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156818. return(vf->offset);
  156819. }
  156820. /* return PCM offset (sample) of next PCM sample to be read */
  156821. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156822. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156823. return(vf->pcm_offset);
  156824. }
  156825. /* return time offset (seconds) of next PCM sample to be read */
  156826. double ov_time_tell(OggVorbis_File *vf){
  156827. int link=0;
  156828. ogg_int64_t pcm_total=0;
  156829. double time_total=0.f;
  156830. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156831. if(vf->seekable){
  156832. pcm_total=ov_pcm_total(vf,-1);
  156833. time_total=ov_time_total(vf,-1);
  156834. /* which bitstream section does this time offset occur in? */
  156835. for(link=vf->links-1;link>=0;link--){
  156836. pcm_total-=vf->pcmlengths[link*2+1];
  156837. time_total-=ov_time_total(vf,link);
  156838. if(vf->pcm_offset>=pcm_total)break;
  156839. }
  156840. }
  156841. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156842. }
  156843. /* link: -1) return the vorbis_info struct for the bitstream section
  156844. currently being decoded
  156845. 0-n) to request information for a specific bitstream section
  156846. In the case of a non-seekable bitstream, any call returns the
  156847. current bitstream. NULL in the case that the machine is not
  156848. initialized */
  156849. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156850. if(vf->seekable){
  156851. if(link<0)
  156852. if(vf->ready_state>=STREAMSET)
  156853. return vf->vi+vf->current_link;
  156854. else
  156855. return vf->vi;
  156856. else
  156857. if(link>=vf->links)
  156858. return NULL;
  156859. else
  156860. return vf->vi+link;
  156861. }else{
  156862. return vf->vi;
  156863. }
  156864. }
  156865. /* grr, strong typing, grr, no templates/inheritence, grr */
  156866. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156867. if(vf->seekable){
  156868. if(link<0)
  156869. if(vf->ready_state>=STREAMSET)
  156870. return vf->vc+vf->current_link;
  156871. else
  156872. return vf->vc;
  156873. else
  156874. if(link>=vf->links)
  156875. return NULL;
  156876. else
  156877. return vf->vc+link;
  156878. }else{
  156879. return vf->vc;
  156880. }
  156881. }
  156882. static int host_is_big_endian() {
  156883. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156884. unsigned char *bytewise = (unsigned char *)&pattern;
  156885. if (bytewise[0] == 0xfe) return 1;
  156886. return 0;
  156887. }
  156888. /* up to this point, everything could more or less hide the multiple
  156889. logical bitstream nature of chaining from the toplevel application
  156890. if the toplevel application didn't particularly care. However, at
  156891. the point that we actually read audio back, the multiple-section
  156892. nature must surface: Multiple bitstream sections do not necessarily
  156893. have to have the same number of channels or sampling rate.
  156894. ov_read returns the sequential logical bitstream number currently
  156895. being decoded along with the PCM data in order that the toplevel
  156896. application can take action on channel/sample rate changes. This
  156897. number will be incremented even for streamed (non-seekable) streams
  156898. (for seekable streams, it represents the actual logical bitstream
  156899. index within the physical bitstream. Note that the accessor
  156900. functions above are aware of this dichotomy).
  156901. input values: buffer) a buffer to hold packed PCM data for return
  156902. length) the byte length requested to be placed into buffer
  156903. bigendianp) should the data be packed LSB first (0) or
  156904. MSB first (1)
  156905. word) word size for output. currently 1 (byte) or
  156906. 2 (16 bit short)
  156907. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156908. 0) EOF
  156909. n) number of bytes of PCM actually returned. The
  156910. below works on a packet-by-packet basis, so the
  156911. return length is not related to the 'length' passed
  156912. in, just guaranteed to fit.
  156913. *section) set to the logical bitstream number */
  156914. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156915. int bigendianp,int word,int sgned,int *bitstream){
  156916. int i,j;
  156917. int host_endian = host_is_big_endian();
  156918. float **pcm;
  156919. long samples;
  156920. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156921. while(1){
  156922. if(vf->ready_state==INITSET){
  156923. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156924. if(samples)break;
  156925. }
  156926. /* suck in another packet */
  156927. {
  156928. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156929. if(ret==OV_EOF)
  156930. return(0);
  156931. if(ret<=0)
  156932. return(ret);
  156933. }
  156934. }
  156935. if(samples>0){
  156936. /* yay! proceed to pack data into the byte buffer */
  156937. long channels=ov_info(vf,-1)->channels;
  156938. long bytespersample=word * channels;
  156939. vorbis_fpu_control fpu;
  156940. (void) fpu; // (to avoid a warning about it being unused)
  156941. if(samples>length/bytespersample)samples=length/bytespersample;
  156942. if(samples <= 0)
  156943. return OV_EINVAL;
  156944. /* a tight loop to pack each size */
  156945. {
  156946. int val;
  156947. if(word==1){
  156948. int off=(sgned?0:128);
  156949. vorbis_fpu_setround(&fpu);
  156950. for(j=0;j<samples;j++)
  156951. for(i=0;i<channels;i++){
  156952. val=vorbis_ftoi(pcm[i][j]*128.f);
  156953. if(val>127)val=127;
  156954. else if(val<-128)val=-128;
  156955. *buffer++=val+off;
  156956. }
  156957. vorbis_fpu_restore(fpu);
  156958. }else{
  156959. int off=(sgned?0:32768);
  156960. if(host_endian==bigendianp){
  156961. if(sgned){
  156962. vorbis_fpu_setround(&fpu);
  156963. for(i=0;i<channels;i++) { /* It's faster in this order */
  156964. float *src=pcm[i];
  156965. short *dest=((short *)buffer)+i;
  156966. for(j=0;j<samples;j++) {
  156967. val=vorbis_ftoi(src[j]*32768.f);
  156968. if(val>32767)val=32767;
  156969. else if(val<-32768)val=-32768;
  156970. *dest=val;
  156971. dest+=channels;
  156972. }
  156973. }
  156974. vorbis_fpu_restore(fpu);
  156975. }else{
  156976. vorbis_fpu_setround(&fpu);
  156977. for(i=0;i<channels;i++) {
  156978. float *src=pcm[i];
  156979. short *dest=((short *)buffer)+i;
  156980. for(j=0;j<samples;j++) {
  156981. val=vorbis_ftoi(src[j]*32768.f);
  156982. if(val>32767)val=32767;
  156983. else if(val<-32768)val=-32768;
  156984. *dest=val+off;
  156985. dest+=channels;
  156986. }
  156987. }
  156988. vorbis_fpu_restore(fpu);
  156989. }
  156990. }else if(bigendianp){
  156991. vorbis_fpu_setround(&fpu);
  156992. for(j=0;j<samples;j++)
  156993. for(i=0;i<channels;i++){
  156994. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156995. if(val>32767)val=32767;
  156996. else if(val<-32768)val=-32768;
  156997. val+=off;
  156998. *buffer++=(val>>8);
  156999. *buffer++=(val&0xff);
  157000. }
  157001. vorbis_fpu_restore(fpu);
  157002. }else{
  157003. int val;
  157004. vorbis_fpu_setround(&fpu);
  157005. for(j=0;j<samples;j++)
  157006. for(i=0;i<channels;i++){
  157007. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157008. if(val>32767)val=32767;
  157009. else if(val<-32768)val=-32768;
  157010. val+=off;
  157011. *buffer++=(val&0xff);
  157012. *buffer++=(val>>8);
  157013. }
  157014. vorbis_fpu_restore(fpu);
  157015. }
  157016. }
  157017. }
  157018. vorbis_synthesis_read(&vf->vd,samples);
  157019. vf->pcm_offset+=samples;
  157020. if(bitstream)*bitstream=vf->current_link;
  157021. return(samples*bytespersample);
  157022. }else{
  157023. return(samples);
  157024. }
  157025. }
  157026. /* input values: pcm_channels) a float vector per channel of output
  157027. length) the sample length being read by the app
  157028. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  157029. 0) EOF
  157030. n) number of samples of PCM actually returned. The
  157031. below works on a packet-by-packet basis, so the
  157032. return length is not related to the 'length' passed
  157033. in, just guaranteed to fit.
  157034. *section) set to the logical bitstream number */
  157035. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  157036. int *bitstream){
  157037. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157038. while(1){
  157039. if(vf->ready_state==INITSET){
  157040. float **pcm;
  157041. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157042. if(samples){
  157043. if(pcm_channels)*pcm_channels=pcm;
  157044. if(samples>length)samples=length;
  157045. vorbis_synthesis_read(&vf->vd,samples);
  157046. vf->pcm_offset+=samples;
  157047. if(bitstream)*bitstream=vf->current_link;
  157048. return samples;
  157049. }
  157050. }
  157051. /* suck in another packet */
  157052. {
  157053. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157054. if(ret==OV_EOF)return(0);
  157055. if(ret<=0)return(ret);
  157056. }
  157057. }
  157058. }
  157059. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  157060. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  157061. ogg_int64_t off);
  157062. static void _ov_splice(float **pcm,float **lappcm,
  157063. int n1, int n2,
  157064. int ch1, int ch2,
  157065. float *w1, float *w2){
  157066. int i,j;
  157067. float *w=w1;
  157068. int n=n1;
  157069. if(n1>n2){
  157070. n=n2;
  157071. w=w2;
  157072. }
  157073. /* splice */
  157074. for(j=0;j<ch1 && j<ch2;j++){
  157075. float *s=lappcm[j];
  157076. float *d=pcm[j];
  157077. for(i=0;i<n;i++){
  157078. float wd=w[i]*w[i];
  157079. float ws=1.-wd;
  157080. d[i]=d[i]*wd + s[i]*ws;
  157081. }
  157082. }
  157083. /* window from zero */
  157084. for(;j<ch2;j++){
  157085. float *d=pcm[j];
  157086. for(i=0;i<n;i++){
  157087. float wd=w[i]*w[i];
  157088. d[i]=d[i]*wd;
  157089. }
  157090. }
  157091. }
  157092. /* make sure vf is INITSET */
  157093. static int _ov_initset(OggVorbis_File *vf){
  157094. while(1){
  157095. if(vf->ready_state==INITSET)break;
  157096. /* suck in another packet */
  157097. {
  157098. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157099. if(ret<0 && ret!=OV_HOLE)return(ret);
  157100. }
  157101. }
  157102. return 0;
  157103. }
  157104. /* make sure vf is INITSET and that we have a primed buffer; if
  157105. we're crosslapping at a stream section boundary, this also makes
  157106. sure we're sanity checking against the right stream information */
  157107. static int _ov_initprime(OggVorbis_File *vf){
  157108. vorbis_dsp_state *vd=&vf->vd;
  157109. while(1){
  157110. if(vf->ready_state==INITSET)
  157111. if(vorbis_synthesis_pcmout(vd,NULL))break;
  157112. /* suck in another packet */
  157113. {
  157114. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157115. if(ret<0 && ret!=OV_HOLE)return(ret);
  157116. }
  157117. }
  157118. return 0;
  157119. }
  157120. /* grab enough data for lapping from vf; this may be in the form of
  157121. unreturned, already-decoded pcm, remaining PCM we will need to
  157122. decode, or synthetic postextrapolation from last packets. */
  157123. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  157124. float **lappcm,int lapsize){
  157125. int lapcount=0,i;
  157126. float **pcm;
  157127. /* try first to decode the lapping data */
  157128. while(lapcount<lapsize){
  157129. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  157130. if(samples){
  157131. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157132. for(i=0;i<vi->channels;i++)
  157133. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157134. lapcount+=samples;
  157135. vorbis_synthesis_read(vd,samples);
  157136. }else{
  157137. /* suck in another packet */
  157138. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  157139. if(ret==OV_EOF)break;
  157140. }
  157141. }
  157142. if(lapcount<lapsize){
  157143. /* failed to get lapping data from normal decode; pry it from the
  157144. postextrapolation buffering, or the second half of the MDCT
  157145. from the last packet */
  157146. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157147. if(samples==0){
  157148. for(i=0;i<vi->channels;i++)
  157149. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157150. lapcount=lapsize;
  157151. }else{
  157152. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157153. for(i=0;i<vi->channels;i++)
  157154. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157155. lapcount+=samples;
  157156. }
  157157. }
  157158. }
  157159. /* this sets up crosslapping of a sample by using trailing data from
  157160. sample 1 and lapping it into the windowing buffer of sample 2 */
  157161. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157162. vorbis_info *vi1,*vi2;
  157163. float **lappcm;
  157164. float **pcm;
  157165. float *w1,*w2;
  157166. int n1,n2,i,ret,hs1,hs2;
  157167. if(vf1==vf2)return(0); /* degenerate case */
  157168. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157169. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157170. /* the relevant overlap buffers must be pre-checked and pre-primed
  157171. before looking at settings in the event that priming would cross
  157172. a bitstream boundary. So, do it now */
  157173. ret=_ov_initset(vf1);
  157174. if(ret)return(ret);
  157175. ret=_ov_initprime(vf2);
  157176. if(ret)return(ret);
  157177. vi1=ov_info(vf1,-1);
  157178. vi2=ov_info(vf2,-1);
  157179. hs1=ov_halfrate_p(vf1);
  157180. hs2=ov_halfrate_p(vf2);
  157181. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157182. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157183. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157184. w1=vorbis_window(&vf1->vd,0);
  157185. w2=vorbis_window(&vf2->vd,0);
  157186. for(i=0;i<vi1->channels;i++)
  157187. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157188. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157189. /* have a lapping buffer from vf1; now to splice it into the lapping
  157190. buffer of vf2 */
  157191. /* consolidate and expose the buffer. */
  157192. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157193. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157194. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157195. /* splice */
  157196. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157197. /* done */
  157198. return(0);
  157199. }
  157200. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157201. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157202. vorbis_info *vi;
  157203. float **lappcm;
  157204. float **pcm;
  157205. float *w1,*w2;
  157206. int n1,n2,ch1,ch2,hs;
  157207. int i,ret;
  157208. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157209. ret=_ov_initset(vf);
  157210. if(ret)return(ret);
  157211. vi=ov_info(vf,-1);
  157212. hs=ov_halfrate_p(vf);
  157213. ch1=vi->channels;
  157214. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157215. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157216. persistent; even if the decode state
  157217. from this link gets dumped, this
  157218. window array continues to exist */
  157219. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157220. for(i=0;i<ch1;i++)
  157221. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157222. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157223. /* have lapping data; seek and prime the buffer */
  157224. ret=localseek(vf,pos);
  157225. if(ret)return ret;
  157226. ret=_ov_initprime(vf);
  157227. if(ret)return(ret);
  157228. /* Guard against cross-link changes; they're perfectly legal */
  157229. vi=ov_info(vf,-1);
  157230. ch2=vi->channels;
  157231. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157232. w2=vorbis_window(&vf->vd,0);
  157233. /* consolidate and expose the buffer. */
  157234. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157235. /* splice */
  157236. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157237. /* done */
  157238. return(0);
  157239. }
  157240. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157241. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157242. }
  157243. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157244. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157245. }
  157246. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157247. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157248. }
  157249. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157250. int (*localseek)(OggVorbis_File *,double)){
  157251. vorbis_info *vi;
  157252. float **lappcm;
  157253. float **pcm;
  157254. float *w1,*w2;
  157255. int n1,n2,ch1,ch2,hs;
  157256. int i,ret;
  157257. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157258. ret=_ov_initset(vf);
  157259. if(ret)return(ret);
  157260. vi=ov_info(vf,-1);
  157261. hs=ov_halfrate_p(vf);
  157262. ch1=vi->channels;
  157263. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157264. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157265. persistent; even if the decode state
  157266. from this link gets dumped, this
  157267. window array continues to exist */
  157268. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157269. for(i=0;i<ch1;i++)
  157270. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157271. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157272. /* have lapping data; seek and prime the buffer */
  157273. ret=localseek(vf,pos);
  157274. if(ret)return ret;
  157275. ret=_ov_initprime(vf);
  157276. if(ret)return(ret);
  157277. /* Guard against cross-link changes; they're perfectly legal */
  157278. vi=ov_info(vf,-1);
  157279. ch2=vi->channels;
  157280. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157281. w2=vorbis_window(&vf->vd,0);
  157282. /* consolidate and expose the buffer. */
  157283. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157284. /* splice */
  157285. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157286. /* done */
  157287. return(0);
  157288. }
  157289. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157290. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157291. }
  157292. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157293. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157294. }
  157295. #endif
  157296. /*** End of inlined file: vorbisfile.c ***/
  157297. /*** Start of inlined file: window.c ***/
  157298. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157299. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157300. // tasks..
  157301. #if JUCE_MSVC
  157302. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157303. #endif
  157304. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157305. #if JUCE_USE_OGGVORBIS
  157306. #include <stdlib.h>
  157307. #include <math.h>
  157308. static float vwin64[32] = {
  157309. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157310. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157311. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157312. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157313. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157314. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157315. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157316. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157317. };
  157318. static float vwin128[64] = {
  157319. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157320. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157321. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157322. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157323. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157324. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157325. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157326. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157327. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157328. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157329. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157330. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157331. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157332. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157333. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157334. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157335. };
  157336. static float vwin256[128] = {
  157337. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157338. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157339. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157340. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157341. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157342. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157343. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157344. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157345. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157346. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157347. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157348. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157349. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157350. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157351. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157352. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157353. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157354. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157355. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157356. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157357. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157358. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157359. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157360. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157361. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157362. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157363. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157364. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157365. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157366. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157367. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157368. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157369. };
  157370. static float vwin512[256] = {
  157371. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157372. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157373. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157374. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157375. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157376. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157377. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157378. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157379. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157380. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157381. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157382. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157383. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157384. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157385. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157386. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157387. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157388. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157389. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157390. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157391. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157392. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157393. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157394. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157395. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157396. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157397. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157398. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157399. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157400. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157401. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157402. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157403. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157404. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157405. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157406. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157407. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157408. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157409. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157410. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157411. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157412. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157413. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157414. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157415. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157416. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157417. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157418. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157419. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157420. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157421. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157422. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157423. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157424. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157425. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157426. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157427. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157428. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157429. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157430. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157431. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157432. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157433. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157434. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157435. };
  157436. static float vwin1024[512] = {
  157437. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157438. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157439. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157440. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157441. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157442. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157443. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157444. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157445. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157446. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157447. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157448. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157449. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157450. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157451. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157452. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157453. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157454. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157455. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157456. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157457. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157458. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157459. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157460. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157461. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157462. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157463. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157464. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157465. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157466. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157467. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157468. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157469. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157470. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157471. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157472. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157473. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157474. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157475. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157476. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157477. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157478. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157479. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157480. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157481. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157482. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157483. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157484. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157485. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157486. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157487. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157488. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157489. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157490. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157491. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157492. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157493. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157494. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157495. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157496. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157497. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157498. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157499. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157500. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157501. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157502. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157503. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157504. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157505. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157506. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157507. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157508. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157509. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157510. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157511. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157512. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157513. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157514. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157515. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157516. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157517. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157518. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157519. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157520. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157521. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157522. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157523. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157524. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157525. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157526. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157527. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157528. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157529. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157530. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157531. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157532. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157533. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157534. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157535. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157536. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157537. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157538. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157539. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157540. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157541. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157542. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157543. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157544. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157545. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157546. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157547. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157548. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157549. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157550. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157551. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157552. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157553. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157554. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157555. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157556. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157557. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157558. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157559. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157560. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157561. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157562. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157563. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157564. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157565. };
  157566. static float vwin2048[1024] = {
  157567. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157568. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157569. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157570. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157571. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157572. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157573. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157574. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157575. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157576. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157577. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157578. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157579. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157580. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157581. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157582. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157583. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157584. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157585. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157586. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157587. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157588. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157589. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157590. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157591. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157592. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157593. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157594. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157595. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157596. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157597. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157598. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157599. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157600. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157601. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157602. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157603. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157604. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157605. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157606. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157607. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157608. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157609. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157610. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157611. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157612. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157613. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157614. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157615. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157616. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157617. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157618. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157619. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157620. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157621. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157622. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157623. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157624. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157625. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157626. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157627. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157628. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157629. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157630. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157631. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157632. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157633. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157634. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157635. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157636. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157637. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157638. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157639. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157640. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157641. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157642. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157643. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157644. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157645. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157646. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157647. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157648. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157649. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157650. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157651. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157652. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157653. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157654. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157655. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157656. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157657. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157658. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157659. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157660. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157661. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157662. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157663. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157664. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157665. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157666. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157667. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157668. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157669. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157670. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157671. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157672. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157673. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157674. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157675. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157676. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157677. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157678. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157679. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157680. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157681. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157682. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157683. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157684. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157685. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157686. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157687. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157688. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157689. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157690. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157691. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157692. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157693. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157694. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157695. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157696. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157697. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157698. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157699. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157700. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157701. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157702. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157703. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157704. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157705. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157706. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157707. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157708. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157709. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157710. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157711. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157712. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157713. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157714. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157715. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157716. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157717. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157718. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157719. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157720. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157721. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157722. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157723. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157724. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157725. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157726. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157727. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157728. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157729. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157730. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157731. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157732. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157733. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157734. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157735. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157736. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157737. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157738. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157739. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157740. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157741. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157742. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157743. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157744. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157745. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157746. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157747. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157748. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157749. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157750. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157751. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157752. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157753. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157754. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157755. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157756. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157757. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157758. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157759. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157760. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157761. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157762. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157763. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157764. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157765. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157766. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157767. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157768. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157769. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157770. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157771. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157772. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157773. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157774. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157775. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157776. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157777. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157778. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157779. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157780. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157781. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157782. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157783. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157784. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157785. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157786. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157787. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157788. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157789. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157790. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157791. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157792. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157793. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157794. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157795. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157796. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157797. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157798. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157799. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157800. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157801. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157802. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157803. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157804. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157805. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157806. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157807. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157808. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157809. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157810. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157811. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157812. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157813. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157814. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157815. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157816. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157817. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157818. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157819. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157820. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157821. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157822. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157823. };
  157824. static float vwin4096[2048] = {
  157825. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157826. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157827. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157828. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157829. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157830. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157831. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157832. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157833. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157834. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157835. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157836. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157837. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157838. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157839. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157840. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157841. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157842. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157843. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157844. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157845. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157846. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157847. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157848. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157849. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157850. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157851. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157852. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157853. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157854. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157855. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157856. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157857. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157858. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157859. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157860. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157861. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157862. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157863. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157864. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157865. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157866. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157867. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157868. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157869. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157870. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157871. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157872. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157873. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157874. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157875. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157876. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157877. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157878. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157879. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157880. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157881. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157882. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157883. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157884. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157885. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157886. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157887. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157888. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157889. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157890. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157891. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157892. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157893. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157894. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157895. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157896. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157897. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157898. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157899. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157900. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157901. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157902. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157903. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157904. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157905. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157906. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157907. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157908. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157909. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157910. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157911. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157912. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157913. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157914. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157915. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157916. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157917. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157918. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157919. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157920. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157921. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157922. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157923. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157924. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157925. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157926. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157927. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157928. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157929. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157930. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157931. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157932. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157933. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157934. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157935. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157936. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157937. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157938. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157939. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157940. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157941. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157942. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157943. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157944. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157945. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157946. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157947. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157948. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157949. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157950. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157951. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157952. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157953. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157954. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157955. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157956. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157957. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157958. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157959. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157960. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157961. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157962. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157963. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157964. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157965. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157966. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157967. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157968. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157969. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157970. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157971. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157972. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157973. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157974. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157975. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157976. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157977. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157978. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157979. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157980. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157981. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157982. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157983. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157984. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157985. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157986. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157987. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157988. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157989. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157990. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157991. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157992. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157993. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157994. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157995. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157996. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157997. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157998. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157999. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  158000. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  158001. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  158002. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  158003. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  158004. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  158005. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  158006. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  158007. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  158008. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  158009. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  158010. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  158011. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  158012. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  158013. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  158014. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  158015. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  158016. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  158017. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  158018. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  158019. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  158020. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  158021. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  158022. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  158023. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  158024. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  158025. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  158026. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  158027. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  158028. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  158029. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  158030. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  158031. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  158032. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  158033. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  158034. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  158035. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  158036. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  158037. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  158038. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  158039. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  158040. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  158041. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  158042. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  158043. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  158044. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  158045. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  158046. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  158047. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  158048. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  158049. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  158050. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  158051. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  158052. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  158053. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  158054. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  158055. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  158056. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  158057. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  158058. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  158059. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  158060. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  158061. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  158062. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  158063. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  158064. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  158065. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  158066. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  158067. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  158068. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  158069. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  158070. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  158071. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  158072. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  158073. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  158074. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  158075. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  158076. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  158077. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  158078. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  158079. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  158080. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  158081. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  158082. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  158083. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  158084. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  158085. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  158086. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  158087. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  158088. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  158089. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  158090. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  158091. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  158092. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  158093. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  158094. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  158095. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  158096. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  158097. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  158098. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  158099. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  158100. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  158101. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  158102. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  158103. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  158104. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  158105. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  158106. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  158107. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  158108. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  158109. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  158110. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  158111. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  158112. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  158113. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  158114. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  158115. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  158116. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  158117. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  158118. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  158119. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  158120. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  158121. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  158122. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  158123. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  158124. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  158125. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  158126. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  158127. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  158128. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  158129. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  158130. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  158131. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  158132. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  158133. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  158134. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  158135. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  158136. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  158137. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  158138. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  158139. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158140. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158141. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158142. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158143. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158144. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158145. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158146. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158147. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158148. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158149. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158150. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158151. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158152. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158153. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158154. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158155. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158156. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158157. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158158. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158159. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158160. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158161. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158162. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158163. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158164. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158165. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158166. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158167. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158168. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158169. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158170. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158171. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158172. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158173. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158174. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158175. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158176. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158177. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158178. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158179. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158180. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158181. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158182. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158183. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158184. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158185. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158186. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158187. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158188. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158189. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158190. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158191. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158192. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158193. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158194. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158195. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158196. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158197. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158198. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158199. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158200. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158201. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158202. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158203. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158204. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158205. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158206. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158207. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158208. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158209. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158210. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158211. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158212. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158213. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158214. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158215. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158216. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158217. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158218. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158219. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158220. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158221. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158222. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158223. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158224. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158225. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158226. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158227. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158228. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158229. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158230. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158231. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158232. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158233. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158234. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158235. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158236. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158237. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158238. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158239. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158240. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158241. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158242. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158243. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158244. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158245. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158246. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158247. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158248. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158249. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158250. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158251. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158252. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158253. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158254. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158255. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158256. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158257. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158258. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158259. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158260. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158261. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158262. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158263. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158264. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158265. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158266. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158267. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158268. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158269. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158270. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158271. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158272. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158273. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158274. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158275. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158276. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158277. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158278. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158279. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158280. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158281. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158282. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158283. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158284. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158285. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158286. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158287. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158288. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158289. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158290. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158291. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158292. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158293. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158294. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158295. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158296. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158297. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158298. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158299. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158300. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158301. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158302. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158303. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158304. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158305. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158306. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158307. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158308. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158309. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158310. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158311. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158312. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158313. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158314. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158315. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158316. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158317. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158318. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158319. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158320. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158321. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158322. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158323. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158324. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158325. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158326. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158327. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158328. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158329. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158330. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158331. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158332. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158333. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158334. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158335. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158336. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158337. };
  158338. static float vwin8192[4096] = {
  158339. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158340. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158341. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158342. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158343. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158344. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158345. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158346. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158347. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158348. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158349. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158350. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158351. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158352. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158353. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158354. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158355. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158356. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158357. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158358. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158359. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158360. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158361. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158362. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158363. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158364. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158365. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158366. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158367. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158368. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158369. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158370. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158371. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158372. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158373. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158374. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158375. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158376. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158377. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158378. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158379. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158380. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158381. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158382. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158383. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158384. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158385. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158386. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158387. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158388. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158389. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158390. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158391. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158392. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158393. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158394. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158395. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158396. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158397. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158398. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158399. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158400. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158401. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158402. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158403. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158404. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158405. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158406. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158407. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158408. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158409. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158410. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158411. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158412. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158413. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158414. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158415. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158416. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158417. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158418. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158419. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158420. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158421. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158422. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158423. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158424. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158425. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158426. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158427. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158428. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158429. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158430. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158431. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158432. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158433. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158434. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158435. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158436. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158437. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158438. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158439. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158440. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158441. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158442. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158443. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158444. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158445. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158446. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158447. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158448. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158449. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158450. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158451. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158452. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158453. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158454. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158455. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158456. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158457. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158458. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158459. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158460. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158461. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158462. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158463. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158464. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158465. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158466. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158467. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158468. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158469. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158470. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158471. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158472. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158473. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158474. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158475. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158476. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158477. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158478. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158479. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158480. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158481. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158482. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158483. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158484. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158485. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158486. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158487. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158488. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158489. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158490. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158491. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158492. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158493. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158494. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158495. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158496. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158497. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158498. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158499. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158500. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158501. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158502. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158503. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158504. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158505. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158506. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158507. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158508. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158509. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158510. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158511. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158512. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158513. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158514. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158515. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158516. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158517. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158518. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158519. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158520. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158521. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158522. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158523. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158524. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158525. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158526. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158527. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158528. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158529. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158530. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158531. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158532. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158533. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158534. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158535. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158536. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158537. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158538. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158539. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158540. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158541. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158542. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158543. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158544. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158545. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158546. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158547. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158548. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158549. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158550. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158551. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158552. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158553. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158554. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158555. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158556. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158557. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158558. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158559. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158560. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158561. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158562. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158563. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158564. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158565. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158566. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158567. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158568. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158569. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158570. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158571. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158572. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158573. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158574. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158575. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158576. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158577. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158578. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158579. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158580. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158581. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158582. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158583. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158584. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158585. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158586. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158587. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158588. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158589. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158590. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158591. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158592. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158593. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158594. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158595. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158596. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158597. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158598. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158599. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158600. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158601. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158602. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158603. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158604. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158605. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158606. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158607. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158608. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158609. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158610. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158611. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158612. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158613. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158614. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158615. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158616. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158617. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158618. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158619. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158620. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158621. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158622. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158623. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158624. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158625. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158626. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158627. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158628. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158629. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158630. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158631. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158632. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158633. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158634. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158635. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158636. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158637. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158638. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158639. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158640. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158641. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158642. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158643. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158644. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158645. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158646. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158647. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158648. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158649. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158650. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158651. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158652. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158653. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158654. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158655. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158656. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158657. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158658. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158659. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158660. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158661. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158662. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158663. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158664. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158665. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158666. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158667. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158668. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158669. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158670. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158671. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158672. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158673. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158674. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158675. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158676. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158677. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158678. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158679. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158680. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158681. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158682. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158683. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158684. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158685. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158686. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158687. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158688. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158689. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158690. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158691. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158692. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158693. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158694. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158695. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158696. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158697. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158698. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158699. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158700. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158701. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158702. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158703. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158704. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158705. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158706. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158707. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158708. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158709. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158710. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158711. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158712. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158713. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158714. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158715. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158716. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158717. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158718. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158719. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158720. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158721. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158722. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158723. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158724. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158725. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158726. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158727. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158728. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158729. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158730. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158731. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158732. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158733. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158734. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158735. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158736. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158737. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158738. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158739. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158740. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158741. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158742. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158743. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158744. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158745. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158746. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158747. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158748. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158749. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158750. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158751. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158752. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158753. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158754. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158755. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158756. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158757. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158758. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158759. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158760. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158761. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158762. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158763. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158764. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158765. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158766. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158767. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158768. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158769. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158770. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158771. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158772. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158773. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158774. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158775. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158776. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158777. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158778. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158779. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158780. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158781. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158782. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158783. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158784. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158785. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158786. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158787. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158788. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158789. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158790. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158791. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158792. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158793. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158794. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158795. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158796. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158797. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158798. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158799. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158800. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158801. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158802. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158803. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158804. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158805. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158806. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158807. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158808. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158809. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158810. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158811. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158812. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158813. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158814. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158815. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158816. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158817. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158818. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158819. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158820. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158821. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158822. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158823. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158824. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158825. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158826. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158827. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158828. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158829. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158830. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158831. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158832. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158833. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158834. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158835. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158836. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158837. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158838. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158839. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158840. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158841. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158842. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158843. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158844. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158845. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158846. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158847. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158848. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158849. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158850. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158851. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158852. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158853. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158854. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158855. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158856. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158857. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158858. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158859. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158860. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158861. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158862. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158863. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158864. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158865. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158866. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158867. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158868. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158869. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158870. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158871. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158872. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158873. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158874. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158875. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158876. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158877. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158878. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158879. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158880. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158881. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158882. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158883. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158884. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158885. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158886. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158887. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158888. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158889. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158890. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158891. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158892. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158893. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158894. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158895. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158896. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158897. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158898. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158899. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158900. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158901. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158902. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158903. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158904. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158905. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158906. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158907. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158908. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158909. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158910. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158911. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158912. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158913. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158914. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158915. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158916. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158917. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158918. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158919. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158920. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158921. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158922. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158923. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158924. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158925. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158926. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158927. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158928. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158929. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158930. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158931. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158932. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158933. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158934. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158935. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158936. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158937. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158938. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158939. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158940. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158941. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158942. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158943. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158944. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158945. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158946. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158947. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158948. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158949. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158950. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158951. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158952. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158953. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158954. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158955. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158956. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158957. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158958. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158959. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158960. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158961. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158962. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158963. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158964. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158965. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158966. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158967. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158968. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158969. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158970. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158971. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158972. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158973. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158974. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158975. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158976. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158977. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158978. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158979. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158980. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158981. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158982. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158983. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158984. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158985. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158986. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158987. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158988. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158989. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158990. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158991. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158992. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158993. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158994. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158995. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158996. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158997. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158998. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158999. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  159000. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  159001. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  159002. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  159003. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  159004. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  159005. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  159006. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  159007. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  159008. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  159009. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  159010. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  159011. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  159012. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  159013. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  159014. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  159015. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  159016. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  159017. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  159018. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  159019. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  159020. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  159021. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  159022. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  159023. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  159024. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  159025. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  159026. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  159027. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  159028. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  159029. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  159030. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  159031. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  159032. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  159033. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  159034. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  159035. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  159036. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  159037. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  159038. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  159039. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  159040. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  159041. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  159042. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  159043. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  159044. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  159045. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  159046. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  159047. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  159048. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  159049. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  159050. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  159051. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  159052. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  159053. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  159054. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  159055. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  159056. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  159057. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  159058. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  159059. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  159060. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  159061. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  159062. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  159063. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  159064. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  159065. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  159066. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  159067. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  159068. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  159069. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  159070. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  159071. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  159072. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  159073. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  159074. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  159075. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  159076. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  159077. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  159078. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  159079. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  159080. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  159081. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  159082. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  159083. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  159084. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  159085. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  159086. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  159087. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  159088. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  159089. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  159090. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  159091. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  159092. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  159093. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  159094. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  159095. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  159096. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  159097. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  159098. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  159099. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  159100. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  159101. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  159102. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  159103. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  159104. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  159105. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  159106. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  159107. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  159108. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  159109. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  159110. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  159111. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  159112. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  159113. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  159114. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  159115. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  159116. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  159117. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  159118. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  159119. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  159120. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  159121. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  159122. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  159123. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  159124. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  159125. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  159126. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  159127. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  159128. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  159129. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  159130. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  159131. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  159132. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  159133. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  159134. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  159135. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  159136. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  159137. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  159138. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  159139. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159140. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159141. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159142. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159143. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159144. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159145. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159146. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159147. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159148. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159149. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159150. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159151. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159152. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159153. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159154. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159155. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159156. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159157. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159158. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159159. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159160. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159161. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159162. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159163. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159164. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159165. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159166. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159167. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159168. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159169. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159170. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159171. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159172. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159173. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159174. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159175. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159176. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159177. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159178. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159179. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159180. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159181. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159182. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159183. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159184. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159185. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159186. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159187. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159188. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159189. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159190. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159191. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159192. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159193. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159194. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159195. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159196. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159197. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159198. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159199. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159200. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159201. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159202. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159203. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159204. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159205. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159206. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159207. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159208. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159209. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159210. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159211. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159212. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159213. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159214. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159215. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159216. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159217. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159218. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159219. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159220. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159221. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159222. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159223. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159224. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159225. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159226. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159227. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159228. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159229. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159230. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159231. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159232. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159233. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159234. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159235. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159236. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159237. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159238. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159239. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159240. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159241. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159242. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159243. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159244. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159245. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159246. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159247. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159248. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159249. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159250. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159251. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159252. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159253. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159254. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159255. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159256. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159257. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159258. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159259. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159260. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159261. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159262. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159263. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159264. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159265. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159266. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159267. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159268. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159269. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159270. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159271. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159272. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159273. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159274. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159275. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159276. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159277. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159278. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159279. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159280. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159281. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159282. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159283. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159284. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159285. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159286. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159287. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159288. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159289. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159290. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159291. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159292. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159293. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159294. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159295. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159296. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159297. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159298. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159299. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159300. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159301. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159302. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159303. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159304. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159305. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159306. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159307. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159308. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159309. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159310. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159311. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159312. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159313. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159314. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159315. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159316. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159317. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159318. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159319. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159320. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159321. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159322. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159323. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159324. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159325. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159326. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159327. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159328. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159329. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159330. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159331. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159332. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159333. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159334. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159335. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159336. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159337. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159338. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159339. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159340. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159341. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159342. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159343. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159344. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159345. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159346. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159347. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159348. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159349. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159350. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159351. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159352. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159353. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159354. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159355. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159356. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159357. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159358. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159359. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159360. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159361. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159362. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159363. };
  159364. static float *vwin[8] = {
  159365. vwin64,
  159366. vwin128,
  159367. vwin256,
  159368. vwin512,
  159369. vwin1024,
  159370. vwin2048,
  159371. vwin4096,
  159372. vwin8192,
  159373. };
  159374. float *_vorbis_window_get(int n){
  159375. return vwin[n];
  159376. }
  159377. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159378. int lW,int W,int nW){
  159379. lW=(W?lW:0);
  159380. nW=(W?nW:0);
  159381. {
  159382. float *windowLW=vwin[winno[lW]];
  159383. float *windowNW=vwin[winno[nW]];
  159384. long n=blocksizes[W];
  159385. long ln=blocksizes[lW];
  159386. long rn=blocksizes[nW];
  159387. long leftbegin=n/4-ln/4;
  159388. long leftend=leftbegin+ln/2;
  159389. long rightbegin=n/2+n/4-rn/4;
  159390. long rightend=rightbegin+rn/2;
  159391. int i,p;
  159392. for(i=0;i<leftbegin;i++)
  159393. d[i]=0.f;
  159394. for(p=0;i<leftend;i++,p++)
  159395. d[i]*=windowLW[p];
  159396. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159397. d[i]*=windowNW[p];
  159398. for(;i<n;i++)
  159399. d[i]=0.f;
  159400. }
  159401. }
  159402. #endif
  159403. /*** End of inlined file: window.c ***/
  159404. #else
  159405. #include <vorbis/vorbisenc.h>
  159406. #include <vorbis/codec.h>
  159407. #include <vorbis/vorbisfile.h>
  159408. #endif
  159409. }
  159410. #undef max
  159411. #undef min
  159412. BEGIN_JUCE_NAMESPACE
  159413. static const char* const oggFormatName = "Ogg-Vorbis file";
  159414. static const char* const oggExtensions[] = { ".ogg", 0 };
  159415. class OggReader : public AudioFormatReader
  159416. {
  159417. OggVorbisNamespace::OggVorbis_File ovFile;
  159418. OggVorbisNamespace::ov_callbacks callbacks;
  159419. AudioSampleBuffer reservoir;
  159420. int reservoirStart, samplesInReservoir;
  159421. public:
  159422. OggReader (InputStream* const inp)
  159423. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159424. reservoir (2, 4096),
  159425. reservoirStart (0),
  159426. samplesInReservoir (0)
  159427. {
  159428. using namespace OggVorbisNamespace;
  159429. sampleRate = 0;
  159430. usesFloatingPointData = true;
  159431. callbacks.read_func = &oggReadCallback;
  159432. callbacks.seek_func = &oggSeekCallback;
  159433. callbacks.close_func = &oggCloseCallback;
  159434. callbacks.tell_func = &oggTellCallback;
  159435. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159436. if (err == 0)
  159437. {
  159438. vorbis_info* info = ov_info (&ovFile, -1);
  159439. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159440. numChannels = info->channels;
  159441. bitsPerSample = 16;
  159442. sampleRate = info->rate;
  159443. reservoir.setSize (numChannels,
  159444. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159445. }
  159446. }
  159447. ~OggReader()
  159448. {
  159449. OggVorbisNamespace::ov_clear (&ovFile);
  159450. }
  159451. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159452. int64 startSampleInFile, int numSamples)
  159453. {
  159454. while (numSamples > 0)
  159455. {
  159456. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159457. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159458. {
  159459. // got a few samples overlapping, so use them before seeking..
  159460. const int numToUse = jmin (numSamples, numAvailable);
  159461. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159462. if (destSamples[i] != 0)
  159463. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159464. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159465. sizeof (float) * numToUse);
  159466. startSampleInFile += numToUse;
  159467. numSamples -= numToUse;
  159468. startOffsetInDestBuffer += numToUse;
  159469. if (numSamples == 0)
  159470. break;
  159471. }
  159472. if (startSampleInFile < reservoirStart
  159473. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159474. {
  159475. // buffer miss, so refill the reservoir
  159476. int bitStream = 0;
  159477. reservoirStart = jmax (0, (int) startSampleInFile);
  159478. samplesInReservoir = reservoir.getNumSamples();
  159479. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159480. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159481. int offset = 0;
  159482. int numToRead = samplesInReservoir;
  159483. while (numToRead > 0)
  159484. {
  159485. float** dataIn = 0;
  159486. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159487. if (samps <= 0)
  159488. break;
  159489. jassert (samps <= numToRead);
  159490. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159491. {
  159492. memcpy (reservoir.getSampleData (i, offset),
  159493. dataIn[i],
  159494. sizeof (float) * samps);
  159495. }
  159496. numToRead -= samps;
  159497. offset += samps;
  159498. }
  159499. if (numToRead > 0)
  159500. reservoir.clear (offset, numToRead);
  159501. }
  159502. }
  159503. if (numSamples > 0)
  159504. {
  159505. for (int i = numDestChannels; --i >= 0;)
  159506. if (destSamples[i] != 0)
  159507. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159508. sizeof (int) * numSamples);
  159509. }
  159510. return true;
  159511. }
  159512. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159513. {
  159514. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159515. }
  159516. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159517. {
  159518. InputStream* const in = static_cast <InputStream*> (datasource);
  159519. if (whence == SEEK_CUR)
  159520. offset += in->getPosition();
  159521. else if (whence == SEEK_END)
  159522. offset += in->getTotalLength();
  159523. in->setPosition (offset);
  159524. return 0;
  159525. }
  159526. static int oggCloseCallback (void*)
  159527. {
  159528. return 0;
  159529. }
  159530. static long oggTellCallback (void* datasource)
  159531. {
  159532. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159533. }
  159534. private:
  159535. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159536. };
  159537. class OggWriter : public AudioFormatWriter
  159538. {
  159539. OggVorbisNamespace::ogg_stream_state os;
  159540. OggVorbisNamespace::ogg_page og;
  159541. OggVorbisNamespace::ogg_packet op;
  159542. OggVorbisNamespace::vorbis_info vi;
  159543. OggVorbisNamespace::vorbis_comment vc;
  159544. OggVorbisNamespace::vorbis_dsp_state vd;
  159545. OggVorbisNamespace::vorbis_block vb;
  159546. public:
  159547. bool ok;
  159548. OggWriter (OutputStream* const out,
  159549. const double sampleRate,
  159550. const int numChannels,
  159551. const int bitsPerSample,
  159552. const int qualityIndex)
  159553. : AudioFormatWriter (out, TRANS (oggFormatName),
  159554. sampleRate,
  159555. numChannels,
  159556. bitsPerSample)
  159557. {
  159558. using namespace OggVorbisNamespace;
  159559. ok = false;
  159560. vorbis_info_init (&vi);
  159561. if (vorbis_encode_init_vbr (&vi,
  159562. numChannels,
  159563. (int) sampleRate,
  159564. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159565. {
  159566. vorbis_comment_init (&vc);
  159567. if (JUCEApplication::getInstance() != 0)
  159568. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8().getAddress()));
  159569. vorbis_analysis_init (&vd, &vi);
  159570. vorbis_block_init (&vd, &vb);
  159571. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159572. ogg_packet header;
  159573. ogg_packet header_comm;
  159574. ogg_packet header_code;
  159575. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159576. ogg_stream_packetin (&os, &header);
  159577. ogg_stream_packetin (&os, &header_comm);
  159578. ogg_stream_packetin (&os, &header_code);
  159579. for (;;)
  159580. {
  159581. if (ogg_stream_flush (&os, &og) == 0)
  159582. break;
  159583. output->write (og.header, og.header_len);
  159584. output->write (og.body, og.body_len);
  159585. }
  159586. ok = true;
  159587. }
  159588. }
  159589. ~OggWriter()
  159590. {
  159591. using namespace OggVorbisNamespace;
  159592. if (ok)
  159593. {
  159594. // write a zero-length packet to show ogg that we're finished..
  159595. write (0, 0);
  159596. ogg_stream_clear (&os);
  159597. vorbis_block_clear (&vb);
  159598. vorbis_dsp_clear (&vd);
  159599. vorbis_comment_clear (&vc);
  159600. vorbis_info_clear (&vi);
  159601. output->flush();
  159602. }
  159603. else
  159604. {
  159605. vorbis_info_clear (&vi);
  159606. output = 0; // to stop the base class deleting this, as it needs to be returned
  159607. // to the caller of createWriter()
  159608. }
  159609. }
  159610. bool write (const int** samplesToWrite, int numSamples)
  159611. {
  159612. using namespace OggVorbisNamespace;
  159613. if (! ok)
  159614. return false;
  159615. if (numSamples > 0)
  159616. {
  159617. const double gain = 1.0 / 0x80000000u;
  159618. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159619. for (int i = numChannels; --i >= 0;)
  159620. {
  159621. float* const dst = vorbisBuffer[i];
  159622. const int* const src = samplesToWrite [i];
  159623. if (src != 0 && dst != 0)
  159624. {
  159625. for (int j = 0; j < numSamples; ++j)
  159626. dst[j] = (float) (src[j] * gain);
  159627. }
  159628. }
  159629. }
  159630. vorbis_analysis_wrote (&vd, numSamples);
  159631. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159632. {
  159633. vorbis_analysis (&vb, 0);
  159634. vorbis_bitrate_addblock (&vb);
  159635. while (vorbis_bitrate_flushpacket (&vd, &op))
  159636. {
  159637. ogg_stream_packetin (&os, &op);
  159638. for (;;)
  159639. {
  159640. if (ogg_stream_pageout (&os, &og) == 0)
  159641. break;
  159642. output->write (og.header, og.header_len);
  159643. output->write (og.body, og.body_len);
  159644. if (ogg_page_eos (&og))
  159645. break;
  159646. }
  159647. }
  159648. }
  159649. return true;
  159650. }
  159651. private:
  159652. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159653. };
  159654. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159655. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159656. {
  159657. }
  159658. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159659. {
  159660. }
  159661. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159662. {
  159663. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159664. return Array <int> (rates);
  159665. }
  159666. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159667. {
  159668. const int depths[] = { 32, 0 };
  159669. return Array <int> (depths);
  159670. }
  159671. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159672. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159673. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159674. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159675. const bool deleteStreamIfOpeningFails)
  159676. {
  159677. ScopedPointer <OggReader> r (new OggReader (in));
  159678. if (r->sampleRate > 0)
  159679. return r.release();
  159680. if (! deleteStreamIfOpeningFails)
  159681. r->input = 0;
  159682. return 0;
  159683. }
  159684. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159685. double sampleRate,
  159686. unsigned int numChannels,
  159687. int bitsPerSample,
  159688. const StringPairArray& /*metadataValues*/,
  159689. int qualityOptionIndex)
  159690. {
  159691. ScopedPointer <OggWriter> w (new OggWriter (out,
  159692. sampleRate,
  159693. numChannels,
  159694. bitsPerSample,
  159695. qualityOptionIndex));
  159696. return w->ok ? w.release() : 0;
  159697. }
  159698. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159699. {
  159700. StringArray s;
  159701. s.add ("Low Quality");
  159702. s.add ("Medium Quality");
  159703. s.add ("High Quality");
  159704. return s;
  159705. }
  159706. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159707. {
  159708. FileInputStream* const in = source.createInputStream();
  159709. if (in != 0)
  159710. {
  159711. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159712. if (r != 0)
  159713. {
  159714. const int64 numSamps = r->lengthInSamples;
  159715. r = 0;
  159716. const int64 fileNumSamps = source.getSize() / 4;
  159717. const double ratio = numSamps / (double) fileNumSamps;
  159718. if (ratio > 12.0)
  159719. return 0;
  159720. else if (ratio > 6.0)
  159721. return 1;
  159722. else
  159723. return 2;
  159724. }
  159725. }
  159726. return 1;
  159727. }
  159728. END_JUCE_NAMESPACE
  159729. #endif
  159730. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159731. #endif
  159732. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159733. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159734. #if JUCE_MSVC
  159735. #pragma warning (push)
  159736. #endif
  159737. namespace jpeglibNamespace
  159738. {
  159739. #if JUCE_INCLUDE_JPEGLIB_CODE
  159740. #if JUCE_MINGW
  159741. typedef unsigned char boolean;
  159742. #endif
  159743. #define JPEG_INTERNALS
  159744. #undef FAR
  159745. /*** Start of inlined file: jpeglib.h ***/
  159746. #ifndef JPEGLIB_H
  159747. #define JPEGLIB_H
  159748. /*
  159749. * First we include the configuration files that record how this
  159750. * installation of the JPEG library is set up. jconfig.h can be
  159751. * generated automatically for many systems. jmorecfg.h contains
  159752. * manual configuration options that most people need not worry about.
  159753. */
  159754. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159755. /*** Start of inlined file: jconfig.h ***/
  159756. /* see jconfig.doc for explanations */
  159757. // disable all the warnings under MSVC
  159758. #ifdef _MSC_VER
  159759. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159760. #endif
  159761. #ifdef __BORLANDC__
  159762. #pragma warn -8057
  159763. #pragma warn -8019
  159764. #pragma warn -8004
  159765. #pragma warn -8008
  159766. #endif
  159767. #define HAVE_PROTOTYPES
  159768. #define HAVE_UNSIGNED_CHAR
  159769. #define HAVE_UNSIGNED_SHORT
  159770. /* #define void char */
  159771. /* #define const */
  159772. #undef CHAR_IS_UNSIGNED
  159773. #define HAVE_STDDEF_H
  159774. #define HAVE_STDLIB_H
  159775. #undef NEED_BSD_STRINGS
  159776. #undef NEED_SYS_TYPES_H
  159777. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159778. #undef NEED_SHORT_EXTERNAL_NAMES
  159779. #undef INCOMPLETE_TYPES_BROKEN
  159780. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159781. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159782. typedef unsigned char boolean;
  159783. #endif
  159784. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159785. #ifdef JPEG_INTERNALS
  159786. #undef RIGHT_SHIFT_IS_UNSIGNED
  159787. #endif /* JPEG_INTERNALS */
  159788. #ifdef JPEG_CJPEG_DJPEG
  159789. #define BMP_SUPPORTED /* BMP image file format */
  159790. #define GIF_SUPPORTED /* GIF image file format */
  159791. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159792. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159793. #define TARGA_SUPPORTED /* Targa image file format */
  159794. #define TWO_FILE_COMMANDLINE /* optional */
  159795. #define USE_SETMODE /* Microsoft has setmode() */
  159796. #undef NEED_SIGNAL_CATCHER
  159797. #undef DONT_USE_B_MODE
  159798. #undef PROGRESS_REPORT /* optional */
  159799. #endif /* JPEG_CJPEG_DJPEG */
  159800. /*** End of inlined file: jconfig.h ***/
  159801. /* widely used configuration options */
  159802. #endif
  159803. /*** Start of inlined file: jmorecfg.h ***/
  159804. /*
  159805. * Define BITS_IN_JSAMPLE as either
  159806. * 8 for 8-bit sample values (the usual setting)
  159807. * 12 for 12-bit sample values
  159808. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159809. * JPEG standard, and the IJG code does not support anything else!
  159810. * We do not support run-time selection of data precision, sorry.
  159811. */
  159812. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159813. /*
  159814. * Maximum number of components (color channels) allowed in JPEG image.
  159815. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159816. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159817. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159818. * really short on memory. (Each allowed component costs a hundred or so
  159819. * bytes of storage, whether actually used in an image or not.)
  159820. */
  159821. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159822. /*
  159823. * Basic data types.
  159824. * You may need to change these if you have a machine with unusual data
  159825. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159826. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159827. * but it had better be at least 16.
  159828. */
  159829. /* Representation of a single sample (pixel element value).
  159830. * We frequently allocate large arrays of these, so it's important to keep
  159831. * them small. But if you have memory to burn and access to char or short
  159832. * arrays is very slow on your hardware, you might want to change these.
  159833. */
  159834. #if BITS_IN_JSAMPLE == 8
  159835. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159836. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159837. */
  159838. #ifdef HAVE_UNSIGNED_CHAR
  159839. typedef unsigned char JSAMPLE;
  159840. #define GETJSAMPLE(value) ((int) (value))
  159841. #else /* not HAVE_UNSIGNED_CHAR */
  159842. typedef char JSAMPLE;
  159843. #ifdef CHAR_IS_UNSIGNED
  159844. #define GETJSAMPLE(value) ((int) (value))
  159845. #else
  159846. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159847. #endif /* CHAR_IS_UNSIGNED */
  159848. #endif /* HAVE_UNSIGNED_CHAR */
  159849. #define MAXJSAMPLE 255
  159850. #define CENTERJSAMPLE 128
  159851. #endif /* BITS_IN_JSAMPLE == 8 */
  159852. #if BITS_IN_JSAMPLE == 12
  159853. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159854. * On nearly all machines "short" will do nicely.
  159855. */
  159856. typedef short JSAMPLE;
  159857. #define GETJSAMPLE(value) ((int) (value))
  159858. #define MAXJSAMPLE 4095
  159859. #define CENTERJSAMPLE 2048
  159860. #endif /* BITS_IN_JSAMPLE == 12 */
  159861. /* Representation of a DCT frequency coefficient.
  159862. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159863. * Again, we allocate large arrays of these, but you can change to int
  159864. * if you have memory to burn and "short" is really slow.
  159865. */
  159866. typedef short JCOEF;
  159867. /* Compressed datastreams are represented as arrays of JOCTET.
  159868. * These must be EXACTLY 8 bits wide, at least once they are written to
  159869. * external storage. Note that when using the stdio data source/destination
  159870. * managers, this is also the data type passed to fread/fwrite.
  159871. */
  159872. #ifdef HAVE_UNSIGNED_CHAR
  159873. typedef unsigned char JOCTET;
  159874. #define GETJOCTET(value) (value)
  159875. #else /* not HAVE_UNSIGNED_CHAR */
  159876. typedef char JOCTET;
  159877. #ifdef CHAR_IS_UNSIGNED
  159878. #define GETJOCTET(value) (value)
  159879. #else
  159880. #define GETJOCTET(value) ((value) & 0xFF)
  159881. #endif /* CHAR_IS_UNSIGNED */
  159882. #endif /* HAVE_UNSIGNED_CHAR */
  159883. /* These typedefs are used for various table entries and so forth.
  159884. * They must be at least as wide as specified; but making them too big
  159885. * won't cost a huge amount of memory, so we don't provide special
  159886. * extraction code like we did for JSAMPLE. (In other words, these
  159887. * typedefs live at a different point on the speed/space tradeoff curve.)
  159888. */
  159889. /* UINT8 must hold at least the values 0..255. */
  159890. #ifdef HAVE_UNSIGNED_CHAR
  159891. typedef unsigned char UINT8;
  159892. #else /* not HAVE_UNSIGNED_CHAR */
  159893. #ifdef CHAR_IS_UNSIGNED
  159894. typedef char UINT8;
  159895. #else /* not CHAR_IS_UNSIGNED */
  159896. typedef short UINT8;
  159897. #endif /* CHAR_IS_UNSIGNED */
  159898. #endif /* HAVE_UNSIGNED_CHAR */
  159899. /* UINT16 must hold at least the values 0..65535. */
  159900. #ifdef HAVE_UNSIGNED_SHORT
  159901. typedef unsigned short UINT16;
  159902. #else /* not HAVE_UNSIGNED_SHORT */
  159903. typedef unsigned int UINT16;
  159904. #endif /* HAVE_UNSIGNED_SHORT */
  159905. /* INT16 must hold at least the values -32768..32767. */
  159906. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159907. typedef short INT16;
  159908. #endif
  159909. /* INT32 must hold at least signed 32-bit values. */
  159910. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159911. typedef long INT32;
  159912. #endif
  159913. /* Datatype used for image dimensions. The JPEG standard only supports
  159914. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159915. * "unsigned int" is sufficient on all machines. However, if you need to
  159916. * handle larger images and you don't mind deviating from the spec, you
  159917. * can change this datatype.
  159918. */
  159919. typedef unsigned int JDIMENSION;
  159920. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159921. /* These macros are used in all function definitions and extern declarations.
  159922. * You could modify them if you need to change function linkage conventions;
  159923. * in particular, you'll need to do that to make the library a Windows DLL.
  159924. * Another application is to make all functions global for use with debuggers
  159925. * or code profilers that require it.
  159926. */
  159927. /* a function called through method pointers: */
  159928. #define METHODDEF(type) static type
  159929. /* a function used only in its module: */
  159930. #define LOCAL(type) static type
  159931. /* a function referenced thru EXTERNs: */
  159932. #define GLOBAL(type) type
  159933. /* a reference to a GLOBAL function: */
  159934. #define EXTERN(type) extern type
  159935. /* This macro is used to declare a "method", that is, a function pointer.
  159936. * We want to supply prototype parameters if the compiler can cope.
  159937. * Note that the arglist parameter must be parenthesized!
  159938. * Again, you can customize this if you need special linkage keywords.
  159939. */
  159940. #ifdef HAVE_PROTOTYPES
  159941. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159942. #else
  159943. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159944. #endif
  159945. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159946. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159947. * by just saying "FAR *" where such a pointer is needed. In a few places
  159948. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159949. */
  159950. #ifdef NEED_FAR_POINTERS
  159951. #define FAR far
  159952. #else
  159953. #define FAR
  159954. #endif
  159955. /*
  159956. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159957. * in standard header files. Or you may have conflicts with application-
  159958. * specific header files that you want to include together with these files.
  159959. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159960. */
  159961. #ifndef HAVE_BOOLEAN
  159962. typedef int boolean;
  159963. #endif
  159964. #ifndef FALSE /* in case these macros already exist */
  159965. #define FALSE 0 /* values of boolean */
  159966. #endif
  159967. #ifndef TRUE
  159968. #define TRUE 1
  159969. #endif
  159970. /*
  159971. * The remaining options affect code selection within the JPEG library,
  159972. * but they don't need to be visible to most applications using the library.
  159973. * To minimize application namespace pollution, the symbols won't be
  159974. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159975. */
  159976. #ifdef JPEG_INTERNALS
  159977. #define JPEG_INTERNAL_OPTIONS
  159978. #endif
  159979. #ifdef JPEG_INTERNAL_OPTIONS
  159980. /*
  159981. * These defines indicate whether to include various optional functions.
  159982. * Undefining some of these symbols will produce a smaller but less capable
  159983. * library. Note that you can leave certain source files out of the
  159984. * compilation/linking process if you've #undef'd the corresponding symbols.
  159985. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159986. */
  159987. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159988. /* Capability options common to encoder and decoder: */
  159989. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159990. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159991. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159992. /* Encoder capability options: */
  159993. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159994. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159995. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159996. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159997. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159998. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159999. * precision, so jchuff.c normally uses entropy optimization to compute
  160000. * usable tables for higher precision. If you don't want to do optimization,
  160001. * you'll have to supply different default Huffman tables.
  160002. * The exact same statements apply for progressive JPEG: the default tables
  160003. * don't work for progressive mode. (This may get fixed, however.)
  160004. */
  160005. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  160006. /* Decoder capability options: */
  160007. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160008. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160009. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160010. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  160011. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  160012. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  160013. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  160014. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  160015. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  160016. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  160017. /* more capability options later, no doubt */
  160018. /*
  160019. * Ordering of RGB data in scanlines passed to or from the application.
  160020. * If your application wants to deal with data in the order B,G,R, just
  160021. * change these macros. You can also deal with formats such as R,G,B,X
  160022. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  160023. * the offsets will also change the order in which colormap data is organized.
  160024. * RESTRICTIONS:
  160025. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  160026. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  160027. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  160028. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  160029. * is not 3 (they don't understand about dummy color components!). So you
  160030. * can't use color quantization if you change that value.
  160031. */
  160032. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  160033. #define RGB_GREEN 1 /* Offset of Green */
  160034. #define RGB_BLUE 2 /* Offset of Blue */
  160035. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  160036. /* Definitions for speed-related optimizations. */
  160037. /* If your compiler supports inline functions, define INLINE
  160038. * as the inline keyword; otherwise define it as empty.
  160039. */
  160040. #ifndef INLINE
  160041. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  160042. #define INLINE __inline__
  160043. #endif
  160044. #ifndef INLINE
  160045. #define INLINE /* default is to define it as empty */
  160046. #endif
  160047. #endif
  160048. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  160049. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  160050. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  160051. */
  160052. #ifndef MULTIPLIER
  160053. #define MULTIPLIER int /* type for fastest integer multiply */
  160054. #endif
  160055. /* FAST_FLOAT should be either float or double, whichever is done faster
  160056. * by your compiler. (Note that this type is only used in the floating point
  160057. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  160058. * Typically, float is faster in ANSI C compilers, while double is faster in
  160059. * pre-ANSI compilers (because they insist on converting to double anyway).
  160060. * The code below therefore chooses float if we have ANSI-style prototypes.
  160061. */
  160062. #ifndef FAST_FLOAT
  160063. #ifdef HAVE_PROTOTYPES
  160064. #define FAST_FLOAT float
  160065. #else
  160066. #define FAST_FLOAT double
  160067. #endif
  160068. #endif
  160069. #endif /* JPEG_INTERNAL_OPTIONS */
  160070. /*** End of inlined file: jmorecfg.h ***/
  160071. /* seldom changed options */
  160072. /* Version ID for the JPEG library.
  160073. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  160074. */
  160075. #define JPEG_LIB_VERSION 62 /* Version 6b */
  160076. /* Various constants determining the sizes of things.
  160077. * All of these are specified by the JPEG standard, so don't change them
  160078. * if you want to be compatible.
  160079. */
  160080. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  160081. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  160082. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  160083. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  160084. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  160085. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  160086. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  160087. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  160088. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  160089. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  160090. * to handle it. We even let you do this from the jconfig.h file. However,
  160091. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  160092. * sometimes emits noncompliant files doesn't mean you should too.
  160093. */
  160094. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  160095. #ifndef D_MAX_BLOCKS_IN_MCU
  160096. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  160097. #endif
  160098. /* Data structures for images (arrays of samples and of DCT coefficients).
  160099. * On 80x86 machines, the image arrays are too big for near pointers,
  160100. * but the pointer arrays can fit in near memory.
  160101. */
  160102. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  160103. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  160104. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  160105. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  160106. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  160107. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  160108. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  160109. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  160110. /* Types for JPEG compression parameters and working tables. */
  160111. /* DCT coefficient quantization tables. */
  160112. typedef struct {
  160113. /* This array gives the coefficient quantizers in natural array order
  160114. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  160115. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  160116. */
  160117. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  160118. /* This field is used only during compression. It's initialized FALSE when
  160119. * the table is created, and set TRUE when it's been output to the file.
  160120. * You could suppress output of a table by setting this to TRUE.
  160121. * (See jpeg_suppress_tables for an example.)
  160122. */
  160123. boolean sent_table; /* TRUE when table has been output */
  160124. } JQUANT_TBL;
  160125. /* Huffman coding tables. */
  160126. typedef struct {
  160127. /* These two fields directly represent the contents of a JPEG DHT marker */
  160128. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  160129. /* length k bits; bits[0] is unused */
  160130. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  160131. /* This field is used only during compression. It's initialized FALSE when
  160132. * the table is created, and set TRUE when it's been output to the file.
  160133. * You could suppress output of a table by setting this to TRUE.
  160134. * (See jpeg_suppress_tables for an example.)
  160135. */
  160136. boolean sent_table; /* TRUE when table has been output */
  160137. } JHUFF_TBL;
  160138. /* Basic info about one component (color channel). */
  160139. typedef struct {
  160140. /* These values are fixed over the whole image. */
  160141. /* For compression, they must be supplied by parameter setup; */
  160142. /* for decompression, they are read from the SOF marker. */
  160143. int component_id; /* identifier for this component (0..255) */
  160144. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160145. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160146. int v_samp_factor; /* vertical sampling factor (1..4) */
  160147. int quant_tbl_no; /* quantization table selector (0..3) */
  160148. /* These values may vary between scans. */
  160149. /* For compression, they must be supplied by parameter setup; */
  160150. /* for decompression, they are read from the SOS marker. */
  160151. /* The decompressor output side may not use these variables. */
  160152. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160153. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160154. /* Remaining fields should be treated as private by applications. */
  160155. /* These values are computed during compression or decompression startup: */
  160156. /* Component's size in DCT blocks.
  160157. * Any dummy blocks added to complete an MCU are not counted; therefore
  160158. * these values do not depend on whether a scan is interleaved or not.
  160159. */
  160160. JDIMENSION width_in_blocks;
  160161. JDIMENSION height_in_blocks;
  160162. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160163. * For decompression this is the size of the output from one DCT block,
  160164. * reflecting any scaling we choose to apply during the IDCT step.
  160165. * Values of 1,2,4,8 are likely to be supported. Note that different
  160166. * components may receive different IDCT scalings.
  160167. */
  160168. int DCT_scaled_size;
  160169. /* The downsampled dimensions are the component's actual, unpadded number
  160170. * of samples at the main buffer (preprocessing/compression interface), thus
  160171. * downsampled_width = ceil(image_width * Hi/Hmax)
  160172. * and similarly for height. For decompression, IDCT scaling is included, so
  160173. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160174. */
  160175. JDIMENSION downsampled_width; /* actual width in samples */
  160176. JDIMENSION downsampled_height; /* actual height in samples */
  160177. /* This flag is used only for decompression. In cases where some of the
  160178. * components will be ignored (eg grayscale output from YCbCr image),
  160179. * we can skip most computations for the unused components.
  160180. */
  160181. boolean component_needed; /* do we need the value of this component? */
  160182. /* These values are computed before starting a scan of the component. */
  160183. /* The decompressor output side may not use these variables. */
  160184. int MCU_width; /* number of blocks per MCU, horizontally */
  160185. int MCU_height; /* number of blocks per MCU, vertically */
  160186. int MCU_blocks; /* MCU_width * MCU_height */
  160187. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160188. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160189. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160190. /* Saved quantization table for component; NULL if none yet saved.
  160191. * See jdinput.c comments about the need for this information.
  160192. * This field is currently used only for decompression.
  160193. */
  160194. JQUANT_TBL * quant_table;
  160195. /* Private per-component storage for DCT or IDCT subsystem. */
  160196. void * dct_table;
  160197. } jpeg_component_info;
  160198. /* The script for encoding a multiple-scan file is an array of these: */
  160199. typedef struct {
  160200. int comps_in_scan; /* number of components encoded in this scan */
  160201. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160202. int Ss, Se; /* progressive JPEG spectral selection parms */
  160203. int Ah, Al; /* progressive JPEG successive approx. parms */
  160204. } jpeg_scan_info;
  160205. /* The decompressor can save APPn and COM markers in a list of these: */
  160206. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160207. struct jpeg_marker_struct {
  160208. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160209. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160210. unsigned int original_length; /* # bytes of data in the file */
  160211. unsigned int data_length; /* # bytes of data saved at data[] */
  160212. JOCTET FAR * data; /* the data contained in the marker */
  160213. /* the marker length word is not counted in data_length or original_length */
  160214. };
  160215. /* Known color spaces. */
  160216. typedef enum {
  160217. JCS_UNKNOWN, /* error/unspecified */
  160218. JCS_GRAYSCALE, /* monochrome */
  160219. JCS_RGB, /* red/green/blue */
  160220. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160221. JCS_CMYK, /* C/M/Y/K */
  160222. JCS_YCCK /* Y/Cb/Cr/K */
  160223. } J_COLOR_SPACE;
  160224. /* DCT/IDCT algorithm options. */
  160225. typedef enum {
  160226. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160227. JDCT_IFAST, /* faster, less accurate integer method */
  160228. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160229. } J_DCT_METHOD;
  160230. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160231. #define JDCT_DEFAULT JDCT_ISLOW
  160232. #endif
  160233. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160234. #define JDCT_FASTEST JDCT_IFAST
  160235. #endif
  160236. /* Dithering options for decompression. */
  160237. typedef enum {
  160238. JDITHER_NONE, /* no dithering */
  160239. JDITHER_ORDERED, /* simple ordered dither */
  160240. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160241. } J_DITHER_MODE;
  160242. /* Common fields between JPEG compression and decompression master structs. */
  160243. #define jpeg_common_fields \
  160244. struct jpeg_error_mgr * err; /* Error handler module */\
  160245. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160246. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160247. void * client_data; /* Available for use by application */\
  160248. boolean is_decompressor; /* So common code can tell which is which */\
  160249. int global_state /* For checking call sequence validity */
  160250. /* Routines that are to be used by both halves of the library are declared
  160251. * to receive a pointer to this structure. There are no actual instances of
  160252. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160253. */
  160254. struct jpeg_common_struct {
  160255. jpeg_common_fields; /* Fields common to both master struct types */
  160256. /* Additional fields follow in an actual jpeg_compress_struct or
  160257. * jpeg_decompress_struct. All three structs must agree on these
  160258. * initial fields! (This would be a lot cleaner in C++.)
  160259. */
  160260. };
  160261. typedef struct jpeg_common_struct * j_common_ptr;
  160262. typedef struct jpeg_compress_struct * j_compress_ptr;
  160263. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160264. /* Master record for a compression instance */
  160265. struct jpeg_compress_struct {
  160266. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160267. /* Destination for compressed data */
  160268. struct jpeg_destination_mgr * dest;
  160269. /* Description of source image --- these fields must be filled in by
  160270. * outer application before starting compression. in_color_space must
  160271. * be correct before you can even call jpeg_set_defaults().
  160272. */
  160273. JDIMENSION image_width; /* input image width */
  160274. JDIMENSION image_height; /* input image height */
  160275. int input_components; /* # of color components in input image */
  160276. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160277. double input_gamma; /* image gamma of input image */
  160278. /* Compression parameters --- these fields must be set before calling
  160279. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160280. * initialize everything to reasonable defaults, then changing anything
  160281. * the application specifically wants to change. That way you won't get
  160282. * burnt when new parameters are added. Also note that there are several
  160283. * helper routines to simplify changing parameters.
  160284. */
  160285. int data_precision; /* bits of precision in image data */
  160286. int num_components; /* # of color components in JPEG image */
  160287. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160288. jpeg_component_info * comp_info;
  160289. /* comp_info[i] describes component that appears i'th in SOF */
  160290. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160291. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160292. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160293. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160294. /* ptrs to Huffman coding tables, or NULL if not defined */
  160295. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160296. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160297. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160298. int num_scans; /* # of entries in scan_info array */
  160299. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160300. /* The default value of scan_info is NULL, which causes a single-scan
  160301. * sequential JPEG file to be emitted. To create a multi-scan file,
  160302. * set num_scans and scan_info to point to an array of scan definitions.
  160303. */
  160304. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160305. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160306. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160307. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160308. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160309. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160310. /* The restart interval can be specified in absolute MCUs by setting
  160311. * restart_interval, or in MCU rows by setting restart_in_rows
  160312. * (in which case the correct restart_interval will be figured
  160313. * for each scan).
  160314. */
  160315. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160316. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160317. /* Parameters controlling emission of special markers. */
  160318. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160319. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160320. UINT8 JFIF_minor_version;
  160321. /* These three values are not used by the JPEG code, merely copied */
  160322. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160323. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160324. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160325. UINT8 density_unit; /* JFIF code for pixel size units */
  160326. UINT16 X_density; /* Horizontal pixel density */
  160327. UINT16 Y_density; /* Vertical pixel density */
  160328. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160329. /* State variable: index of next scanline to be written to
  160330. * jpeg_write_scanlines(). Application may use this to control its
  160331. * processing loop, e.g., "while (next_scanline < image_height)".
  160332. */
  160333. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160334. /* Remaining fields are known throughout compressor, but generally
  160335. * should not be touched by a surrounding application.
  160336. */
  160337. /*
  160338. * These fields are computed during compression startup
  160339. */
  160340. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160341. int max_h_samp_factor; /* largest h_samp_factor */
  160342. int max_v_samp_factor; /* largest v_samp_factor */
  160343. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160344. /* The coefficient controller receives data in units of MCU rows as defined
  160345. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160346. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160347. * "iMCU" (interleaved MCU) row.
  160348. */
  160349. /*
  160350. * These fields are valid during any one scan.
  160351. * They describe the components and MCUs actually appearing in the scan.
  160352. */
  160353. int comps_in_scan; /* # of JPEG components in this scan */
  160354. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160355. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160356. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160357. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160358. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160359. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160360. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160361. /* i'th block in an MCU */
  160362. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160363. /*
  160364. * Links to compression subobjects (methods and private variables of modules)
  160365. */
  160366. struct jpeg_comp_master * master;
  160367. struct jpeg_c_main_controller * main;
  160368. struct jpeg_c_prep_controller * prep;
  160369. struct jpeg_c_coef_controller * coef;
  160370. struct jpeg_marker_writer * marker;
  160371. struct jpeg_color_converter * cconvert;
  160372. struct jpeg_downsampler * downsample;
  160373. struct jpeg_forward_dct * fdct;
  160374. struct jpeg_entropy_encoder * entropy;
  160375. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160376. int script_space_size;
  160377. };
  160378. /* Master record for a decompression instance */
  160379. struct jpeg_decompress_struct {
  160380. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160381. /* Source of compressed data */
  160382. struct jpeg_source_mgr * src;
  160383. /* Basic description of image --- filled in by jpeg_read_header(). */
  160384. /* Application may inspect these values to decide how to process image. */
  160385. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160386. JDIMENSION image_height; /* nominal image height */
  160387. int num_components; /* # of color components in JPEG image */
  160388. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160389. /* Decompression processing parameters --- these fields must be set before
  160390. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160391. * them to default values.
  160392. */
  160393. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160394. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160395. double output_gamma; /* image gamma wanted in output */
  160396. boolean buffered_image; /* TRUE=multiple output passes */
  160397. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160398. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160399. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160400. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160401. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160402. /* the following are ignored if not quantize_colors: */
  160403. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160404. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160405. int desired_number_of_colors; /* max # colors to use in created colormap */
  160406. /* these are significant only in buffered-image mode: */
  160407. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160408. boolean enable_external_quant;/* enable future use of external colormap */
  160409. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160410. /* Description of actual output image that will be returned to application.
  160411. * These fields are computed by jpeg_start_decompress().
  160412. * You can also use jpeg_calc_output_dimensions() to determine these values
  160413. * in advance of calling jpeg_start_decompress().
  160414. */
  160415. JDIMENSION output_width; /* scaled image width */
  160416. JDIMENSION output_height; /* scaled image height */
  160417. int out_color_components; /* # of color components in out_color_space */
  160418. int output_components; /* # of color components returned */
  160419. /* output_components is 1 (a colormap index) when quantizing colors;
  160420. * otherwise it equals out_color_components.
  160421. */
  160422. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160423. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160424. * high, space and time will be wasted due to unnecessary data copying.
  160425. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160426. */
  160427. /* When quantizing colors, the output colormap is described by these fields.
  160428. * The application can supply a colormap by setting colormap non-NULL before
  160429. * calling jpeg_start_decompress; otherwise a colormap is created during
  160430. * jpeg_start_decompress or jpeg_start_output.
  160431. * The map has out_color_components rows and actual_number_of_colors columns.
  160432. */
  160433. int actual_number_of_colors; /* number of entries in use */
  160434. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160435. /* State variables: these variables indicate the progress of decompression.
  160436. * The application may examine these but must not modify them.
  160437. */
  160438. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160439. * Application may use this to control its processing loop, e.g.,
  160440. * "while (output_scanline < output_height)".
  160441. */
  160442. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160443. /* Current input scan number and number of iMCU rows completed in scan.
  160444. * These indicate the progress of the decompressor input side.
  160445. */
  160446. int input_scan_number; /* Number of SOS markers seen so far */
  160447. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160448. /* The "output scan number" is the notional scan being displayed by the
  160449. * output side. The decompressor will not allow output scan/row number
  160450. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160451. */
  160452. int output_scan_number; /* Nominal scan number being displayed */
  160453. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160454. /* Current progression status. coef_bits[c][i] indicates the precision
  160455. * with which component c's DCT coefficient i (in zigzag order) is known.
  160456. * It is -1 when no data has yet been received, otherwise it is the point
  160457. * transform (shift) value for the most recent scan of the coefficient
  160458. * (thus, 0 at completion of the progression).
  160459. * This pointer is NULL when reading a non-progressive file.
  160460. */
  160461. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160462. /* Internal JPEG parameters --- the application usually need not look at
  160463. * these fields. Note that the decompressor output side may not use
  160464. * any parameters that can change between scans.
  160465. */
  160466. /* Quantization and Huffman tables are carried forward across input
  160467. * datastreams when processing abbreviated JPEG datastreams.
  160468. */
  160469. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160470. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160471. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160472. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160473. /* ptrs to Huffman coding tables, or NULL if not defined */
  160474. /* These parameters are never carried across datastreams, since they
  160475. * are given in SOF/SOS markers or defined to be reset by SOI.
  160476. */
  160477. int data_precision; /* bits of precision in image data */
  160478. jpeg_component_info * comp_info;
  160479. /* comp_info[i] describes component that appears i'th in SOF */
  160480. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160481. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160482. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160483. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160484. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160485. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160486. /* These fields record data obtained from optional markers recognized by
  160487. * the JPEG library.
  160488. */
  160489. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160490. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160491. UINT8 JFIF_major_version; /* JFIF version number */
  160492. UINT8 JFIF_minor_version;
  160493. UINT8 density_unit; /* JFIF code for pixel size units */
  160494. UINT16 X_density; /* Horizontal pixel density */
  160495. UINT16 Y_density; /* Vertical pixel density */
  160496. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160497. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160498. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160499. /* Aside from the specific data retained from APPn markers known to the
  160500. * library, the uninterpreted contents of any or all APPn and COM markers
  160501. * can be saved in a list for examination by the application.
  160502. */
  160503. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160504. /* Remaining fields are known throughout decompressor, but generally
  160505. * should not be touched by a surrounding application.
  160506. */
  160507. /*
  160508. * These fields are computed during decompression startup
  160509. */
  160510. int max_h_samp_factor; /* largest h_samp_factor */
  160511. int max_v_samp_factor; /* largest v_samp_factor */
  160512. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160513. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160514. /* The coefficient controller's input and output progress is measured in
  160515. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160516. * in fully interleaved JPEG scans, but are used whether the scan is
  160517. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160518. * rows of each component. Therefore, the IDCT output contains
  160519. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160520. */
  160521. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160522. /*
  160523. * These fields are valid during any one scan.
  160524. * They describe the components and MCUs actually appearing in the scan.
  160525. * Note that the decompressor output side must not use these fields.
  160526. */
  160527. int comps_in_scan; /* # of JPEG components in this scan */
  160528. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160529. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160530. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160531. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160532. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160533. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160534. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160535. /* i'th block in an MCU */
  160536. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160537. /* This field is shared between entropy decoder and marker parser.
  160538. * It is either zero or the code of a JPEG marker that has been
  160539. * read from the data source, but has not yet been processed.
  160540. */
  160541. int unread_marker;
  160542. /*
  160543. * Links to decompression subobjects (methods, private variables of modules)
  160544. */
  160545. struct jpeg_decomp_master * master;
  160546. struct jpeg_d_main_controller * main;
  160547. struct jpeg_d_coef_controller * coef;
  160548. struct jpeg_d_post_controller * post;
  160549. struct jpeg_input_controller * inputctl;
  160550. struct jpeg_marker_reader * marker;
  160551. struct jpeg_entropy_decoder * entropy;
  160552. struct jpeg_inverse_dct * idct;
  160553. struct jpeg_upsampler * upsample;
  160554. struct jpeg_color_deconverter * cconvert;
  160555. struct jpeg_color_quantizer * cquantize;
  160556. };
  160557. /* "Object" declarations for JPEG modules that may be supplied or called
  160558. * directly by the surrounding application.
  160559. * As with all objects in the JPEG library, these structs only define the
  160560. * publicly visible methods and state variables of a module. Additional
  160561. * private fields may exist after the public ones.
  160562. */
  160563. /* Error handler object */
  160564. struct jpeg_error_mgr {
  160565. /* Error exit handler: does not return to caller */
  160566. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160567. /* Conditionally emit a trace or warning message */
  160568. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160569. /* Routine that actually outputs a trace or error message */
  160570. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160571. /* Format a message string for the most recent JPEG error or message */
  160572. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160573. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160574. /* Reset error state variables at start of a new image */
  160575. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160576. /* The message ID code and any parameters are saved here.
  160577. * A message can have one string parameter or up to 8 int parameters.
  160578. */
  160579. int msg_code;
  160580. #define JMSG_STR_PARM_MAX 80
  160581. union {
  160582. int i[8];
  160583. char s[JMSG_STR_PARM_MAX];
  160584. } msg_parm;
  160585. /* Standard state variables for error facility */
  160586. int trace_level; /* max msg_level that will be displayed */
  160587. /* For recoverable corrupt-data errors, we emit a warning message,
  160588. * but keep going unless emit_message chooses to abort. emit_message
  160589. * should count warnings in num_warnings. The surrounding application
  160590. * can check for bad data by seeing if num_warnings is nonzero at the
  160591. * end of processing.
  160592. */
  160593. long num_warnings; /* number of corrupt-data warnings */
  160594. /* These fields point to the table(s) of error message strings.
  160595. * An application can change the table pointer to switch to a different
  160596. * message list (typically, to change the language in which errors are
  160597. * reported). Some applications may wish to add additional error codes
  160598. * that will be handled by the JPEG library error mechanism; the second
  160599. * table pointer is used for this purpose.
  160600. *
  160601. * First table includes all errors generated by JPEG library itself.
  160602. * Error code 0 is reserved for a "no such error string" message.
  160603. */
  160604. const char * const * jpeg_message_table; /* Library errors */
  160605. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160606. /* Second table can be added by application (see cjpeg/djpeg for example).
  160607. * It contains strings numbered first_addon_message..last_addon_message.
  160608. */
  160609. const char * const * addon_message_table; /* Non-library errors */
  160610. int first_addon_message; /* code for first string in addon table */
  160611. int last_addon_message; /* code for last string in addon table */
  160612. };
  160613. /* Progress monitor object */
  160614. struct jpeg_progress_mgr {
  160615. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160616. long pass_counter; /* work units completed in this pass */
  160617. long pass_limit; /* total number of work units in this pass */
  160618. int completed_passes; /* passes completed so far */
  160619. int total_passes; /* total number of passes expected */
  160620. };
  160621. /* Data destination object for compression */
  160622. struct jpeg_destination_mgr {
  160623. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160624. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160625. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160626. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160627. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160628. };
  160629. /* Data source object for decompression */
  160630. struct jpeg_source_mgr {
  160631. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160632. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160633. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160634. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160635. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160636. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160637. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160638. };
  160639. /* Memory manager object.
  160640. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160641. * and "really big" objects (virtual arrays with backing store if needed).
  160642. * The memory manager does not allow individual objects to be freed; rather,
  160643. * each created object is assigned to a pool, and whole pools can be freed
  160644. * at once. This is faster and more convenient than remembering exactly what
  160645. * to free, especially where malloc()/free() are not too speedy.
  160646. * NB: alloc routines never return NULL. They exit to error_exit if not
  160647. * successful.
  160648. */
  160649. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160650. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160651. #define JPOOL_NUMPOOLS 2
  160652. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160653. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160654. struct jpeg_memory_mgr {
  160655. /* Method pointers */
  160656. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160657. size_t sizeofobject));
  160658. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160659. size_t sizeofobject));
  160660. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160661. JDIMENSION samplesperrow,
  160662. JDIMENSION numrows));
  160663. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160664. JDIMENSION blocksperrow,
  160665. JDIMENSION numrows));
  160666. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160667. int pool_id,
  160668. boolean pre_zero,
  160669. JDIMENSION samplesperrow,
  160670. JDIMENSION numrows,
  160671. JDIMENSION maxaccess));
  160672. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160673. int pool_id,
  160674. boolean pre_zero,
  160675. JDIMENSION blocksperrow,
  160676. JDIMENSION numrows,
  160677. JDIMENSION maxaccess));
  160678. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160679. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160680. jvirt_sarray_ptr ptr,
  160681. JDIMENSION start_row,
  160682. JDIMENSION num_rows,
  160683. boolean writable));
  160684. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160685. jvirt_barray_ptr ptr,
  160686. JDIMENSION start_row,
  160687. JDIMENSION num_rows,
  160688. boolean writable));
  160689. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160690. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160691. /* Limit on memory allocation for this JPEG object. (Note that this is
  160692. * merely advisory, not a guaranteed maximum; it only affects the space
  160693. * used for virtual-array buffers.) May be changed by outer application
  160694. * after creating the JPEG object.
  160695. */
  160696. long max_memory_to_use;
  160697. /* Maximum allocation request accepted by alloc_large. */
  160698. long max_alloc_chunk;
  160699. };
  160700. /* Routine signature for application-supplied marker processing methods.
  160701. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160702. */
  160703. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160704. /* Declarations for routines called by application.
  160705. * The JPP macro hides prototype parameters from compilers that can't cope.
  160706. * Note JPP requires double parentheses.
  160707. */
  160708. #ifdef HAVE_PROTOTYPES
  160709. #define JPP(arglist) arglist
  160710. #else
  160711. #define JPP(arglist) ()
  160712. #endif
  160713. /* Short forms of external names for systems with brain-damaged linkers.
  160714. * We shorten external names to be unique in the first six letters, which
  160715. * is good enough for all known systems.
  160716. * (If your compiler itself needs names to be unique in less than 15
  160717. * characters, you are out of luck. Get a better compiler.)
  160718. */
  160719. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160720. #define jpeg_std_error jStdError
  160721. #define jpeg_CreateCompress jCreaCompress
  160722. #define jpeg_CreateDecompress jCreaDecompress
  160723. #define jpeg_destroy_compress jDestCompress
  160724. #define jpeg_destroy_decompress jDestDecompress
  160725. #define jpeg_stdio_dest jStdDest
  160726. #define jpeg_stdio_src jStdSrc
  160727. #define jpeg_set_defaults jSetDefaults
  160728. #define jpeg_set_colorspace jSetColorspace
  160729. #define jpeg_default_colorspace jDefColorspace
  160730. #define jpeg_set_quality jSetQuality
  160731. #define jpeg_set_linear_quality jSetLQuality
  160732. #define jpeg_add_quant_table jAddQuantTable
  160733. #define jpeg_quality_scaling jQualityScaling
  160734. #define jpeg_simple_progression jSimProgress
  160735. #define jpeg_suppress_tables jSuppressTables
  160736. #define jpeg_alloc_quant_table jAlcQTable
  160737. #define jpeg_alloc_huff_table jAlcHTable
  160738. #define jpeg_start_compress jStrtCompress
  160739. #define jpeg_write_scanlines jWrtScanlines
  160740. #define jpeg_finish_compress jFinCompress
  160741. #define jpeg_write_raw_data jWrtRawData
  160742. #define jpeg_write_marker jWrtMarker
  160743. #define jpeg_write_m_header jWrtMHeader
  160744. #define jpeg_write_m_byte jWrtMByte
  160745. #define jpeg_write_tables jWrtTables
  160746. #define jpeg_read_header jReadHeader
  160747. #define jpeg_start_decompress jStrtDecompress
  160748. #define jpeg_read_scanlines jReadScanlines
  160749. #define jpeg_finish_decompress jFinDecompress
  160750. #define jpeg_read_raw_data jReadRawData
  160751. #define jpeg_has_multiple_scans jHasMultScn
  160752. #define jpeg_start_output jStrtOutput
  160753. #define jpeg_finish_output jFinOutput
  160754. #define jpeg_input_complete jInComplete
  160755. #define jpeg_new_colormap jNewCMap
  160756. #define jpeg_consume_input jConsumeInput
  160757. #define jpeg_calc_output_dimensions jCalcDimensions
  160758. #define jpeg_save_markers jSaveMarkers
  160759. #define jpeg_set_marker_processor jSetMarker
  160760. #define jpeg_read_coefficients jReadCoefs
  160761. #define jpeg_write_coefficients jWrtCoefs
  160762. #define jpeg_copy_critical_parameters jCopyCrit
  160763. #define jpeg_abort_compress jAbrtCompress
  160764. #define jpeg_abort_decompress jAbrtDecompress
  160765. #define jpeg_abort jAbort
  160766. #define jpeg_destroy jDestroy
  160767. #define jpeg_resync_to_restart jResyncRestart
  160768. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160769. /* Default error-management setup */
  160770. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160771. JPP((struct jpeg_error_mgr * err));
  160772. /* Initialization of JPEG compression objects.
  160773. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160774. * names that applications should call. These expand to calls on
  160775. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160776. * passed for version mismatch checking.
  160777. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160778. */
  160779. #define jpeg_create_compress(cinfo) \
  160780. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160781. (size_t) sizeof(struct jpeg_compress_struct))
  160782. #define jpeg_create_decompress(cinfo) \
  160783. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160784. (size_t) sizeof(struct jpeg_decompress_struct))
  160785. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160786. int version, size_t structsize));
  160787. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160788. int version, size_t structsize));
  160789. /* Destruction of JPEG compression objects */
  160790. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160791. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160792. /* Standard data source and destination managers: stdio streams. */
  160793. /* Caller is responsible for opening the file before and closing after. */
  160794. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160795. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160796. /* Default parameter setup for compression */
  160797. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160798. /* Compression parameter setup aids */
  160799. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160800. J_COLOR_SPACE colorspace));
  160801. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160802. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160803. boolean force_baseline));
  160804. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160805. int scale_factor,
  160806. boolean force_baseline));
  160807. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160808. const unsigned int *basic_table,
  160809. int scale_factor,
  160810. boolean force_baseline));
  160811. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160812. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160813. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160814. boolean suppress));
  160815. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160816. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160817. /* Main entry points for compression */
  160818. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160819. boolean write_all_tables));
  160820. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160821. JSAMPARRAY scanlines,
  160822. JDIMENSION num_lines));
  160823. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160824. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160825. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160826. JSAMPIMAGE data,
  160827. JDIMENSION num_lines));
  160828. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160829. EXTERN(void) jpeg_write_marker
  160830. JPP((j_compress_ptr cinfo, int marker,
  160831. const JOCTET * dataptr, unsigned int datalen));
  160832. /* Same, but piecemeal. */
  160833. EXTERN(void) jpeg_write_m_header
  160834. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160835. EXTERN(void) jpeg_write_m_byte
  160836. JPP((j_compress_ptr cinfo, int val));
  160837. /* Alternate compression function: just write an abbreviated table file */
  160838. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160839. /* Decompression startup: read start of JPEG datastream to see what's there */
  160840. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160841. boolean require_image));
  160842. /* Return value is one of: */
  160843. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160844. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160845. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160846. /* If you pass require_image = TRUE (normal case), you need not check for
  160847. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160848. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160849. * give a suspension return (the stdio source module doesn't).
  160850. */
  160851. /* Main entry points for decompression */
  160852. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160853. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160854. JSAMPARRAY scanlines,
  160855. JDIMENSION max_lines));
  160856. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160857. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160858. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160859. JSAMPIMAGE data,
  160860. JDIMENSION max_lines));
  160861. /* Additional entry points for buffered-image mode. */
  160862. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160863. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160864. int scan_number));
  160865. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160866. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160867. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160868. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160869. /* Return value is one of: */
  160870. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160871. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160872. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160873. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160874. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160875. /* Precalculate output dimensions for current decompression parameters. */
  160876. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160877. /* Control saving of COM and APPn markers into marker_list. */
  160878. EXTERN(void) jpeg_save_markers
  160879. JPP((j_decompress_ptr cinfo, int marker_code,
  160880. unsigned int length_limit));
  160881. /* Install a special processing method for COM or APPn markers. */
  160882. EXTERN(void) jpeg_set_marker_processor
  160883. JPP((j_decompress_ptr cinfo, int marker_code,
  160884. jpeg_marker_parser_method routine));
  160885. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160886. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160887. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160888. jvirt_barray_ptr * coef_arrays));
  160889. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160890. j_compress_ptr dstinfo));
  160891. /* If you choose to abort compression or decompression before completing
  160892. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160893. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160894. * if you're done with the JPEG object, but if you want to clean it up and
  160895. * reuse it, call this:
  160896. */
  160897. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160898. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160899. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160900. * flavor of JPEG object. These may be more convenient in some places.
  160901. */
  160902. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160903. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160904. /* Default restart-marker-resync procedure for use by data source modules */
  160905. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160906. int desired));
  160907. /* These marker codes are exported since applications and data source modules
  160908. * are likely to want to use them.
  160909. */
  160910. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160911. #define JPEG_EOI 0xD9 /* EOI marker code */
  160912. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160913. #define JPEG_COM 0xFE /* COM marker code */
  160914. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160915. * for structure definitions that are never filled in, keep it quiet by
  160916. * supplying dummy definitions for the various substructures.
  160917. */
  160918. #ifdef INCOMPLETE_TYPES_BROKEN
  160919. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160920. struct jvirt_sarray_control { long dummy; };
  160921. struct jvirt_barray_control { long dummy; };
  160922. struct jpeg_comp_master { long dummy; };
  160923. struct jpeg_c_main_controller { long dummy; };
  160924. struct jpeg_c_prep_controller { long dummy; };
  160925. struct jpeg_c_coef_controller { long dummy; };
  160926. struct jpeg_marker_writer { long dummy; };
  160927. struct jpeg_color_converter { long dummy; };
  160928. struct jpeg_downsampler { long dummy; };
  160929. struct jpeg_forward_dct { long dummy; };
  160930. struct jpeg_entropy_encoder { long dummy; };
  160931. struct jpeg_decomp_master { long dummy; };
  160932. struct jpeg_d_main_controller { long dummy; };
  160933. struct jpeg_d_coef_controller { long dummy; };
  160934. struct jpeg_d_post_controller { long dummy; };
  160935. struct jpeg_input_controller { long dummy; };
  160936. struct jpeg_marker_reader { long dummy; };
  160937. struct jpeg_entropy_decoder { long dummy; };
  160938. struct jpeg_inverse_dct { long dummy; };
  160939. struct jpeg_upsampler { long dummy; };
  160940. struct jpeg_color_deconverter { long dummy; };
  160941. struct jpeg_color_quantizer { long dummy; };
  160942. #endif /* JPEG_INTERNALS */
  160943. #endif /* INCOMPLETE_TYPES_BROKEN */
  160944. /*
  160945. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160946. * The internal structure declarations are read only when that is true.
  160947. * Applications using the library should not include jpegint.h, but may wish
  160948. * to include jerror.h.
  160949. */
  160950. #ifdef JPEG_INTERNALS
  160951. /*** Start of inlined file: jpegint.h ***/
  160952. /* Declarations for both compression & decompression */
  160953. typedef enum { /* Operating modes for buffer controllers */
  160954. JBUF_PASS_THRU, /* Plain stripwise operation */
  160955. /* Remaining modes require a full-image buffer to have been created */
  160956. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160957. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160958. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160959. } J_BUF_MODE;
  160960. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160961. #define CSTATE_START 100 /* after create_compress */
  160962. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160963. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160964. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160965. #define DSTATE_START 200 /* after create_decompress */
  160966. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160967. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160968. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160969. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160970. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160971. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160972. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160973. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160974. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160975. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160976. /* Declarations for compression modules */
  160977. /* Master control module */
  160978. struct jpeg_comp_master {
  160979. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160980. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160981. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160982. /* State variables made visible to other modules */
  160983. boolean call_pass_startup; /* True if pass_startup must be called */
  160984. boolean is_last_pass; /* True during last pass */
  160985. };
  160986. /* Main buffer control (downsampled-data buffer) */
  160987. struct jpeg_c_main_controller {
  160988. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160989. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160990. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160991. JDIMENSION in_rows_avail));
  160992. };
  160993. /* Compression preprocessing (downsampling input buffer control) */
  160994. struct jpeg_c_prep_controller {
  160995. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160996. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160997. JSAMPARRAY input_buf,
  160998. JDIMENSION *in_row_ctr,
  160999. JDIMENSION in_rows_avail,
  161000. JSAMPIMAGE output_buf,
  161001. JDIMENSION *out_row_group_ctr,
  161002. JDIMENSION out_row_groups_avail));
  161003. };
  161004. /* Coefficient buffer control */
  161005. struct jpeg_c_coef_controller {
  161006. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161007. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  161008. JSAMPIMAGE input_buf));
  161009. };
  161010. /* Colorspace conversion */
  161011. struct jpeg_color_converter {
  161012. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161013. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  161014. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161015. JDIMENSION output_row, int num_rows));
  161016. };
  161017. /* Downsampling */
  161018. struct jpeg_downsampler {
  161019. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161020. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  161021. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  161022. JSAMPIMAGE output_buf,
  161023. JDIMENSION out_row_group_index));
  161024. boolean need_context_rows; /* TRUE if need rows above & below */
  161025. };
  161026. /* Forward DCT (also controls coefficient quantization) */
  161027. struct jpeg_forward_dct {
  161028. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161029. /* perhaps this should be an array??? */
  161030. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  161031. jpeg_component_info * compptr,
  161032. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161033. JDIMENSION start_row, JDIMENSION start_col,
  161034. JDIMENSION num_blocks));
  161035. };
  161036. /* Entropy encoding */
  161037. struct jpeg_entropy_encoder {
  161038. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  161039. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  161040. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161041. };
  161042. /* Marker writing */
  161043. struct jpeg_marker_writer {
  161044. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  161045. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  161046. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  161047. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  161048. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  161049. /* These routines are exported to allow insertion of extra markers */
  161050. /* Probably only COM and APPn markers should be written this way */
  161051. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  161052. unsigned int datalen));
  161053. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  161054. };
  161055. /* Declarations for decompression modules */
  161056. /* Master control module */
  161057. struct jpeg_decomp_master {
  161058. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  161059. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  161060. /* State variables made visible to other modules */
  161061. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  161062. };
  161063. /* Input control module */
  161064. struct jpeg_input_controller {
  161065. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  161066. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  161067. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161068. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  161069. /* State variables made visible to other modules */
  161070. boolean has_multiple_scans; /* True if file has multiple scans */
  161071. boolean eoi_reached; /* True when EOI has been consumed */
  161072. };
  161073. /* Main buffer control (downsampled-data buffer) */
  161074. struct jpeg_d_main_controller {
  161075. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161076. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  161077. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  161078. JDIMENSION out_rows_avail));
  161079. };
  161080. /* Coefficient buffer control */
  161081. struct jpeg_d_coef_controller {
  161082. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161083. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  161084. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  161085. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  161086. JSAMPIMAGE output_buf));
  161087. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  161088. jvirt_barray_ptr *coef_arrays;
  161089. };
  161090. /* Decompression postprocessing (color quantization buffer control) */
  161091. struct jpeg_d_post_controller {
  161092. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161093. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  161094. JSAMPIMAGE input_buf,
  161095. JDIMENSION *in_row_group_ctr,
  161096. JDIMENSION in_row_groups_avail,
  161097. JSAMPARRAY output_buf,
  161098. JDIMENSION *out_row_ctr,
  161099. JDIMENSION out_rows_avail));
  161100. };
  161101. /* Marker reading & parsing */
  161102. struct jpeg_marker_reader {
  161103. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  161104. /* Read markers until SOS or EOI.
  161105. * Returns same codes as are defined for jpeg_consume_input:
  161106. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  161107. */
  161108. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  161109. /* Read a restart marker --- exported for use by entropy decoder only */
  161110. jpeg_marker_parser_method read_restart_marker;
  161111. /* State of marker reader --- nominally internal, but applications
  161112. * supplying COM or APPn handlers might like to know the state.
  161113. */
  161114. boolean saw_SOI; /* found SOI? */
  161115. boolean saw_SOF; /* found SOF? */
  161116. int next_restart_num; /* next restart number expected (0-7) */
  161117. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  161118. };
  161119. /* Entropy decoding */
  161120. struct jpeg_entropy_decoder {
  161121. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161122. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  161123. JBLOCKROW *MCU_data));
  161124. /* This is here to share code between baseline and progressive decoders; */
  161125. /* other modules probably should not use it */
  161126. boolean insufficient_data; /* set TRUE after emitting warning */
  161127. };
  161128. /* Inverse DCT (also performs dequantization) */
  161129. typedef JMETHOD(void, inverse_DCT_method_ptr,
  161130. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161131. JCOEFPTR coef_block,
  161132. JSAMPARRAY output_buf, JDIMENSION output_col));
  161133. struct jpeg_inverse_dct {
  161134. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161135. /* It is useful to allow each component to have a separate IDCT method. */
  161136. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  161137. };
  161138. /* Upsampling (note that upsampler must also call color converter) */
  161139. struct jpeg_upsampler {
  161140. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161141. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161142. JSAMPIMAGE input_buf,
  161143. JDIMENSION *in_row_group_ctr,
  161144. JDIMENSION in_row_groups_avail,
  161145. JSAMPARRAY output_buf,
  161146. JDIMENSION *out_row_ctr,
  161147. JDIMENSION out_rows_avail));
  161148. boolean need_context_rows; /* TRUE if need rows above & below */
  161149. };
  161150. /* Colorspace conversion */
  161151. struct jpeg_color_deconverter {
  161152. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161153. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161154. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161155. JSAMPARRAY output_buf, int num_rows));
  161156. };
  161157. /* Color quantization or color precision reduction */
  161158. struct jpeg_color_quantizer {
  161159. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161160. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161161. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161162. int num_rows));
  161163. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161164. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161165. };
  161166. /* Miscellaneous useful macros */
  161167. #undef MAX
  161168. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161169. #undef MIN
  161170. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161171. /* We assume that right shift corresponds to signed division by 2 with
  161172. * rounding towards minus infinity. This is correct for typical "arithmetic
  161173. * shift" instructions that shift in copies of the sign bit. But some
  161174. * C compilers implement >> with an unsigned shift. For these machines you
  161175. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161176. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161177. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161178. * included in the variables of any routine using RIGHT_SHIFT.
  161179. */
  161180. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161181. #define SHIFT_TEMPS INT32 shift_temp;
  161182. #define RIGHT_SHIFT(x,shft) \
  161183. ((shift_temp = (x)) < 0 ? \
  161184. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161185. (shift_temp >> (shft)))
  161186. #else
  161187. #define SHIFT_TEMPS
  161188. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161189. #endif
  161190. /* Short forms of external names for systems with brain-damaged linkers. */
  161191. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161192. #define jinit_compress_master jICompress
  161193. #define jinit_c_master_control jICMaster
  161194. #define jinit_c_main_controller jICMainC
  161195. #define jinit_c_prep_controller jICPrepC
  161196. #define jinit_c_coef_controller jICCoefC
  161197. #define jinit_color_converter jICColor
  161198. #define jinit_downsampler jIDownsampler
  161199. #define jinit_forward_dct jIFDCT
  161200. #define jinit_huff_encoder jIHEncoder
  161201. #define jinit_phuff_encoder jIPHEncoder
  161202. #define jinit_marker_writer jIMWriter
  161203. #define jinit_master_decompress jIDMaster
  161204. #define jinit_d_main_controller jIDMainC
  161205. #define jinit_d_coef_controller jIDCoefC
  161206. #define jinit_d_post_controller jIDPostC
  161207. #define jinit_input_controller jIInCtlr
  161208. #define jinit_marker_reader jIMReader
  161209. #define jinit_huff_decoder jIHDecoder
  161210. #define jinit_phuff_decoder jIPHDecoder
  161211. #define jinit_inverse_dct jIIDCT
  161212. #define jinit_upsampler jIUpsampler
  161213. #define jinit_color_deconverter jIDColor
  161214. #define jinit_1pass_quantizer jI1Quant
  161215. #define jinit_2pass_quantizer jI2Quant
  161216. #define jinit_merged_upsampler jIMUpsampler
  161217. #define jinit_memory_mgr jIMemMgr
  161218. #define jdiv_round_up jDivRound
  161219. #define jround_up jRound
  161220. #define jcopy_sample_rows jCopySamples
  161221. #define jcopy_block_row jCopyBlocks
  161222. #define jzero_far jZeroFar
  161223. #define jpeg_zigzag_order jZIGTable
  161224. #define jpeg_natural_order jZAGTable
  161225. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161226. /* Compression module initialization routines */
  161227. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161228. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161229. boolean transcode_only));
  161230. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161231. boolean need_full_buffer));
  161232. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161233. boolean need_full_buffer));
  161234. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161235. boolean need_full_buffer));
  161236. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161237. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161238. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161239. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161240. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161241. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161242. /* Decompression module initialization routines */
  161243. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161244. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161245. boolean need_full_buffer));
  161246. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161247. boolean need_full_buffer));
  161248. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161249. boolean need_full_buffer));
  161250. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161251. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161252. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161253. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161254. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161255. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161256. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161257. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161258. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161259. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161260. /* Memory manager initialization */
  161261. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161262. /* Utility routines in jutils.c */
  161263. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161264. EXTERN(long) jround_up JPP((long a, long b));
  161265. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161266. JSAMPARRAY output_array, int dest_row,
  161267. int num_rows, JDIMENSION num_cols));
  161268. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161269. JDIMENSION num_blocks));
  161270. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161271. /* Constant tables in jutils.c */
  161272. #if 0 /* This table is not actually needed in v6a */
  161273. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161274. #endif
  161275. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161276. /* Suppress undefined-structure complaints if necessary. */
  161277. #ifdef INCOMPLETE_TYPES_BROKEN
  161278. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161279. struct jvirt_sarray_control { long dummy; };
  161280. struct jvirt_barray_control { long dummy; };
  161281. #endif
  161282. #endif /* INCOMPLETE_TYPES_BROKEN */
  161283. /*** End of inlined file: jpegint.h ***/
  161284. /* fetch private declarations */
  161285. /*** Start of inlined file: jerror.h ***/
  161286. /*
  161287. * To define the enum list of message codes, include this file without
  161288. * defining macro JMESSAGE. To create a message string table, include it
  161289. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161290. */
  161291. #ifndef JMESSAGE
  161292. #ifndef JERROR_H
  161293. /* First time through, define the enum list */
  161294. #define JMAKE_ENUM_LIST
  161295. #else
  161296. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161297. #define JMESSAGE(code,string)
  161298. #endif /* JERROR_H */
  161299. #endif /* JMESSAGE */
  161300. #ifdef JMAKE_ENUM_LIST
  161301. typedef enum {
  161302. #define JMESSAGE(code,string) code ,
  161303. #endif /* JMAKE_ENUM_LIST */
  161304. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161305. /* For maintenance convenience, list is alphabetical by message code name */
  161306. JMESSAGE(JERR_ARITH_NOTIMPL,
  161307. "Sorry, there are legal restrictions on arithmetic coding")
  161308. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161309. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161310. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161311. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161312. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161313. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161314. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161315. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161316. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161317. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161318. JMESSAGE(JERR_BAD_LIB_VERSION,
  161319. "Wrong JPEG library version: library is %d, caller expects %d")
  161320. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161321. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161322. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161323. JMESSAGE(JERR_BAD_PROGRESSION,
  161324. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161325. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161326. "Invalid progressive parameters at scan script entry %d")
  161327. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161328. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161329. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161330. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161331. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161332. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161333. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161334. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161335. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161336. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161337. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161338. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161339. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161340. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161341. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161342. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161343. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161344. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161345. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161346. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161347. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161348. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161349. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161350. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161351. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161352. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161353. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161354. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161355. "Cannot transcode due to multiple use of quantization table %d")
  161356. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161357. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161358. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161359. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161360. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161361. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161362. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161363. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161364. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161365. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161366. JMESSAGE(JERR_QUANT_COMPONENTS,
  161367. "Cannot quantize more than %d color components")
  161368. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161369. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161370. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161371. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161372. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161373. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161374. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161375. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161376. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161377. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161378. JMESSAGE(JERR_TFILE_WRITE,
  161379. "Write failed on temporary file --- out of disk space?")
  161380. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161381. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161382. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161383. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161384. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161385. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161386. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161387. JMESSAGE(JMSG_VERSION, JVERSION)
  161388. JMESSAGE(JTRC_16BIT_TABLES,
  161389. "Caution: quantization tables are too coarse for baseline JPEG")
  161390. JMESSAGE(JTRC_ADOBE,
  161391. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161392. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161393. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161394. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161395. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161396. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161397. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161398. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161399. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161400. JMESSAGE(JTRC_EOI, "End Of Image")
  161401. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161402. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161403. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161404. "Warning: thumbnail image size does not match data length %u")
  161405. JMESSAGE(JTRC_JFIF_EXTENSION,
  161406. "JFIF extension marker: type 0x%02x, length %u")
  161407. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161408. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161409. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161410. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161411. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161412. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161413. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161414. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161415. JMESSAGE(JTRC_RST, "RST%d")
  161416. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161417. "Smoothing not supported with nonstandard sampling ratios")
  161418. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161419. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161420. JMESSAGE(JTRC_SOI, "Start of Image")
  161421. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161422. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161423. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161424. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161425. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161426. JMESSAGE(JTRC_THUMB_JPEG,
  161427. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161428. JMESSAGE(JTRC_THUMB_PALETTE,
  161429. "JFIF extension marker: palette thumbnail image, length %u")
  161430. JMESSAGE(JTRC_THUMB_RGB,
  161431. "JFIF extension marker: RGB thumbnail image, length %u")
  161432. JMESSAGE(JTRC_UNKNOWN_IDS,
  161433. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161434. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161435. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161436. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161437. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161438. "Inconsistent progression sequence for component %d coefficient %d")
  161439. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161440. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161441. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161442. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161443. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161444. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161445. JMESSAGE(JWRN_MUST_RESYNC,
  161446. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161447. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161448. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161449. #ifdef JMAKE_ENUM_LIST
  161450. JMSG_LASTMSGCODE
  161451. } J_MESSAGE_CODE;
  161452. #undef JMAKE_ENUM_LIST
  161453. #endif /* JMAKE_ENUM_LIST */
  161454. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161455. #undef JMESSAGE
  161456. #ifndef JERROR_H
  161457. #define JERROR_H
  161458. /* Macros to simplify using the error and trace message stuff */
  161459. /* The first parameter is either type of cinfo pointer */
  161460. /* Fatal errors (print message and exit) */
  161461. #define ERREXIT(cinfo,code) \
  161462. ((cinfo)->err->msg_code = (code), \
  161463. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161464. #define ERREXIT1(cinfo,code,p1) \
  161465. ((cinfo)->err->msg_code = (code), \
  161466. (cinfo)->err->msg_parm.i[0] = (p1), \
  161467. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161468. #define ERREXIT2(cinfo,code,p1,p2) \
  161469. ((cinfo)->err->msg_code = (code), \
  161470. (cinfo)->err->msg_parm.i[0] = (p1), \
  161471. (cinfo)->err->msg_parm.i[1] = (p2), \
  161472. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161473. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161474. ((cinfo)->err->msg_code = (code), \
  161475. (cinfo)->err->msg_parm.i[0] = (p1), \
  161476. (cinfo)->err->msg_parm.i[1] = (p2), \
  161477. (cinfo)->err->msg_parm.i[2] = (p3), \
  161478. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161479. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161480. ((cinfo)->err->msg_code = (code), \
  161481. (cinfo)->err->msg_parm.i[0] = (p1), \
  161482. (cinfo)->err->msg_parm.i[1] = (p2), \
  161483. (cinfo)->err->msg_parm.i[2] = (p3), \
  161484. (cinfo)->err->msg_parm.i[3] = (p4), \
  161485. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161486. #define ERREXITS(cinfo,code,str) \
  161487. ((cinfo)->err->msg_code = (code), \
  161488. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161489. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161490. #define MAKESTMT(stuff) do { stuff } while (0)
  161491. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161492. #define WARNMS(cinfo,code) \
  161493. ((cinfo)->err->msg_code = (code), \
  161494. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161495. #define WARNMS1(cinfo,code,p1) \
  161496. ((cinfo)->err->msg_code = (code), \
  161497. (cinfo)->err->msg_parm.i[0] = (p1), \
  161498. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161499. #define WARNMS2(cinfo,code,p1,p2) \
  161500. ((cinfo)->err->msg_code = (code), \
  161501. (cinfo)->err->msg_parm.i[0] = (p1), \
  161502. (cinfo)->err->msg_parm.i[1] = (p2), \
  161503. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161504. /* Informational/debugging messages */
  161505. #define TRACEMS(cinfo,lvl,code) \
  161506. ((cinfo)->err->msg_code = (code), \
  161507. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161508. #define TRACEMS1(cinfo,lvl,code,p1) \
  161509. ((cinfo)->err->msg_code = (code), \
  161510. (cinfo)->err->msg_parm.i[0] = (p1), \
  161511. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161512. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161513. ((cinfo)->err->msg_code = (code), \
  161514. (cinfo)->err->msg_parm.i[0] = (p1), \
  161515. (cinfo)->err->msg_parm.i[1] = (p2), \
  161516. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161517. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161518. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161519. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161520. (cinfo)->err->msg_code = (code); \
  161521. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161522. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161523. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161524. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161525. (cinfo)->err->msg_code = (code); \
  161526. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161527. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161528. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161529. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161530. _mp[4] = (p5); \
  161531. (cinfo)->err->msg_code = (code); \
  161532. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161533. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161534. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161535. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161536. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161537. (cinfo)->err->msg_code = (code); \
  161538. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161539. #define TRACEMSS(cinfo,lvl,code,str) \
  161540. ((cinfo)->err->msg_code = (code), \
  161541. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161542. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161543. #endif /* JERROR_H */
  161544. /*** End of inlined file: jerror.h ***/
  161545. /* fetch error codes too */
  161546. #endif
  161547. #endif /* JPEGLIB_H */
  161548. /*** End of inlined file: jpeglib.h ***/
  161549. /*** Start of inlined file: jcapimin.c ***/
  161550. #define JPEG_INTERNALS
  161551. /*** Start of inlined file: jinclude.h ***/
  161552. /* Include auto-config file to find out which system include files we need. */
  161553. #ifndef __jinclude_h__
  161554. #define __jinclude_h__
  161555. /*** Start of inlined file: jconfig.h ***/
  161556. /* see jconfig.doc for explanations */
  161557. // disable all the warnings under MSVC
  161558. #ifdef _MSC_VER
  161559. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161560. #endif
  161561. #ifdef __BORLANDC__
  161562. #pragma warn -8057
  161563. #pragma warn -8019
  161564. #pragma warn -8004
  161565. #pragma warn -8008
  161566. #endif
  161567. #define HAVE_PROTOTYPES
  161568. #define HAVE_UNSIGNED_CHAR
  161569. #define HAVE_UNSIGNED_SHORT
  161570. /* #define void char */
  161571. /* #define const */
  161572. #undef CHAR_IS_UNSIGNED
  161573. #define HAVE_STDDEF_H
  161574. #define HAVE_STDLIB_H
  161575. #undef NEED_BSD_STRINGS
  161576. #undef NEED_SYS_TYPES_H
  161577. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161578. #undef NEED_SHORT_EXTERNAL_NAMES
  161579. #undef INCOMPLETE_TYPES_BROKEN
  161580. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161581. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161582. typedef unsigned char boolean;
  161583. #endif
  161584. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161585. #ifdef JPEG_INTERNALS
  161586. #undef RIGHT_SHIFT_IS_UNSIGNED
  161587. #endif /* JPEG_INTERNALS */
  161588. #ifdef JPEG_CJPEG_DJPEG
  161589. #define BMP_SUPPORTED /* BMP image file format */
  161590. #define GIF_SUPPORTED /* GIF image file format */
  161591. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161592. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161593. #define TARGA_SUPPORTED /* Targa image file format */
  161594. #define TWO_FILE_COMMANDLINE /* optional */
  161595. #define USE_SETMODE /* Microsoft has setmode() */
  161596. #undef NEED_SIGNAL_CATCHER
  161597. #undef DONT_USE_B_MODE
  161598. #undef PROGRESS_REPORT /* optional */
  161599. #endif /* JPEG_CJPEG_DJPEG */
  161600. /*** End of inlined file: jconfig.h ***/
  161601. /* auto configuration options */
  161602. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161603. /*
  161604. * We need the NULL macro and size_t typedef.
  161605. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161606. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161607. * pull in <sys/types.h> as well.
  161608. * Note that the core JPEG library does not require <stdio.h>;
  161609. * only the default error handler and data source/destination modules do.
  161610. * But we must pull it in because of the references to FILE in jpeglib.h.
  161611. * You can remove those references if you want to compile without <stdio.h>.
  161612. */
  161613. #ifdef HAVE_STDDEF_H
  161614. #include <stddef.h>
  161615. #endif
  161616. #ifdef HAVE_STDLIB_H
  161617. #include <stdlib.h>
  161618. #endif
  161619. #ifdef NEED_SYS_TYPES_H
  161620. #include <sys/types.h>
  161621. #endif
  161622. #include <stdio.h>
  161623. /*
  161624. * We need memory copying and zeroing functions, plus strncpy().
  161625. * ANSI and System V implementations declare these in <string.h>.
  161626. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161627. * Some systems may declare memset and memcpy in <memory.h>.
  161628. *
  161629. * NOTE: we assume the size parameters to these functions are of type size_t.
  161630. * Change the casts in these macros if not!
  161631. */
  161632. #ifdef NEED_BSD_STRINGS
  161633. #include <strings.h>
  161634. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161635. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161636. #else /* not BSD, assume ANSI/SysV string lib */
  161637. #include <string.h>
  161638. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161639. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161640. #endif
  161641. /*
  161642. * In ANSI C, and indeed any rational implementation, size_t is also the
  161643. * type returned by sizeof(). However, it seems there are some irrational
  161644. * implementations out there, in which sizeof() returns an int even though
  161645. * size_t is defined as long or unsigned long. To ensure consistent results
  161646. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161647. */
  161648. #define SIZEOF(object) ((size_t) sizeof(object))
  161649. /*
  161650. * The modules that use fread() and fwrite() always invoke them through
  161651. * these macros. On some systems you may need to twiddle the argument casts.
  161652. * CAUTION: argument order is different from underlying functions!
  161653. */
  161654. #define JFREAD(file,buf,sizeofbuf) \
  161655. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161656. #define JFWRITE(file,buf,sizeofbuf) \
  161657. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161658. typedef enum { /* JPEG marker codes */
  161659. M_SOF0 = 0xc0,
  161660. M_SOF1 = 0xc1,
  161661. M_SOF2 = 0xc2,
  161662. M_SOF3 = 0xc3,
  161663. M_SOF5 = 0xc5,
  161664. M_SOF6 = 0xc6,
  161665. M_SOF7 = 0xc7,
  161666. M_JPG = 0xc8,
  161667. M_SOF9 = 0xc9,
  161668. M_SOF10 = 0xca,
  161669. M_SOF11 = 0xcb,
  161670. M_SOF13 = 0xcd,
  161671. M_SOF14 = 0xce,
  161672. M_SOF15 = 0xcf,
  161673. M_DHT = 0xc4,
  161674. M_DAC = 0xcc,
  161675. M_RST0 = 0xd0,
  161676. M_RST1 = 0xd1,
  161677. M_RST2 = 0xd2,
  161678. M_RST3 = 0xd3,
  161679. M_RST4 = 0xd4,
  161680. M_RST5 = 0xd5,
  161681. M_RST6 = 0xd6,
  161682. M_RST7 = 0xd7,
  161683. M_SOI = 0xd8,
  161684. M_EOI = 0xd9,
  161685. M_SOS = 0xda,
  161686. M_DQT = 0xdb,
  161687. M_DNL = 0xdc,
  161688. M_DRI = 0xdd,
  161689. M_DHP = 0xde,
  161690. M_EXP = 0xdf,
  161691. M_APP0 = 0xe0,
  161692. M_APP1 = 0xe1,
  161693. M_APP2 = 0xe2,
  161694. M_APP3 = 0xe3,
  161695. M_APP4 = 0xe4,
  161696. M_APP5 = 0xe5,
  161697. M_APP6 = 0xe6,
  161698. M_APP7 = 0xe7,
  161699. M_APP8 = 0xe8,
  161700. M_APP9 = 0xe9,
  161701. M_APP10 = 0xea,
  161702. M_APP11 = 0xeb,
  161703. M_APP12 = 0xec,
  161704. M_APP13 = 0xed,
  161705. M_APP14 = 0xee,
  161706. M_APP15 = 0xef,
  161707. M_JPG0 = 0xf0,
  161708. M_JPG13 = 0xfd,
  161709. M_COM = 0xfe,
  161710. M_TEM = 0x01,
  161711. M_ERROR = 0x100
  161712. } JPEG_MARKER;
  161713. /*
  161714. * Figure F.12: extend sign bit.
  161715. * On some machines, a shift and add will be faster than a table lookup.
  161716. */
  161717. #ifdef AVOID_TABLES
  161718. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161719. #else
  161720. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161721. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161722. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161723. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161724. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161725. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161726. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161727. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161728. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161729. #endif /* AVOID_TABLES */
  161730. #endif
  161731. /*** End of inlined file: jinclude.h ***/
  161732. /*
  161733. * Initialization of a JPEG compression object.
  161734. * The error manager must already be set up (in case memory manager fails).
  161735. */
  161736. GLOBAL(void)
  161737. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161738. {
  161739. int i;
  161740. /* Guard against version mismatches between library and caller. */
  161741. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161742. if (version != JPEG_LIB_VERSION)
  161743. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161744. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161745. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161746. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161747. /* For debugging purposes, we zero the whole master structure.
  161748. * But the application has already set the err pointer, and may have set
  161749. * client_data, so we have to save and restore those fields.
  161750. * Note: if application hasn't set client_data, tools like Purify may
  161751. * complain here.
  161752. */
  161753. {
  161754. struct jpeg_error_mgr * err = cinfo->err;
  161755. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161756. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161757. cinfo->err = err;
  161758. cinfo->client_data = client_data;
  161759. }
  161760. cinfo->is_decompressor = FALSE;
  161761. /* Initialize a memory manager instance for this object */
  161762. jinit_memory_mgr((j_common_ptr) cinfo);
  161763. /* Zero out pointers to permanent structures. */
  161764. cinfo->progress = NULL;
  161765. cinfo->dest = NULL;
  161766. cinfo->comp_info = NULL;
  161767. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161768. cinfo->quant_tbl_ptrs[i] = NULL;
  161769. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161770. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161771. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161772. }
  161773. cinfo->script_space = NULL;
  161774. cinfo->input_gamma = 1.0; /* in case application forgets */
  161775. /* OK, I'm ready */
  161776. cinfo->global_state = CSTATE_START;
  161777. }
  161778. /*
  161779. * Destruction of a JPEG compression object
  161780. */
  161781. GLOBAL(void)
  161782. jpeg_destroy_compress (j_compress_ptr cinfo)
  161783. {
  161784. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161785. }
  161786. /*
  161787. * Abort processing of a JPEG compression operation,
  161788. * but don't destroy the object itself.
  161789. */
  161790. GLOBAL(void)
  161791. jpeg_abort_compress (j_compress_ptr cinfo)
  161792. {
  161793. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161794. }
  161795. /*
  161796. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161797. * Marks all currently defined tables as already written (if suppress)
  161798. * or not written (if !suppress). This will control whether they get emitted
  161799. * by a subsequent jpeg_start_compress call.
  161800. *
  161801. * This routine is exported for use by applications that want to produce
  161802. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161803. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161804. * jcparam.o would be linked whether the application used it or not.
  161805. */
  161806. GLOBAL(void)
  161807. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161808. {
  161809. int i;
  161810. JQUANT_TBL * qtbl;
  161811. JHUFF_TBL * htbl;
  161812. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161813. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161814. qtbl->sent_table = suppress;
  161815. }
  161816. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161817. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161818. htbl->sent_table = suppress;
  161819. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161820. htbl->sent_table = suppress;
  161821. }
  161822. }
  161823. /*
  161824. * Finish JPEG compression.
  161825. *
  161826. * If a multipass operating mode was selected, this may do a great deal of
  161827. * work including most of the actual output.
  161828. */
  161829. GLOBAL(void)
  161830. jpeg_finish_compress (j_compress_ptr cinfo)
  161831. {
  161832. JDIMENSION iMCU_row;
  161833. if (cinfo->global_state == CSTATE_SCANNING ||
  161834. cinfo->global_state == CSTATE_RAW_OK) {
  161835. /* Terminate first pass */
  161836. if (cinfo->next_scanline < cinfo->image_height)
  161837. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161838. (*cinfo->master->finish_pass) (cinfo);
  161839. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161840. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161841. /* Perform any remaining passes */
  161842. while (! cinfo->master->is_last_pass) {
  161843. (*cinfo->master->prepare_for_pass) (cinfo);
  161844. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161845. if (cinfo->progress != NULL) {
  161846. cinfo->progress->pass_counter = (long) iMCU_row;
  161847. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161848. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161849. }
  161850. /* We bypass the main controller and invoke coef controller directly;
  161851. * all work is being done from the coefficient buffer.
  161852. */
  161853. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161854. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161855. }
  161856. (*cinfo->master->finish_pass) (cinfo);
  161857. }
  161858. /* Write EOI, do final cleanup */
  161859. (*cinfo->marker->write_file_trailer) (cinfo);
  161860. (*cinfo->dest->term_destination) (cinfo);
  161861. /* We can use jpeg_abort to release memory and reset global_state */
  161862. jpeg_abort((j_common_ptr) cinfo);
  161863. }
  161864. /*
  161865. * Write a special marker.
  161866. * This is only recommended for writing COM or APPn markers.
  161867. * Must be called after jpeg_start_compress() and before
  161868. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161869. */
  161870. GLOBAL(void)
  161871. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161872. const JOCTET *dataptr, unsigned int datalen)
  161873. {
  161874. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161875. if (cinfo->next_scanline != 0 ||
  161876. (cinfo->global_state != CSTATE_SCANNING &&
  161877. cinfo->global_state != CSTATE_RAW_OK &&
  161878. cinfo->global_state != CSTATE_WRCOEFS))
  161879. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161880. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161881. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161882. while (datalen--) {
  161883. (*write_marker_byte) (cinfo, *dataptr);
  161884. dataptr++;
  161885. }
  161886. }
  161887. /* Same, but piecemeal. */
  161888. GLOBAL(void)
  161889. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161890. {
  161891. if (cinfo->next_scanline != 0 ||
  161892. (cinfo->global_state != CSTATE_SCANNING &&
  161893. cinfo->global_state != CSTATE_RAW_OK &&
  161894. cinfo->global_state != CSTATE_WRCOEFS))
  161895. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161896. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161897. }
  161898. GLOBAL(void)
  161899. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161900. {
  161901. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161902. }
  161903. /*
  161904. * Alternate compression function: just write an abbreviated table file.
  161905. * Before calling this, all parameters and a data destination must be set up.
  161906. *
  161907. * To produce a pair of files containing abbreviated tables and abbreviated
  161908. * image data, one would proceed as follows:
  161909. *
  161910. * initialize JPEG object
  161911. * set JPEG parameters
  161912. * set destination to table file
  161913. * jpeg_write_tables(cinfo);
  161914. * set destination to image file
  161915. * jpeg_start_compress(cinfo, FALSE);
  161916. * write data...
  161917. * jpeg_finish_compress(cinfo);
  161918. *
  161919. * jpeg_write_tables has the side effect of marking all tables written
  161920. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161921. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161922. */
  161923. GLOBAL(void)
  161924. jpeg_write_tables (j_compress_ptr cinfo)
  161925. {
  161926. if (cinfo->global_state != CSTATE_START)
  161927. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161928. /* (Re)initialize error mgr and destination modules */
  161929. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161930. (*cinfo->dest->init_destination) (cinfo);
  161931. /* Initialize the marker writer ... bit of a crock to do it here. */
  161932. jinit_marker_writer(cinfo);
  161933. /* Write them tables! */
  161934. (*cinfo->marker->write_tables_only) (cinfo);
  161935. /* And clean up. */
  161936. (*cinfo->dest->term_destination) (cinfo);
  161937. /*
  161938. * In library releases up through v6a, we called jpeg_abort() here to free
  161939. * any working memory allocated by the destination manager and marker
  161940. * writer. Some applications had a problem with that: they allocated space
  161941. * of their own from the library memory manager, and didn't want it to go
  161942. * away during write_tables. So now we do nothing. This will cause a
  161943. * memory leak if an app calls write_tables repeatedly without doing a full
  161944. * compression cycle or otherwise resetting the JPEG object. However, that
  161945. * seems less bad than unexpectedly freeing memory in the normal case.
  161946. * An app that prefers the old behavior can call jpeg_abort for itself after
  161947. * each call to jpeg_write_tables().
  161948. */
  161949. }
  161950. /*** End of inlined file: jcapimin.c ***/
  161951. /*** Start of inlined file: jcapistd.c ***/
  161952. #define JPEG_INTERNALS
  161953. /*
  161954. * Compression initialization.
  161955. * Before calling this, all parameters and a data destination must be set up.
  161956. *
  161957. * We require a write_all_tables parameter as a failsafe check when writing
  161958. * multiple datastreams from the same compression object. Since prior runs
  161959. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161960. * would emit an abbreviated stream (no tables) by default. This may be what
  161961. * is wanted, but for safety's sake it should not be the default behavior:
  161962. * programmers should have to make a deliberate choice to emit abbreviated
  161963. * images. Therefore the documentation and examples should encourage people
  161964. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161965. * wrong thing.
  161966. */
  161967. GLOBAL(void)
  161968. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161969. {
  161970. if (cinfo->global_state != CSTATE_START)
  161971. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161972. if (write_all_tables)
  161973. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161974. /* (Re)initialize error mgr and destination modules */
  161975. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161976. (*cinfo->dest->init_destination) (cinfo);
  161977. /* Perform master selection of active modules */
  161978. jinit_compress_master(cinfo);
  161979. /* Set up for the first pass */
  161980. (*cinfo->master->prepare_for_pass) (cinfo);
  161981. /* Ready for application to drive first pass through jpeg_write_scanlines
  161982. * or jpeg_write_raw_data.
  161983. */
  161984. cinfo->next_scanline = 0;
  161985. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161986. }
  161987. /*
  161988. * Write some scanlines of data to the JPEG compressor.
  161989. *
  161990. * The return value will be the number of lines actually written.
  161991. * This should be less than the supplied num_lines only in case that
  161992. * the data destination module has requested suspension of the compressor,
  161993. * or if more than image_height scanlines are passed in.
  161994. *
  161995. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161996. * this likely signals an application programmer error. However,
  161997. * excess scanlines passed in the last valid call are *silently* ignored,
  161998. * so that the application need not adjust num_lines for end-of-image
  161999. * when using a multiple-scanline buffer.
  162000. */
  162001. GLOBAL(JDIMENSION)
  162002. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  162003. JDIMENSION num_lines)
  162004. {
  162005. JDIMENSION row_ctr, rows_left;
  162006. if (cinfo->global_state != CSTATE_SCANNING)
  162007. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162008. if (cinfo->next_scanline >= cinfo->image_height)
  162009. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162010. /* Call progress monitor hook if present */
  162011. if (cinfo->progress != NULL) {
  162012. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162013. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162014. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162015. }
  162016. /* Give master control module another chance if this is first call to
  162017. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  162018. * delayed so that application can write COM, etc, markers between
  162019. * jpeg_start_compress and jpeg_write_scanlines.
  162020. */
  162021. if (cinfo->master->call_pass_startup)
  162022. (*cinfo->master->pass_startup) (cinfo);
  162023. /* Ignore any extra scanlines at bottom of image. */
  162024. rows_left = cinfo->image_height - cinfo->next_scanline;
  162025. if (num_lines > rows_left)
  162026. num_lines = rows_left;
  162027. row_ctr = 0;
  162028. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  162029. cinfo->next_scanline += row_ctr;
  162030. return row_ctr;
  162031. }
  162032. /*
  162033. * Alternate entry point to write raw data.
  162034. * Processes exactly one iMCU row per call, unless suspended.
  162035. */
  162036. GLOBAL(JDIMENSION)
  162037. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  162038. JDIMENSION num_lines)
  162039. {
  162040. JDIMENSION lines_per_iMCU_row;
  162041. if (cinfo->global_state != CSTATE_RAW_OK)
  162042. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162043. if (cinfo->next_scanline >= cinfo->image_height) {
  162044. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162045. return 0;
  162046. }
  162047. /* Call progress monitor hook if present */
  162048. if (cinfo->progress != NULL) {
  162049. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162050. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162051. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162052. }
  162053. /* Give master control module another chance if this is first call to
  162054. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  162055. * delayed so that application can write COM, etc, markers between
  162056. * jpeg_start_compress and jpeg_write_raw_data.
  162057. */
  162058. if (cinfo->master->call_pass_startup)
  162059. (*cinfo->master->pass_startup) (cinfo);
  162060. /* Verify that at least one iMCU row has been passed. */
  162061. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  162062. if (num_lines < lines_per_iMCU_row)
  162063. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162064. /* Directly compress the row. */
  162065. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  162066. /* If compressor did not consume the whole row, suspend processing. */
  162067. return 0;
  162068. }
  162069. /* OK, we processed one iMCU row. */
  162070. cinfo->next_scanline += lines_per_iMCU_row;
  162071. return lines_per_iMCU_row;
  162072. }
  162073. /*** End of inlined file: jcapistd.c ***/
  162074. /*** Start of inlined file: jccoefct.c ***/
  162075. #define JPEG_INTERNALS
  162076. /* We use a full-image coefficient buffer when doing Huffman optimization,
  162077. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  162078. * step is run during the first pass, and subsequent passes need only read
  162079. * the buffered coefficients.
  162080. */
  162081. #ifdef ENTROPY_OPT_SUPPORTED
  162082. #define FULL_COEF_BUFFER_SUPPORTED
  162083. #else
  162084. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162085. #define FULL_COEF_BUFFER_SUPPORTED
  162086. #endif
  162087. #endif
  162088. /* Private buffer controller object */
  162089. typedef struct {
  162090. struct jpeg_c_coef_controller pub; /* public fields */
  162091. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162092. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162093. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162094. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162095. /* For single-pass compression, it's sufficient to buffer just one MCU
  162096. * (although this may prove a bit slow in practice). We allocate a
  162097. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  162098. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  162099. * it's not really very big; this is to keep the module interfaces unchanged
  162100. * when a large coefficient buffer is necessary.)
  162101. * In multi-pass modes, this array points to the current MCU's blocks
  162102. * within the virtual arrays.
  162103. */
  162104. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162105. /* In multi-pass modes, we need a virtual block array for each component. */
  162106. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162107. } my_coef_controller;
  162108. typedef my_coef_controller * my_coef_ptr;
  162109. /* Forward declarations */
  162110. METHODDEF(boolean) compress_data
  162111. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162112. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162113. METHODDEF(boolean) compress_first_pass
  162114. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162115. METHODDEF(boolean) compress_output
  162116. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162117. #endif
  162118. LOCAL(void)
  162119. start_iMCU_row (j_compress_ptr cinfo)
  162120. /* Reset within-iMCU-row counters for a new row */
  162121. {
  162122. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162123. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162124. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162125. * But at the bottom of the image, process only what's left.
  162126. */
  162127. if (cinfo->comps_in_scan > 1) {
  162128. coef->MCU_rows_per_iMCU_row = 1;
  162129. } else {
  162130. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162131. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162132. else
  162133. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162134. }
  162135. coef->mcu_ctr = 0;
  162136. coef->MCU_vert_offset = 0;
  162137. }
  162138. /*
  162139. * Initialize for a processing pass.
  162140. */
  162141. METHODDEF(void)
  162142. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162143. {
  162144. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162145. coef->iMCU_row_num = 0;
  162146. start_iMCU_row(cinfo);
  162147. switch (pass_mode) {
  162148. case JBUF_PASS_THRU:
  162149. if (coef->whole_image[0] != NULL)
  162150. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162151. coef->pub.compress_data = compress_data;
  162152. break;
  162153. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162154. case JBUF_SAVE_AND_PASS:
  162155. if (coef->whole_image[0] == NULL)
  162156. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162157. coef->pub.compress_data = compress_first_pass;
  162158. break;
  162159. case JBUF_CRANK_DEST:
  162160. if (coef->whole_image[0] == NULL)
  162161. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162162. coef->pub.compress_data = compress_output;
  162163. break;
  162164. #endif
  162165. default:
  162166. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162167. break;
  162168. }
  162169. }
  162170. /*
  162171. * Process some data in the single-pass case.
  162172. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162173. * per call, ie, v_samp_factor block rows for each component in the image.
  162174. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162175. *
  162176. * NB: input_buf contains a plane for each component in image,
  162177. * which we index according to the component's SOF position.
  162178. */
  162179. METHODDEF(boolean)
  162180. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162181. {
  162182. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162183. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162184. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162185. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162186. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162187. JDIMENSION ypos, xpos;
  162188. jpeg_component_info *compptr;
  162189. /* Loop to write as much as one whole iMCU row */
  162190. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162191. yoffset++) {
  162192. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162193. MCU_col_num++) {
  162194. /* Determine where data comes from in input_buf and do the DCT thing.
  162195. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162196. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162197. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162198. * specially. The data in them does not matter for image reconstruction,
  162199. * so we fill them with values that will encode to the smallest amount of
  162200. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162201. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162202. */
  162203. blkn = 0;
  162204. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162205. compptr = cinfo->cur_comp_info[ci];
  162206. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162207. : compptr->last_col_width;
  162208. xpos = MCU_col_num * compptr->MCU_sample_width;
  162209. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162210. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162211. if (coef->iMCU_row_num < last_iMCU_row ||
  162212. yoffset+yindex < compptr->last_row_height) {
  162213. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162214. input_buf[compptr->component_index],
  162215. coef->MCU_buffer[blkn],
  162216. ypos, xpos, (JDIMENSION) blockcnt);
  162217. if (blockcnt < compptr->MCU_width) {
  162218. /* Create some dummy blocks at the right edge of the image. */
  162219. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162220. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162221. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162222. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162223. }
  162224. }
  162225. } else {
  162226. /* Create a row of dummy blocks at the bottom of the image. */
  162227. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162228. compptr->MCU_width * SIZEOF(JBLOCK));
  162229. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162230. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162231. }
  162232. }
  162233. blkn += compptr->MCU_width;
  162234. ypos += DCTSIZE;
  162235. }
  162236. }
  162237. /* Try to write the MCU. In event of a suspension failure, we will
  162238. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162239. */
  162240. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162241. /* Suspension forced; update state counters and exit */
  162242. coef->MCU_vert_offset = yoffset;
  162243. coef->mcu_ctr = MCU_col_num;
  162244. return FALSE;
  162245. }
  162246. }
  162247. /* Completed an MCU row, but perhaps not an iMCU row */
  162248. coef->mcu_ctr = 0;
  162249. }
  162250. /* Completed the iMCU row, advance counters for next one */
  162251. coef->iMCU_row_num++;
  162252. start_iMCU_row(cinfo);
  162253. return TRUE;
  162254. }
  162255. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162256. /*
  162257. * Process some data in the first pass of a multi-pass case.
  162258. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162259. * per call, ie, v_samp_factor block rows for each component in the image.
  162260. * This amount of data is read from the source buffer, DCT'd and quantized,
  162261. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162262. * as needed at the right and lower edges. (The dummy blocks are constructed
  162263. * in the virtual arrays, which have been padded appropriately.) This makes
  162264. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162265. *
  162266. * We must also emit the data to the entropy encoder. This is conveniently
  162267. * done by calling compress_output() after we've loaded the current strip
  162268. * of the virtual arrays.
  162269. *
  162270. * NB: input_buf contains a plane for each component in image. All
  162271. * components are DCT'd and loaded into the virtual arrays in this pass.
  162272. * However, it may be that only a subset of the components are emitted to
  162273. * the entropy encoder during this first pass; be careful about looking
  162274. * at the scan-dependent variables (MCU dimensions, etc).
  162275. */
  162276. METHODDEF(boolean)
  162277. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162278. {
  162279. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162280. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162281. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162282. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162283. JCOEF lastDC;
  162284. jpeg_component_info *compptr;
  162285. JBLOCKARRAY buffer;
  162286. JBLOCKROW thisblockrow, lastblockrow;
  162287. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162288. ci++, compptr++) {
  162289. /* Align the virtual buffer for this component. */
  162290. buffer = (*cinfo->mem->access_virt_barray)
  162291. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162292. coef->iMCU_row_num * compptr->v_samp_factor,
  162293. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162294. /* Count non-dummy DCT block rows in this iMCU row. */
  162295. if (coef->iMCU_row_num < last_iMCU_row)
  162296. block_rows = compptr->v_samp_factor;
  162297. else {
  162298. /* NB: can't use last_row_height here, since may not be set! */
  162299. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162300. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162301. }
  162302. blocks_across = compptr->width_in_blocks;
  162303. h_samp_factor = compptr->h_samp_factor;
  162304. /* Count number of dummy blocks to be added at the right margin. */
  162305. ndummy = (int) (blocks_across % h_samp_factor);
  162306. if (ndummy > 0)
  162307. ndummy = h_samp_factor - ndummy;
  162308. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162309. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162310. */
  162311. for (block_row = 0; block_row < block_rows; block_row++) {
  162312. thisblockrow = buffer[block_row];
  162313. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162314. input_buf[ci], thisblockrow,
  162315. (JDIMENSION) (block_row * DCTSIZE),
  162316. (JDIMENSION) 0, blocks_across);
  162317. if (ndummy > 0) {
  162318. /* Create dummy blocks at the right edge of the image. */
  162319. thisblockrow += blocks_across; /* => first dummy block */
  162320. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162321. lastDC = thisblockrow[-1][0];
  162322. for (bi = 0; bi < ndummy; bi++) {
  162323. thisblockrow[bi][0] = lastDC;
  162324. }
  162325. }
  162326. }
  162327. /* If at end of image, create dummy block rows as needed.
  162328. * The tricky part here is that within each MCU, we want the DC values
  162329. * of the dummy blocks to match the last real block's DC value.
  162330. * This squeezes a few more bytes out of the resulting file...
  162331. */
  162332. if (coef->iMCU_row_num == last_iMCU_row) {
  162333. blocks_across += ndummy; /* include lower right corner */
  162334. MCUs_across = blocks_across / h_samp_factor;
  162335. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162336. block_row++) {
  162337. thisblockrow = buffer[block_row];
  162338. lastblockrow = buffer[block_row-1];
  162339. jzero_far((void FAR *) thisblockrow,
  162340. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162341. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162342. lastDC = lastblockrow[h_samp_factor-1][0];
  162343. for (bi = 0; bi < h_samp_factor; bi++) {
  162344. thisblockrow[bi][0] = lastDC;
  162345. }
  162346. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162347. lastblockrow += h_samp_factor;
  162348. }
  162349. }
  162350. }
  162351. }
  162352. /* NB: compress_output will increment iMCU_row_num if successful.
  162353. * A suspension return will result in redoing all the work above next time.
  162354. */
  162355. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162356. return compress_output(cinfo, input_buf);
  162357. }
  162358. /*
  162359. * Process some data in subsequent passes of a multi-pass case.
  162360. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162361. * per call, ie, v_samp_factor block rows for each component in the scan.
  162362. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162363. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162364. *
  162365. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162366. */
  162367. METHODDEF(boolean)
  162368. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162369. {
  162370. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162371. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162372. int blkn, ci, xindex, yindex, yoffset;
  162373. JDIMENSION start_col;
  162374. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162375. JBLOCKROW buffer_ptr;
  162376. jpeg_component_info *compptr;
  162377. /* Align the virtual buffers for the components used in this scan.
  162378. * NB: during first pass, this is safe only because the buffers will
  162379. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162380. */
  162381. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162382. compptr = cinfo->cur_comp_info[ci];
  162383. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162384. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162385. coef->iMCU_row_num * compptr->v_samp_factor,
  162386. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162387. }
  162388. /* Loop to process one whole iMCU row */
  162389. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162390. yoffset++) {
  162391. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162392. MCU_col_num++) {
  162393. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162394. blkn = 0; /* index of current DCT block within MCU */
  162395. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162396. compptr = cinfo->cur_comp_info[ci];
  162397. start_col = MCU_col_num * compptr->MCU_width;
  162398. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162399. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162400. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162401. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162402. }
  162403. }
  162404. }
  162405. /* Try to write the MCU. */
  162406. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162407. /* Suspension forced; update state counters and exit */
  162408. coef->MCU_vert_offset = yoffset;
  162409. coef->mcu_ctr = MCU_col_num;
  162410. return FALSE;
  162411. }
  162412. }
  162413. /* Completed an MCU row, but perhaps not an iMCU row */
  162414. coef->mcu_ctr = 0;
  162415. }
  162416. /* Completed the iMCU row, advance counters for next one */
  162417. coef->iMCU_row_num++;
  162418. start_iMCU_row(cinfo);
  162419. return TRUE;
  162420. }
  162421. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162422. /*
  162423. * Initialize coefficient buffer controller.
  162424. */
  162425. GLOBAL(void)
  162426. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162427. {
  162428. my_coef_ptr coef;
  162429. coef = (my_coef_ptr)
  162430. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162431. SIZEOF(my_coef_controller));
  162432. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162433. coef->pub.start_pass = start_pass_coef;
  162434. /* Create the coefficient buffer. */
  162435. if (need_full_buffer) {
  162436. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162437. /* Allocate a full-image virtual array for each component, */
  162438. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162439. int ci;
  162440. jpeg_component_info *compptr;
  162441. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162442. ci++, compptr++) {
  162443. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162444. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162445. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162446. (long) compptr->h_samp_factor),
  162447. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162448. (long) compptr->v_samp_factor),
  162449. (JDIMENSION) compptr->v_samp_factor);
  162450. }
  162451. #else
  162452. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162453. #endif
  162454. } else {
  162455. /* We only need a single-MCU buffer. */
  162456. JBLOCKROW buffer;
  162457. int i;
  162458. buffer = (JBLOCKROW)
  162459. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162460. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162461. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162462. coef->MCU_buffer[i] = buffer + i;
  162463. }
  162464. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162465. }
  162466. }
  162467. /*** End of inlined file: jccoefct.c ***/
  162468. /*** Start of inlined file: jccolor.c ***/
  162469. #define JPEG_INTERNALS
  162470. /* Private subobject */
  162471. typedef struct {
  162472. struct jpeg_color_converter pub; /* public fields */
  162473. /* Private state for RGB->YCC conversion */
  162474. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162475. } my_color_converter;
  162476. typedef my_color_converter * my_cconvert_ptr;
  162477. /**************** RGB -> YCbCr conversion: most common case **************/
  162478. /*
  162479. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162480. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162481. * The conversion equations to be implemented are therefore
  162482. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162483. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162484. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162485. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162486. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162487. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162488. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162489. * were not represented exactly. Now we sacrifice exact representation of
  162490. * maximum red and maximum blue in order to get exact grayscales.
  162491. *
  162492. * To avoid floating-point arithmetic, we represent the fractional constants
  162493. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162494. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162495. *
  162496. * For even more speed, we avoid doing any multiplications in the inner loop
  162497. * by precalculating the constants times R,G,B for all possible values.
  162498. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162499. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162500. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162501. * colorspace anyway.
  162502. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162503. * in the tables to save adding them separately in the inner loop.
  162504. */
  162505. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162506. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162507. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162508. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162509. /* We allocate one big table and divide it up into eight parts, instead of
  162510. * doing eight alloc_small requests. This lets us use a single table base
  162511. * address, which can be held in a register in the inner loops on many
  162512. * machines (more than can hold all eight addresses, anyway).
  162513. */
  162514. #define R_Y_OFF 0 /* offset to R => Y section */
  162515. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162516. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162517. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162518. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162519. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162520. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162521. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162522. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162523. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162524. /*
  162525. * Initialize for RGB->YCC colorspace conversion.
  162526. */
  162527. METHODDEF(void)
  162528. rgb_ycc_start (j_compress_ptr cinfo)
  162529. {
  162530. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162531. INT32 * rgb_ycc_tab;
  162532. INT32 i;
  162533. /* Allocate and fill in the conversion tables. */
  162534. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162535. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162536. (TABLE_SIZE * SIZEOF(INT32)));
  162537. for (i = 0; i <= MAXJSAMPLE; i++) {
  162538. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162539. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162540. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162541. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162542. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162543. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162544. * This ensures that the maximum output will round to MAXJSAMPLE
  162545. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162546. */
  162547. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162548. /* B=>Cb and R=>Cr tables are the same
  162549. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162550. */
  162551. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162552. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162553. }
  162554. }
  162555. /*
  162556. * Convert some rows of samples to the JPEG colorspace.
  162557. *
  162558. * Note that we change from the application's interleaved-pixel format
  162559. * to our internal noninterleaved, one-plane-per-component format.
  162560. * The input buffer is therefore three times as wide as the output buffer.
  162561. *
  162562. * A starting row offset is provided only for the output buffer. The caller
  162563. * can easily adjust the passed input_buf value to accommodate any row
  162564. * offset required on that side.
  162565. */
  162566. METHODDEF(void)
  162567. rgb_ycc_convert (j_compress_ptr cinfo,
  162568. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162569. JDIMENSION output_row, int num_rows)
  162570. {
  162571. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162572. register int r, g, b;
  162573. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162574. register JSAMPROW inptr;
  162575. register JSAMPROW outptr0, outptr1, outptr2;
  162576. register JDIMENSION col;
  162577. JDIMENSION num_cols = cinfo->image_width;
  162578. while (--num_rows >= 0) {
  162579. inptr = *input_buf++;
  162580. outptr0 = output_buf[0][output_row];
  162581. outptr1 = output_buf[1][output_row];
  162582. outptr2 = output_buf[2][output_row];
  162583. output_row++;
  162584. for (col = 0; col < num_cols; col++) {
  162585. r = GETJSAMPLE(inptr[RGB_RED]);
  162586. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162587. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162588. inptr += RGB_PIXELSIZE;
  162589. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162590. * must be too; we do not need an explicit range-limiting operation.
  162591. * Hence the value being shifted is never negative, and we don't
  162592. * need the general RIGHT_SHIFT macro.
  162593. */
  162594. /* Y */
  162595. outptr0[col] = (JSAMPLE)
  162596. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162597. >> SCALEBITS);
  162598. /* Cb */
  162599. outptr1[col] = (JSAMPLE)
  162600. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162601. >> SCALEBITS);
  162602. /* Cr */
  162603. outptr2[col] = (JSAMPLE)
  162604. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162605. >> SCALEBITS);
  162606. }
  162607. }
  162608. }
  162609. /**************** Cases other than RGB -> YCbCr **************/
  162610. /*
  162611. * Convert some rows of samples to the JPEG colorspace.
  162612. * This version handles RGB->grayscale conversion, which is the same
  162613. * as the RGB->Y portion of RGB->YCbCr.
  162614. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162615. */
  162616. METHODDEF(void)
  162617. rgb_gray_convert (j_compress_ptr cinfo,
  162618. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162619. JDIMENSION output_row, int num_rows)
  162620. {
  162621. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162622. register int r, g, b;
  162623. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162624. register JSAMPROW inptr;
  162625. register JSAMPROW outptr;
  162626. register JDIMENSION col;
  162627. JDIMENSION num_cols = cinfo->image_width;
  162628. while (--num_rows >= 0) {
  162629. inptr = *input_buf++;
  162630. outptr = output_buf[0][output_row];
  162631. output_row++;
  162632. for (col = 0; col < num_cols; col++) {
  162633. r = GETJSAMPLE(inptr[RGB_RED]);
  162634. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162635. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162636. inptr += RGB_PIXELSIZE;
  162637. /* Y */
  162638. outptr[col] = (JSAMPLE)
  162639. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162640. >> SCALEBITS);
  162641. }
  162642. }
  162643. }
  162644. /*
  162645. * Convert some rows of samples to the JPEG colorspace.
  162646. * This version handles Adobe-style CMYK->YCCK conversion,
  162647. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162648. * conversion as above, while passing K (black) unchanged.
  162649. * We assume rgb_ycc_start has been called.
  162650. */
  162651. METHODDEF(void)
  162652. cmyk_ycck_convert (j_compress_ptr cinfo,
  162653. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162654. JDIMENSION output_row, int num_rows)
  162655. {
  162656. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162657. register int r, g, b;
  162658. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162659. register JSAMPROW inptr;
  162660. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162661. register JDIMENSION col;
  162662. JDIMENSION num_cols = cinfo->image_width;
  162663. while (--num_rows >= 0) {
  162664. inptr = *input_buf++;
  162665. outptr0 = output_buf[0][output_row];
  162666. outptr1 = output_buf[1][output_row];
  162667. outptr2 = output_buf[2][output_row];
  162668. outptr3 = output_buf[3][output_row];
  162669. output_row++;
  162670. for (col = 0; col < num_cols; col++) {
  162671. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162672. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162673. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162674. /* K passes through as-is */
  162675. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162676. inptr += 4;
  162677. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162678. * must be too; we do not need an explicit range-limiting operation.
  162679. * Hence the value being shifted is never negative, and we don't
  162680. * need the general RIGHT_SHIFT macro.
  162681. */
  162682. /* Y */
  162683. outptr0[col] = (JSAMPLE)
  162684. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162685. >> SCALEBITS);
  162686. /* Cb */
  162687. outptr1[col] = (JSAMPLE)
  162688. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162689. >> SCALEBITS);
  162690. /* Cr */
  162691. outptr2[col] = (JSAMPLE)
  162692. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162693. >> SCALEBITS);
  162694. }
  162695. }
  162696. }
  162697. /*
  162698. * Convert some rows of samples to the JPEG colorspace.
  162699. * This version handles grayscale output with no conversion.
  162700. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162701. */
  162702. METHODDEF(void)
  162703. grayscale_convert (j_compress_ptr cinfo,
  162704. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162705. JDIMENSION output_row, int num_rows)
  162706. {
  162707. register JSAMPROW inptr;
  162708. register JSAMPROW outptr;
  162709. register JDIMENSION col;
  162710. JDIMENSION num_cols = cinfo->image_width;
  162711. int instride = cinfo->input_components;
  162712. while (--num_rows >= 0) {
  162713. inptr = *input_buf++;
  162714. outptr = output_buf[0][output_row];
  162715. output_row++;
  162716. for (col = 0; col < num_cols; col++) {
  162717. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162718. inptr += instride;
  162719. }
  162720. }
  162721. }
  162722. /*
  162723. * Convert some rows of samples to the JPEG colorspace.
  162724. * This version handles multi-component colorspaces without conversion.
  162725. * We assume input_components == num_components.
  162726. */
  162727. METHODDEF(void)
  162728. null_convert (j_compress_ptr cinfo,
  162729. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162730. JDIMENSION output_row, int num_rows)
  162731. {
  162732. register JSAMPROW inptr;
  162733. register JSAMPROW outptr;
  162734. register JDIMENSION col;
  162735. register int ci;
  162736. int nc = cinfo->num_components;
  162737. JDIMENSION num_cols = cinfo->image_width;
  162738. while (--num_rows >= 0) {
  162739. /* It seems fastest to make a separate pass for each component. */
  162740. for (ci = 0; ci < nc; ci++) {
  162741. inptr = *input_buf;
  162742. outptr = output_buf[ci][output_row];
  162743. for (col = 0; col < num_cols; col++) {
  162744. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162745. inptr += nc;
  162746. }
  162747. }
  162748. input_buf++;
  162749. output_row++;
  162750. }
  162751. }
  162752. /*
  162753. * Empty method for start_pass.
  162754. */
  162755. METHODDEF(void)
  162756. null_method (j_compress_ptr)
  162757. {
  162758. /* no work needed */
  162759. }
  162760. /*
  162761. * Module initialization routine for input colorspace conversion.
  162762. */
  162763. GLOBAL(void)
  162764. jinit_color_converter (j_compress_ptr cinfo)
  162765. {
  162766. my_cconvert_ptr cconvert;
  162767. cconvert = (my_cconvert_ptr)
  162768. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162769. SIZEOF(my_color_converter));
  162770. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162771. /* set start_pass to null method until we find out differently */
  162772. cconvert->pub.start_pass = null_method;
  162773. /* Make sure input_components agrees with in_color_space */
  162774. switch (cinfo->in_color_space) {
  162775. case JCS_GRAYSCALE:
  162776. if (cinfo->input_components != 1)
  162777. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162778. break;
  162779. case JCS_RGB:
  162780. #if RGB_PIXELSIZE != 3
  162781. if (cinfo->input_components != RGB_PIXELSIZE)
  162782. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162783. break;
  162784. #endif /* else share code with YCbCr */
  162785. case JCS_YCbCr:
  162786. if (cinfo->input_components != 3)
  162787. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162788. break;
  162789. case JCS_CMYK:
  162790. case JCS_YCCK:
  162791. if (cinfo->input_components != 4)
  162792. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162793. break;
  162794. default: /* JCS_UNKNOWN can be anything */
  162795. if (cinfo->input_components < 1)
  162796. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162797. break;
  162798. }
  162799. /* Check num_components, set conversion method based on requested space */
  162800. switch (cinfo->jpeg_color_space) {
  162801. case JCS_GRAYSCALE:
  162802. if (cinfo->num_components != 1)
  162803. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162804. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162805. cconvert->pub.color_convert = grayscale_convert;
  162806. else if (cinfo->in_color_space == JCS_RGB) {
  162807. cconvert->pub.start_pass = rgb_ycc_start;
  162808. cconvert->pub.color_convert = rgb_gray_convert;
  162809. } else if (cinfo->in_color_space == JCS_YCbCr)
  162810. cconvert->pub.color_convert = grayscale_convert;
  162811. else
  162812. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162813. break;
  162814. case JCS_RGB:
  162815. if (cinfo->num_components != 3)
  162816. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162817. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162818. cconvert->pub.color_convert = null_convert;
  162819. else
  162820. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162821. break;
  162822. case JCS_YCbCr:
  162823. if (cinfo->num_components != 3)
  162824. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162825. if (cinfo->in_color_space == JCS_RGB) {
  162826. cconvert->pub.start_pass = rgb_ycc_start;
  162827. cconvert->pub.color_convert = rgb_ycc_convert;
  162828. } else if (cinfo->in_color_space == JCS_YCbCr)
  162829. cconvert->pub.color_convert = null_convert;
  162830. else
  162831. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162832. break;
  162833. case JCS_CMYK:
  162834. if (cinfo->num_components != 4)
  162835. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162836. if (cinfo->in_color_space == JCS_CMYK)
  162837. cconvert->pub.color_convert = null_convert;
  162838. else
  162839. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162840. break;
  162841. case JCS_YCCK:
  162842. if (cinfo->num_components != 4)
  162843. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162844. if (cinfo->in_color_space == JCS_CMYK) {
  162845. cconvert->pub.start_pass = rgb_ycc_start;
  162846. cconvert->pub.color_convert = cmyk_ycck_convert;
  162847. } else if (cinfo->in_color_space == JCS_YCCK)
  162848. cconvert->pub.color_convert = null_convert;
  162849. else
  162850. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162851. break;
  162852. default: /* allow null conversion of JCS_UNKNOWN */
  162853. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162854. cinfo->num_components != cinfo->input_components)
  162855. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162856. cconvert->pub.color_convert = null_convert;
  162857. break;
  162858. }
  162859. }
  162860. /*** End of inlined file: jccolor.c ***/
  162861. #undef FIX
  162862. /*** Start of inlined file: jcdctmgr.c ***/
  162863. #define JPEG_INTERNALS
  162864. /*** Start of inlined file: jdct.h ***/
  162865. /*
  162866. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162867. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162868. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162869. * implementations use an array of type FAST_FLOAT, instead.)
  162870. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162871. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162872. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162873. * convention improves accuracy in integer implementations and saves some
  162874. * work in floating-point ones.
  162875. * Quantization of the output coefficients is done by jcdctmgr.c.
  162876. */
  162877. #ifndef __jdct_h__
  162878. #define __jdct_h__
  162879. #if BITS_IN_JSAMPLE == 8
  162880. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162881. #else
  162882. typedef INT32 DCTELEM; /* must have 32 bits */
  162883. #endif
  162884. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162885. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162886. /*
  162887. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162888. * to an output sample array. The routine must dequantize the input data as
  162889. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162890. * pointed to by compptr->dct_table. The output data is to be placed into the
  162891. * sample array starting at a specified column. (Any row offset needed will
  162892. * be applied to the array pointer before it is passed to the IDCT code.)
  162893. * Note that the number of samples emitted by the IDCT routine is
  162894. * DCT_scaled_size * DCT_scaled_size.
  162895. */
  162896. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162897. /*
  162898. * Each IDCT routine has its own ideas about the best dct_table element type.
  162899. */
  162900. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162901. #if BITS_IN_JSAMPLE == 8
  162902. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162903. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162904. #else
  162905. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162906. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162907. #endif
  162908. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162909. /*
  162910. * Each IDCT routine is responsible for range-limiting its results and
  162911. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162912. * be quite far out of range if the input data is corrupt, so a bulletproof
  162913. * range-limiting step is required. We use a mask-and-table-lookup method
  162914. * to do the combined operations quickly. See the comments with
  162915. * prepare_range_limit_table (in jdmaster.c) for more info.
  162916. */
  162917. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162918. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162919. /* Short forms of external names for systems with brain-damaged linkers. */
  162920. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162921. #define jpeg_fdct_islow jFDislow
  162922. #define jpeg_fdct_ifast jFDifast
  162923. #define jpeg_fdct_float jFDfloat
  162924. #define jpeg_idct_islow jRDislow
  162925. #define jpeg_idct_ifast jRDifast
  162926. #define jpeg_idct_float jRDfloat
  162927. #define jpeg_idct_4x4 jRD4x4
  162928. #define jpeg_idct_2x2 jRD2x2
  162929. #define jpeg_idct_1x1 jRD1x1
  162930. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162931. /* Extern declarations for the forward and inverse DCT routines. */
  162932. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162933. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162934. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162935. EXTERN(void) jpeg_idct_islow
  162936. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162937. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162938. EXTERN(void) jpeg_idct_ifast
  162939. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162940. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162941. EXTERN(void) jpeg_idct_float
  162942. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162943. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162944. EXTERN(void) jpeg_idct_4x4
  162945. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162946. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162947. EXTERN(void) jpeg_idct_2x2
  162948. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162949. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162950. EXTERN(void) jpeg_idct_1x1
  162951. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162952. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162953. /*
  162954. * Macros for handling fixed-point arithmetic; these are used by many
  162955. * but not all of the DCT/IDCT modules.
  162956. *
  162957. * All values are expected to be of type INT32.
  162958. * Fractional constants are scaled left by CONST_BITS bits.
  162959. * CONST_BITS is defined within each module using these macros,
  162960. * and may differ from one module to the next.
  162961. */
  162962. #define ONE ((INT32) 1)
  162963. #define CONST_SCALE (ONE << CONST_BITS)
  162964. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162965. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162966. * thus causing a lot of useless floating-point operations at run time.
  162967. */
  162968. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162969. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162970. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162971. * the fudge factor is correct for either sign of X.
  162972. */
  162973. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162974. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162975. * This macro is used only when the two inputs will actually be no more than
  162976. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162977. * full 32x32 multiply. This provides a useful speedup on many machines.
  162978. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162979. * in C, but some C compilers will do the right thing if you provide the
  162980. * correct combination of casts.
  162981. */
  162982. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162983. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162984. #endif
  162985. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162986. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162987. #endif
  162988. #ifndef MULTIPLY16C16 /* default definition */
  162989. #define MULTIPLY16C16(var,const) ((var) * (const))
  162990. #endif
  162991. /* Same except both inputs are variables. */
  162992. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162993. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162994. #endif
  162995. #ifndef MULTIPLY16V16 /* default definition */
  162996. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162997. #endif
  162998. #endif
  162999. /*** End of inlined file: jdct.h ***/
  163000. /* Private declarations for DCT subsystem */
  163001. /* Private subobject for this module */
  163002. typedef struct {
  163003. struct jpeg_forward_dct pub; /* public fields */
  163004. /* Pointer to the DCT routine actually in use */
  163005. forward_DCT_method_ptr do_dct;
  163006. /* The actual post-DCT divisors --- not identical to the quant table
  163007. * entries, because of scaling (especially for an unnormalized DCT).
  163008. * Each table is given in normal array order.
  163009. */
  163010. DCTELEM * divisors[NUM_QUANT_TBLS];
  163011. #ifdef DCT_FLOAT_SUPPORTED
  163012. /* Same as above for the floating-point case. */
  163013. float_DCT_method_ptr do_float_dct;
  163014. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  163015. #endif
  163016. } my_fdct_controller;
  163017. typedef my_fdct_controller * my_fdct_ptr;
  163018. /*
  163019. * Initialize for a processing pass.
  163020. * Verify that all referenced Q-tables are present, and set up
  163021. * the divisor table for each one.
  163022. * In the current implementation, DCT of all components is done during
  163023. * the first pass, even if only some components will be output in the
  163024. * first scan. Hence all components should be examined here.
  163025. */
  163026. METHODDEF(void)
  163027. start_pass_fdctmgr (j_compress_ptr cinfo)
  163028. {
  163029. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163030. int ci, qtblno, i;
  163031. jpeg_component_info *compptr;
  163032. JQUANT_TBL * qtbl;
  163033. DCTELEM * dtbl;
  163034. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163035. ci++, compptr++) {
  163036. qtblno = compptr->quant_tbl_no;
  163037. /* Make sure specified quantization table is present */
  163038. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163039. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163040. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163041. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  163042. /* Compute divisors for this quant table */
  163043. /* We may do this more than once for same table, but it's not a big deal */
  163044. switch (cinfo->dct_method) {
  163045. #ifdef DCT_ISLOW_SUPPORTED
  163046. case JDCT_ISLOW:
  163047. /* For LL&M IDCT method, divisors are equal to raw quantization
  163048. * coefficients multiplied by 8 (to counteract scaling).
  163049. */
  163050. if (fdct->divisors[qtblno] == NULL) {
  163051. fdct->divisors[qtblno] = (DCTELEM *)
  163052. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163053. DCTSIZE2 * SIZEOF(DCTELEM));
  163054. }
  163055. dtbl = fdct->divisors[qtblno];
  163056. for (i = 0; i < DCTSIZE2; i++) {
  163057. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  163058. }
  163059. break;
  163060. #endif
  163061. #ifdef DCT_IFAST_SUPPORTED
  163062. case JDCT_IFAST:
  163063. {
  163064. /* For AA&N IDCT method, divisors are equal to quantization
  163065. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163066. * scalefactor[0] = 1
  163067. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163068. * We apply a further scale factor of 8.
  163069. */
  163070. #define CONST_BITS 14
  163071. static const INT16 aanscales[DCTSIZE2] = {
  163072. /* precomputed values scaled up by 14 bits */
  163073. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163074. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163075. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163076. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163077. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163078. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163079. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163080. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163081. };
  163082. SHIFT_TEMPS
  163083. if (fdct->divisors[qtblno] == NULL) {
  163084. fdct->divisors[qtblno] = (DCTELEM *)
  163085. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163086. DCTSIZE2 * SIZEOF(DCTELEM));
  163087. }
  163088. dtbl = fdct->divisors[qtblno];
  163089. for (i = 0; i < DCTSIZE2; i++) {
  163090. dtbl[i] = (DCTELEM)
  163091. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163092. (INT32) aanscales[i]),
  163093. CONST_BITS-3);
  163094. }
  163095. }
  163096. break;
  163097. #endif
  163098. #ifdef DCT_FLOAT_SUPPORTED
  163099. case JDCT_FLOAT:
  163100. {
  163101. /* For float AA&N IDCT method, divisors are equal to quantization
  163102. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163103. * scalefactor[0] = 1
  163104. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163105. * We apply a further scale factor of 8.
  163106. * What's actually stored is 1/divisor so that the inner loop can
  163107. * use a multiplication rather than a division.
  163108. */
  163109. FAST_FLOAT * fdtbl;
  163110. int row, col;
  163111. static const double aanscalefactor[DCTSIZE] = {
  163112. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163113. 1.0, 0.785694958, 0.541196100, 0.275899379
  163114. };
  163115. if (fdct->float_divisors[qtblno] == NULL) {
  163116. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  163117. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163118. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  163119. }
  163120. fdtbl = fdct->float_divisors[qtblno];
  163121. i = 0;
  163122. for (row = 0; row < DCTSIZE; row++) {
  163123. for (col = 0; col < DCTSIZE; col++) {
  163124. fdtbl[i] = (FAST_FLOAT)
  163125. (1.0 / (((double) qtbl->quantval[i] *
  163126. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  163127. i++;
  163128. }
  163129. }
  163130. }
  163131. break;
  163132. #endif
  163133. default:
  163134. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163135. break;
  163136. }
  163137. }
  163138. }
  163139. /*
  163140. * Perform forward DCT on one or more blocks of a component.
  163141. *
  163142. * The input samples are taken from the sample_data[] array starting at
  163143. * position start_row/start_col, and moving to the right for any additional
  163144. * blocks. The quantized coefficients are returned in coef_blocks[].
  163145. */
  163146. METHODDEF(void)
  163147. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163148. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163149. JDIMENSION start_row, JDIMENSION start_col,
  163150. JDIMENSION num_blocks)
  163151. /* This version is used for integer DCT implementations. */
  163152. {
  163153. /* This routine is heavily used, so it's worth coding it tightly. */
  163154. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163155. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163156. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163157. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163158. JDIMENSION bi;
  163159. sample_data += start_row; /* fold in the vertical offset once */
  163160. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163161. /* Load data into workspace, applying unsigned->signed conversion */
  163162. { register DCTELEM *workspaceptr;
  163163. register JSAMPROW elemptr;
  163164. register int elemr;
  163165. workspaceptr = workspace;
  163166. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163167. elemptr = sample_data[elemr] + start_col;
  163168. #if DCTSIZE == 8 /* unroll the inner loop */
  163169. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163170. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163171. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163172. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163173. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163174. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163175. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163176. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163177. #else
  163178. { register int elemc;
  163179. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163180. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163181. }
  163182. }
  163183. #endif
  163184. }
  163185. }
  163186. /* Perform the DCT */
  163187. (*do_dct) (workspace);
  163188. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163189. { register DCTELEM temp, qval;
  163190. register int i;
  163191. register JCOEFPTR output_ptr = coef_blocks[bi];
  163192. for (i = 0; i < DCTSIZE2; i++) {
  163193. qval = divisors[i];
  163194. temp = workspace[i];
  163195. /* Divide the coefficient value by qval, ensuring proper rounding.
  163196. * Since C does not specify the direction of rounding for negative
  163197. * quotients, we have to force the dividend positive for portability.
  163198. *
  163199. * In most files, at least half of the output values will be zero
  163200. * (at default quantization settings, more like three-quarters...)
  163201. * so we should ensure that this case is fast. On many machines,
  163202. * a comparison is enough cheaper than a divide to make a special test
  163203. * a win. Since both inputs will be nonnegative, we need only test
  163204. * for a < b to discover whether a/b is 0.
  163205. * If your machine's division is fast enough, define FAST_DIVIDE.
  163206. */
  163207. #ifdef FAST_DIVIDE
  163208. #define DIVIDE_BY(a,b) a /= b
  163209. #else
  163210. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163211. #endif
  163212. if (temp < 0) {
  163213. temp = -temp;
  163214. temp += qval>>1; /* for rounding */
  163215. DIVIDE_BY(temp, qval);
  163216. temp = -temp;
  163217. } else {
  163218. temp += qval>>1; /* for rounding */
  163219. DIVIDE_BY(temp, qval);
  163220. }
  163221. output_ptr[i] = (JCOEF) temp;
  163222. }
  163223. }
  163224. }
  163225. }
  163226. #ifdef DCT_FLOAT_SUPPORTED
  163227. METHODDEF(void)
  163228. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163229. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163230. JDIMENSION start_row, JDIMENSION start_col,
  163231. JDIMENSION num_blocks)
  163232. /* This version is used for floating-point DCT implementations. */
  163233. {
  163234. /* This routine is heavily used, so it's worth coding it tightly. */
  163235. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163236. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163237. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163238. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163239. JDIMENSION bi;
  163240. sample_data += start_row; /* fold in the vertical offset once */
  163241. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163242. /* Load data into workspace, applying unsigned->signed conversion */
  163243. { register FAST_FLOAT *workspaceptr;
  163244. register JSAMPROW elemptr;
  163245. register int elemr;
  163246. workspaceptr = workspace;
  163247. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163248. elemptr = sample_data[elemr] + start_col;
  163249. #if DCTSIZE == 8 /* unroll the inner loop */
  163250. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163251. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163252. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163253. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163254. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163255. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163256. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163257. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163258. #else
  163259. { register int elemc;
  163260. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163261. *workspaceptr++ = (FAST_FLOAT)
  163262. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163263. }
  163264. }
  163265. #endif
  163266. }
  163267. }
  163268. /* Perform the DCT */
  163269. (*do_dct) (workspace);
  163270. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163271. { register FAST_FLOAT temp;
  163272. register int i;
  163273. register JCOEFPTR output_ptr = coef_blocks[bi];
  163274. for (i = 0; i < DCTSIZE2; i++) {
  163275. /* Apply the quantization and scaling factor */
  163276. temp = workspace[i] * divisors[i];
  163277. /* Round to nearest integer.
  163278. * Since C does not specify the direction of rounding for negative
  163279. * quotients, we have to force the dividend positive for portability.
  163280. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163281. * code should work for either 16-bit or 32-bit ints.
  163282. */
  163283. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163284. }
  163285. }
  163286. }
  163287. }
  163288. #endif /* DCT_FLOAT_SUPPORTED */
  163289. /*
  163290. * Initialize FDCT manager.
  163291. */
  163292. GLOBAL(void)
  163293. jinit_forward_dct (j_compress_ptr cinfo)
  163294. {
  163295. my_fdct_ptr fdct;
  163296. int i;
  163297. fdct = (my_fdct_ptr)
  163298. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163299. SIZEOF(my_fdct_controller));
  163300. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163301. fdct->pub.start_pass = start_pass_fdctmgr;
  163302. switch (cinfo->dct_method) {
  163303. #ifdef DCT_ISLOW_SUPPORTED
  163304. case JDCT_ISLOW:
  163305. fdct->pub.forward_DCT = forward_DCT;
  163306. fdct->do_dct = jpeg_fdct_islow;
  163307. break;
  163308. #endif
  163309. #ifdef DCT_IFAST_SUPPORTED
  163310. case JDCT_IFAST:
  163311. fdct->pub.forward_DCT = forward_DCT;
  163312. fdct->do_dct = jpeg_fdct_ifast;
  163313. break;
  163314. #endif
  163315. #ifdef DCT_FLOAT_SUPPORTED
  163316. case JDCT_FLOAT:
  163317. fdct->pub.forward_DCT = forward_DCT_float;
  163318. fdct->do_float_dct = jpeg_fdct_float;
  163319. break;
  163320. #endif
  163321. default:
  163322. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163323. break;
  163324. }
  163325. /* Mark divisor tables unallocated */
  163326. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163327. fdct->divisors[i] = NULL;
  163328. #ifdef DCT_FLOAT_SUPPORTED
  163329. fdct->float_divisors[i] = NULL;
  163330. #endif
  163331. }
  163332. }
  163333. /*** End of inlined file: jcdctmgr.c ***/
  163334. #undef CONST_BITS
  163335. /*** Start of inlined file: jchuff.c ***/
  163336. #define JPEG_INTERNALS
  163337. /*** Start of inlined file: jchuff.h ***/
  163338. /* The legal range of a DCT coefficient is
  163339. * -1024 .. +1023 for 8-bit data;
  163340. * -16384 .. +16383 for 12-bit data.
  163341. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163342. */
  163343. #ifndef _jchuff_h_
  163344. #define _jchuff_h_
  163345. #if BITS_IN_JSAMPLE == 8
  163346. #define MAX_COEF_BITS 10
  163347. #else
  163348. #define MAX_COEF_BITS 14
  163349. #endif
  163350. /* Derived data constructed for each Huffman table */
  163351. typedef struct {
  163352. unsigned int ehufco[256]; /* code for each symbol */
  163353. char ehufsi[256]; /* length of code for each symbol */
  163354. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163355. } c_derived_tbl;
  163356. /* Short forms of external names for systems with brain-damaged linkers. */
  163357. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163358. #define jpeg_make_c_derived_tbl jMkCDerived
  163359. #define jpeg_gen_optimal_table jGenOptTbl
  163360. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163361. /* Expand a Huffman table definition into the derived format */
  163362. EXTERN(void) jpeg_make_c_derived_tbl
  163363. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163364. c_derived_tbl ** pdtbl));
  163365. /* Generate an optimal table definition given the specified counts */
  163366. EXTERN(void) jpeg_gen_optimal_table
  163367. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163368. #endif
  163369. /*** End of inlined file: jchuff.h ***/
  163370. /* Declarations shared with jcphuff.c */
  163371. /* Expanded entropy encoder object for Huffman encoding.
  163372. *
  163373. * The savable_state subrecord contains fields that change within an MCU,
  163374. * but must not be updated permanently until we complete the MCU.
  163375. */
  163376. typedef struct {
  163377. INT32 put_buffer; /* current bit-accumulation buffer */
  163378. int put_bits; /* # of bits now in it */
  163379. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163380. } savable_state;
  163381. /* This macro is to work around compilers with missing or broken
  163382. * structure assignment. You'll need to fix this code if you have
  163383. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163384. */
  163385. #ifndef NO_STRUCT_ASSIGN
  163386. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163387. #else
  163388. #if MAX_COMPS_IN_SCAN == 4
  163389. #define ASSIGN_STATE(dest,src) \
  163390. ((dest).put_buffer = (src).put_buffer, \
  163391. (dest).put_bits = (src).put_bits, \
  163392. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163393. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163394. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163395. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163396. #endif
  163397. #endif
  163398. typedef struct {
  163399. struct jpeg_entropy_encoder pub; /* public fields */
  163400. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163401. /* These fields are NOT loaded into local working state. */
  163402. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163403. int next_restart_num; /* next restart number to write (0-7) */
  163404. /* Pointers to derived tables (these workspaces have image lifespan) */
  163405. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163406. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163407. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163408. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163409. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163410. #endif
  163411. } huff_entropy_encoder;
  163412. typedef huff_entropy_encoder * huff_entropy_ptr;
  163413. /* Working state while writing an MCU.
  163414. * This struct contains all the fields that are needed by subroutines.
  163415. */
  163416. typedef struct {
  163417. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163418. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163419. savable_state cur; /* Current bit buffer & DC state */
  163420. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163421. } working_state;
  163422. /* Forward declarations */
  163423. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163424. JBLOCKROW *MCU_data));
  163425. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163426. #ifdef ENTROPY_OPT_SUPPORTED
  163427. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163428. JBLOCKROW *MCU_data));
  163429. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163430. #endif
  163431. /*
  163432. * Initialize for a Huffman-compressed scan.
  163433. * If gather_statistics is TRUE, we do not output anything during the scan,
  163434. * just count the Huffman symbols used and generate Huffman code tables.
  163435. */
  163436. METHODDEF(void)
  163437. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163438. {
  163439. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163440. int ci, dctbl, actbl;
  163441. jpeg_component_info * compptr;
  163442. if (gather_statistics) {
  163443. #ifdef ENTROPY_OPT_SUPPORTED
  163444. entropy->pub.encode_mcu = encode_mcu_gather;
  163445. entropy->pub.finish_pass = finish_pass_gather;
  163446. #else
  163447. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163448. #endif
  163449. } else {
  163450. entropy->pub.encode_mcu = encode_mcu_huff;
  163451. entropy->pub.finish_pass = finish_pass_huff;
  163452. }
  163453. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163454. compptr = cinfo->cur_comp_info[ci];
  163455. dctbl = compptr->dc_tbl_no;
  163456. actbl = compptr->ac_tbl_no;
  163457. if (gather_statistics) {
  163458. #ifdef ENTROPY_OPT_SUPPORTED
  163459. /* Check for invalid table indexes */
  163460. /* (make_c_derived_tbl does this in the other path) */
  163461. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163462. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163463. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163464. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163465. /* Allocate and zero the statistics tables */
  163466. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163467. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163468. entropy->dc_count_ptrs[dctbl] = (long *)
  163469. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163470. 257 * SIZEOF(long));
  163471. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163472. if (entropy->ac_count_ptrs[actbl] == NULL)
  163473. entropy->ac_count_ptrs[actbl] = (long *)
  163474. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163475. 257 * SIZEOF(long));
  163476. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163477. #endif
  163478. } else {
  163479. /* Compute derived values for Huffman tables */
  163480. /* We may do this more than once for a table, but it's not expensive */
  163481. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163482. & entropy->dc_derived_tbls[dctbl]);
  163483. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163484. & entropy->ac_derived_tbls[actbl]);
  163485. }
  163486. /* Initialize DC predictions to 0 */
  163487. entropy->saved.last_dc_val[ci] = 0;
  163488. }
  163489. /* Initialize bit buffer to empty */
  163490. entropy->saved.put_buffer = 0;
  163491. entropy->saved.put_bits = 0;
  163492. /* Initialize restart stuff */
  163493. entropy->restarts_to_go = cinfo->restart_interval;
  163494. entropy->next_restart_num = 0;
  163495. }
  163496. /*
  163497. * Compute the derived values for a Huffman table.
  163498. * This routine also performs some validation checks on the table.
  163499. *
  163500. * Note this is also used by jcphuff.c.
  163501. */
  163502. GLOBAL(void)
  163503. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163504. c_derived_tbl ** pdtbl)
  163505. {
  163506. JHUFF_TBL *htbl;
  163507. c_derived_tbl *dtbl;
  163508. int p, i, l, lastp, si, maxsymbol;
  163509. char huffsize[257];
  163510. unsigned int huffcode[257];
  163511. unsigned int code;
  163512. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163513. * paralleling the order of the symbols themselves in htbl->huffval[].
  163514. */
  163515. /* Find the input Huffman table */
  163516. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163517. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163518. htbl =
  163519. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163520. if (htbl == NULL)
  163521. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163522. /* Allocate a workspace if we haven't already done so. */
  163523. if (*pdtbl == NULL)
  163524. *pdtbl = (c_derived_tbl *)
  163525. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163526. SIZEOF(c_derived_tbl));
  163527. dtbl = *pdtbl;
  163528. /* Figure C.1: make table of Huffman code length for each symbol */
  163529. p = 0;
  163530. for (l = 1; l <= 16; l++) {
  163531. i = (int) htbl->bits[l];
  163532. if (i < 0 || p + i > 256) /* protect against table overrun */
  163533. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163534. while (i--)
  163535. huffsize[p++] = (char) l;
  163536. }
  163537. huffsize[p] = 0;
  163538. lastp = p;
  163539. /* Figure C.2: generate the codes themselves */
  163540. /* We also validate that the counts represent a legal Huffman code tree. */
  163541. code = 0;
  163542. si = huffsize[0];
  163543. p = 0;
  163544. while (huffsize[p]) {
  163545. while (((int) huffsize[p]) == si) {
  163546. huffcode[p++] = code;
  163547. code++;
  163548. }
  163549. /* code is now 1 more than the last code used for codelength si; but
  163550. * it must still fit in si bits, since no code is allowed to be all ones.
  163551. */
  163552. if (((INT32) code) >= (((INT32) 1) << si))
  163553. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163554. code <<= 1;
  163555. si++;
  163556. }
  163557. /* Figure C.3: generate encoding tables */
  163558. /* These are code and size indexed by symbol value */
  163559. /* Set all codeless symbols to have code length 0;
  163560. * this lets us detect duplicate VAL entries here, and later
  163561. * allows emit_bits to detect any attempt to emit such symbols.
  163562. */
  163563. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163564. /* This is also a convenient place to check for out-of-range
  163565. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163566. * but only 0..15 for DC. (We could constrain them further
  163567. * based on data depth and mode, but this seems enough.)
  163568. */
  163569. maxsymbol = isDC ? 15 : 255;
  163570. for (p = 0; p < lastp; p++) {
  163571. i = htbl->huffval[p];
  163572. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163573. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163574. dtbl->ehufco[i] = huffcode[p];
  163575. dtbl->ehufsi[i] = huffsize[p];
  163576. }
  163577. }
  163578. /* Outputting bytes to the file */
  163579. /* Emit a byte, taking 'action' if must suspend. */
  163580. #define emit_byte(state,val,action) \
  163581. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163582. if (--(state)->free_in_buffer == 0) \
  163583. if (! dump_buffer(state)) \
  163584. { action; } }
  163585. LOCAL(boolean)
  163586. dump_buffer (working_state * state)
  163587. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163588. {
  163589. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163590. if (! (*dest->empty_output_buffer) (state->cinfo))
  163591. return FALSE;
  163592. /* After a successful buffer dump, must reset buffer pointers */
  163593. state->next_output_byte = dest->next_output_byte;
  163594. state->free_in_buffer = dest->free_in_buffer;
  163595. return TRUE;
  163596. }
  163597. /* Outputting bits to the file */
  163598. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163599. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163600. * in one call, and we never retain more than 7 bits in put_buffer
  163601. * between calls, so 24 bits are sufficient.
  163602. */
  163603. INLINE
  163604. LOCAL(boolean)
  163605. emit_bits (working_state * state, unsigned int code, int size)
  163606. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163607. {
  163608. /* This routine is heavily used, so it's worth coding tightly. */
  163609. register INT32 put_buffer = (INT32) code;
  163610. register int put_bits = state->cur.put_bits;
  163611. /* if size is 0, caller used an invalid Huffman table entry */
  163612. if (size == 0)
  163613. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163614. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163615. put_bits += size; /* new number of bits in buffer */
  163616. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163617. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163618. while (put_bits >= 8) {
  163619. int c = (int) ((put_buffer >> 16) & 0xFF);
  163620. emit_byte(state, c, return FALSE);
  163621. if (c == 0xFF) { /* need to stuff a zero byte? */
  163622. emit_byte(state, 0, return FALSE);
  163623. }
  163624. put_buffer <<= 8;
  163625. put_bits -= 8;
  163626. }
  163627. state->cur.put_buffer = put_buffer; /* update state variables */
  163628. state->cur.put_bits = put_bits;
  163629. return TRUE;
  163630. }
  163631. LOCAL(boolean)
  163632. flush_bits (working_state * state)
  163633. {
  163634. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163635. return FALSE;
  163636. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163637. state->cur.put_bits = 0;
  163638. return TRUE;
  163639. }
  163640. /* Encode a single block's worth of coefficients */
  163641. LOCAL(boolean)
  163642. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163643. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163644. {
  163645. register int temp, temp2;
  163646. register int nbits;
  163647. register int k, r, i;
  163648. /* Encode the DC coefficient difference per section F.1.2.1 */
  163649. temp = temp2 = block[0] - last_dc_val;
  163650. if (temp < 0) {
  163651. temp = -temp; /* temp is abs value of input */
  163652. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163653. /* This code assumes we are on a two's complement machine */
  163654. temp2--;
  163655. }
  163656. /* Find the number of bits needed for the magnitude of the coefficient */
  163657. nbits = 0;
  163658. while (temp) {
  163659. nbits++;
  163660. temp >>= 1;
  163661. }
  163662. /* Check for out-of-range coefficient values.
  163663. * Since we're encoding a difference, the range limit is twice as much.
  163664. */
  163665. if (nbits > MAX_COEF_BITS+1)
  163666. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163667. /* Emit the Huffman-coded symbol for the number of bits */
  163668. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163669. return FALSE;
  163670. /* Emit that number of bits of the value, if positive, */
  163671. /* or the complement of its magnitude, if negative. */
  163672. if (nbits) /* emit_bits rejects calls with size 0 */
  163673. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163674. return FALSE;
  163675. /* Encode the AC coefficients per section F.1.2.2 */
  163676. r = 0; /* r = run length of zeros */
  163677. for (k = 1; k < DCTSIZE2; k++) {
  163678. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163679. r++;
  163680. } else {
  163681. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163682. while (r > 15) {
  163683. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163684. return FALSE;
  163685. r -= 16;
  163686. }
  163687. temp2 = temp;
  163688. if (temp < 0) {
  163689. temp = -temp; /* temp is abs value of input */
  163690. /* This code assumes we are on a two's complement machine */
  163691. temp2--;
  163692. }
  163693. /* Find the number of bits needed for the magnitude of the coefficient */
  163694. nbits = 1; /* there must be at least one 1 bit */
  163695. while ((temp >>= 1))
  163696. nbits++;
  163697. /* Check for out-of-range coefficient values */
  163698. if (nbits > MAX_COEF_BITS)
  163699. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163700. /* Emit Huffman symbol for run length / number of bits */
  163701. i = (r << 4) + nbits;
  163702. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163703. return FALSE;
  163704. /* Emit that number of bits of the value, if positive, */
  163705. /* or the complement of its magnitude, if negative. */
  163706. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163707. return FALSE;
  163708. r = 0;
  163709. }
  163710. }
  163711. /* If the last coef(s) were zero, emit an end-of-block code */
  163712. if (r > 0)
  163713. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163714. return FALSE;
  163715. return TRUE;
  163716. }
  163717. /*
  163718. * Emit a restart marker & resynchronize predictions.
  163719. */
  163720. LOCAL(boolean)
  163721. emit_restart (working_state * state, int restart_num)
  163722. {
  163723. int ci;
  163724. if (! flush_bits(state))
  163725. return FALSE;
  163726. emit_byte(state, 0xFF, return FALSE);
  163727. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163728. /* Re-initialize DC predictions to 0 */
  163729. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163730. state->cur.last_dc_val[ci] = 0;
  163731. /* The restart counter is not updated until we successfully write the MCU. */
  163732. return TRUE;
  163733. }
  163734. /*
  163735. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163736. */
  163737. METHODDEF(boolean)
  163738. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163739. {
  163740. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163741. working_state state;
  163742. int blkn, ci;
  163743. jpeg_component_info * compptr;
  163744. /* Load up working state */
  163745. state.next_output_byte = cinfo->dest->next_output_byte;
  163746. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163747. ASSIGN_STATE(state.cur, entropy->saved);
  163748. state.cinfo = cinfo;
  163749. /* Emit restart marker if needed */
  163750. if (cinfo->restart_interval) {
  163751. if (entropy->restarts_to_go == 0)
  163752. if (! emit_restart(&state, entropy->next_restart_num))
  163753. return FALSE;
  163754. }
  163755. /* Encode the MCU data blocks */
  163756. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163757. ci = cinfo->MCU_membership[blkn];
  163758. compptr = cinfo->cur_comp_info[ci];
  163759. if (! encode_one_block(&state,
  163760. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163761. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163762. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163763. return FALSE;
  163764. /* Update last_dc_val */
  163765. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163766. }
  163767. /* Completed MCU, so update state */
  163768. cinfo->dest->next_output_byte = state.next_output_byte;
  163769. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163770. ASSIGN_STATE(entropy->saved, state.cur);
  163771. /* Update restart-interval state too */
  163772. if (cinfo->restart_interval) {
  163773. if (entropy->restarts_to_go == 0) {
  163774. entropy->restarts_to_go = cinfo->restart_interval;
  163775. entropy->next_restart_num++;
  163776. entropy->next_restart_num &= 7;
  163777. }
  163778. entropy->restarts_to_go--;
  163779. }
  163780. return TRUE;
  163781. }
  163782. /*
  163783. * Finish up at the end of a Huffman-compressed scan.
  163784. */
  163785. METHODDEF(void)
  163786. finish_pass_huff (j_compress_ptr cinfo)
  163787. {
  163788. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163789. working_state state;
  163790. /* Load up working state ... flush_bits needs it */
  163791. state.next_output_byte = cinfo->dest->next_output_byte;
  163792. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163793. ASSIGN_STATE(state.cur, entropy->saved);
  163794. state.cinfo = cinfo;
  163795. /* Flush out the last data */
  163796. if (! flush_bits(&state))
  163797. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163798. /* Update state */
  163799. cinfo->dest->next_output_byte = state.next_output_byte;
  163800. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163801. ASSIGN_STATE(entropy->saved, state.cur);
  163802. }
  163803. /*
  163804. * Huffman coding optimization.
  163805. *
  163806. * We first scan the supplied data and count the number of uses of each symbol
  163807. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163808. * Then we build a Huffman coding tree for the observed counts.
  163809. * Symbols which are not needed at all for the particular image are not
  163810. * assigned any code, which saves space in the DHT marker as well as in
  163811. * the compressed data.
  163812. */
  163813. #ifdef ENTROPY_OPT_SUPPORTED
  163814. /* Process a single block's worth of coefficients */
  163815. LOCAL(void)
  163816. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163817. long dc_counts[], long ac_counts[])
  163818. {
  163819. register int temp;
  163820. register int nbits;
  163821. register int k, r;
  163822. /* Encode the DC coefficient difference per section F.1.2.1 */
  163823. temp = block[0] - last_dc_val;
  163824. if (temp < 0)
  163825. temp = -temp;
  163826. /* Find the number of bits needed for the magnitude of the coefficient */
  163827. nbits = 0;
  163828. while (temp) {
  163829. nbits++;
  163830. temp >>= 1;
  163831. }
  163832. /* Check for out-of-range coefficient values.
  163833. * Since we're encoding a difference, the range limit is twice as much.
  163834. */
  163835. if (nbits > MAX_COEF_BITS+1)
  163836. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163837. /* Count the Huffman symbol for the number of bits */
  163838. dc_counts[nbits]++;
  163839. /* Encode the AC coefficients per section F.1.2.2 */
  163840. r = 0; /* r = run length of zeros */
  163841. for (k = 1; k < DCTSIZE2; k++) {
  163842. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163843. r++;
  163844. } else {
  163845. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163846. while (r > 15) {
  163847. ac_counts[0xF0]++;
  163848. r -= 16;
  163849. }
  163850. /* Find the number of bits needed for the magnitude of the coefficient */
  163851. if (temp < 0)
  163852. temp = -temp;
  163853. /* Find the number of bits needed for the magnitude of the coefficient */
  163854. nbits = 1; /* there must be at least one 1 bit */
  163855. while ((temp >>= 1))
  163856. nbits++;
  163857. /* Check for out-of-range coefficient values */
  163858. if (nbits > MAX_COEF_BITS)
  163859. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163860. /* Count Huffman symbol for run length / number of bits */
  163861. ac_counts[(r << 4) + nbits]++;
  163862. r = 0;
  163863. }
  163864. }
  163865. /* If the last coef(s) were zero, emit an end-of-block code */
  163866. if (r > 0)
  163867. ac_counts[0]++;
  163868. }
  163869. /*
  163870. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163871. * No data is actually output, so no suspension return is possible.
  163872. */
  163873. METHODDEF(boolean)
  163874. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163875. {
  163876. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163877. int blkn, ci;
  163878. jpeg_component_info * compptr;
  163879. /* Take care of restart intervals if needed */
  163880. if (cinfo->restart_interval) {
  163881. if (entropy->restarts_to_go == 0) {
  163882. /* Re-initialize DC predictions to 0 */
  163883. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163884. entropy->saved.last_dc_val[ci] = 0;
  163885. /* Update restart state */
  163886. entropy->restarts_to_go = cinfo->restart_interval;
  163887. }
  163888. entropy->restarts_to_go--;
  163889. }
  163890. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163891. ci = cinfo->MCU_membership[blkn];
  163892. compptr = cinfo->cur_comp_info[ci];
  163893. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163894. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163895. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163896. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163897. }
  163898. return TRUE;
  163899. }
  163900. /*
  163901. * Generate the best Huffman code table for the given counts, fill htbl.
  163902. * Note this is also used by jcphuff.c.
  163903. *
  163904. * The JPEG standard requires that no symbol be assigned a codeword of all
  163905. * one bits (so that padding bits added at the end of a compressed segment
  163906. * can't look like a valid code). Because of the canonical ordering of
  163907. * codewords, this just means that there must be an unused slot in the
  163908. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163909. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163910. * with count 1. In theory that's not optimal; giving it count zero but
  163911. * including it in the symbol set anyway should give a better Huffman code.
  163912. * But the theoretically better code actually seems to come out worse in
  163913. * practice, because it produces more all-ones bytes (which incur stuffed
  163914. * zero bytes in the final file). In any case the difference is tiny.
  163915. *
  163916. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163917. * If some symbols have a very small but nonzero probability, the Huffman tree
  163918. * must be adjusted to meet the code length restriction. We currently use
  163919. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163920. * optimal; it may not choose the best possible limited-length code. But
  163921. * typically only very-low-frequency symbols will be given less-than-optimal
  163922. * lengths, so the code is almost optimal. Experimental comparisons against
  163923. * an optimal limited-length-code algorithm indicate that the difference is
  163924. * microscopic --- usually less than a hundredth of a percent of total size.
  163925. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163926. */
  163927. GLOBAL(void)
  163928. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163929. {
  163930. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163931. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163932. int codesize[257]; /* codesize[k] = code length of symbol k */
  163933. int others[257]; /* next symbol in current branch of tree */
  163934. int c1, c2;
  163935. int p, i, j;
  163936. long v;
  163937. /* This algorithm is explained in section K.2 of the JPEG standard */
  163938. MEMZERO(bits, SIZEOF(bits));
  163939. MEMZERO(codesize, SIZEOF(codesize));
  163940. for (i = 0; i < 257; i++)
  163941. others[i] = -1; /* init links to empty */
  163942. freq[256] = 1; /* make sure 256 has a nonzero count */
  163943. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163944. * that no real symbol is given code-value of all ones, because 256
  163945. * will be placed last in the largest codeword category.
  163946. */
  163947. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163948. for (;;) {
  163949. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163950. /* In case of ties, take the larger symbol number */
  163951. c1 = -1;
  163952. v = 1000000000L;
  163953. for (i = 0; i <= 256; i++) {
  163954. if (freq[i] && freq[i] <= v) {
  163955. v = freq[i];
  163956. c1 = i;
  163957. }
  163958. }
  163959. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163960. /* In case of ties, take the larger symbol number */
  163961. c2 = -1;
  163962. v = 1000000000L;
  163963. for (i = 0; i <= 256; i++) {
  163964. if (freq[i] && freq[i] <= v && i != c1) {
  163965. v = freq[i];
  163966. c2 = i;
  163967. }
  163968. }
  163969. /* Done if we've merged everything into one frequency */
  163970. if (c2 < 0)
  163971. break;
  163972. /* Else merge the two counts/trees */
  163973. freq[c1] += freq[c2];
  163974. freq[c2] = 0;
  163975. /* Increment the codesize of everything in c1's tree branch */
  163976. codesize[c1]++;
  163977. while (others[c1] >= 0) {
  163978. c1 = others[c1];
  163979. codesize[c1]++;
  163980. }
  163981. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163982. /* Increment the codesize of everything in c2's tree branch */
  163983. codesize[c2]++;
  163984. while (others[c2] >= 0) {
  163985. c2 = others[c2];
  163986. codesize[c2]++;
  163987. }
  163988. }
  163989. /* Now count the number of symbols of each code length */
  163990. for (i = 0; i <= 256; i++) {
  163991. if (codesize[i]) {
  163992. /* The JPEG standard seems to think that this can't happen, */
  163993. /* but I'm paranoid... */
  163994. if (codesize[i] > MAX_CLEN)
  163995. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163996. bits[codesize[i]]++;
  163997. }
  163998. }
  163999. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  164000. * Huffman procedure assigned any such lengths, we must adjust the coding.
  164001. * Here is what the JPEG spec says about how this next bit works:
  164002. * Since symbols are paired for the longest Huffman code, the symbols are
  164003. * removed from this length category two at a time. The prefix for the pair
  164004. * (which is one bit shorter) is allocated to one of the pair; then,
  164005. * skipping the BITS entry for that prefix length, a code word from the next
  164006. * shortest nonzero BITS entry is converted into a prefix for two code words
  164007. * one bit longer.
  164008. */
  164009. for (i = MAX_CLEN; i > 16; i--) {
  164010. while (bits[i] > 0) {
  164011. j = i - 2; /* find length of new prefix to be used */
  164012. while (bits[j] == 0)
  164013. j--;
  164014. bits[i] -= 2; /* remove two symbols */
  164015. bits[i-1]++; /* one goes in this length */
  164016. bits[j+1] += 2; /* two new symbols in this length */
  164017. bits[j]--; /* symbol of this length is now a prefix */
  164018. }
  164019. }
  164020. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  164021. while (bits[i] == 0) /* find largest codelength still in use */
  164022. i--;
  164023. bits[i]--;
  164024. /* Return final symbol counts (only for lengths 0..16) */
  164025. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  164026. /* Return a list of the symbols sorted by code length */
  164027. /* It's not real clear to me why we don't need to consider the codelength
  164028. * changes made above, but the JPEG spec seems to think this works.
  164029. */
  164030. p = 0;
  164031. for (i = 1; i <= MAX_CLEN; i++) {
  164032. for (j = 0; j <= 255; j++) {
  164033. if (codesize[j] == i) {
  164034. htbl->huffval[p] = (UINT8) j;
  164035. p++;
  164036. }
  164037. }
  164038. }
  164039. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  164040. htbl->sent_table = FALSE;
  164041. }
  164042. /*
  164043. * Finish up a statistics-gathering pass and create the new Huffman tables.
  164044. */
  164045. METHODDEF(void)
  164046. finish_pass_gather (j_compress_ptr cinfo)
  164047. {
  164048. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164049. int ci, dctbl, actbl;
  164050. jpeg_component_info * compptr;
  164051. JHUFF_TBL **htblptr;
  164052. boolean did_dc[NUM_HUFF_TBLS];
  164053. boolean did_ac[NUM_HUFF_TBLS];
  164054. /* It's important not to apply jpeg_gen_optimal_table more than once
  164055. * per table, because it clobbers the input frequency counts!
  164056. */
  164057. MEMZERO(did_dc, SIZEOF(did_dc));
  164058. MEMZERO(did_ac, SIZEOF(did_ac));
  164059. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164060. compptr = cinfo->cur_comp_info[ci];
  164061. dctbl = compptr->dc_tbl_no;
  164062. actbl = compptr->ac_tbl_no;
  164063. if (! did_dc[dctbl]) {
  164064. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  164065. if (*htblptr == NULL)
  164066. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164067. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  164068. did_dc[dctbl] = TRUE;
  164069. }
  164070. if (! did_ac[actbl]) {
  164071. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  164072. if (*htblptr == NULL)
  164073. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164074. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  164075. did_ac[actbl] = TRUE;
  164076. }
  164077. }
  164078. }
  164079. #endif /* ENTROPY_OPT_SUPPORTED */
  164080. /*
  164081. * Module initialization routine for Huffman entropy encoding.
  164082. */
  164083. GLOBAL(void)
  164084. jinit_huff_encoder (j_compress_ptr cinfo)
  164085. {
  164086. huff_entropy_ptr entropy;
  164087. int i;
  164088. entropy = (huff_entropy_ptr)
  164089. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164090. SIZEOF(huff_entropy_encoder));
  164091. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  164092. entropy->pub.start_pass = start_pass_huff;
  164093. /* Mark tables unallocated */
  164094. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164095. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164096. #ifdef ENTROPY_OPT_SUPPORTED
  164097. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  164098. #endif
  164099. }
  164100. }
  164101. /*** End of inlined file: jchuff.c ***/
  164102. #undef emit_byte
  164103. /*** Start of inlined file: jcinit.c ***/
  164104. #define JPEG_INTERNALS
  164105. /*
  164106. * Master selection of compression modules.
  164107. * This is done once at the start of processing an image. We determine
  164108. * which modules will be used and give them appropriate initialization calls.
  164109. */
  164110. GLOBAL(void)
  164111. jinit_compress_master (j_compress_ptr cinfo)
  164112. {
  164113. /* Initialize master control (includes parameter checking/processing) */
  164114. jinit_c_master_control(cinfo, FALSE /* full compression */);
  164115. /* Preprocessing */
  164116. if (! cinfo->raw_data_in) {
  164117. jinit_color_converter(cinfo);
  164118. jinit_downsampler(cinfo);
  164119. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  164120. }
  164121. /* Forward DCT */
  164122. jinit_forward_dct(cinfo);
  164123. /* Entropy encoding: either Huffman or arithmetic coding. */
  164124. if (cinfo->arith_code) {
  164125. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164126. } else {
  164127. if (cinfo->progressive_mode) {
  164128. #ifdef C_PROGRESSIVE_SUPPORTED
  164129. jinit_phuff_encoder(cinfo);
  164130. #else
  164131. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164132. #endif
  164133. } else
  164134. jinit_huff_encoder(cinfo);
  164135. }
  164136. /* Need a full-image coefficient buffer in any multi-pass mode. */
  164137. jinit_c_coef_controller(cinfo,
  164138. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  164139. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  164140. jinit_marker_writer(cinfo);
  164141. /* We can now tell the memory manager to allocate virtual arrays. */
  164142. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164143. /* Write the datastream header (SOI) immediately.
  164144. * Frame and scan headers are postponed till later.
  164145. * This lets application insert special markers after the SOI.
  164146. */
  164147. (*cinfo->marker->write_file_header) (cinfo);
  164148. }
  164149. /*** End of inlined file: jcinit.c ***/
  164150. /*** Start of inlined file: jcmainct.c ***/
  164151. #define JPEG_INTERNALS
  164152. /* Note: currently, there is no operating mode in which a full-image buffer
  164153. * is needed at this step. If there were, that mode could not be used with
  164154. * "raw data" input, since this module is bypassed in that case. However,
  164155. * we've left the code here for possible use in special applications.
  164156. */
  164157. #undef FULL_MAIN_BUFFER_SUPPORTED
  164158. /* Private buffer controller object */
  164159. typedef struct {
  164160. struct jpeg_c_main_controller pub; /* public fields */
  164161. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164162. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164163. boolean suspended; /* remember if we suspended output */
  164164. J_BUF_MODE pass_mode; /* current operating mode */
  164165. /* If using just a strip buffer, this points to the entire set of buffers
  164166. * (we allocate one for each component). In the full-image case, this
  164167. * points to the currently accessible strips of the virtual arrays.
  164168. */
  164169. JSAMPARRAY buffer[MAX_COMPONENTS];
  164170. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164171. /* If using full-image storage, this array holds pointers to virtual-array
  164172. * control blocks for each component. Unused if not full-image storage.
  164173. */
  164174. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164175. #endif
  164176. } my_main_controller;
  164177. typedef my_main_controller * my_main_ptr;
  164178. /* Forward declarations */
  164179. METHODDEF(void) process_data_simple_main
  164180. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164181. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164182. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164183. METHODDEF(void) process_data_buffer_main
  164184. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164185. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164186. #endif
  164187. /*
  164188. * Initialize for a processing pass.
  164189. */
  164190. METHODDEF(void)
  164191. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164192. {
  164193. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164194. /* Do nothing in raw-data mode. */
  164195. if (cinfo->raw_data_in)
  164196. return;
  164197. main_->cur_iMCU_row = 0; /* initialize counters */
  164198. main_->rowgroup_ctr = 0;
  164199. main_->suspended = FALSE;
  164200. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164201. switch (pass_mode) {
  164202. case JBUF_PASS_THRU:
  164203. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164204. if (main_->whole_image[0] != NULL)
  164205. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164206. #endif
  164207. main_->pub.process_data = process_data_simple_main;
  164208. break;
  164209. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164210. case JBUF_SAVE_SOURCE:
  164211. case JBUF_CRANK_DEST:
  164212. case JBUF_SAVE_AND_PASS:
  164213. if (main_->whole_image[0] == NULL)
  164214. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164215. main_->pub.process_data = process_data_buffer_main;
  164216. break;
  164217. #endif
  164218. default:
  164219. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164220. break;
  164221. }
  164222. }
  164223. /*
  164224. * Process some data.
  164225. * This routine handles the simple pass-through mode,
  164226. * where we have only a strip buffer.
  164227. */
  164228. METHODDEF(void)
  164229. process_data_simple_main (j_compress_ptr cinfo,
  164230. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164231. JDIMENSION in_rows_avail)
  164232. {
  164233. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164234. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164235. /* Read input data if we haven't filled the main buffer yet */
  164236. if (main_->rowgroup_ctr < DCTSIZE)
  164237. (*cinfo->prep->pre_process_data) (cinfo,
  164238. input_buf, in_row_ctr, in_rows_avail,
  164239. main_->buffer, &main_->rowgroup_ctr,
  164240. (JDIMENSION) DCTSIZE);
  164241. /* If we don't have a full iMCU row buffered, return to application for
  164242. * more data. Note that preprocessor will always pad to fill the iMCU row
  164243. * at the bottom of the image.
  164244. */
  164245. if (main_->rowgroup_ctr != DCTSIZE)
  164246. return;
  164247. /* Send the completed row to the compressor */
  164248. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164249. /* If compressor did not consume the whole row, then we must need to
  164250. * suspend processing and return to the application. In this situation
  164251. * we pretend we didn't yet consume the last input row; otherwise, if
  164252. * it happened to be the last row of the image, the application would
  164253. * think we were done.
  164254. */
  164255. if (! main_->suspended) {
  164256. (*in_row_ctr)--;
  164257. main_->suspended = TRUE;
  164258. }
  164259. return;
  164260. }
  164261. /* We did finish the row. Undo our little suspension hack if a previous
  164262. * call suspended; then mark the main buffer empty.
  164263. */
  164264. if (main_->suspended) {
  164265. (*in_row_ctr)++;
  164266. main_->suspended = FALSE;
  164267. }
  164268. main_->rowgroup_ctr = 0;
  164269. main_->cur_iMCU_row++;
  164270. }
  164271. }
  164272. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164273. /*
  164274. * Process some data.
  164275. * This routine handles all of the modes that use a full-size buffer.
  164276. */
  164277. METHODDEF(void)
  164278. process_data_buffer_main (j_compress_ptr cinfo,
  164279. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164280. JDIMENSION in_rows_avail)
  164281. {
  164282. my_main_ptr main = (my_main_ptr) cinfo->main;
  164283. int ci;
  164284. jpeg_component_info *compptr;
  164285. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164286. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164287. /* Realign the virtual buffers if at the start of an iMCU row. */
  164288. if (main->rowgroup_ctr == 0) {
  164289. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164290. ci++, compptr++) {
  164291. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164292. ((j_common_ptr) cinfo, main->whole_image[ci],
  164293. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164294. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164295. }
  164296. /* In a read pass, pretend we just read some source data. */
  164297. if (! writing) {
  164298. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164299. main->rowgroup_ctr = DCTSIZE;
  164300. }
  164301. }
  164302. /* If a write pass, read input data until the current iMCU row is full. */
  164303. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164304. if (writing) {
  164305. (*cinfo->prep->pre_process_data) (cinfo,
  164306. input_buf, in_row_ctr, in_rows_avail,
  164307. main->buffer, &main->rowgroup_ctr,
  164308. (JDIMENSION) DCTSIZE);
  164309. /* Return to application if we need more data to fill the iMCU row. */
  164310. if (main->rowgroup_ctr < DCTSIZE)
  164311. return;
  164312. }
  164313. /* Emit data, unless this is a sink-only pass. */
  164314. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164315. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164316. /* If compressor did not consume the whole row, then we must need to
  164317. * suspend processing and return to the application. In this situation
  164318. * we pretend we didn't yet consume the last input row; otherwise, if
  164319. * it happened to be the last row of the image, the application would
  164320. * think we were done.
  164321. */
  164322. if (! main->suspended) {
  164323. (*in_row_ctr)--;
  164324. main->suspended = TRUE;
  164325. }
  164326. return;
  164327. }
  164328. /* We did finish the row. Undo our little suspension hack if a previous
  164329. * call suspended; then mark the main buffer empty.
  164330. */
  164331. if (main->suspended) {
  164332. (*in_row_ctr)++;
  164333. main->suspended = FALSE;
  164334. }
  164335. }
  164336. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164337. main->rowgroup_ctr = 0;
  164338. main->cur_iMCU_row++;
  164339. }
  164340. }
  164341. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164342. /*
  164343. * Initialize main buffer controller.
  164344. */
  164345. GLOBAL(void)
  164346. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164347. {
  164348. my_main_ptr main_;
  164349. int ci;
  164350. jpeg_component_info *compptr;
  164351. main_ = (my_main_ptr)
  164352. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164353. SIZEOF(my_main_controller));
  164354. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164355. main_->pub.start_pass = start_pass_main;
  164356. /* We don't need to create a buffer in raw-data mode. */
  164357. if (cinfo->raw_data_in)
  164358. return;
  164359. /* Create the buffer. It holds downsampled data, so each component
  164360. * may be of a different size.
  164361. */
  164362. if (need_full_buffer) {
  164363. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164364. /* Allocate a full-image virtual array for each component */
  164365. /* Note we pad the bottom to a multiple of the iMCU height */
  164366. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164367. ci++, compptr++) {
  164368. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164369. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164370. compptr->width_in_blocks * DCTSIZE,
  164371. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164372. (long) compptr->v_samp_factor) * DCTSIZE,
  164373. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164374. }
  164375. #else
  164376. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164377. #endif
  164378. } else {
  164379. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164380. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164381. #endif
  164382. /* Allocate a strip buffer for each component */
  164383. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164384. ci++, compptr++) {
  164385. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164386. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164387. compptr->width_in_blocks * DCTSIZE,
  164388. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164389. }
  164390. }
  164391. }
  164392. /*** End of inlined file: jcmainct.c ***/
  164393. /*** Start of inlined file: jcmarker.c ***/
  164394. #define JPEG_INTERNALS
  164395. /* Private state */
  164396. typedef struct {
  164397. struct jpeg_marker_writer pub; /* public fields */
  164398. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164399. } my_marker_writer;
  164400. typedef my_marker_writer * my_marker_ptr;
  164401. /*
  164402. * Basic output routines.
  164403. *
  164404. * Note that we do not support suspension while writing a marker.
  164405. * Therefore, an application using suspension must ensure that there is
  164406. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164407. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164408. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164409. * modes are not supported at all with suspension, so those two are the only
  164410. * points where markers will be written.
  164411. */
  164412. LOCAL(void)
  164413. emit_byte (j_compress_ptr cinfo, int val)
  164414. /* Emit a byte */
  164415. {
  164416. struct jpeg_destination_mgr * dest = cinfo->dest;
  164417. *(dest->next_output_byte)++ = (JOCTET) val;
  164418. if (--dest->free_in_buffer == 0) {
  164419. if (! (*dest->empty_output_buffer) (cinfo))
  164420. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164421. }
  164422. }
  164423. LOCAL(void)
  164424. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164425. /* Emit a marker code */
  164426. {
  164427. emit_byte(cinfo, 0xFF);
  164428. emit_byte(cinfo, (int) mark);
  164429. }
  164430. LOCAL(void)
  164431. emit_2bytes (j_compress_ptr cinfo, int value)
  164432. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164433. {
  164434. emit_byte(cinfo, (value >> 8) & 0xFF);
  164435. emit_byte(cinfo, value & 0xFF);
  164436. }
  164437. /*
  164438. * Routines to write specific marker types.
  164439. */
  164440. LOCAL(int)
  164441. emit_dqt (j_compress_ptr cinfo, int index)
  164442. /* Emit a DQT marker */
  164443. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164444. {
  164445. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164446. int prec;
  164447. int i;
  164448. if (qtbl == NULL)
  164449. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164450. prec = 0;
  164451. for (i = 0; i < DCTSIZE2; i++) {
  164452. if (qtbl->quantval[i] > 255)
  164453. prec = 1;
  164454. }
  164455. if (! qtbl->sent_table) {
  164456. emit_marker(cinfo, M_DQT);
  164457. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164458. emit_byte(cinfo, index + (prec<<4));
  164459. for (i = 0; i < DCTSIZE2; i++) {
  164460. /* The table entries must be emitted in zigzag order. */
  164461. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164462. if (prec)
  164463. emit_byte(cinfo, (int) (qval >> 8));
  164464. emit_byte(cinfo, (int) (qval & 0xFF));
  164465. }
  164466. qtbl->sent_table = TRUE;
  164467. }
  164468. return prec;
  164469. }
  164470. LOCAL(void)
  164471. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164472. /* Emit a DHT marker */
  164473. {
  164474. JHUFF_TBL * htbl;
  164475. int length, i;
  164476. if (is_ac) {
  164477. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164478. index += 0x10; /* output index has AC bit set */
  164479. } else {
  164480. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164481. }
  164482. if (htbl == NULL)
  164483. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164484. if (! htbl->sent_table) {
  164485. emit_marker(cinfo, M_DHT);
  164486. length = 0;
  164487. for (i = 1; i <= 16; i++)
  164488. length += htbl->bits[i];
  164489. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164490. emit_byte(cinfo, index);
  164491. for (i = 1; i <= 16; i++)
  164492. emit_byte(cinfo, htbl->bits[i]);
  164493. for (i = 0; i < length; i++)
  164494. emit_byte(cinfo, htbl->huffval[i]);
  164495. htbl->sent_table = TRUE;
  164496. }
  164497. }
  164498. LOCAL(void)
  164499. emit_dac (j_compress_ptr)
  164500. /* Emit a DAC marker */
  164501. /* Since the useful info is so small, we want to emit all the tables in */
  164502. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164503. {
  164504. #ifdef C_ARITH_CODING_SUPPORTED
  164505. char dc_in_use[NUM_ARITH_TBLS];
  164506. char ac_in_use[NUM_ARITH_TBLS];
  164507. int length, i;
  164508. jpeg_component_info *compptr;
  164509. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164510. dc_in_use[i] = ac_in_use[i] = 0;
  164511. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164512. compptr = cinfo->cur_comp_info[i];
  164513. dc_in_use[compptr->dc_tbl_no] = 1;
  164514. ac_in_use[compptr->ac_tbl_no] = 1;
  164515. }
  164516. length = 0;
  164517. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164518. length += dc_in_use[i] + ac_in_use[i];
  164519. emit_marker(cinfo, M_DAC);
  164520. emit_2bytes(cinfo, length*2 + 2);
  164521. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164522. if (dc_in_use[i]) {
  164523. emit_byte(cinfo, i);
  164524. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164525. }
  164526. if (ac_in_use[i]) {
  164527. emit_byte(cinfo, i + 0x10);
  164528. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164529. }
  164530. }
  164531. #endif /* C_ARITH_CODING_SUPPORTED */
  164532. }
  164533. LOCAL(void)
  164534. emit_dri (j_compress_ptr cinfo)
  164535. /* Emit a DRI marker */
  164536. {
  164537. emit_marker(cinfo, M_DRI);
  164538. emit_2bytes(cinfo, 4); /* fixed length */
  164539. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164540. }
  164541. LOCAL(void)
  164542. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164543. /* Emit a SOF marker */
  164544. {
  164545. int ci;
  164546. jpeg_component_info *compptr;
  164547. emit_marker(cinfo, code);
  164548. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164549. /* Make sure image isn't bigger than SOF field can handle */
  164550. if ((long) cinfo->image_height > 65535L ||
  164551. (long) cinfo->image_width > 65535L)
  164552. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164553. emit_byte(cinfo, cinfo->data_precision);
  164554. emit_2bytes(cinfo, (int) cinfo->image_height);
  164555. emit_2bytes(cinfo, (int) cinfo->image_width);
  164556. emit_byte(cinfo, cinfo->num_components);
  164557. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164558. ci++, compptr++) {
  164559. emit_byte(cinfo, compptr->component_id);
  164560. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164561. emit_byte(cinfo, compptr->quant_tbl_no);
  164562. }
  164563. }
  164564. LOCAL(void)
  164565. emit_sos (j_compress_ptr cinfo)
  164566. /* Emit a SOS marker */
  164567. {
  164568. int i, td, ta;
  164569. jpeg_component_info *compptr;
  164570. emit_marker(cinfo, M_SOS);
  164571. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164572. emit_byte(cinfo, cinfo->comps_in_scan);
  164573. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164574. compptr = cinfo->cur_comp_info[i];
  164575. emit_byte(cinfo, compptr->component_id);
  164576. td = compptr->dc_tbl_no;
  164577. ta = compptr->ac_tbl_no;
  164578. if (cinfo->progressive_mode) {
  164579. /* Progressive mode: only DC or only AC tables are used in one scan;
  164580. * furthermore, Huffman coding of DC refinement uses no table at all.
  164581. * We emit 0 for unused field(s); this is recommended by the P&M text
  164582. * but does not seem to be specified in the standard.
  164583. */
  164584. if (cinfo->Ss == 0) {
  164585. ta = 0; /* DC scan */
  164586. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164587. td = 0; /* no DC table either */
  164588. } else {
  164589. td = 0; /* AC scan */
  164590. }
  164591. }
  164592. emit_byte(cinfo, (td << 4) + ta);
  164593. }
  164594. emit_byte(cinfo, cinfo->Ss);
  164595. emit_byte(cinfo, cinfo->Se);
  164596. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164597. }
  164598. LOCAL(void)
  164599. emit_jfif_app0 (j_compress_ptr cinfo)
  164600. /* Emit a JFIF-compliant APP0 marker */
  164601. {
  164602. /*
  164603. * Length of APP0 block (2 bytes)
  164604. * Block ID (4 bytes - ASCII "JFIF")
  164605. * Zero byte (1 byte to terminate the ID string)
  164606. * Version Major, Minor (2 bytes - major first)
  164607. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164608. * Xdpu (2 bytes - dots per unit horizontal)
  164609. * Ydpu (2 bytes - dots per unit vertical)
  164610. * Thumbnail X size (1 byte)
  164611. * Thumbnail Y size (1 byte)
  164612. */
  164613. emit_marker(cinfo, M_APP0);
  164614. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164615. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164616. emit_byte(cinfo, 0x46);
  164617. emit_byte(cinfo, 0x49);
  164618. emit_byte(cinfo, 0x46);
  164619. emit_byte(cinfo, 0);
  164620. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164621. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164622. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164623. emit_2bytes(cinfo, (int) cinfo->X_density);
  164624. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164625. emit_byte(cinfo, 0); /* No thumbnail image */
  164626. emit_byte(cinfo, 0);
  164627. }
  164628. LOCAL(void)
  164629. emit_adobe_app14 (j_compress_ptr cinfo)
  164630. /* Emit an Adobe APP14 marker */
  164631. {
  164632. /*
  164633. * Length of APP14 block (2 bytes)
  164634. * Block ID (5 bytes - ASCII "Adobe")
  164635. * Version Number (2 bytes - currently 100)
  164636. * Flags0 (2 bytes - currently 0)
  164637. * Flags1 (2 bytes - currently 0)
  164638. * Color transform (1 byte)
  164639. *
  164640. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164641. * now in circulation seem to use Version = 100, so that's what we write.
  164642. *
  164643. * We write the color transform byte as 1 if the JPEG color space is
  164644. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164645. * whether the encoder performed a transformation, which is pretty useless.
  164646. */
  164647. emit_marker(cinfo, M_APP14);
  164648. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164649. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164650. emit_byte(cinfo, 0x64);
  164651. emit_byte(cinfo, 0x6F);
  164652. emit_byte(cinfo, 0x62);
  164653. emit_byte(cinfo, 0x65);
  164654. emit_2bytes(cinfo, 100); /* Version */
  164655. emit_2bytes(cinfo, 0); /* Flags0 */
  164656. emit_2bytes(cinfo, 0); /* Flags1 */
  164657. switch (cinfo->jpeg_color_space) {
  164658. case JCS_YCbCr:
  164659. emit_byte(cinfo, 1); /* Color transform = 1 */
  164660. break;
  164661. case JCS_YCCK:
  164662. emit_byte(cinfo, 2); /* Color transform = 2 */
  164663. break;
  164664. default:
  164665. emit_byte(cinfo, 0); /* Color transform = 0 */
  164666. break;
  164667. }
  164668. }
  164669. /*
  164670. * These routines allow writing an arbitrary marker with parameters.
  164671. * The only intended use is to emit COM or APPn markers after calling
  164672. * write_file_header and before calling write_frame_header.
  164673. * Other uses are not guaranteed to produce desirable results.
  164674. * Counting the parameter bytes properly is the caller's responsibility.
  164675. */
  164676. METHODDEF(void)
  164677. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164678. /* Emit an arbitrary marker header */
  164679. {
  164680. if (datalen > (unsigned int) 65533) /* safety check */
  164681. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164682. emit_marker(cinfo, (JPEG_MARKER) marker);
  164683. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164684. }
  164685. METHODDEF(void)
  164686. write_marker_byte (j_compress_ptr cinfo, int val)
  164687. /* Emit one byte of marker parameters following write_marker_header */
  164688. {
  164689. emit_byte(cinfo, val);
  164690. }
  164691. /*
  164692. * Write datastream header.
  164693. * This consists of an SOI and optional APPn markers.
  164694. * We recommend use of the JFIF marker, but not the Adobe marker,
  164695. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164696. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164697. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164698. * Note that an application can write additional header markers after
  164699. * jpeg_start_compress returns.
  164700. */
  164701. METHODDEF(void)
  164702. write_file_header (j_compress_ptr cinfo)
  164703. {
  164704. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164705. emit_marker(cinfo, M_SOI); /* first the SOI */
  164706. /* SOI is defined to reset restart interval to 0 */
  164707. marker->last_restart_interval = 0;
  164708. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164709. emit_jfif_app0(cinfo);
  164710. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164711. emit_adobe_app14(cinfo);
  164712. }
  164713. /*
  164714. * Write frame header.
  164715. * This consists of DQT and SOFn markers.
  164716. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164717. * This avoids compatibility problems with incorrect implementations that
  164718. * try to error-check the quant table numbers as soon as they see the SOF.
  164719. */
  164720. METHODDEF(void)
  164721. write_frame_header (j_compress_ptr cinfo)
  164722. {
  164723. int ci, prec;
  164724. boolean is_baseline;
  164725. jpeg_component_info *compptr;
  164726. /* Emit DQT for each quantization table.
  164727. * Note that emit_dqt() suppresses any duplicate tables.
  164728. */
  164729. prec = 0;
  164730. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164731. ci++, compptr++) {
  164732. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164733. }
  164734. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164735. /* Check for a non-baseline specification.
  164736. * Note we assume that Huffman table numbers won't be changed later.
  164737. */
  164738. if (cinfo->arith_code || cinfo->progressive_mode ||
  164739. cinfo->data_precision != 8) {
  164740. is_baseline = FALSE;
  164741. } else {
  164742. is_baseline = TRUE;
  164743. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164744. ci++, compptr++) {
  164745. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164746. is_baseline = FALSE;
  164747. }
  164748. if (prec && is_baseline) {
  164749. is_baseline = FALSE;
  164750. /* If it's baseline except for quantizer size, warn the user */
  164751. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164752. }
  164753. }
  164754. /* Emit the proper SOF marker */
  164755. if (cinfo->arith_code) {
  164756. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164757. } else {
  164758. if (cinfo->progressive_mode)
  164759. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164760. else if (is_baseline)
  164761. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164762. else
  164763. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164764. }
  164765. }
  164766. /*
  164767. * Write scan header.
  164768. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164769. * Compressed data will be written following the SOS.
  164770. */
  164771. METHODDEF(void)
  164772. write_scan_header (j_compress_ptr cinfo)
  164773. {
  164774. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164775. int i;
  164776. jpeg_component_info *compptr;
  164777. if (cinfo->arith_code) {
  164778. /* Emit arith conditioning info. We may have some duplication
  164779. * if the file has multiple scans, but it's so small it's hardly
  164780. * worth worrying about.
  164781. */
  164782. emit_dac(cinfo);
  164783. } else {
  164784. /* Emit Huffman tables.
  164785. * Note that emit_dht() suppresses any duplicate tables.
  164786. */
  164787. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164788. compptr = cinfo->cur_comp_info[i];
  164789. if (cinfo->progressive_mode) {
  164790. /* Progressive mode: only DC or only AC tables are used in one scan */
  164791. if (cinfo->Ss == 0) {
  164792. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164793. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164794. } else {
  164795. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164796. }
  164797. } else {
  164798. /* Sequential mode: need both DC and AC tables */
  164799. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164800. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164801. }
  164802. }
  164803. }
  164804. /* Emit DRI if required --- note that DRI value could change for each scan.
  164805. * We avoid wasting space with unnecessary DRIs, however.
  164806. */
  164807. if (cinfo->restart_interval != marker->last_restart_interval) {
  164808. emit_dri(cinfo);
  164809. marker->last_restart_interval = cinfo->restart_interval;
  164810. }
  164811. emit_sos(cinfo);
  164812. }
  164813. /*
  164814. * Write datastream trailer.
  164815. */
  164816. METHODDEF(void)
  164817. write_file_trailer (j_compress_ptr cinfo)
  164818. {
  164819. emit_marker(cinfo, M_EOI);
  164820. }
  164821. /*
  164822. * Write an abbreviated table-specification datastream.
  164823. * This consists of SOI, DQT and DHT tables, and EOI.
  164824. * Any table that is defined and not marked sent_table = TRUE will be
  164825. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164826. */
  164827. METHODDEF(void)
  164828. write_tables_only (j_compress_ptr cinfo)
  164829. {
  164830. int i;
  164831. emit_marker(cinfo, M_SOI);
  164832. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164833. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164834. (void) emit_dqt(cinfo, i);
  164835. }
  164836. if (! cinfo->arith_code) {
  164837. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164838. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164839. emit_dht(cinfo, i, FALSE);
  164840. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164841. emit_dht(cinfo, i, TRUE);
  164842. }
  164843. }
  164844. emit_marker(cinfo, M_EOI);
  164845. }
  164846. /*
  164847. * Initialize the marker writer module.
  164848. */
  164849. GLOBAL(void)
  164850. jinit_marker_writer (j_compress_ptr cinfo)
  164851. {
  164852. my_marker_ptr marker;
  164853. /* Create the subobject */
  164854. marker = (my_marker_ptr)
  164855. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164856. SIZEOF(my_marker_writer));
  164857. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164858. /* Initialize method pointers */
  164859. marker->pub.write_file_header = write_file_header;
  164860. marker->pub.write_frame_header = write_frame_header;
  164861. marker->pub.write_scan_header = write_scan_header;
  164862. marker->pub.write_file_trailer = write_file_trailer;
  164863. marker->pub.write_tables_only = write_tables_only;
  164864. marker->pub.write_marker_header = write_marker_header;
  164865. marker->pub.write_marker_byte = write_marker_byte;
  164866. /* Initialize private state */
  164867. marker->last_restart_interval = 0;
  164868. }
  164869. /*** End of inlined file: jcmarker.c ***/
  164870. /*** Start of inlined file: jcmaster.c ***/
  164871. #define JPEG_INTERNALS
  164872. /* Private state */
  164873. typedef enum {
  164874. main_pass, /* input data, also do first output step */
  164875. huff_opt_pass, /* Huffman code optimization pass */
  164876. output_pass /* data output pass */
  164877. } c_pass_type;
  164878. typedef struct {
  164879. struct jpeg_comp_master pub; /* public fields */
  164880. c_pass_type pass_type; /* the type of the current pass */
  164881. int pass_number; /* # of passes completed */
  164882. int total_passes; /* total # of passes needed */
  164883. int scan_number; /* current index in scan_info[] */
  164884. } my_comp_master;
  164885. typedef my_comp_master * my_master_ptr;
  164886. /*
  164887. * Support routines that do various essential calculations.
  164888. */
  164889. LOCAL(void)
  164890. initial_setup (j_compress_ptr cinfo)
  164891. /* Do computations that are needed before master selection phase */
  164892. {
  164893. int ci;
  164894. jpeg_component_info *compptr;
  164895. long samplesperrow;
  164896. JDIMENSION jd_samplesperrow;
  164897. /* Sanity check on image dimensions */
  164898. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164899. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164900. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164901. /* Make sure image isn't bigger than I can handle */
  164902. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164903. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164904. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164905. /* Width of an input scanline must be representable as JDIMENSION. */
  164906. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164907. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164908. if ((long) jd_samplesperrow != samplesperrow)
  164909. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164910. /* For now, precision must match compiled-in value... */
  164911. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164912. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164913. /* Check that number of components won't exceed internal array sizes */
  164914. if (cinfo->num_components > MAX_COMPONENTS)
  164915. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164916. MAX_COMPONENTS);
  164917. /* Compute maximum sampling factors; check factor validity */
  164918. cinfo->max_h_samp_factor = 1;
  164919. cinfo->max_v_samp_factor = 1;
  164920. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164921. ci++, compptr++) {
  164922. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164923. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164924. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164925. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164926. compptr->h_samp_factor);
  164927. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164928. compptr->v_samp_factor);
  164929. }
  164930. /* Compute dimensions of components */
  164931. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164932. ci++, compptr++) {
  164933. /* Fill in the correct component_index value; don't rely on application */
  164934. compptr->component_index = ci;
  164935. /* For compression, we never do DCT scaling. */
  164936. compptr->DCT_scaled_size = DCTSIZE;
  164937. /* Size in DCT blocks */
  164938. compptr->width_in_blocks = (JDIMENSION)
  164939. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164940. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164941. compptr->height_in_blocks = (JDIMENSION)
  164942. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164943. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164944. /* Size in samples */
  164945. compptr->downsampled_width = (JDIMENSION)
  164946. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164947. (long) cinfo->max_h_samp_factor);
  164948. compptr->downsampled_height = (JDIMENSION)
  164949. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164950. (long) cinfo->max_v_samp_factor);
  164951. /* Mark component needed (this flag isn't actually used for compression) */
  164952. compptr->component_needed = TRUE;
  164953. }
  164954. /* Compute number of fully interleaved MCU rows (number of times that
  164955. * main controller will call coefficient controller).
  164956. */
  164957. cinfo->total_iMCU_rows = (JDIMENSION)
  164958. jdiv_round_up((long) cinfo->image_height,
  164959. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164960. }
  164961. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164962. LOCAL(void)
  164963. validate_script (j_compress_ptr cinfo)
  164964. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164965. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164966. */
  164967. {
  164968. const jpeg_scan_info * scanptr;
  164969. int scanno, ncomps, ci, coefi, thisi;
  164970. int Ss, Se, Ah, Al;
  164971. boolean component_sent[MAX_COMPONENTS];
  164972. #ifdef C_PROGRESSIVE_SUPPORTED
  164973. int * last_bitpos_ptr;
  164974. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164975. /* -1 until that coefficient has been seen; then last Al for it */
  164976. #endif
  164977. if (cinfo->num_scans <= 0)
  164978. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164979. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164980. * for progressive JPEG, no scan can have this.
  164981. */
  164982. scanptr = cinfo->scan_info;
  164983. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164984. #ifdef C_PROGRESSIVE_SUPPORTED
  164985. cinfo->progressive_mode = TRUE;
  164986. last_bitpos_ptr = & last_bitpos[0][0];
  164987. for (ci = 0; ci < cinfo->num_components; ci++)
  164988. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164989. *last_bitpos_ptr++ = -1;
  164990. #else
  164991. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164992. #endif
  164993. } else {
  164994. cinfo->progressive_mode = FALSE;
  164995. for (ci = 0; ci < cinfo->num_components; ci++)
  164996. component_sent[ci] = FALSE;
  164997. }
  164998. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164999. /* Validate component indexes */
  165000. ncomps = scanptr->comps_in_scan;
  165001. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  165002. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  165003. for (ci = 0; ci < ncomps; ci++) {
  165004. thisi = scanptr->component_index[ci];
  165005. if (thisi < 0 || thisi >= cinfo->num_components)
  165006. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165007. /* Components must appear in SOF order within each scan */
  165008. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  165009. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165010. }
  165011. /* Validate progression parameters */
  165012. Ss = scanptr->Ss;
  165013. Se = scanptr->Se;
  165014. Ah = scanptr->Ah;
  165015. Al = scanptr->Al;
  165016. if (cinfo->progressive_mode) {
  165017. #ifdef C_PROGRESSIVE_SUPPORTED
  165018. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  165019. * seems wrong: the upper bound ought to depend on data precision.
  165020. * Perhaps they really meant 0..N+1 for N-bit precision.
  165021. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  165022. * out-of-range reconstructed DC values during the first DC scan,
  165023. * which might cause problems for some decoders.
  165024. */
  165025. #if BITS_IN_JSAMPLE == 8
  165026. #define MAX_AH_AL 10
  165027. #else
  165028. #define MAX_AH_AL 13
  165029. #endif
  165030. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  165031. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  165032. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165033. if (Ss == 0) {
  165034. if (Se != 0) /* DC and AC together not OK */
  165035. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165036. } else {
  165037. if (ncomps != 1) /* AC scans must be for only one component */
  165038. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165039. }
  165040. for (ci = 0; ci < ncomps; ci++) {
  165041. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  165042. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  165043. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165044. for (coefi = Ss; coefi <= Se; coefi++) {
  165045. if (last_bitpos_ptr[coefi] < 0) {
  165046. /* first scan of this coefficient */
  165047. if (Ah != 0)
  165048. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165049. } else {
  165050. /* not first scan */
  165051. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  165052. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165053. }
  165054. last_bitpos_ptr[coefi] = Al;
  165055. }
  165056. }
  165057. #endif
  165058. } else {
  165059. /* For sequential JPEG, all progression parameters must be these: */
  165060. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  165061. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165062. /* Make sure components are not sent twice */
  165063. for (ci = 0; ci < ncomps; ci++) {
  165064. thisi = scanptr->component_index[ci];
  165065. if (component_sent[thisi])
  165066. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165067. component_sent[thisi] = TRUE;
  165068. }
  165069. }
  165070. }
  165071. /* Now verify that everything got sent. */
  165072. if (cinfo->progressive_mode) {
  165073. #ifdef C_PROGRESSIVE_SUPPORTED
  165074. /* For progressive mode, we only check that at least some DC data
  165075. * got sent for each component; the spec does not require that all bits
  165076. * of all coefficients be transmitted. Would it be wiser to enforce
  165077. * transmission of all coefficient bits??
  165078. */
  165079. for (ci = 0; ci < cinfo->num_components; ci++) {
  165080. if (last_bitpos[ci][0] < 0)
  165081. ERREXIT(cinfo, JERR_MISSING_DATA);
  165082. }
  165083. #endif
  165084. } else {
  165085. for (ci = 0; ci < cinfo->num_components; ci++) {
  165086. if (! component_sent[ci])
  165087. ERREXIT(cinfo, JERR_MISSING_DATA);
  165088. }
  165089. }
  165090. }
  165091. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  165092. LOCAL(void)
  165093. select_scan_parameters (j_compress_ptr cinfo)
  165094. /* Set up the scan parameters for the current scan */
  165095. {
  165096. int ci;
  165097. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165098. if (cinfo->scan_info != NULL) {
  165099. /* Prepare for current scan --- the script is already validated */
  165100. my_master_ptr master = (my_master_ptr) cinfo->master;
  165101. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  165102. cinfo->comps_in_scan = scanptr->comps_in_scan;
  165103. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  165104. cinfo->cur_comp_info[ci] =
  165105. &cinfo->comp_info[scanptr->component_index[ci]];
  165106. }
  165107. cinfo->Ss = scanptr->Ss;
  165108. cinfo->Se = scanptr->Se;
  165109. cinfo->Ah = scanptr->Ah;
  165110. cinfo->Al = scanptr->Al;
  165111. }
  165112. else
  165113. #endif
  165114. {
  165115. /* Prepare for single sequential-JPEG scan containing all components */
  165116. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  165117. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165118. MAX_COMPS_IN_SCAN);
  165119. cinfo->comps_in_scan = cinfo->num_components;
  165120. for (ci = 0; ci < cinfo->num_components; ci++) {
  165121. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  165122. }
  165123. cinfo->Ss = 0;
  165124. cinfo->Se = DCTSIZE2-1;
  165125. cinfo->Ah = 0;
  165126. cinfo->Al = 0;
  165127. }
  165128. }
  165129. LOCAL(void)
  165130. per_scan_setup (j_compress_ptr cinfo)
  165131. /* Do computations that are needed before processing a JPEG scan */
  165132. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  165133. {
  165134. int ci, mcublks, tmp;
  165135. jpeg_component_info *compptr;
  165136. if (cinfo->comps_in_scan == 1) {
  165137. /* Noninterleaved (single-component) scan */
  165138. compptr = cinfo->cur_comp_info[0];
  165139. /* Overall image size in MCUs */
  165140. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165141. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165142. /* For noninterleaved scan, always one block per MCU */
  165143. compptr->MCU_width = 1;
  165144. compptr->MCU_height = 1;
  165145. compptr->MCU_blocks = 1;
  165146. compptr->MCU_sample_width = DCTSIZE;
  165147. compptr->last_col_width = 1;
  165148. /* For noninterleaved scans, it is convenient to define last_row_height
  165149. * as the number of block rows present in the last iMCU row.
  165150. */
  165151. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165152. if (tmp == 0) tmp = compptr->v_samp_factor;
  165153. compptr->last_row_height = tmp;
  165154. /* Prepare array describing MCU composition */
  165155. cinfo->blocks_in_MCU = 1;
  165156. cinfo->MCU_membership[0] = 0;
  165157. } else {
  165158. /* Interleaved (multi-component) scan */
  165159. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165160. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165161. MAX_COMPS_IN_SCAN);
  165162. /* Overall image size in MCUs */
  165163. cinfo->MCUs_per_row = (JDIMENSION)
  165164. jdiv_round_up((long) cinfo->image_width,
  165165. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165166. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165167. jdiv_round_up((long) cinfo->image_height,
  165168. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165169. cinfo->blocks_in_MCU = 0;
  165170. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165171. compptr = cinfo->cur_comp_info[ci];
  165172. /* Sampling factors give # of blocks of component in each MCU */
  165173. compptr->MCU_width = compptr->h_samp_factor;
  165174. compptr->MCU_height = compptr->v_samp_factor;
  165175. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165176. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165177. /* Figure number of non-dummy blocks in last MCU column & row */
  165178. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165179. if (tmp == 0) tmp = compptr->MCU_width;
  165180. compptr->last_col_width = tmp;
  165181. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165182. if (tmp == 0) tmp = compptr->MCU_height;
  165183. compptr->last_row_height = tmp;
  165184. /* Prepare array describing MCU composition */
  165185. mcublks = compptr->MCU_blocks;
  165186. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165187. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165188. while (mcublks-- > 0) {
  165189. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165190. }
  165191. }
  165192. }
  165193. /* Convert restart specified in rows to actual MCU count. */
  165194. /* Note that count must fit in 16 bits, so we provide limiting. */
  165195. if (cinfo->restart_in_rows > 0) {
  165196. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165197. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165198. }
  165199. }
  165200. /*
  165201. * Per-pass setup.
  165202. * This is called at the beginning of each pass. We determine which modules
  165203. * will be active during this pass and give them appropriate start_pass calls.
  165204. * We also set is_last_pass to indicate whether any more passes will be
  165205. * required.
  165206. */
  165207. METHODDEF(void)
  165208. prepare_for_pass (j_compress_ptr cinfo)
  165209. {
  165210. my_master_ptr master = (my_master_ptr) cinfo->master;
  165211. switch (master->pass_type) {
  165212. case main_pass:
  165213. /* Initial pass: will collect input data, and do either Huffman
  165214. * optimization or data output for the first scan.
  165215. */
  165216. select_scan_parameters(cinfo);
  165217. per_scan_setup(cinfo);
  165218. if (! cinfo->raw_data_in) {
  165219. (*cinfo->cconvert->start_pass) (cinfo);
  165220. (*cinfo->downsample->start_pass) (cinfo);
  165221. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165222. }
  165223. (*cinfo->fdct->start_pass) (cinfo);
  165224. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165225. (*cinfo->coef->start_pass) (cinfo,
  165226. (master->total_passes > 1 ?
  165227. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165228. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165229. if (cinfo->optimize_coding) {
  165230. /* No immediate data output; postpone writing frame/scan headers */
  165231. master->pub.call_pass_startup = FALSE;
  165232. } else {
  165233. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165234. master->pub.call_pass_startup = TRUE;
  165235. }
  165236. break;
  165237. #ifdef ENTROPY_OPT_SUPPORTED
  165238. case huff_opt_pass:
  165239. /* Do Huffman optimization for a scan after the first one. */
  165240. select_scan_parameters(cinfo);
  165241. per_scan_setup(cinfo);
  165242. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165243. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165244. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165245. master->pub.call_pass_startup = FALSE;
  165246. break;
  165247. }
  165248. /* Special case: Huffman DC refinement scans need no Huffman table
  165249. * and therefore we can skip the optimization pass for them.
  165250. */
  165251. master->pass_type = output_pass;
  165252. master->pass_number++;
  165253. /*FALLTHROUGH*/
  165254. #endif
  165255. case output_pass:
  165256. /* Do a data-output pass. */
  165257. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165258. if (! cinfo->optimize_coding) {
  165259. select_scan_parameters(cinfo);
  165260. per_scan_setup(cinfo);
  165261. }
  165262. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165263. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165264. /* We emit frame/scan headers now */
  165265. if (master->scan_number == 0)
  165266. (*cinfo->marker->write_frame_header) (cinfo);
  165267. (*cinfo->marker->write_scan_header) (cinfo);
  165268. master->pub.call_pass_startup = FALSE;
  165269. break;
  165270. default:
  165271. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165272. }
  165273. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165274. /* Set up progress monitor's pass info if present */
  165275. if (cinfo->progress != NULL) {
  165276. cinfo->progress->completed_passes = master->pass_number;
  165277. cinfo->progress->total_passes = master->total_passes;
  165278. }
  165279. }
  165280. /*
  165281. * Special start-of-pass hook.
  165282. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165283. * In single-pass processing, we need this hook because we don't want to
  165284. * write frame/scan headers during jpeg_start_compress; we want to let the
  165285. * application write COM markers etc. between jpeg_start_compress and the
  165286. * jpeg_write_scanlines loop.
  165287. * In multi-pass processing, this routine is not used.
  165288. */
  165289. METHODDEF(void)
  165290. pass_startup (j_compress_ptr cinfo)
  165291. {
  165292. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165293. (*cinfo->marker->write_frame_header) (cinfo);
  165294. (*cinfo->marker->write_scan_header) (cinfo);
  165295. }
  165296. /*
  165297. * Finish up at end of pass.
  165298. */
  165299. METHODDEF(void)
  165300. finish_pass_master (j_compress_ptr cinfo)
  165301. {
  165302. my_master_ptr master = (my_master_ptr) cinfo->master;
  165303. /* The entropy coder always needs an end-of-pass call,
  165304. * either to analyze statistics or to flush its output buffer.
  165305. */
  165306. (*cinfo->entropy->finish_pass) (cinfo);
  165307. /* Update state for next pass */
  165308. switch (master->pass_type) {
  165309. case main_pass:
  165310. /* next pass is either output of scan 0 (after optimization)
  165311. * or output of scan 1 (if no optimization).
  165312. */
  165313. master->pass_type = output_pass;
  165314. if (! cinfo->optimize_coding)
  165315. master->scan_number++;
  165316. break;
  165317. case huff_opt_pass:
  165318. /* next pass is always output of current scan */
  165319. master->pass_type = output_pass;
  165320. break;
  165321. case output_pass:
  165322. /* next pass is either optimization or output of next scan */
  165323. if (cinfo->optimize_coding)
  165324. master->pass_type = huff_opt_pass;
  165325. master->scan_number++;
  165326. break;
  165327. }
  165328. master->pass_number++;
  165329. }
  165330. /*
  165331. * Initialize master compression control.
  165332. */
  165333. GLOBAL(void)
  165334. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165335. {
  165336. my_master_ptr master;
  165337. master = (my_master_ptr)
  165338. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165339. SIZEOF(my_comp_master));
  165340. cinfo->master = (struct jpeg_comp_master *) master;
  165341. master->pub.prepare_for_pass = prepare_for_pass;
  165342. master->pub.pass_startup = pass_startup;
  165343. master->pub.finish_pass = finish_pass_master;
  165344. master->pub.is_last_pass = FALSE;
  165345. /* Validate parameters, determine derived values */
  165346. initial_setup(cinfo);
  165347. if (cinfo->scan_info != NULL) {
  165348. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165349. validate_script(cinfo);
  165350. #else
  165351. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165352. #endif
  165353. } else {
  165354. cinfo->progressive_mode = FALSE;
  165355. cinfo->num_scans = 1;
  165356. }
  165357. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165358. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165359. /* Initialize my private state */
  165360. if (transcode_only) {
  165361. /* no main pass in transcoding */
  165362. if (cinfo->optimize_coding)
  165363. master->pass_type = huff_opt_pass;
  165364. else
  165365. master->pass_type = output_pass;
  165366. } else {
  165367. /* for normal compression, first pass is always this type: */
  165368. master->pass_type = main_pass;
  165369. }
  165370. master->scan_number = 0;
  165371. master->pass_number = 0;
  165372. if (cinfo->optimize_coding)
  165373. master->total_passes = cinfo->num_scans * 2;
  165374. else
  165375. master->total_passes = cinfo->num_scans;
  165376. }
  165377. /*** End of inlined file: jcmaster.c ***/
  165378. /*** Start of inlined file: jcomapi.c ***/
  165379. #define JPEG_INTERNALS
  165380. /*
  165381. * Abort processing of a JPEG compression or decompression operation,
  165382. * but don't destroy the object itself.
  165383. *
  165384. * For this, we merely clean up all the nonpermanent memory pools.
  165385. * Note that temp files (virtual arrays) are not allowed to belong to
  165386. * the permanent pool, so we will be able to close all temp files here.
  165387. * Closing a data source or destination, if necessary, is the application's
  165388. * responsibility.
  165389. */
  165390. GLOBAL(void)
  165391. jpeg_abort (j_common_ptr cinfo)
  165392. {
  165393. int pool;
  165394. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165395. if (cinfo->mem == NULL)
  165396. return;
  165397. /* Releasing pools in reverse order might help avoid fragmentation
  165398. * with some (brain-damaged) malloc libraries.
  165399. */
  165400. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165401. (*cinfo->mem->free_pool) (cinfo, pool);
  165402. }
  165403. /* Reset overall state for possible reuse of object */
  165404. if (cinfo->is_decompressor) {
  165405. cinfo->global_state = DSTATE_START;
  165406. /* Try to keep application from accessing now-deleted marker list.
  165407. * A bit kludgy to do it here, but this is the most central place.
  165408. */
  165409. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165410. } else {
  165411. cinfo->global_state = CSTATE_START;
  165412. }
  165413. }
  165414. /*
  165415. * Destruction of a JPEG object.
  165416. *
  165417. * Everything gets deallocated except the master jpeg_compress_struct itself
  165418. * and the error manager struct. Both of these are supplied by the application
  165419. * and must be freed, if necessary, by the application. (Often they are on
  165420. * the stack and so don't need to be freed anyway.)
  165421. * Closing a data source or destination, if necessary, is the application's
  165422. * responsibility.
  165423. */
  165424. GLOBAL(void)
  165425. jpeg_destroy (j_common_ptr cinfo)
  165426. {
  165427. /* We need only tell the memory manager to release everything. */
  165428. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165429. if (cinfo->mem != NULL)
  165430. (*cinfo->mem->self_destruct) (cinfo);
  165431. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165432. cinfo->global_state = 0; /* mark it destroyed */
  165433. }
  165434. /*
  165435. * Convenience routines for allocating quantization and Huffman tables.
  165436. * (Would jutils.c be a more reasonable place to put these?)
  165437. */
  165438. GLOBAL(JQUANT_TBL *)
  165439. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165440. {
  165441. JQUANT_TBL *tbl;
  165442. tbl = (JQUANT_TBL *)
  165443. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165444. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165445. return tbl;
  165446. }
  165447. GLOBAL(JHUFF_TBL *)
  165448. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165449. {
  165450. JHUFF_TBL *tbl;
  165451. tbl = (JHUFF_TBL *)
  165452. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165453. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165454. return tbl;
  165455. }
  165456. /*** End of inlined file: jcomapi.c ***/
  165457. /*** Start of inlined file: jcparam.c ***/
  165458. #define JPEG_INTERNALS
  165459. /*
  165460. * Quantization table setup routines
  165461. */
  165462. GLOBAL(void)
  165463. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165464. const unsigned int *basic_table,
  165465. int scale_factor, boolean force_baseline)
  165466. /* Define a quantization table equal to the basic_table times
  165467. * a scale factor (given as a percentage).
  165468. * If force_baseline is TRUE, the computed quantization table entries
  165469. * are limited to 1..255 for JPEG baseline compatibility.
  165470. */
  165471. {
  165472. JQUANT_TBL ** qtblptr;
  165473. int i;
  165474. long temp;
  165475. /* Safety check to ensure start_compress not called yet. */
  165476. if (cinfo->global_state != CSTATE_START)
  165477. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165478. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165479. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165480. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165481. if (*qtblptr == NULL)
  165482. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165483. for (i = 0; i < DCTSIZE2; i++) {
  165484. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165485. /* limit the values to the valid range */
  165486. if (temp <= 0L) temp = 1L;
  165487. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165488. if (force_baseline && temp > 255L)
  165489. temp = 255L; /* limit to baseline range if requested */
  165490. (*qtblptr)->quantval[i] = (UINT16) temp;
  165491. }
  165492. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165493. (*qtblptr)->sent_table = FALSE;
  165494. }
  165495. GLOBAL(void)
  165496. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165497. boolean force_baseline)
  165498. /* Set or change the 'quality' (quantization) setting, using default tables
  165499. * and a straight percentage-scaling quality scale. In most cases it's better
  165500. * to use jpeg_set_quality (below); this entry point is provided for
  165501. * applications that insist on a linear percentage scaling.
  165502. */
  165503. {
  165504. /* These are the sample quantization tables given in JPEG spec section K.1.
  165505. * The spec says that the values given produce "good" quality, and
  165506. * when divided by 2, "very good" quality.
  165507. */
  165508. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165509. 16, 11, 10, 16, 24, 40, 51, 61,
  165510. 12, 12, 14, 19, 26, 58, 60, 55,
  165511. 14, 13, 16, 24, 40, 57, 69, 56,
  165512. 14, 17, 22, 29, 51, 87, 80, 62,
  165513. 18, 22, 37, 56, 68, 109, 103, 77,
  165514. 24, 35, 55, 64, 81, 104, 113, 92,
  165515. 49, 64, 78, 87, 103, 121, 120, 101,
  165516. 72, 92, 95, 98, 112, 100, 103, 99
  165517. };
  165518. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165519. 17, 18, 24, 47, 99, 99, 99, 99,
  165520. 18, 21, 26, 66, 99, 99, 99, 99,
  165521. 24, 26, 56, 99, 99, 99, 99, 99,
  165522. 47, 66, 99, 99, 99, 99, 99, 99,
  165523. 99, 99, 99, 99, 99, 99, 99, 99,
  165524. 99, 99, 99, 99, 99, 99, 99, 99,
  165525. 99, 99, 99, 99, 99, 99, 99, 99,
  165526. 99, 99, 99, 99, 99, 99, 99, 99
  165527. };
  165528. /* Set up two quantization tables using the specified scaling */
  165529. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165530. scale_factor, force_baseline);
  165531. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165532. scale_factor, force_baseline);
  165533. }
  165534. GLOBAL(int)
  165535. jpeg_quality_scaling (int quality)
  165536. /* Convert a user-specified quality rating to a percentage scaling factor
  165537. * for an underlying quantization table, using our recommended scaling curve.
  165538. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165539. */
  165540. {
  165541. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165542. if (quality <= 0) quality = 1;
  165543. if (quality > 100) quality = 100;
  165544. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165545. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165546. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165547. * to make all the table entries 1 (hence, minimum quantization loss).
  165548. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165549. */
  165550. if (quality < 50)
  165551. quality = 5000 / quality;
  165552. else
  165553. quality = 200 - quality*2;
  165554. return quality;
  165555. }
  165556. GLOBAL(void)
  165557. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165558. /* Set or change the 'quality' (quantization) setting, using default tables.
  165559. * This is the standard quality-adjusting entry point for typical user
  165560. * interfaces; only those who want detailed control over quantization tables
  165561. * would use the preceding three routines directly.
  165562. */
  165563. {
  165564. /* Convert user 0-100 rating to percentage scaling */
  165565. quality = jpeg_quality_scaling(quality);
  165566. /* Set up standard quality tables */
  165567. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165568. }
  165569. /*
  165570. * Huffman table setup routines
  165571. */
  165572. LOCAL(void)
  165573. add_huff_table (j_compress_ptr cinfo,
  165574. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165575. /* Define a Huffman table */
  165576. {
  165577. int nsymbols, len;
  165578. if (*htblptr == NULL)
  165579. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165580. /* Copy the number-of-symbols-of-each-code-length counts */
  165581. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165582. /* Validate the counts. We do this here mainly so we can copy the right
  165583. * number of symbols from the val[] array, without risking marching off
  165584. * the end of memory. jchuff.c will do a more thorough test later.
  165585. */
  165586. nsymbols = 0;
  165587. for (len = 1; len <= 16; len++)
  165588. nsymbols += bits[len];
  165589. if (nsymbols < 1 || nsymbols > 256)
  165590. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165591. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165592. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165593. (*htblptr)->sent_table = FALSE;
  165594. }
  165595. LOCAL(void)
  165596. std_huff_tables (j_compress_ptr cinfo)
  165597. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165598. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165599. {
  165600. static const UINT8 bits_dc_luminance[17] =
  165601. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165602. static const UINT8 val_dc_luminance[] =
  165603. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165604. static const UINT8 bits_dc_chrominance[17] =
  165605. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165606. static const UINT8 val_dc_chrominance[] =
  165607. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165608. static const UINT8 bits_ac_luminance[17] =
  165609. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165610. static const UINT8 val_ac_luminance[] =
  165611. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165612. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165613. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165614. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165615. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165616. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165617. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165618. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165619. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165620. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165621. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165622. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165623. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165624. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165625. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165626. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165627. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165628. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165629. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165630. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165631. 0xf9, 0xfa };
  165632. static const UINT8 bits_ac_chrominance[17] =
  165633. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165634. static const UINT8 val_ac_chrominance[] =
  165635. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165636. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165637. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165638. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165639. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165640. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165641. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165642. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165643. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165644. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165645. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165646. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165647. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165648. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165649. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165650. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165651. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165652. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165653. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165654. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165655. 0xf9, 0xfa };
  165656. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165657. bits_dc_luminance, val_dc_luminance);
  165658. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165659. bits_ac_luminance, val_ac_luminance);
  165660. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165661. bits_dc_chrominance, val_dc_chrominance);
  165662. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165663. bits_ac_chrominance, val_ac_chrominance);
  165664. }
  165665. /*
  165666. * Default parameter setup for compression.
  165667. *
  165668. * Applications that don't choose to use this routine must do their
  165669. * own setup of all these parameters. Alternately, you can call this
  165670. * to establish defaults and then alter parameters selectively. This
  165671. * is the recommended approach since, if we add any new parameters,
  165672. * your code will still work (they'll be set to reasonable defaults).
  165673. */
  165674. GLOBAL(void)
  165675. jpeg_set_defaults (j_compress_ptr cinfo)
  165676. {
  165677. int i;
  165678. /* Safety check to ensure start_compress not called yet. */
  165679. if (cinfo->global_state != CSTATE_START)
  165680. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165681. /* Allocate comp_info array large enough for maximum component count.
  165682. * Array is made permanent in case application wants to compress
  165683. * multiple images at same param settings.
  165684. */
  165685. if (cinfo->comp_info == NULL)
  165686. cinfo->comp_info = (jpeg_component_info *)
  165687. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165688. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165689. /* Initialize everything not dependent on the color space */
  165690. cinfo->data_precision = BITS_IN_JSAMPLE;
  165691. /* Set up two quantization tables using default quality of 75 */
  165692. jpeg_set_quality(cinfo, 75, TRUE);
  165693. /* Set up two Huffman tables */
  165694. std_huff_tables(cinfo);
  165695. /* Initialize default arithmetic coding conditioning */
  165696. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165697. cinfo->arith_dc_L[i] = 0;
  165698. cinfo->arith_dc_U[i] = 1;
  165699. cinfo->arith_ac_K[i] = 5;
  165700. }
  165701. /* Default is no multiple-scan output */
  165702. cinfo->scan_info = NULL;
  165703. cinfo->num_scans = 0;
  165704. /* Expect normal source image, not raw downsampled data */
  165705. cinfo->raw_data_in = FALSE;
  165706. /* Use Huffman coding, not arithmetic coding, by default */
  165707. cinfo->arith_code = FALSE;
  165708. /* By default, don't do extra passes to optimize entropy coding */
  165709. cinfo->optimize_coding = FALSE;
  165710. /* The standard Huffman tables are only valid for 8-bit data precision.
  165711. * If the precision is higher, force optimization on so that usable
  165712. * tables will be computed. This test can be removed if default tables
  165713. * are supplied that are valid for the desired precision.
  165714. */
  165715. if (cinfo->data_precision > 8)
  165716. cinfo->optimize_coding = TRUE;
  165717. /* By default, use the simpler non-cosited sampling alignment */
  165718. cinfo->CCIR601_sampling = FALSE;
  165719. /* No input smoothing */
  165720. cinfo->smoothing_factor = 0;
  165721. /* DCT algorithm preference */
  165722. cinfo->dct_method = JDCT_DEFAULT;
  165723. /* No restart markers */
  165724. cinfo->restart_interval = 0;
  165725. cinfo->restart_in_rows = 0;
  165726. /* Fill in default JFIF marker parameters. Note that whether the marker
  165727. * will actually be written is determined by jpeg_set_colorspace.
  165728. *
  165729. * By default, the library emits JFIF version code 1.01.
  165730. * An application that wants to emit JFIF 1.02 extension markers should set
  165731. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165732. * to 1.02, but there may still be some decoders in use that will complain
  165733. * about that; saying 1.01 should minimize compatibility problems.
  165734. */
  165735. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165736. cinfo->JFIF_minor_version = 1;
  165737. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165738. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165739. cinfo->Y_density = 1;
  165740. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165741. jpeg_default_colorspace(cinfo);
  165742. }
  165743. /*
  165744. * Select an appropriate JPEG colorspace for in_color_space.
  165745. */
  165746. GLOBAL(void)
  165747. jpeg_default_colorspace (j_compress_ptr cinfo)
  165748. {
  165749. switch (cinfo->in_color_space) {
  165750. case JCS_GRAYSCALE:
  165751. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165752. break;
  165753. case JCS_RGB:
  165754. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165755. break;
  165756. case JCS_YCbCr:
  165757. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165758. break;
  165759. case JCS_CMYK:
  165760. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165761. break;
  165762. case JCS_YCCK:
  165763. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165764. break;
  165765. case JCS_UNKNOWN:
  165766. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165767. break;
  165768. default:
  165769. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165770. }
  165771. }
  165772. /*
  165773. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165774. */
  165775. GLOBAL(void)
  165776. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165777. {
  165778. jpeg_component_info * compptr;
  165779. int ci;
  165780. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165781. (compptr = &cinfo->comp_info[index], \
  165782. compptr->component_id = (id), \
  165783. compptr->h_samp_factor = (hsamp), \
  165784. compptr->v_samp_factor = (vsamp), \
  165785. compptr->quant_tbl_no = (quant), \
  165786. compptr->dc_tbl_no = (dctbl), \
  165787. compptr->ac_tbl_no = (actbl) )
  165788. /* Safety check to ensure start_compress not called yet. */
  165789. if (cinfo->global_state != CSTATE_START)
  165790. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165791. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165792. * tables 1 for chrominance components.
  165793. */
  165794. cinfo->jpeg_color_space = colorspace;
  165795. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165796. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165797. switch (colorspace) {
  165798. case JCS_GRAYSCALE:
  165799. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165800. cinfo->num_components = 1;
  165801. /* JFIF specifies component ID 1 */
  165802. SET_COMP(0, 1, 1,1, 0, 0,0);
  165803. break;
  165804. case JCS_RGB:
  165805. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165806. cinfo->num_components = 3;
  165807. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165808. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165809. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165810. break;
  165811. case JCS_YCbCr:
  165812. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165813. cinfo->num_components = 3;
  165814. /* JFIF specifies component IDs 1,2,3 */
  165815. /* We default to 2x2 subsamples of chrominance */
  165816. SET_COMP(0, 1, 2,2, 0, 0,0);
  165817. SET_COMP(1, 2, 1,1, 1, 1,1);
  165818. SET_COMP(2, 3, 1,1, 1, 1,1);
  165819. break;
  165820. case JCS_CMYK:
  165821. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165822. cinfo->num_components = 4;
  165823. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165824. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165825. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165826. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165827. break;
  165828. case JCS_YCCK:
  165829. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165830. cinfo->num_components = 4;
  165831. SET_COMP(0, 1, 2,2, 0, 0,0);
  165832. SET_COMP(1, 2, 1,1, 1, 1,1);
  165833. SET_COMP(2, 3, 1,1, 1, 1,1);
  165834. SET_COMP(3, 4, 2,2, 0, 0,0);
  165835. break;
  165836. case JCS_UNKNOWN:
  165837. cinfo->num_components = cinfo->input_components;
  165838. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165839. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165840. MAX_COMPONENTS);
  165841. for (ci = 0; ci < cinfo->num_components; ci++) {
  165842. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165843. }
  165844. break;
  165845. default:
  165846. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165847. }
  165848. }
  165849. #ifdef C_PROGRESSIVE_SUPPORTED
  165850. LOCAL(jpeg_scan_info *)
  165851. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165852. int Ss, int Se, int Ah, int Al)
  165853. /* Support routine: generate one scan for specified component */
  165854. {
  165855. scanptr->comps_in_scan = 1;
  165856. scanptr->component_index[0] = ci;
  165857. scanptr->Ss = Ss;
  165858. scanptr->Se = Se;
  165859. scanptr->Ah = Ah;
  165860. scanptr->Al = Al;
  165861. scanptr++;
  165862. return scanptr;
  165863. }
  165864. LOCAL(jpeg_scan_info *)
  165865. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165866. int Ss, int Se, int Ah, int Al)
  165867. /* Support routine: generate one scan for each component */
  165868. {
  165869. int ci;
  165870. for (ci = 0; ci < ncomps; ci++) {
  165871. scanptr->comps_in_scan = 1;
  165872. scanptr->component_index[0] = ci;
  165873. scanptr->Ss = Ss;
  165874. scanptr->Se = Se;
  165875. scanptr->Ah = Ah;
  165876. scanptr->Al = Al;
  165877. scanptr++;
  165878. }
  165879. return scanptr;
  165880. }
  165881. LOCAL(jpeg_scan_info *)
  165882. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165883. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165884. {
  165885. int ci;
  165886. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165887. /* Single interleaved DC scan */
  165888. scanptr->comps_in_scan = ncomps;
  165889. for (ci = 0; ci < ncomps; ci++)
  165890. scanptr->component_index[ci] = ci;
  165891. scanptr->Ss = scanptr->Se = 0;
  165892. scanptr->Ah = Ah;
  165893. scanptr->Al = Al;
  165894. scanptr++;
  165895. } else {
  165896. /* Noninterleaved DC scan for each component */
  165897. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165898. }
  165899. return scanptr;
  165900. }
  165901. /*
  165902. * Create a recommended progressive-JPEG script.
  165903. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165904. */
  165905. GLOBAL(void)
  165906. jpeg_simple_progression (j_compress_ptr cinfo)
  165907. {
  165908. int ncomps = cinfo->num_components;
  165909. int nscans;
  165910. jpeg_scan_info * scanptr;
  165911. /* Safety check to ensure start_compress not called yet. */
  165912. if (cinfo->global_state != CSTATE_START)
  165913. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165914. /* Figure space needed for script. Calculation must match code below! */
  165915. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165916. /* Custom script for YCbCr color images. */
  165917. nscans = 10;
  165918. } else {
  165919. /* All-purpose script for other color spaces. */
  165920. if (ncomps > MAX_COMPS_IN_SCAN)
  165921. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165922. else
  165923. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165924. }
  165925. /* Allocate space for script.
  165926. * We need to put it in the permanent pool in case the application performs
  165927. * multiple compressions without changing the settings. To avoid a memory
  165928. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165929. * object, we try to re-use previously allocated space, and we allocate
  165930. * enough space to handle YCbCr even if initially asked for grayscale.
  165931. */
  165932. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165933. cinfo->script_space_size = MAX(nscans, 10);
  165934. cinfo->script_space = (jpeg_scan_info *)
  165935. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165936. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165937. }
  165938. scanptr = cinfo->script_space;
  165939. cinfo->scan_info = scanptr;
  165940. cinfo->num_scans = nscans;
  165941. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165942. /* Custom script for YCbCr color images. */
  165943. /* Initial DC scan */
  165944. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165945. /* Initial AC scan: get some luma data out in a hurry */
  165946. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165947. /* Chroma data is too small to be worth expending many scans on */
  165948. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165949. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165950. /* Complete spectral selection for luma AC */
  165951. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165952. /* Refine next bit of luma AC */
  165953. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165954. /* Finish DC successive approximation */
  165955. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165956. /* Finish AC successive approximation */
  165957. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165958. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165959. /* Luma bottom bit comes last since it's usually largest scan */
  165960. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165961. } else {
  165962. /* All-purpose script for other color spaces. */
  165963. /* Successive approximation first pass */
  165964. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165965. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165966. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165967. /* Successive approximation second pass */
  165968. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165969. /* Successive approximation final pass */
  165970. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165971. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165972. }
  165973. }
  165974. #endif /* C_PROGRESSIVE_SUPPORTED */
  165975. /*** End of inlined file: jcparam.c ***/
  165976. /*** Start of inlined file: jcphuff.c ***/
  165977. #define JPEG_INTERNALS
  165978. #ifdef C_PROGRESSIVE_SUPPORTED
  165979. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165980. typedef struct {
  165981. struct jpeg_entropy_encoder pub; /* public fields */
  165982. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165983. boolean gather_statistics;
  165984. /* Bit-level coding status.
  165985. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165986. */
  165987. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165988. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165989. INT32 put_buffer; /* current bit-accumulation buffer */
  165990. int put_bits; /* # of bits now in it */
  165991. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165992. /* Coding status for DC components */
  165993. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165994. /* Coding status for AC components */
  165995. int ac_tbl_no; /* the table number of the single component */
  165996. unsigned int EOBRUN; /* run length of EOBs */
  165997. unsigned int BE; /* # of buffered correction bits before MCU */
  165998. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165999. /* packing correction bits tightly would save some space but cost time... */
  166000. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166001. int next_restart_num; /* next restart number to write (0-7) */
  166002. /* Pointers to derived tables (these workspaces have image lifespan).
  166003. * Since any one scan codes only DC or only AC, we only need one set
  166004. * of tables, not one for DC and one for AC.
  166005. */
  166006. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  166007. /* Statistics tables for optimization; again, one set is enough */
  166008. long * count_ptrs[NUM_HUFF_TBLS];
  166009. } phuff_entropy_encoder;
  166010. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  166011. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  166012. * buffer can hold. Larger sizes may slightly improve compression, but
  166013. * 1000 is already well into the realm of overkill.
  166014. * The minimum safe size is 64 bits.
  166015. */
  166016. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  166017. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  166018. * We assume that int right shift is unsigned if INT32 right shift is,
  166019. * which should be safe.
  166020. */
  166021. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  166022. #define ISHIFT_TEMPS int ishift_temp;
  166023. #define IRIGHT_SHIFT(x,shft) \
  166024. ((ishift_temp = (x)) < 0 ? \
  166025. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  166026. (ishift_temp >> (shft)))
  166027. #else
  166028. #define ISHIFT_TEMPS
  166029. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  166030. #endif
  166031. /* Forward declarations */
  166032. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  166033. JBLOCKROW *MCU_data));
  166034. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  166035. JBLOCKROW *MCU_data));
  166036. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  166037. JBLOCKROW *MCU_data));
  166038. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  166039. JBLOCKROW *MCU_data));
  166040. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  166041. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  166042. /*
  166043. * Initialize for a Huffman-compressed scan using progressive JPEG.
  166044. */
  166045. METHODDEF(void)
  166046. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  166047. {
  166048. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166049. boolean is_DC_band;
  166050. int ci, tbl;
  166051. jpeg_component_info * compptr;
  166052. entropy->cinfo = cinfo;
  166053. entropy->gather_statistics = gather_statistics;
  166054. is_DC_band = (cinfo->Ss == 0);
  166055. /* We assume jcmaster.c already validated the scan parameters. */
  166056. /* Select execution routines */
  166057. if (cinfo->Ah == 0) {
  166058. if (is_DC_band)
  166059. entropy->pub.encode_mcu = encode_mcu_DC_first;
  166060. else
  166061. entropy->pub.encode_mcu = encode_mcu_AC_first;
  166062. } else {
  166063. if (is_DC_band)
  166064. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  166065. else {
  166066. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  166067. /* AC refinement needs a correction bit buffer */
  166068. if (entropy->bit_buffer == NULL)
  166069. entropy->bit_buffer = (char *)
  166070. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166071. MAX_CORR_BITS * SIZEOF(char));
  166072. }
  166073. }
  166074. if (gather_statistics)
  166075. entropy->pub.finish_pass = finish_pass_gather_phuff;
  166076. else
  166077. entropy->pub.finish_pass = finish_pass_phuff;
  166078. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  166079. * for AC coefficients.
  166080. */
  166081. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166082. compptr = cinfo->cur_comp_info[ci];
  166083. /* Initialize DC predictions to 0 */
  166084. entropy->last_dc_val[ci] = 0;
  166085. /* Get table index */
  166086. if (is_DC_band) {
  166087. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166088. continue;
  166089. tbl = compptr->dc_tbl_no;
  166090. } else {
  166091. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  166092. }
  166093. if (gather_statistics) {
  166094. /* Check for invalid table index */
  166095. /* (make_c_derived_tbl does this in the other path) */
  166096. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  166097. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  166098. /* Allocate and zero the statistics tables */
  166099. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  166100. if (entropy->count_ptrs[tbl] == NULL)
  166101. entropy->count_ptrs[tbl] = (long *)
  166102. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166103. 257 * SIZEOF(long));
  166104. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  166105. } else {
  166106. /* Compute derived values for Huffman table */
  166107. /* We may do this more than once for a table, but it's not expensive */
  166108. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  166109. & entropy->derived_tbls[tbl]);
  166110. }
  166111. }
  166112. /* Initialize AC stuff */
  166113. entropy->EOBRUN = 0;
  166114. entropy->BE = 0;
  166115. /* Initialize bit buffer to empty */
  166116. entropy->put_buffer = 0;
  166117. entropy->put_bits = 0;
  166118. /* Initialize restart stuff */
  166119. entropy->restarts_to_go = cinfo->restart_interval;
  166120. entropy->next_restart_num = 0;
  166121. }
  166122. /* Outputting bytes to the file.
  166123. * NB: these must be called only when actually outputting,
  166124. * that is, entropy->gather_statistics == FALSE.
  166125. */
  166126. /* Emit a byte */
  166127. #define emit_byte(entropy,val) \
  166128. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  166129. if (--(entropy)->free_in_buffer == 0) \
  166130. dump_buffer_p(entropy); }
  166131. LOCAL(void)
  166132. dump_buffer_p (phuff_entropy_ptr entropy)
  166133. /* Empty the output buffer; we do not support suspension in this module. */
  166134. {
  166135. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  166136. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  166137. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  166138. /* After a successful buffer dump, must reset buffer pointers */
  166139. entropy->next_output_byte = dest->next_output_byte;
  166140. entropy->free_in_buffer = dest->free_in_buffer;
  166141. }
  166142. /* Outputting bits to the file */
  166143. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166144. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166145. * in one call, and we never retain more than 7 bits in put_buffer
  166146. * between calls, so 24 bits are sufficient.
  166147. */
  166148. INLINE
  166149. LOCAL(void)
  166150. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166151. /* Emit some bits, unless we are in gather mode */
  166152. {
  166153. /* This routine is heavily used, so it's worth coding tightly. */
  166154. register INT32 put_buffer = (INT32) code;
  166155. register int put_bits = entropy->put_bits;
  166156. /* if size is 0, caller used an invalid Huffman table entry */
  166157. if (size == 0)
  166158. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166159. if (entropy->gather_statistics)
  166160. return; /* do nothing if we're only getting stats */
  166161. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166162. put_bits += size; /* new number of bits in buffer */
  166163. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166164. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166165. while (put_bits >= 8) {
  166166. int c = (int) ((put_buffer >> 16) & 0xFF);
  166167. emit_byte(entropy, c);
  166168. if (c == 0xFF) { /* need to stuff a zero byte? */
  166169. emit_byte(entropy, 0);
  166170. }
  166171. put_buffer <<= 8;
  166172. put_bits -= 8;
  166173. }
  166174. entropy->put_buffer = put_buffer; /* update variables */
  166175. entropy->put_bits = put_bits;
  166176. }
  166177. LOCAL(void)
  166178. flush_bits_p (phuff_entropy_ptr entropy)
  166179. {
  166180. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166181. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166182. entropy->put_bits = 0;
  166183. }
  166184. /*
  166185. * Emit (or just count) a Huffman symbol.
  166186. */
  166187. INLINE
  166188. LOCAL(void)
  166189. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166190. {
  166191. if (entropy->gather_statistics)
  166192. entropy->count_ptrs[tbl_no][symbol]++;
  166193. else {
  166194. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166195. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166196. }
  166197. }
  166198. /*
  166199. * Emit bits from a correction bit buffer.
  166200. */
  166201. LOCAL(void)
  166202. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166203. unsigned int nbits)
  166204. {
  166205. if (entropy->gather_statistics)
  166206. return; /* no real work */
  166207. while (nbits > 0) {
  166208. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166209. bufstart++;
  166210. nbits--;
  166211. }
  166212. }
  166213. /*
  166214. * Emit any pending EOBRUN symbol.
  166215. */
  166216. LOCAL(void)
  166217. emit_eobrun (phuff_entropy_ptr entropy)
  166218. {
  166219. register int temp, nbits;
  166220. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166221. temp = entropy->EOBRUN;
  166222. nbits = 0;
  166223. while ((temp >>= 1))
  166224. nbits++;
  166225. /* safety check: shouldn't happen given limited correction-bit buffer */
  166226. if (nbits > 14)
  166227. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166228. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166229. if (nbits)
  166230. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166231. entropy->EOBRUN = 0;
  166232. /* Emit any buffered correction bits */
  166233. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166234. entropy->BE = 0;
  166235. }
  166236. }
  166237. /*
  166238. * Emit a restart marker & resynchronize predictions.
  166239. */
  166240. LOCAL(void)
  166241. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166242. {
  166243. int ci;
  166244. emit_eobrun(entropy);
  166245. if (! entropy->gather_statistics) {
  166246. flush_bits_p(entropy);
  166247. emit_byte(entropy, 0xFF);
  166248. emit_byte(entropy, JPEG_RST0 + restart_num);
  166249. }
  166250. if (entropy->cinfo->Ss == 0) {
  166251. /* Re-initialize DC predictions to 0 */
  166252. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166253. entropy->last_dc_val[ci] = 0;
  166254. } else {
  166255. /* Re-initialize all AC-related fields to 0 */
  166256. entropy->EOBRUN = 0;
  166257. entropy->BE = 0;
  166258. }
  166259. }
  166260. /*
  166261. * MCU encoding for DC initial scan (either spectral selection,
  166262. * or first pass of successive approximation).
  166263. */
  166264. METHODDEF(boolean)
  166265. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166266. {
  166267. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166268. register int temp, temp2;
  166269. register int nbits;
  166270. int blkn, ci;
  166271. int Al = cinfo->Al;
  166272. JBLOCKROW block;
  166273. jpeg_component_info * compptr;
  166274. ISHIFT_TEMPS
  166275. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166276. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166277. /* Emit restart marker if needed */
  166278. if (cinfo->restart_interval)
  166279. if (entropy->restarts_to_go == 0)
  166280. emit_restart_p(entropy, entropy->next_restart_num);
  166281. /* Encode the MCU data blocks */
  166282. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166283. block = MCU_data[blkn];
  166284. ci = cinfo->MCU_membership[blkn];
  166285. compptr = cinfo->cur_comp_info[ci];
  166286. /* Compute the DC value after the required point transform by Al.
  166287. * This is simply an arithmetic right shift.
  166288. */
  166289. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166290. /* DC differences are figured on the point-transformed values. */
  166291. temp = temp2 - entropy->last_dc_val[ci];
  166292. entropy->last_dc_val[ci] = temp2;
  166293. /* Encode the DC coefficient difference per section G.1.2.1 */
  166294. temp2 = temp;
  166295. if (temp < 0) {
  166296. temp = -temp; /* temp is abs value of input */
  166297. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166298. /* This code assumes we are on a two's complement machine */
  166299. temp2--;
  166300. }
  166301. /* Find the number of bits needed for the magnitude of the coefficient */
  166302. nbits = 0;
  166303. while (temp) {
  166304. nbits++;
  166305. temp >>= 1;
  166306. }
  166307. /* Check for out-of-range coefficient values.
  166308. * Since we're encoding a difference, the range limit is twice as much.
  166309. */
  166310. if (nbits > MAX_COEF_BITS+1)
  166311. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166312. /* Count/emit the Huffman-coded symbol for the number of bits */
  166313. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166314. /* Emit that number of bits of the value, if positive, */
  166315. /* or the complement of its magnitude, if negative. */
  166316. if (nbits) /* emit_bits rejects calls with size 0 */
  166317. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166318. }
  166319. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166320. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166321. /* Update restart-interval state too */
  166322. if (cinfo->restart_interval) {
  166323. if (entropy->restarts_to_go == 0) {
  166324. entropy->restarts_to_go = cinfo->restart_interval;
  166325. entropy->next_restart_num++;
  166326. entropy->next_restart_num &= 7;
  166327. }
  166328. entropy->restarts_to_go--;
  166329. }
  166330. return TRUE;
  166331. }
  166332. /*
  166333. * MCU encoding for AC initial scan (either spectral selection,
  166334. * or first pass of successive approximation).
  166335. */
  166336. METHODDEF(boolean)
  166337. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166338. {
  166339. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166340. register int temp, temp2;
  166341. register int nbits;
  166342. register int r, k;
  166343. int Se = cinfo->Se;
  166344. int Al = cinfo->Al;
  166345. JBLOCKROW block;
  166346. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166347. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166348. /* Emit restart marker if needed */
  166349. if (cinfo->restart_interval)
  166350. if (entropy->restarts_to_go == 0)
  166351. emit_restart_p(entropy, entropy->next_restart_num);
  166352. /* Encode the MCU data block */
  166353. block = MCU_data[0];
  166354. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166355. r = 0; /* r = run length of zeros */
  166356. for (k = cinfo->Ss; k <= Se; k++) {
  166357. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166358. r++;
  166359. continue;
  166360. }
  166361. /* We must apply the point transform by Al. For AC coefficients this
  166362. * is an integer division with rounding towards 0. To do this portably
  166363. * in C, we shift after obtaining the absolute value; so the code is
  166364. * interwoven with finding the abs value (temp) and output bits (temp2).
  166365. */
  166366. if (temp < 0) {
  166367. temp = -temp; /* temp is abs value of input */
  166368. temp >>= Al; /* apply the point transform */
  166369. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166370. temp2 = ~temp;
  166371. } else {
  166372. temp >>= Al; /* apply the point transform */
  166373. temp2 = temp;
  166374. }
  166375. /* Watch out for case that nonzero coef is zero after point transform */
  166376. if (temp == 0) {
  166377. r++;
  166378. continue;
  166379. }
  166380. /* Emit any pending EOBRUN */
  166381. if (entropy->EOBRUN > 0)
  166382. emit_eobrun(entropy);
  166383. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166384. while (r > 15) {
  166385. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166386. r -= 16;
  166387. }
  166388. /* Find the number of bits needed for the magnitude of the coefficient */
  166389. nbits = 1; /* there must be at least one 1 bit */
  166390. while ((temp >>= 1))
  166391. nbits++;
  166392. /* Check for out-of-range coefficient values */
  166393. if (nbits > MAX_COEF_BITS)
  166394. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166395. /* Count/emit Huffman symbol for run length / number of bits */
  166396. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166397. /* Emit that number of bits of the value, if positive, */
  166398. /* or the complement of its magnitude, if negative. */
  166399. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166400. r = 0; /* reset zero run length */
  166401. }
  166402. if (r > 0) { /* If there are trailing zeroes, */
  166403. entropy->EOBRUN++; /* count an EOB */
  166404. if (entropy->EOBRUN == 0x7FFF)
  166405. emit_eobrun(entropy); /* force it out to avoid overflow */
  166406. }
  166407. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166408. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166409. /* Update restart-interval state too */
  166410. if (cinfo->restart_interval) {
  166411. if (entropy->restarts_to_go == 0) {
  166412. entropy->restarts_to_go = cinfo->restart_interval;
  166413. entropy->next_restart_num++;
  166414. entropy->next_restart_num &= 7;
  166415. }
  166416. entropy->restarts_to_go--;
  166417. }
  166418. return TRUE;
  166419. }
  166420. /*
  166421. * MCU encoding for DC successive approximation refinement scan.
  166422. * Note: we assume such scans can be multi-component, although the spec
  166423. * is not very clear on the point.
  166424. */
  166425. METHODDEF(boolean)
  166426. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166427. {
  166428. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166429. register int temp;
  166430. int blkn;
  166431. int Al = cinfo->Al;
  166432. JBLOCKROW block;
  166433. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166434. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166435. /* Emit restart marker if needed */
  166436. if (cinfo->restart_interval)
  166437. if (entropy->restarts_to_go == 0)
  166438. emit_restart_p(entropy, entropy->next_restart_num);
  166439. /* Encode the MCU data blocks */
  166440. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166441. block = MCU_data[blkn];
  166442. /* We simply emit the Al'th bit of the DC coefficient value. */
  166443. temp = (*block)[0];
  166444. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166445. }
  166446. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166447. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166448. /* Update restart-interval state too */
  166449. if (cinfo->restart_interval) {
  166450. if (entropy->restarts_to_go == 0) {
  166451. entropy->restarts_to_go = cinfo->restart_interval;
  166452. entropy->next_restart_num++;
  166453. entropy->next_restart_num &= 7;
  166454. }
  166455. entropy->restarts_to_go--;
  166456. }
  166457. return TRUE;
  166458. }
  166459. /*
  166460. * MCU encoding for AC successive approximation refinement scan.
  166461. */
  166462. METHODDEF(boolean)
  166463. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166464. {
  166465. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166466. register int temp;
  166467. register int r, k;
  166468. int EOB;
  166469. char *BR_buffer;
  166470. unsigned int BR;
  166471. int Se = cinfo->Se;
  166472. int Al = cinfo->Al;
  166473. JBLOCKROW block;
  166474. int absvalues[DCTSIZE2];
  166475. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166476. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166477. /* Emit restart marker if needed */
  166478. if (cinfo->restart_interval)
  166479. if (entropy->restarts_to_go == 0)
  166480. emit_restart_p(entropy, entropy->next_restart_num);
  166481. /* Encode the MCU data block */
  166482. block = MCU_data[0];
  166483. /* It is convenient to make a pre-pass to determine the transformed
  166484. * coefficients' absolute values and the EOB position.
  166485. */
  166486. EOB = 0;
  166487. for (k = cinfo->Ss; k <= Se; k++) {
  166488. temp = (*block)[jpeg_natural_order[k]];
  166489. /* We must apply the point transform by Al. For AC coefficients this
  166490. * is an integer division with rounding towards 0. To do this portably
  166491. * in C, we shift after obtaining the absolute value.
  166492. */
  166493. if (temp < 0)
  166494. temp = -temp; /* temp is abs value of input */
  166495. temp >>= Al; /* apply the point transform */
  166496. absvalues[k] = temp; /* save abs value for main pass */
  166497. if (temp == 1)
  166498. EOB = k; /* EOB = index of last newly-nonzero coef */
  166499. }
  166500. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166501. r = 0; /* r = run length of zeros */
  166502. BR = 0; /* BR = count of buffered bits added now */
  166503. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166504. for (k = cinfo->Ss; k <= Se; k++) {
  166505. if ((temp = absvalues[k]) == 0) {
  166506. r++;
  166507. continue;
  166508. }
  166509. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166510. while (r > 15 && k <= EOB) {
  166511. /* emit any pending EOBRUN and the BE correction bits */
  166512. emit_eobrun(entropy);
  166513. /* Emit ZRL */
  166514. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166515. r -= 16;
  166516. /* Emit buffered correction bits that must be associated with ZRL */
  166517. emit_buffered_bits(entropy, BR_buffer, BR);
  166518. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166519. BR = 0;
  166520. }
  166521. /* If the coef was previously nonzero, it only needs a correction bit.
  166522. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166523. * that we also need to test r > 15. But if r > 15, we can only get here
  166524. * if k > EOB, which implies that this coefficient is not 1.
  166525. */
  166526. if (temp > 1) {
  166527. /* The correction bit is the next bit of the absolute value. */
  166528. BR_buffer[BR++] = (char) (temp & 1);
  166529. continue;
  166530. }
  166531. /* Emit any pending EOBRUN and the BE correction bits */
  166532. emit_eobrun(entropy);
  166533. /* Count/emit Huffman symbol for run length / number of bits */
  166534. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166535. /* Emit output bit for newly-nonzero coef */
  166536. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166537. emit_bits_p(entropy, (unsigned int) temp, 1);
  166538. /* Emit buffered correction bits that must be associated with this code */
  166539. emit_buffered_bits(entropy, BR_buffer, BR);
  166540. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166541. BR = 0;
  166542. r = 0; /* reset zero run length */
  166543. }
  166544. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166545. entropy->EOBRUN++; /* count an EOB */
  166546. entropy->BE += BR; /* concat my correction bits to older ones */
  166547. /* We force out the EOB if we risk either:
  166548. * 1. overflow of the EOB counter;
  166549. * 2. overflow of the correction bit buffer during the next MCU.
  166550. */
  166551. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166552. emit_eobrun(entropy);
  166553. }
  166554. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166555. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166556. /* Update restart-interval state too */
  166557. if (cinfo->restart_interval) {
  166558. if (entropy->restarts_to_go == 0) {
  166559. entropy->restarts_to_go = cinfo->restart_interval;
  166560. entropy->next_restart_num++;
  166561. entropy->next_restart_num &= 7;
  166562. }
  166563. entropy->restarts_to_go--;
  166564. }
  166565. return TRUE;
  166566. }
  166567. /*
  166568. * Finish up at the end of a Huffman-compressed progressive scan.
  166569. */
  166570. METHODDEF(void)
  166571. finish_pass_phuff (j_compress_ptr cinfo)
  166572. {
  166573. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166574. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166575. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166576. /* Flush out any buffered data */
  166577. emit_eobrun(entropy);
  166578. flush_bits_p(entropy);
  166579. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166580. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166581. }
  166582. /*
  166583. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166584. */
  166585. METHODDEF(void)
  166586. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166587. {
  166588. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166589. boolean is_DC_band;
  166590. int ci, tbl;
  166591. jpeg_component_info * compptr;
  166592. JHUFF_TBL **htblptr;
  166593. boolean did[NUM_HUFF_TBLS];
  166594. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166595. emit_eobrun(entropy);
  166596. is_DC_band = (cinfo->Ss == 0);
  166597. /* It's important not to apply jpeg_gen_optimal_table more than once
  166598. * per table, because it clobbers the input frequency counts!
  166599. */
  166600. MEMZERO(did, SIZEOF(did));
  166601. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166602. compptr = cinfo->cur_comp_info[ci];
  166603. if (is_DC_band) {
  166604. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166605. continue;
  166606. tbl = compptr->dc_tbl_no;
  166607. } else {
  166608. tbl = compptr->ac_tbl_no;
  166609. }
  166610. if (! did[tbl]) {
  166611. if (is_DC_band)
  166612. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166613. else
  166614. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166615. if (*htblptr == NULL)
  166616. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166617. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166618. did[tbl] = TRUE;
  166619. }
  166620. }
  166621. }
  166622. /*
  166623. * Module initialization routine for progressive Huffman entropy encoding.
  166624. */
  166625. GLOBAL(void)
  166626. jinit_phuff_encoder (j_compress_ptr cinfo)
  166627. {
  166628. phuff_entropy_ptr entropy;
  166629. int i;
  166630. entropy = (phuff_entropy_ptr)
  166631. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166632. SIZEOF(phuff_entropy_encoder));
  166633. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166634. entropy->pub.start_pass = start_pass_phuff;
  166635. /* Mark tables unallocated */
  166636. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166637. entropy->derived_tbls[i] = NULL;
  166638. entropy->count_ptrs[i] = NULL;
  166639. }
  166640. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166641. }
  166642. #endif /* C_PROGRESSIVE_SUPPORTED */
  166643. /*** End of inlined file: jcphuff.c ***/
  166644. /*** Start of inlined file: jcprepct.c ***/
  166645. #define JPEG_INTERNALS
  166646. /* At present, jcsample.c can request context rows only for smoothing.
  166647. * In the future, we might also need context rows for CCIR601 sampling
  166648. * or other more-complex downsampling procedures. The code to support
  166649. * context rows should be compiled only if needed.
  166650. */
  166651. #ifdef INPUT_SMOOTHING_SUPPORTED
  166652. #define CONTEXT_ROWS_SUPPORTED
  166653. #endif
  166654. /*
  166655. * For the simple (no-context-row) case, we just need to buffer one
  166656. * row group's worth of pixels for the downsampling step. At the bottom of
  166657. * the image, we pad to a full row group by replicating the last pixel row.
  166658. * The downsampler's last output row is then replicated if needed to pad
  166659. * out to a full iMCU row.
  166660. *
  166661. * When providing context rows, we must buffer three row groups' worth of
  166662. * pixels. Three row groups are physically allocated, but the row pointer
  166663. * arrays are made five row groups high, with the extra pointers above and
  166664. * below "wrapping around" to point to the last and first real row groups.
  166665. * This allows the downsampler to access the proper context rows.
  166666. * At the top and bottom of the image, we create dummy context rows by
  166667. * copying the first or last real pixel row. This copying could be avoided
  166668. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166669. * trouble on the compression side.
  166670. */
  166671. /* Private buffer controller object */
  166672. typedef struct {
  166673. struct jpeg_c_prep_controller pub; /* public fields */
  166674. /* Downsampling input buffer. This buffer holds color-converted data
  166675. * until we have enough to do a downsample step.
  166676. */
  166677. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166678. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166679. int next_buf_row; /* index of next row to store in color_buf */
  166680. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166681. int this_row_group; /* starting row index of group to process */
  166682. int next_buf_stop; /* downsample when we reach this index */
  166683. #endif
  166684. } my_prep_controller;
  166685. typedef my_prep_controller * my_prep_ptr;
  166686. /*
  166687. * Initialize for a processing pass.
  166688. */
  166689. METHODDEF(void)
  166690. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166691. {
  166692. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166693. if (pass_mode != JBUF_PASS_THRU)
  166694. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166695. /* Initialize total-height counter for detecting bottom of image */
  166696. prep->rows_to_go = cinfo->image_height;
  166697. /* Mark the conversion buffer empty */
  166698. prep->next_buf_row = 0;
  166699. #ifdef CONTEXT_ROWS_SUPPORTED
  166700. /* Preset additional state variables for context mode.
  166701. * These aren't used in non-context mode, so we needn't test which mode.
  166702. */
  166703. prep->this_row_group = 0;
  166704. /* Set next_buf_stop to stop after two row groups have been read in. */
  166705. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166706. #endif
  166707. }
  166708. /*
  166709. * Expand an image vertically from height input_rows to height output_rows,
  166710. * by duplicating the bottom row.
  166711. */
  166712. LOCAL(void)
  166713. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166714. int input_rows, int output_rows)
  166715. {
  166716. register int row;
  166717. for (row = input_rows; row < output_rows; row++) {
  166718. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166719. 1, num_cols);
  166720. }
  166721. }
  166722. /*
  166723. * Process some data in the simple no-context case.
  166724. *
  166725. * Preprocessor output data is counted in "row groups". A row group
  166726. * is defined to be v_samp_factor sample rows of each component.
  166727. * Downsampling will produce this much data from each max_v_samp_factor
  166728. * input rows.
  166729. */
  166730. METHODDEF(void)
  166731. pre_process_data (j_compress_ptr cinfo,
  166732. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166733. JDIMENSION in_rows_avail,
  166734. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166735. JDIMENSION out_row_groups_avail)
  166736. {
  166737. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166738. int numrows, ci;
  166739. JDIMENSION inrows;
  166740. jpeg_component_info * compptr;
  166741. while (*in_row_ctr < in_rows_avail &&
  166742. *out_row_group_ctr < out_row_groups_avail) {
  166743. /* Do color conversion to fill the conversion buffer. */
  166744. inrows = in_rows_avail - *in_row_ctr;
  166745. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166746. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166747. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166748. prep->color_buf,
  166749. (JDIMENSION) prep->next_buf_row,
  166750. numrows);
  166751. *in_row_ctr += numrows;
  166752. prep->next_buf_row += numrows;
  166753. prep->rows_to_go -= numrows;
  166754. /* If at bottom of image, pad to fill the conversion buffer. */
  166755. if (prep->rows_to_go == 0 &&
  166756. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166757. for (ci = 0; ci < cinfo->num_components; ci++) {
  166758. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166759. prep->next_buf_row, cinfo->max_v_samp_factor);
  166760. }
  166761. prep->next_buf_row = cinfo->max_v_samp_factor;
  166762. }
  166763. /* If we've filled the conversion buffer, empty it. */
  166764. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166765. (*cinfo->downsample->downsample) (cinfo,
  166766. prep->color_buf, (JDIMENSION) 0,
  166767. output_buf, *out_row_group_ctr);
  166768. prep->next_buf_row = 0;
  166769. (*out_row_group_ctr)++;
  166770. }
  166771. /* If at bottom of image, pad the output to a full iMCU height.
  166772. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166773. */
  166774. if (prep->rows_to_go == 0 &&
  166775. *out_row_group_ctr < out_row_groups_avail) {
  166776. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166777. ci++, compptr++) {
  166778. expand_bottom_edge(output_buf[ci],
  166779. compptr->width_in_blocks * DCTSIZE,
  166780. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166781. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166782. }
  166783. *out_row_group_ctr = out_row_groups_avail;
  166784. break; /* can exit outer loop without test */
  166785. }
  166786. }
  166787. }
  166788. #ifdef CONTEXT_ROWS_SUPPORTED
  166789. /*
  166790. * Process some data in the context case.
  166791. */
  166792. METHODDEF(void)
  166793. pre_process_context (j_compress_ptr cinfo,
  166794. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166795. JDIMENSION in_rows_avail,
  166796. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166797. JDIMENSION out_row_groups_avail)
  166798. {
  166799. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166800. int numrows, ci;
  166801. int buf_height = cinfo->max_v_samp_factor * 3;
  166802. JDIMENSION inrows;
  166803. while (*out_row_group_ctr < out_row_groups_avail) {
  166804. if (*in_row_ctr < in_rows_avail) {
  166805. /* Do color conversion to fill the conversion buffer. */
  166806. inrows = in_rows_avail - *in_row_ctr;
  166807. numrows = prep->next_buf_stop - prep->next_buf_row;
  166808. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166809. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166810. prep->color_buf,
  166811. (JDIMENSION) prep->next_buf_row,
  166812. numrows);
  166813. /* Pad at top of image, if first time through */
  166814. if (prep->rows_to_go == cinfo->image_height) {
  166815. for (ci = 0; ci < cinfo->num_components; ci++) {
  166816. int row;
  166817. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166818. jcopy_sample_rows(prep->color_buf[ci], 0,
  166819. prep->color_buf[ci], -row,
  166820. 1, cinfo->image_width);
  166821. }
  166822. }
  166823. }
  166824. *in_row_ctr += numrows;
  166825. prep->next_buf_row += numrows;
  166826. prep->rows_to_go -= numrows;
  166827. } else {
  166828. /* Return for more data, unless we are at the bottom of the image. */
  166829. if (prep->rows_to_go != 0)
  166830. break;
  166831. /* When at bottom of image, pad to fill the conversion buffer. */
  166832. if (prep->next_buf_row < prep->next_buf_stop) {
  166833. for (ci = 0; ci < cinfo->num_components; ci++) {
  166834. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166835. prep->next_buf_row, prep->next_buf_stop);
  166836. }
  166837. prep->next_buf_row = prep->next_buf_stop;
  166838. }
  166839. }
  166840. /* If we've gotten enough data, downsample a row group. */
  166841. if (prep->next_buf_row == prep->next_buf_stop) {
  166842. (*cinfo->downsample->downsample) (cinfo,
  166843. prep->color_buf,
  166844. (JDIMENSION) prep->this_row_group,
  166845. output_buf, *out_row_group_ctr);
  166846. (*out_row_group_ctr)++;
  166847. /* Advance pointers with wraparound as necessary. */
  166848. prep->this_row_group += cinfo->max_v_samp_factor;
  166849. if (prep->this_row_group >= buf_height)
  166850. prep->this_row_group = 0;
  166851. if (prep->next_buf_row >= buf_height)
  166852. prep->next_buf_row = 0;
  166853. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166854. }
  166855. }
  166856. }
  166857. /*
  166858. * Create the wrapped-around downsampling input buffer needed for context mode.
  166859. */
  166860. LOCAL(void)
  166861. create_context_buffer (j_compress_ptr cinfo)
  166862. {
  166863. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166864. int rgroup_height = cinfo->max_v_samp_factor;
  166865. int ci, i;
  166866. jpeg_component_info * compptr;
  166867. JSAMPARRAY true_buffer, fake_buffer;
  166868. /* Grab enough space for fake row pointers for all the components;
  166869. * we need five row groups' worth of pointers for each component.
  166870. */
  166871. fake_buffer = (JSAMPARRAY)
  166872. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166873. (cinfo->num_components * 5 * rgroup_height) *
  166874. SIZEOF(JSAMPROW));
  166875. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166876. ci++, compptr++) {
  166877. /* Allocate the actual buffer space (3 row groups) for this component.
  166878. * We make the buffer wide enough to allow the downsampler to edge-expand
  166879. * horizontally within the buffer, if it so chooses.
  166880. */
  166881. true_buffer = (*cinfo->mem->alloc_sarray)
  166882. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166883. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166884. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166885. (JDIMENSION) (3 * rgroup_height));
  166886. /* Copy true buffer row pointers into the middle of the fake row array */
  166887. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166888. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166889. /* Fill in the above and below wraparound pointers */
  166890. for (i = 0; i < rgroup_height; i++) {
  166891. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166892. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166893. }
  166894. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166895. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166896. }
  166897. }
  166898. #endif /* CONTEXT_ROWS_SUPPORTED */
  166899. /*
  166900. * Initialize preprocessing controller.
  166901. */
  166902. GLOBAL(void)
  166903. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166904. {
  166905. my_prep_ptr prep;
  166906. int ci;
  166907. jpeg_component_info * compptr;
  166908. if (need_full_buffer) /* safety check */
  166909. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166910. prep = (my_prep_ptr)
  166911. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166912. SIZEOF(my_prep_controller));
  166913. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166914. prep->pub.start_pass = start_pass_prep;
  166915. /* Allocate the color conversion buffer.
  166916. * We make the buffer wide enough to allow the downsampler to edge-expand
  166917. * horizontally within the buffer, if it so chooses.
  166918. */
  166919. if (cinfo->downsample->need_context_rows) {
  166920. /* Set up to provide context rows */
  166921. #ifdef CONTEXT_ROWS_SUPPORTED
  166922. prep->pub.pre_process_data = pre_process_context;
  166923. create_context_buffer(cinfo);
  166924. #else
  166925. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166926. #endif
  166927. } else {
  166928. /* No context, just make it tall enough for one row group */
  166929. prep->pub.pre_process_data = pre_process_data;
  166930. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166931. ci++, compptr++) {
  166932. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166933. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166934. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166935. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166936. (JDIMENSION) cinfo->max_v_samp_factor);
  166937. }
  166938. }
  166939. }
  166940. /*** End of inlined file: jcprepct.c ***/
  166941. /*** Start of inlined file: jcsample.c ***/
  166942. #define JPEG_INTERNALS
  166943. /* Pointer to routine to downsample a single component */
  166944. typedef JMETHOD(void, downsample1_ptr,
  166945. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166946. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166947. /* Private subobject */
  166948. typedef struct {
  166949. struct jpeg_downsampler pub; /* public fields */
  166950. /* Downsampling method pointers, one per component */
  166951. downsample1_ptr methods[MAX_COMPONENTS];
  166952. } my_downsampler;
  166953. typedef my_downsampler * my_downsample_ptr;
  166954. /*
  166955. * Initialize for a downsampling pass.
  166956. */
  166957. METHODDEF(void)
  166958. start_pass_downsample (j_compress_ptr)
  166959. {
  166960. /* no work for now */
  166961. }
  166962. /*
  166963. * Expand a component horizontally from width input_cols to width output_cols,
  166964. * by duplicating the rightmost samples.
  166965. */
  166966. LOCAL(void)
  166967. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166968. JDIMENSION input_cols, JDIMENSION output_cols)
  166969. {
  166970. register JSAMPROW ptr;
  166971. register JSAMPLE pixval;
  166972. register int count;
  166973. int row;
  166974. int numcols = (int) (output_cols - input_cols);
  166975. if (numcols > 0) {
  166976. for (row = 0; row < num_rows; row++) {
  166977. ptr = image_data[row] + input_cols;
  166978. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166979. for (count = numcols; count > 0; count--)
  166980. *ptr++ = pixval;
  166981. }
  166982. }
  166983. }
  166984. /*
  166985. * Do downsampling for a whole row group (all components).
  166986. *
  166987. * In this version we simply downsample each component independently.
  166988. */
  166989. METHODDEF(void)
  166990. sep_downsample (j_compress_ptr cinfo,
  166991. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166992. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166993. {
  166994. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166995. int ci;
  166996. jpeg_component_info * compptr;
  166997. JSAMPARRAY in_ptr, out_ptr;
  166998. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166999. ci++, compptr++) {
  167000. in_ptr = input_buf[ci] + in_row_index;
  167001. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  167002. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  167003. }
  167004. }
  167005. /*
  167006. * Downsample pixel values of a single component.
  167007. * One row group is processed per call.
  167008. * This version handles arbitrary integral sampling ratios, without smoothing.
  167009. * Note that this version is not actually used for customary sampling ratios.
  167010. */
  167011. METHODDEF(void)
  167012. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167013. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167014. {
  167015. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  167016. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  167017. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167018. JSAMPROW inptr, outptr;
  167019. INT32 outvalue;
  167020. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  167021. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  167022. numpix = h_expand * v_expand;
  167023. numpix2 = numpix/2;
  167024. /* Expand input data enough to let all the output samples be generated
  167025. * by the standard loop. Special-casing padded output would be more
  167026. * efficient.
  167027. */
  167028. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167029. cinfo->image_width, output_cols * h_expand);
  167030. inrow = 0;
  167031. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167032. outptr = output_data[outrow];
  167033. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  167034. outcol++, outcol_h += h_expand) {
  167035. outvalue = 0;
  167036. for (v = 0; v < v_expand; v++) {
  167037. inptr = input_data[inrow+v] + outcol_h;
  167038. for (h = 0; h < h_expand; h++) {
  167039. outvalue += (INT32) GETJSAMPLE(*inptr++);
  167040. }
  167041. }
  167042. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  167043. }
  167044. inrow += v_expand;
  167045. }
  167046. }
  167047. /*
  167048. * Downsample pixel values of a single component.
  167049. * This version handles the special case of a full-size component,
  167050. * without smoothing.
  167051. */
  167052. METHODDEF(void)
  167053. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167054. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167055. {
  167056. /* Copy the data */
  167057. jcopy_sample_rows(input_data, 0, output_data, 0,
  167058. cinfo->max_v_samp_factor, cinfo->image_width);
  167059. /* Edge-expand */
  167060. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  167061. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  167062. }
  167063. /*
  167064. * Downsample pixel values of a single component.
  167065. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  167066. * without smoothing.
  167067. *
  167068. * A note about the "bias" calculations: when rounding fractional values to
  167069. * integer, we do not want to always round 0.5 up to the next integer.
  167070. * If we did that, we'd introduce a noticeable bias towards larger values.
  167071. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167072. * alternate pixel locations (a simple ordered dither pattern).
  167073. */
  167074. METHODDEF(void)
  167075. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167076. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167077. {
  167078. int outrow;
  167079. JDIMENSION outcol;
  167080. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167081. register JSAMPROW inptr, outptr;
  167082. register int bias;
  167083. /* Expand input data enough to let all the output samples be generated
  167084. * by the standard loop. Special-casing padded output would be more
  167085. * efficient.
  167086. */
  167087. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167088. cinfo->image_width, output_cols * 2);
  167089. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167090. outptr = output_data[outrow];
  167091. inptr = input_data[outrow];
  167092. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  167093. for (outcol = 0; outcol < output_cols; outcol++) {
  167094. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  167095. + bias) >> 1);
  167096. bias ^= 1; /* 0=>1, 1=>0 */
  167097. inptr += 2;
  167098. }
  167099. }
  167100. }
  167101. /*
  167102. * Downsample pixel values of a single component.
  167103. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167104. * without smoothing.
  167105. */
  167106. METHODDEF(void)
  167107. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167108. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167109. {
  167110. int inrow, outrow;
  167111. JDIMENSION outcol;
  167112. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167113. register JSAMPROW inptr0, inptr1, outptr;
  167114. register int bias;
  167115. /* Expand input data enough to let all the output samples be generated
  167116. * by the standard loop. Special-casing padded output would be more
  167117. * efficient.
  167118. */
  167119. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167120. cinfo->image_width, output_cols * 2);
  167121. inrow = 0;
  167122. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167123. outptr = output_data[outrow];
  167124. inptr0 = input_data[inrow];
  167125. inptr1 = input_data[inrow+1];
  167126. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  167127. for (outcol = 0; outcol < output_cols; outcol++) {
  167128. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167129. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  167130. + bias) >> 2);
  167131. bias ^= 3; /* 1=>2, 2=>1 */
  167132. inptr0 += 2; inptr1 += 2;
  167133. }
  167134. inrow += 2;
  167135. }
  167136. }
  167137. #ifdef INPUT_SMOOTHING_SUPPORTED
  167138. /*
  167139. * Downsample pixel values of a single component.
  167140. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167141. * with smoothing. One row of context is required.
  167142. */
  167143. METHODDEF(void)
  167144. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167145. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167146. {
  167147. int inrow, outrow;
  167148. JDIMENSION colctr;
  167149. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167150. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167151. INT32 membersum, neighsum, memberscale, neighscale;
  167152. /* Expand input data enough to let all the output samples be generated
  167153. * by the standard loop. Special-casing padded output would be more
  167154. * efficient.
  167155. */
  167156. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167157. cinfo->image_width, output_cols * 2);
  167158. /* We don't bother to form the individual "smoothed" input pixel values;
  167159. * we can directly compute the output which is the average of the four
  167160. * smoothed values. Each of the four member pixels contributes a fraction
  167161. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167162. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167163. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167164. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167165. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167166. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167167. * factors are scaled by 2^16 = 65536.
  167168. * Also recall that SF = smoothing_factor / 1024.
  167169. */
  167170. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167171. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167172. inrow = 0;
  167173. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167174. outptr = output_data[outrow];
  167175. inptr0 = input_data[inrow];
  167176. inptr1 = input_data[inrow+1];
  167177. above_ptr = input_data[inrow-1];
  167178. below_ptr = input_data[inrow+2];
  167179. /* Special case for first column: pretend column -1 is same as column 0 */
  167180. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167181. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167182. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167183. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167184. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167185. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167186. neighsum += neighsum;
  167187. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167188. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167189. membersum = membersum * memberscale + neighsum * neighscale;
  167190. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167191. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167192. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167193. /* sum of pixels directly mapped to this output element */
  167194. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167195. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167196. /* sum of edge-neighbor pixels */
  167197. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167198. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167199. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167200. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167201. /* The edge-neighbors count twice as much as corner-neighbors */
  167202. neighsum += neighsum;
  167203. /* Add in the corner-neighbors */
  167204. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167205. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167206. /* form final output scaled up by 2^16 */
  167207. membersum = membersum * memberscale + neighsum * neighscale;
  167208. /* round, descale and output it */
  167209. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167210. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167211. }
  167212. /* Special case for last column */
  167213. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167214. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167215. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167216. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167217. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167218. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167219. neighsum += neighsum;
  167220. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167221. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167222. membersum = membersum * memberscale + neighsum * neighscale;
  167223. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167224. inrow += 2;
  167225. }
  167226. }
  167227. /*
  167228. * Downsample pixel values of a single component.
  167229. * This version handles the special case of a full-size component,
  167230. * with smoothing. One row of context is required.
  167231. */
  167232. METHODDEF(void)
  167233. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167234. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167235. {
  167236. int outrow;
  167237. JDIMENSION colctr;
  167238. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167239. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167240. INT32 membersum, neighsum, memberscale, neighscale;
  167241. int colsum, lastcolsum, nextcolsum;
  167242. /* Expand input data enough to let all the output samples be generated
  167243. * by the standard loop. Special-casing padded output would be more
  167244. * efficient.
  167245. */
  167246. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167247. cinfo->image_width, output_cols);
  167248. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167249. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167250. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167251. * Also recall that SF = smoothing_factor / 1024.
  167252. */
  167253. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167254. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167255. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167256. outptr = output_data[outrow];
  167257. inptr = input_data[outrow];
  167258. above_ptr = input_data[outrow-1];
  167259. below_ptr = input_data[outrow+1];
  167260. /* Special case for first column */
  167261. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167262. GETJSAMPLE(*inptr);
  167263. membersum = GETJSAMPLE(*inptr++);
  167264. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167265. GETJSAMPLE(*inptr);
  167266. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167267. membersum = membersum * memberscale + neighsum * neighscale;
  167268. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167269. lastcolsum = colsum; colsum = nextcolsum;
  167270. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167271. membersum = GETJSAMPLE(*inptr++);
  167272. above_ptr++; below_ptr++;
  167273. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167274. GETJSAMPLE(*inptr);
  167275. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167276. membersum = membersum * memberscale + neighsum * neighscale;
  167277. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167278. lastcolsum = colsum; colsum = nextcolsum;
  167279. }
  167280. /* Special case for last column */
  167281. membersum = GETJSAMPLE(*inptr);
  167282. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167283. membersum = membersum * memberscale + neighsum * neighscale;
  167284. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167285. }
  167286. }
  167287. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167288. /*
  167289. * Module initialization routine for downsampling.
  167290. * Note that we must select a routine for each component.
  167291. */
  167292. GLOBAL(void)
  167293. jinit_downsampler (j_compress_ptr cinfo)
  167294. {
  167295. my_downsample_ptr downsample;
  167296. int ci;
  167297. jpeg_component_info * compptr;
  167298. boolean smoothok = TRUE;
  167299. downsample = (my_downsample_ptr)
  167300. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167301. SIZEOF(my_downsampler));
  167302. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167303. downsample->pub.start_pass = start_pass_downsample;
  167304. downsample->pub.downsample = sep_downsample;
  167305. downsample->pub.need_context_rows = FALSE;
  167306. if (cinfo->CCIR601_sampling)
  167307. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167308. /* Verify we can handle the sampling factors, and set up method pointers */
  167309. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167310. ci++, compptr++) {
  167311. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167312. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167313. #ifdef INPUT_SMOOTHING_SUPPORTED
  167314. if (cinfo->smoothing_factor) {
  167315. downsample->methods[ci] = fullsize_smooth_downsample;
  167316. downsample->pub.need_context_rows = TRUE;
  167317. } else
  167318. #endif
  167319. downsample->methods[ci] = fullsize_downsample;
  167320. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167321. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167322. smoothok = FALSE;
  167323. downsample->methods[ci] = h2v1_downsample;
  167324. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167325. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167326. #ifdef INPUT_SMOOTHING_SUPPORTED
  167327. if (cinfo->smoothing_factor) {
  167328. downsample->methods[ci] = h2v2_smooth_downsample;
  167329. downsample->pub.need_context_rows = TRUE;
  167330. } else
  167331. #endif
  167332. downsample->methods[ci] = h2v2_downsample;
  167333. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167334. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167335. smoothok = FALSE;
  167336. downsample->methods[ci] = int_downsample;
  167337. } else
  167338. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167339. }
  167340. #ifdef INPUT_SMOOTHING_SUPPORTED
  167341. if (cinfo->smoothing_factor && !smoothok)
  167342. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167343. #endif
  167344. }
  167345. /*** End of inlined file: jcsample.c ***/
  167346. /*** Start of inlined file: jctrans.c ***/
  167347. #define JPEG_INTERNALS
  167348. /* Forward declarations */
  167349. LOCAL(void) transencode_master_selection
  167350. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167351. LOCAL(void) transencode_coef_controller
  167352. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167353. /*
  167354. * Compression initialization for writing raw-coefficient data.
  167355. * Before calling this, all parameters and a data destination must be set up.
  167356. * Call jpeg_finish_compress() to actually write the data.
  167357. *
  167358. * The number of passed virtual arrays must match cinfo->num_components.
  167359. * Note that the virtual arrays need not be filled or even realized at
  167360. * the time write_coefficients is called; indeed, if the virtual arrays
  167361. * were requested from this compression object's memory manager, they
  167362. * typically will be realized during this routine and filled afterwards.
  167363. */
  167364. GLOBAL(void)
  167365. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167366. {
  167367. if (cinfo->global_state != CSTATE_START)
  167368. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167369. /* Mark all tables to be written */
  167370. jpeg_suppress_tables(cinfo, FALSE);
  167371. /* (Re)initialize error mgr and destination modules */
  167372. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167373. (*cinfo->dest->init_destination) (cinfo);
  167374. /* Perform master selection of active modules */
  167375. transencode_master_selection(cinfo, coef_arrays);
  167376. /* Wait for jpeg_finish_compress() call */
  167377. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167378. cinfo->global_state = CSTATE_WRCOEFS;
  167379. }
  167380. /*
  167381. * Initialize the compression object with default parameters,
  167382. * then copy from the source object all parameters needed for lossless
  167383. * transcoding. Parameters that can be varied without loss (such as
  167384. * scan script and Huffman optimization) are left in their default states.
  167385. */
  167386. GLOBAL(void)
  167387. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167388. j_compress_ptr dstinfo)
  167389. {
  167390. JQUANT_TBL ** qtblptr;
  167391. jpeg_component_info *incomp, *outcomp;
  167392. JQUANT_TBL *c_quant, *slot_quant;
  167393. int tblno, ci, coefi;
  167394. /* Safety check to ensure start_compress not called yet. */
  167395. if (dstinfo->global_state != CSTATE_START)
  167396. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167397. /* Copy fundamental image dimensions */
  167398. dstinfo->image_width = srcinfo->image_width;
  167399. dstinfo->image_height = srcinfo->image_height;
  167400. dstinfo->input_components = srcinfo->num_components;
  167401. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167402. /* Initialize all parameters to default values */
  167403. jpeg_set_defaults(dstinfo);
  167404. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167405. * Fix it to get the right header markers for the image colorspace.
  167406. */
  167407. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167408. dstinfo->data_precision = srcinfo->data_precision;
  167409. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167410. /* Copy the source's quantization tables. */
  167411. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167412. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167413. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167414. if (*qtblptr == NULL)
  167415. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167416. MEMCOPY((*qtblptr)->quantval,
  167417. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167418. SIZEOF((*qtblptr)->quantval));
  167419. (*qtblptr)->sent_table = FALSE;
  167420. }
  167421. }
  167422. /* Copy the source's per-component info.
  167423. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167424. */
  167425. dstinfo->num_components = srcinfo->num_components;
  167426. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167427. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167428. MAX_COMPONENTS);
  167429. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167430. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167431. outcomp->component_id = incomp->component_id;
  167432. outcomp->h_samp_factor = incomp->h_samp_factor;
  167433. outcomp->v_samp_factor = incomp->v_samp_factor;
  167434. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167435. /* Make sure saved quantization table for component matches the qtable
  167436. * slot. If not, the input file re-used this qtable slot.
  167437. * IJG encoder currently cannot duplicate this.
  167438. */
  167439. tblno = outcomp->quant_tbl_no;
  167440. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167441. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167442. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167443. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167444. c_quant = incomp->quant_table;
  167445. if (c_quant != NULL) {
  167446. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167447. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167448. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167449. }
  167450. }
  167451. /* Note: we do not copy the source's Huffman table assignments;
  167452. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167453. */
  167454. }
  167455. /* Also copy JFIF version and resolution information, if available.
  167456. * Strictly speaking this isn't "critical" info, but it's nearly
  167457. * always appropriate to copy it if available. In particular,
  167458. * if the application chooses to copy JFIF 1.02 extension markers from
  167459. * the source file, we need to copy the version to make sure we don't
  167460. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167461. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167462. */
  167463. if (srcinfo->saw_JFIF_marker) {
  167464. if (srcinfo->JFIF_major_version == 1) {
  167465. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167466. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167467. }
  167468. dstinfo->density_unit = srcinfo->density_unit;
  167469. dstinfo->X_density = srcinfo->X_density;
  167470. dstinfo->Y_density = srcinfo->Y_density;
  167471. }
  167472. }
  167473. /*
  167474. * Master selection of compression modules for transcoding.
  167475. * This substitutes for jcinit.c's initialization of the full compressor.
  167476. */
  167477. LOCAL(void)
  167478. transencode_master_selection (j_compress_ptr cinfo,
  167479. jvirt_barray_ptr * coef_arrays)
  167480. {
  167481. /* Although we don't actually use input_components for transcoding,
  167482. * jcmaster.c's initial_setup will complain if input_components is 0.
  167483. */
  167484. cinfo->input_components = 1;
  167485. /* Initialize master control (includes parameter checking/processing) */
  167486. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167487. /* Entropy encoding: either Huffman or arithmetic coding. */
  167488. if (cinfo->arith_code) {
  167489. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167490. } else {
  167491. if (cinfo->progressive_mode) {
  167492. #ifdef C_PROGRESSIVE_SUPPORTED
  167493. jinit_phuff_encoder(cinfo);
  167494. #else
  167495. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167496. #endif
  167497. } else
  167498. jinit_huff_encoder(cinfo);
  167499. }
  167500. /* We need a special coefficient buffer controller. */
  167501. transencode_coef_controller(cinfo, coef_arrays);
  167502. jinit_marker_writer(cinfo);
  167503. /* We can now tell the memory manager to allocate virtual arrays. */
  167504. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167505. /* Write the datastream header (SOI, JFIF) immediately.
  167506. * Frame and scan headers are postponed till later.
  167507. * This lets application insert special markers after the SOI.
  167508. */
  167509. (*cinfo->marker->write_file_header) (cinfo);
  167510. }
  167511. /*
  167512. * The rest of this file is a special implementation of the coefficient
  167513. * buffer controller. This is similar to jccoefct.c, but it handles only
  167514. * output from presupplied virtual arrays. Furthermore, we generate any
  167515. * dummy padding blocks on-the-fly rather than expecting them to be present
  167516. * in the arrays.
  167517. */
  167518. /* Private buffer controller object */
  167519. typedef struct {
  167520. struct jpeg_c_coef_controller pub; /* public fields */
  167521. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167522. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167523. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167524. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167525. /* Virtual block array for each component. */
  167526. jvirt_barray_ptr * whole_image;
  167527. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167528. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167529. } my_coef_controller2;
  167530. typedef my_coef_controller2 * my_coef_ptr2;
  167531. LOCAL(void)
  167532. start_iMCU_row2 (j_compress_ptr cinfo)
  167533. /* Reset within-iMCU-row counters for a new row */
  167534. {
  167535. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167536. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167537. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167538. * But at the bottom of the image, process only what's left.
  167539. */
  167540. if (cinfo->comps_in_scan > 1) {
  167541. coef->MCU_rows_per_iMCU_row = 1;
  167542. } else {
  167543. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167544. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167545. else
  167546. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167547. }
  167548. coef->mcu_ctr = 0;
  167549. coef->MCU_vert_offset = 0;
  167550. }
  167551. /*
  167552. * Initialize for a processing pass.
  167553. */
  167554. METHODDEF(void)
  167555. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167556. {
  167557. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167558. if (pass_mode != JBUF_CRANK_DEST)
  167559. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167560. coef->iMCU_row_num = 0;
  167561. start_iMCU_row2(cinfo);
  167562. }
  167563. /*
  167564. * Process some data.
  167565. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167566. * per call, ie, v_samp_factor block rows for each component in the scan.
  167567. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167568. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167569. *
  167570. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167571. */
  167572. METHODDEF(boolean)
  167573. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167574. {
  167575. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167576. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167577. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167578. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167579. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167580. JDIMENSION start_col;
  167581. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167582. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167583. JBLOCKROW buffer_ptr;
  167584. jpeg_component_info *compptr;
  167585. /* Align the virtual buffers for the components used in this scan. */
  167586. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167587. compptr = cinfo->cur_comp_info[ci];
  167588. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167589. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167590. coef->iMCU_row_num * compptr->v_samp_factor,
  167591. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167592. }
  167593. /* Loop to process one whole iMCU row */
  167594. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167595. yoffset++) {
  167596. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167597. MCU_col_num++) {
  167598. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167599. blkn = 0; /* index of current DCT block within MCU */
  167600. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167601. compptr = cinfo->cur_comp_info[ci];
  167602. start_col = MCU_col_num * compptr->MCU_width;
  167603. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167604. : compptr->last_col_width;
  167605. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167606. if (coef->iMCU_row_num < last_iMCU_row ||
  167607. yindex+yoffset < compptr->last_row_height) {
  167608. /* Fill in pointers to real blocks in this row */
  167609. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167610. for (xindex = 0; xindex < blockcnt; xindex++)
  167611. MCU_buffer[blkn++] = buffer_ptr++;
  167612. } else {
  167613. /* At bottom of image, need a whole row of dummy blocks */
  167614. xindex = 0;
  167615. }
  167616. /* Fill in any dummy blocks needed in this row.
  167617. * Dummy blocks are filled in the same way as in jccoefct.c:
  167618. * all zeroes in the AC entries, DC entries equal to previous
  167619. * block's DC value. The init routine has already zeroed the
  167620. * AC entries, so we need only set the DC entries correctly.
  167621. */
  167622. for (; xindex < compptr->MCU_width; xindex++) {
  167623. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167624. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167625. blkn++;
  167626. }
  167627. }
  167628. }
  167629. /* Try to write the MCU. */
  167630. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167631. /* Suspension forced; update state counters and exit */
  167632. coef->MCU_vert_offset = yoffset;
  167633. coef->mcu_ctr = MCU_col_num;
  167634. return FALSE;
  167635. }
  167636. }
  167637. /* Completed an MCU row, but perhaps not an iMCU row */
  167638. coef->mcu_ctr = 0;
  167639. }
  167640. /* Completed the iMCU row, advance counters for next one */
  167641. coef->iMCU_row_num++;
  167642. start_iMCU_row2(cinfo);
  167643. return TRUE;
  167644. }
  167645. /*
  167646. * Initialize coefficient buffer controller.
  167647. *
  167648. * Each passed coefficient array must be the right size for that
  167649. * coefficient: width_in_blocks wide and height_in_blocks high,
  167650. * with unitheight at least v_samp_factor.
  167651. */
  167652. LOCAL(void)
  167653. transencode_coef_controller (j_compress_ptr cinfo,
  167654. jvirt_barray_ptr * coef_arrays)
  167655. {
  167656. my_coef_ptr2 coef;
  167657. JBLOCKROW buffer;
  167658. int i;
  167659. coef = (my_coef_ptr2)
  167660. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167661. SIZEOF(my_coef_controller2));
  167662. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167663. coef->pub.start_pass = start_pass_coef2;
  167664. coef->pub.compress_data = compress_output2;
  167665. /* Save pointer to virtual arrays */
  167666. coef->whole_image = coef_arrays;
  167667. /* Allocate and pre-zero space for dummy DCT blocks. */
  167668. buffer = (JBLOCKROW)
  167669. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167670. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167671. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167672. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167673. coef->dummy_buffer[i] = buffer + i;
  167674. }
  167675. }
  167676. /*** End of inlined file: jctrans.c ***/
  167677. /*** Start of inlined file: jdapistd.c ***/
  167678. #define JPEG_INTERNALS
  167679. /* Forward declarations */
  167680. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167681. /*
  167682. * Decompression initialization.
  167683. * jpeg_read_header must be completed before calling this.
  167684. *
  167685. * If a multipass operating mode was selected, this will do all but the
  167686. * last pass, and thus may take a great deal of time.
  167687. *
  167688. * Returns FALSE if suspended. The return value need be inspected only if
  167689. * a suspending data source is used.
  167690. */
  167691. GLOBAL(boolean)
  167692. jpeg_start_decompress (j_decompress_ptr cinfo)
  167693. {
  167694. if (cinfo->global_state == DSTATE_READY) {
  167695. /* First call: initialize master control, select active modules */
  167696. jinit_master_decompress(cinfo);
  167697. if (cinfo->buffered_image) {
  167698. /* No more work here; expecting jpeg_start_output next */
  167699. cinfo->global_state = DSTATE_BUFIMAGE;
  167700. return TRUE;
  167701. }
  167702. cinfo->global_state = DSTATE_PRELOAD;
  167703. }
  167704. if (cinfo->global_state == DSTATE_PRELOAD) {
  167705. /* If file has multiple scans, absorb them all into the coef buffer */
  167706. if (cinfo->inputctl->has_multiple_scans) {
  167707. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167708. for (;;) {
  167709. int retcode;
  167710. /* Call progress monitor hook if present */
  167711. if (cinfo->progress != NULL)
  167712. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167713. /* Absorb some more input */
  167714. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167715. if (retcode == JPEG_SUSPENDED)
  167716. return FALSE;
  167717. if (retcode == JPEG_REACHED_EOI)
  167718. break;
  167719. /* Advance progress counter if appropriate */
  167720. if (cinfo->progress != NULL &&
  167721. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167722. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167723. /* jdmaster underestimated number of scans; ratchet up one scan */
  167724. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167725. }
  167726. }
  167727. }
  167728. #else
  167729. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167730. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167731. }
  167732. cinfo->output_scan_number = cinfo->input_scan_number;
  167733. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167734. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167735. /* Perform any dummy output passes, and set up for the final pass */
  167736. return output_pass_setup(cinfo);
  167737. }
  167738. /*
  167739. * Set up for an output pass, and perform any dummy pass(es) needed.
  167740. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167741. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167742. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167743. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167744. */
  167745. LOCAL(boolean)
  167746. output_pass_setup (j_decompress_ptr cinfo)
  167747. {
  167748. if (cinfo->global_state != DSTATE_PRESCAN) {
  167749. /* First call: do pass setup */
  167750. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167751. cinfo->output_scanline = 0;
  167752. cinfo->global_state = DSTATE_PRESCAN;
  167753. }
  167754. /* Loop over any required dummy passes */
  167755. while (cinfo->master->is_dummy_pass) {
  167756. #ifdef QUANT_2PASS_SUPPORTED
  167757. /* Crank through the dummy pass */
  167758. while (cinfo->output_scanline < cinfo->output_height) {
  167759. JDIMENSION last_scanline;
  167760. /* Call progress monitor hook if present */
  167761. if (cinfo->progress != NULL) {
  167762. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167763. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167764. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167765. }
  167766. /* Process some data */
  167767. last_scanline = cinfo->output_scanline;
  167768. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167769. &cinfo->output_scanline, (JDIMENSION) 0);
  167770. if (cinfo->output_scanline == last_scanline)
  167771. return FALSE; /* No progress made, must suspend */
  167772. }
  167773. /* Finish up dummy pass, and set up for another one */
  167774. (*cinfo->master->finish_output_pass) (cinfo);
  167775. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167776. cinfo->output_scanline = 0;
  167777. #else
  167778. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167779. #endif /* QUANT_2PASS_SUPPORTED */
  167780. }
  167781. /* Ready for application to drive output pass through
  167782. * jpeg_read_scanlines or jpeg_read_raw_data.
  167783. */
  167784. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167785. return TRUE;
  167786. }
  167787. /*
  167788. * Read some scanlines of data from the JPEG decompressor.
  167789. *
  167790. * The return value will be the number of lines actually read.
  167791. * This may be less than the number requested in several cases,
  167792. * including bottom of image, data source suspension, and operating
  167793. * modes that emit multiple scanlines at a time.
  167794. *
  167795. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167796. * this likely signals an application programmer error. However,
  167797. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167798. */
  167799. GLOBAL(JDIMENSION)
  167800. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167801. JDIMENSION max_lines)
  167802. {
  167803. JDIMENSION row_ctr;
  167804. if (cinfo->global_state != DSTATE_SCANNING)
  167805. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167806. if (cinfo->output_scanline >= cinfo->output_height) {
  167807. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167808. return 0;
  167809. }
  167810. /* Call progress monitor hook if present */
  167811. if (cinfo->progress != NULL) {
  167812. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167813. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167814. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167815. }
  167816. /* Process some data */
  167817. row_ctr = 0;
  167818. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167819. cinfo->output_scanline += row_ctr;
  167820. return row_ctr;
  167821. }
  167822. /*
  167823. * Alternate entry point to read raw data.
  167824. * Processes exactly one iMCU row per call, unless suspended.
  167825. */
  167826. GLOBAL(JDIMENSION)
  167827. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167828. JDIMENSION max_lines)
  167829. {
  167830. JDIMENSION lines_per_iMCU_row;
  167831. if (cinfo->global_state != DSTATE_RAW_OK)
  167832. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167833. if (cinfo->output_scanline >= cinfo->output_height) {
  167834. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167835. return 0;
  167836. }
  167837. /* Call progress monitor hook if present */
  167838. if (cinfo->progress != NULL) {
  167839. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167840. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167841. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167842. }
  167843. /* Verify that at least one iMCU row can be returned. */
  167844. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167845. if (max_lines < lines_per_iMCU_row)
  167846. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167847. /* Decompress directly into user's buffer. */
  167848. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167849. return 0; /* suspension forced, can do nothing more */
  167850. /* OK, we processed one iMCU row. */
  167851. cinfo->output_scanline += lines_per_iMCU_row;
  167852. return lines_per_iMCU_row;
  167853. }
  167854. /* Additional entry points for buffered-image mode. */
  167855. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167856. /*
  167857. * Initialize for an output pass in buffered-image mode.
  167858. */
  167859. GLOBAL(boolean)
  167860. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167861. {
  167862. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167863. cinfo->global_state != DSTATE_PRESCAN)
  167864. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167865. /* Limit scan number to valid range */
  167866. if (scan_number <= 0)
  167867. scan_number = 1;
  167868. if (cinfo->inputctl->eoi_reached &&
  167869. scan_number > cinfo->input_scan_number)
  167870. scan_number = cinfo->input_scan_number;
  167871. cinfo->output_scan_number = scan_number;
  167872. /* Perform any dummy output passes, and set up for the real pass */
  167873. return output_pass_setup(cinfo);
  167874. }
  167875. /*
  167876. * Finish up after an output pass in buffered-image mode.
  167877. *
  167878. * Returns FALSE if suspended. The return value need be inspected only if
  167879. * a suspending data source is used.
  167880. */
  167881. GLOBAL(boolean)
  167882. jpeg_finish_output (j_decompress_ptr cinfo)
  167883. {
  167884. if ((cinfo->global_state == DSTATE_SCANNING ||
  167885. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167886. /* Terminate this pass. */
  167887. /* We do not require the whole pass to have been completed. */
  167888. (*cinfo->master->finish_output_pass) (cinfo);
  167889. cinfo->global_state = DSTATE_BUFPOST;
  167890. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167891. /* BUFPOST = repeat call after a suspension, anything else is error */
  167892. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167893. }
  167894. /* Read markers looking for SOS or EOI */
  167895. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167896. ! cinfo->inputctl->eoi_reached) {
  167897. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167898. return FALSE; /* Suspend, come back later */
  167899. }
  167900. cinfo->global_state = DSTATE_BUFIMAGE;
  167901. return TRUE;
  167902. }
  167903. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167904. /*** End of inlined file: jdapistd.c ***/
  167905. /*** Start of inlined file: jdapimin.c ***/
  167906. #define JPEG_INTERNALS
  167907. /*
  167908. * Initialization of a JPEG decompression object.
  167909. * The error manager must already be set up (in case memory manager fails).
  167910. */
  167911. GLOBAL(void)
  167912. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167913. {
  167914. int i;
  167915. /* Guard against version mismatches between library and caller. */
  167916. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167917. if (version != JPEG_LIB_VERSION)
  167918. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167919. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167920. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167921. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167922. /* For debugging purposes, we zero the whole master structure.
  167923. * But the application has already set the err pointer, and may have set
  167924. * client_data, so we have to save and restore those fields.
  167925. * Note: if application hasn't set client_data, tools like Purify may
  167926. * complain here.
  167927. */
  167928. {
  167929. struct jpeg_error_mgr * err = cinfo->err;
  167930. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167931. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167932. cinfo->err = err;
  167933. cinfo->client_data = client_data;
  167934. }
  167935. cinfo->is_decompressor = TRUE;
  167936. /* Initialize a memory manager instance for this object */
  167937. jinit_memory_mgr((j_common_ptr) cinfo);
  167938. /* Zero out pointers to permanent structures. */
  167939. cinfo->progress = NULL;
  167940. cinfo->src = NULL;
  167941. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167942. cinfo->quant_tbl_ptrs[i] = NULL;
  167943. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167944. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167945. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167946. }
  167947. /* Initialize marker processor so application can override methods
  167948. * for COM, APPn markers before calling jpeg_read_header.
  167949. */
  167950. cinfo->marker_list = NULL;
  167951. jinit_marker_reader(cinfo);
  167952. /* And initialize the overall input controller. */
  167953. jinit_input_controller(cinfo);
  167954. /* OK, I'm ready */
  167955. cinfo->global_state = DSTATE_START;
  167956. }
  167957. /*
  167958. * Destruction of a JPEG decompression object
  167959. */
  167960. GLOBAL(void)
  167961. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167962. {
  167963. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167964. }
  167965. /*
  167966. * Abort processing of a JPEG decompression operation,
  167967. * but don't destroy the object itself.
  167968. */
  167969. GLOBAL(void)
  167970. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167971. {
  167972. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167973. }
  167974. /*
  167975. * Set default decompression parameters.
  167976. */
  167977. LOCAL(void)
  167978. default_decompress_parms (j_decompress_ptr cinfo)
  167979. {
  167980. /* Guess the input colorspace, and set output colorspace accordingly. */
  167981. /* (Wish JPEG committee had provided a real way to specify this...) */
  167982. /* Note application may override our guesses. */
  167983. switch (cinfo->num_components) {
  167984. case 1:
  167985. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167986. cinfo->out_color_space = JCS_GRAYSCALE;
  167987. break;
  167988. case 3:
  167989. if (cinfo->saw_JFIF_marker) {
  167990. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167991. } else if (cinfo->saw_Adobe_marker) {
  167992. switch (cinfo->Adobe_transform) {
  167993. case 0:
  167994. cinfo->jpeg_color_space = JCS_RGB;
  167995. break;
  167996. case 1:
  167997. cinfo->jpeg_color_space = JCS_YCbCr;
  167998. break;
  167999. default:
  168000. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168001. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168002. break;
  168003. }
  168004. } else {
  168005. /* Saw no special markers, try to guess from the component IDs */
  168006. int cid0 = cinfo->comp_info[0].component_id;
  168007. int cid1 = cinfo->comp_info[1].component_id;
  168008. int cid2 = cinfo->comp_info[2].component_id;
  168009. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  168010. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  168011. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  168012. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  168013. else {
  168014. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  168015. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168016. }
  168017. }
  168018. /* Always guess RGB is proper output colorspace. */
  168019. cinfo->out_color_space = JCS_RGB;
  168020. break;
  168021. case 4:
  168022. if (cinfo->saw_Adobe_marker) {
  168023. switch (cinfo->Adobe_transform) {
  168024. case 0:
  168025. cinfo->jpeg_color_space = JCS_CMYK;
  168026. break;
  168027. case 2:
  168028. cinfo->jpeg_color_space = JCS_YCCK;
  168029. break;
  168030. default:
  168031. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168032. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  168033. break;
  168034. }
  168035. } else {
  168036. /* No special markers, assume straight CMYK. */
  168037. cinfo->jpeg_color_space = JCS_CMYK;
  168038. }
  168039. cinfo->out_color_space = JCS_CMYK;
  168040. break;
  168041. default:
  168042. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168043. cinfo->out_color_space = JCS_UNKNOWN;
  168044. break;
  168045. }
  168046. /* Set defaults for other decompression parameters. */
  168047. cinfo->scale_num = 1; /* 1:1 scaling */
  168048. cinfo->scale_denom = 1;
  168049. cinfo->output_gamma = 1.0;
  168050. cinfo->buffered_image = FALSE;
  168051. cinfo->raw_data_out = FALSE;
  168052. cinfo->dct_method = JDCT_DEFAULT;
  168053. cinfo->do_fancy_upsampling = TRUE;
  168054. cinfo->do_block_smoothing = TRUE;
  168055. cinfo->quantize_colors = FALSE;
  168056. /* We set these in case application only sets quantize_colors. */
  168057. cinfo->dither_mode = JDITHER_FS;
  168058. #ifdef QUANT_2PASS_SUPPORTED
  168059. cinfo->two_pass_quantize = TRUE;
  168060. #else
  168061. cinfo->two_pass_quantize = FALSE;
  168062. #endif
  168063. cinfo->desired_number_of_colors = 256;
  168064. cinfo->colormap = NULL;
  168065. /* Initialize for no mode change in buffered-image mode. */
  168066. cinfo->enable_1pass_quant = FALSE;
  168067. cinfo->enable_external_quant = FALSE;
  168068. cinfo->enable_2pass_quant = FALSE;
  168069. }
  168070. /*
  168071. * Decompression startup: read start of JPEG datastream to see what's there.
  168072. * Need only initialize JPEG object and supply a data source before calling.
  168073. *
  168074. * This routine will read as far as the first SOS marker (ie, actual start of
  168075. * compressed data), and will save all tables and parameters in the JPEG
  168076. * object. It will also initialize the decompression parameters to default
  168077. * values, and finally return JPEG_HEADER_OK. On return, the application may
  168078. * adjust the decompression parameters and then call jpeg_start_decompress.
  168079. * (Or, if the application only wanted to determine the image parameters,
  168080. * the data need not be decompressed. In that case, call jpeg_abort or
  168081. * jpeg_destroy to release any temporary space.)
  168082. * If an abbreviated (tables only) datastream is presented, the routine will
  168083. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  168084. * re-use the JPEG object to read the abbreviated image datastream(s).
  168085. * It is unnecessary (but OK) to call jpeg_abort in this case.
  168086. * The JPEG_SUSPENDED return code only occurs if the data source module
  168087. * requests suspension of the decompressor. In this case the application
  168088. * should load more source data and then re-call jpeg_read_header to resume
  168089. * processing.
  168090. * If a non-suspending data source is used and require_image is TRUE, then the
  168091. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  168092. *
  168093. * This routine is now just a front end to jpeg_consume_input, with some
  168094. * extra error checking.
  168095. */
  168096. GLOBAL(int)
  168097. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  168098. {
  168099. int retcode;
  168100. if (cinfo->global_state != DSTATE_START &&
  168101. cinfo->global_state != DSTATE_INHEADER)
  168102. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168103. retcode = jpeg_consume_input(cinfo);
  168104. switch (retcode) {
  168105. case JPEG_REACHED_SOS:
  168106. retcode = JPEG_HEADER_OK;
  168107. break;
  168108. case JPEG_REACHED_EOI:
  168109. if (require_image) /* Complain if application wanted an image */
  168110. ERREXIT(cinfo, JERR_NO_IMAGE);
  168111. /* Reset to start state; it would be safer to require the application to
  168112. * call jpeg_abort, but we can't change it now for compatibility reasons.
  168113. * A side effect is to free any temporary memory (there shouldn't be any).
  168114. */
  168115. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  168116. retcode = JPEG_HEADER_TABLES_ONLY;
  168117. break;
  168118. case JPEG_SUSPENDED:
  168119. /* no work */
  168120. break;
  168121. }
  168122. return retcode;
  168123. }
  168124. /*
  168125. * Consume data in advance of what the decompressor requires.
  168126. * This can be called at any time once the decompressor object has
  168127. * been created and a data source has been set up.
  168128. *
  168129. * This routine is essentially a state machine that handles a couple
  168130. * of critical state-transition actions, namely initial setup and
  168131. * transition from header scanning to ready-for-start_decompress.
  168132. * All the actual input is done via the input controller's consume_input
  168133. * method.
  168134. */
  168135. GLOBAL(int)
  168136. jpeg_consume_input (j_decompress_ptr cinfo)
  168137. {
  168138. int retcode = JPEG_SUSPENDED;
  168139. /* NB: every possible DSTATE value should be listed in this switch */
  168140. switch (cinfo->global_state) {
  168141. case DSTATE_START:
  168142. /* Start-of-datastream actions: reset appropriate modules */
  168143. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168144. /* Initialize application's data source module */
  168145. (*cinfo->src->init_source) (cinfo);
  168146. cinfo->global_state = DSTATE_INHEADER;
  168147. /*FALLTHROUGH*/
  168148. case DSTATE_INHEADER:
  168149. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168150. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168151. /* Set up default parameters based on header data */
  168152. default_decompress_parms(cinfo);
  168153. /* Set global state: ready for start_decompress */
  168154. cinfo->global_state = DSTATE_READY;
  168155. }
  168156. break;
  168157. case DSTATE_READY:
  168158. /* Can't advance past first SOS until start_decompress is called */
  168159. retcode = JPEG_REACHED_SOS;
  168160. break;
  168161. case DSTATE_PRELOAD:
  168162. case DSTATE_PRESCAN:
  168163. case DSTATE_SCANNING:
  168164. case DSTATE_RAW_OK:
  168165. case DSTATE_BUFIMAGE:
  168166. case DSTATE_BUFPOST:
  168167. case DSTATE_STOPPING:
  168168. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168169. break;
  168170. default:
  168171. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168172. }
  168173. return retcode;
  168174. }
  168175. /*
  168176. * Have we finished reading the input file?
  168177. */
  168178. GLOBAL(boolean)
  168179. jpeg_input_complete (j_decompress_ptr cinfo)
  168180. {
  168181. /* Check for valid jpeg object */
  168182. if (cinfo->global_state < DSTATE_START ||
  168183. cinfo->global_state > DSTATE_STOPPING)
  168184. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168185. return cinfo->inputctl->eoi_reached;
  168186. }
  168187. /*
  168188. * Is there more than one scan?
  168189. */
  168190. GLOBAL(boolean)
  168191. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168192. {
  168193. /* Only valid after jpeg_read_header completes */
  168194. if (cinfo->global_state < DSTATE_READY ||
  168195. cinfo->global_state > DSTATE_STOPPING)
  168196. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168197. return cinfo->inputctl->has_multiple_scans;
  168198. }
  168199. /*
  168200. * Finish JPEG decompression.
  168201. *
  168202. * This will normally just verify the file trailer and release temp storage.
  168203. *
  168204. * Returns FALSE if suspended. The return value need be inspected only if
  168205. * a suspending data source is used.
  168206. */
  168207. GLOBAL(boolean)
  168208. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168209. {
  168210. if ((cinfo->global_state == DSTATE_SCANNING ||
  168211. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168212. /* Terminate final pass of non-buffered mode */
  168213. if (cinfo->output_scanline < cinfo->output_height)
  168214. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168215. (*cinfo->master->finish_output_pass) (cinfo);
  168216. cinfo->global_state = DSTATE_STOPPING;
  168217. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168218. /* Finishing after a buffered-image operation */
  168219. cinfo->global_state = DSTATE_STOPPING;
  168220. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168221. /* STOPPING = repeat call after a suspension, anything else is error */
  168222. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168223. }
  168224. /* Read until EOI */
  168225. while (! cinfo->inputctl->eoi_reached) {
  168226. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168227. return FALSE; /* Suspend, come back later */
  168228. }
  168229. /* Do final cleanup */
  168230. (*cinfo->src->term_source) (cinfo);
  168231. /* We can use jpeg_abort to release memory and reset global_state */
  168232. jpeg_abort((j_common_ptr) cinfo);
  168233. return TRUE;
  168234. }
  168235. /*** End of inlined file: jdapimin.c ***/
  168236. /*** Start of inlined file: jdatasrc.c ***/
  168237. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168238. /*** Start of inlined file: jerror.h ***/
  168239. /*
  168240. * To define the enum list of message codes, include this file without
  168241. * defining macro JMESSAGE. To create a message string table, include it
  168242. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168243. */
  168244. #ifndef JMESSAGE
  168245. #ifndef JERROR_H
  168246. /* First time through, define the enum list */
  168247. #define JMAKE_ENUM_LIST
  168248. #else
  168249. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168250. #define JMESSAGE(code,string)
  168251. #endif /* JERROR_H */
  168252. #endif /* JMESSAGE */
  168253. #ifdef JMAKE_ENUM_LIST
  168254. typedef enum {
  168255. #define JMESSAGE(code,string) code ,
  168256. #endif /* JMAKE_ENUM_LIST */
  168257. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168258. /* For maintenance convenience, list is alphabetical by message code name */
  168259. JMESSAGE(JERR_ARITH_NOTIMPL,
  168260. "Sorry, there are legal restrictions on arithmetic coding")
  168261. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168262. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168263. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168264. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168265. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168266. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168267. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168268. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168269. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168270. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168271. JMESSAGE(JERR_BAD_LIB_VERSION,
  168272. "Wrong JPEG library version: library is %d, caller expects %d")
  168273. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168274. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168275. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168276. JMESSAGE(JERR_BAD_PROGRESSION,
  168277. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168278. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168279. "Invalid progressive parameters at scan script entry %d")
  168280. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168281. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168282. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168283. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168284. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168285. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168286. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168287. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168288. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168289. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168290. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168291. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168292. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168293. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168294. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168295. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168296. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168297. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168298. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168299. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168300. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168301. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168302. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168303. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168304. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168305. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168306. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168307. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168308. "Cannot transcode due to multiple use of quantization table %d")
  168309. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168310. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168311. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168312. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168313. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168314. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168315. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168316. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168317. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168318. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168319. JMESSAGE(JERR_QUANT_COMPONENTS,
  168320. "Cannot quantize more than %d color components")
  168321. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168322. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168323. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168324. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168325. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168326. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168327. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168328. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168329. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168330. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168331. JMESSAGE(JERR_TFILE_WRITE,
  168332. "Write failed on temporary file --- out of disk space?")
  168333. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168334. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168335. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168336. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168337. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168338. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168339. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168340. JMESSAGE(JMSG_VERSION, JVERSION)
  168341. JMESSAGE(JTRC_16BIT_TABLES,
  168342. "Caution: quantization tables are too coarse for baseline JPEG")
  168343. JMESSAGE(JTRC_ADOBE,
  168344. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168345. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168346. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168347. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168348. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168349. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168350. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168351. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168352. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168353. JMESSAGE(JTRC_EOI, "End Of Image")
  168354. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168355. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168356. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168357. "Warning: thumbnail image size does not match data length %u")
  168358. JMESSAGE(JTRC_JFIF_EXTENSION,
  168359. "JFIF extension marker: type 0x%02x, length %u")
  168360. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168361. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168362. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168363. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168364. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168365. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168366. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168367. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168368. JMESSAGE(JTRC_RST, "RST%d")
  168369. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168370. "Smoothing not supported with nonstandard sampling ratios")
  168371. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168372. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168373. JMESSAGE(JTRC_SOI, "Start of Image")
  168374. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168375. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168376. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168377. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168378. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168379. JMESSAGE(JTRC_THUMB_JPEG,
  168380. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168381. JMESSAGE(JTRC_THUMB_PALETTE,
  168382. "JFIF extension marker: palette thumbnail image, length %u")
  168383. JMESSAGE(JTRC_THUMB_RGB,
  168384. "JFIF extension marker: RGB thumbnail image, length %u")
  168385. JMESSAGE(JTRC_UNKNOWN_IDS,
  168386. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168387. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168388. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168389. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168390. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168391. "Inconsistent progression sequence for component %d coefficient %d")
  168392. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168393. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168394. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168395. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168396. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168397. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168398. JMESSAGE(JWRN_MUST_RESYNC,
  168399. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168400. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168401. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168402. #ifdef JMAKE_ENUM_LIST
  168403. JMSG_LASTMSGCODE
  168404. } J_MESSAGE_CODE;
  168405. #undef JMAKE_ENUM_LIST
  168406. #endif /* JMAKE_ENUM_LIST */
  168407. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168408. #undef JMESSAGE
  168409. #ifndef JERROR_H
  168410. #define JERROR_H
  168411. /* Macros to simplify using the error and trace message stuff */
  168412. /* The first parameter is either type of cinfo pointer */
  168413. /* Fatal errors (print message and exit) */
  168414. #define ERREXIT(cinfo,code) \
  168415. ((cinfo)->err->msg_code = (code), \
  168416. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168417. #define ERREXIT1(cinfo,code,p1) \
  168418. ((cinfo)->err->msg_code = (code), \
  168419. (cinfo)->err->msg_parm.i[0] = (p1), \
  168420. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168421. #define ERREXIT2(cinfo,code,p1,p2) \
  168422. ((cinfo)->err->msg_code = (code), \
  168423. (cinfo)->err->msg_parm.i[0] = (p1), \
  168424. (cinfo)->err->msg_parm.i[1] = (p2), \
  168425. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168426. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168427. ((cinfo)->err->msg_code = (code), \
  168428. (cinfo)->err->msg_parm.i[0] = (p1), \
  168429. (cinfo)->err->msg_parm.i[1] = (p2), \
  168430. (cinfo)->err->msg_parm.i[2] = (p3), \
  168431. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168432. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168433. ((cinfo)->err->msg_code = (code), \
  168434. (cinfo)->err->msg_parm.i[0] = (p1), \
  168435. (cinfo)->err->msg_parm.i[1] = (p2), \
  168436. (cinfo)->err->msg_parm.i[2] = (p3), \
  168437. (cinfo)->err->msg_parm.i[3] = (p4), \
  168438. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168439. #define ERREXITS(cinfo,code,str) \
  168440. ((cinfo)->err->msg_code = (code), \
  168441. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168442. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168443. #define MAKESTMT(stuff) do { stuff } while (0)
  168444. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168445. #define WARNMS(cinfo,code) \
  168446. ((cinfo)->err->msg_code = (code), \
  168447. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168448. #define WARNMS1(cinfo,code,p1) \
  168449. ((cinfo)->err->msg_code = (code), \
  168450. (cinfo)->err->msg_parm.i[0] = (p1), \
  168451. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168452. #define WARNMS2(cinfo,code,p1,p2) \
  168453. ((cinfo)->err->msg_code = (code), \
  168454. (cinfo)->err->msg_parm.i[0] = (p1), \
  168455. (cinfo)->err->msg_parm.i[1] = (p2), \
  168456. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168457. /* Informational/debugging messages */
  168458. #define TRACEMS(cinfo,lvl,code) \
  168459. ((cinfo)->err->msg_code = (code), \
  168460. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168461. #define TRACEMS1(cinfo,lvl,code,p1) \
  168462. ((cinfo)->err->msg_code = (code), \
  168463. (cinfo)->err->msg_parm.i[0] = (p1), \
  168464. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168465. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168466. ((cinfo)->err->msg_code = (code), \
  168467. (cinfo)->err->msg_parm.i[0] = (p1), \
  168468. (cinfo)->err->msg_parm.i[1] = (p2), \
  168469. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168470. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168471. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168472. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168473. (cinfo)->err->msg_code = (code); \
  168474. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168475. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168476. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168477. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168478. (cinfo)->err->msg_code = (code); \
  168479. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168480. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168481. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168482. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168483. _mp[4] = (p5); \
  168484. (cinfo)->err->msg_code = (code); \
  168485. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168486. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168487. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168488. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168489. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168490. (cinfo)->err->msg_code = (code); \
  168491. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168492. #define TRACEMSS(cinfo,lvl,code,str) \
  168493. ((cinfo)->err->msg_code = (code), \
  168494. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168495. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168496. #endif /* JERROR_H */
  168497. /*** End of inlined file: jerror.h ***/
  168498. /* Expanded data source object for stdio input */
  168499. typedef struct {
  168500. struct jpeg_source_mgr pub; /* public fields */
  168501. FILE * infile; /* source stream */
  168502. JOCTET * buffer; /* start of buffer */
  168503. boolean start_of_file; /* have we gotten any data yet? */
  168504. } my_source_mgr;
  168505. typedef my_source_mgr * my_src_ptr;
  168506. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168507. /*
  168508. * Initialize source --- called by jpeg_read_header
  168509. * before any data is actually read.
  168510. */
  168511. METHODDEF(void)
  168512. init_source (j_decompress_ptr cinfo)
  168513. {
  168514. my_src_ptr src = (my_src_ptr) cinfo->src;
  168515. /* We reset the empty-input-file flag for each image,
  168516. * but we don't clear the input buffer.
  168517. * This is correct behavior for reading a series of images from one source.
  168518. */
  168519. src->start_of_file = TRUE;
  168520. }
  168521. /*
  168522. * Fill the input buffer --- called whenever buffer is emptied.
  168523. *
  168524. * In typical applications, this should read fresh data into the buffer
  168525. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168526. * reset the pointer & count to the start of the buffer, and return TRUE
  168527. * indicating that the buffer has been reloaded. It is not necessary to
  168528. * fill the buffer entirely, only to obtain at least one more byte.
  168529. *
  168530. * There is no such thing as an EOF return. If the end of the file has been
  168531. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168532. * the buffer. In most cases, generating a warning message and inserting a
  168533. * fake EOI marker is the best course of action --- this will allow the
  168534. * decompressor to output however much of the image is there. However,
  168535. * the resulting error message is misleading if the real problem is an empty
  168536. * input file, so we handle that case specially.
  168537. *
  168538. * In applications that need to be able to suspend compression due to input
  168539. * not being available yet, a FALSE return indicates that no more data can be
  168540. * obtained right now, but more may be forthcoming later. In this situation,
  168541. * the decompressor will return to its caller (with an indication of the
  168542. * number of scanlines it has read, if any). The application should resume
  168543. * decompression after it has loaded more data into the input buffer. Note
  168544. * that there are substantial restrictions on the use of suspension --- see
  168545. * the documentation.
  168546. *
  168547. * When suspending, the decompressor will back up to a convenient restart point
  168548. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168549. * indicate where the restart point will be if the current call returns FALSE.
  168550. * Data beyond this point must be rescanned after resumption, so move it to
  168551. * the front of the buffer rather than discarding it.
  168552. */
  168553. METHODDEF(boolean)
  168554. fill_input_buffer (j_decompress_ptr cinfo)
  168555. {
  168556. my_src_ptr src = (my_src_ptr) cinfo->src;
  168557. size_t nbytes;
  168558. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168559. if (nbytes <= 0) {
  168560. if (src->start_of_file) /* Treat empty input file as fatal error */
  168561. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168562. WARNMS(cinfo, JWRN_JPEG_EOF);
  168563. /* Insert a fake EOI marker */
  168564. src->buffer[0] = (JOCTET) 0xFF;
  168565. src->buffer[1] = (JOCTET) JPEG_EOI;
  168566. nbytes = 2;
  168567. }
  168568. src->pub.next_input_byte = src->buffer;
  168569. src->pub.bytes_in_buffer = nbytes;
  168570. src->start_of_file = FALSE;
  168571. return TRUE;
  168572. }
  168573. /*
  168574. * Skip data --- used to skip over a potentially large amount of
  168575. * uninteresting data (such as an APPn marker).
  168576. *
  168577. * Writers of suspendable-input applications must note that skip_input_data
  168578. * is not granted the right to give a suspension return. If the skip extends
  168579. * beyond the data currently in the buffer, the buffer can be marked empty so
  168580. * that the next read will cause a fill_input_buffer call that can suspend.
  168581. * Arranging for additional bytes to be discarded before reloading the input
  168582. * buffer is the application writer's problem.
  168583. */
  168584. METHODDEF(void)
  168585. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168586. {
  168587. my_src_ptr src = (my_src_ptr) cinfo->src;
  168588. /* Just a dumb implementation for now. Could use fseek() except
  168589. * it doesn't work on pipes. Not clear that being smart is worth
  168590. * any trouble anyway --- large skips are infrequent.
  168591. */
  168592. if (num_bytes > 0) {
  168593. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168594. num_bytes -= (long) src->pub.bytes_in_buffer;
  168595. (void) fill_input_buffer(cinfo);
  168596. /* note we assume that fill_input_buffer will never return FALSE,
  168597. * so suspension need not be handled.
  168598. */
  168599. }
  168600. src->pub.next_input_byte += (size_t) num_bytes;
  168601. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168602. }
  168603. }
  168604. /*
  168605. * An additional method that can be provided by data source modules is the
  168606. * resync_to_restart method for error recovery in the presence of RST markers.
  168607. * For the moment, this source module just uses the default resync method
  168608. * provided by the JPEG library. That method assumes that no backtracking
  168609. * is possible.
  168610. */
  168611. /*
  168612. * Terminate source --- called by jpeg_finish_decompress
  168613. * after all data has been read. Often a no-op.
  168614. *
  168615. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168616. * application must deal with any cleanup that should happen even
  168617. * for error exit.
  168618. */
  168619. METHODDEF(void)
  168620. term_source (j_decompress_ptr)
  168621. {
  168622. /* no work necessary here */
  168623. }
  168624. /*
  168625. * Prepare for input from a stdio stream.
  168626. * The caller must have already opened the stream, and is responsible
  168627. * for closing it after finishing decompression.
  168628. */
  168629. GLOBAL(void)
  168630. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168631. {
  168632. my_src_ptr src;
  168633. /* The source object and input buffer are made permanent so that a series
  168634. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168635. * only before the first one. (If we discarded the buffer at the end of
  168636. * one image, we'd likely lose the start of the next one.)
  168637. * This makes it unsafe to use this manager and a different source
  168638. * manager serially with the same JPEG object. Caveat programmer.
  168639. */
  168640. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168641. cinfo->src = (struct jpeg_source_mgr *)
  168642. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168643. SIZEOF(my_source_mgr));
  168644. src = (my_src_ptr) cinfo->src;
  168645. src->buffer = (JOCTET *)
  168646. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168647. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168648. }
  168649. src = (my_src_ptr) cinfo->src;
  168650. src->pub.init_source = init_source;
  168651. src->pub.fill_input_buffer = fill_input_buffer;
  168652. src->pub.skip_input_data = skip_input_data;
  168653. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168654. src->pub.term_source = term_source;
  168655. src->infile = infile;
  168656. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168657. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168658. }
  168659. /*** End of inlined file: jdatasrc.c ***/
  168660. /*** Start of inlined file: jdcoefct.c ***/
  168661. #define JPEG_INTERNALS
  168662. /* Block smoothing is only applicable for progressive JPEG, so: */
  168663. #ifndef D_PROGRESSIVE_SUPPORTED
  168664. #undef BLOCK_SMOOTHING_SUPPORTED
  168665. #endif
  168666. /* Private buffer controller object */
  168667. typedef struct {
  168668. struct jpeg_d_coef_controller pub; /* public fields */
  168669. /* These variables keep track of the current location of the input side. */
  168670. /* cinfo->input_iMCU_row is also used for this. */
  168671. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168672. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168673. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168674. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168675. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168676. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168677. * and let the entropy decoder write into that workspace each time.
  168678. * (On 80x86, the workspace is FAR even though it's not really very big;
  168679. * this is to keep the module interfaces unchanged when a large coefficient
  168680. * buffer is necessary.)
  168681. * In multi-pass modes, this array points to the current MCU's blocks
  168682. * within the virtual arrays; it is used only by the input side.
  168683. */
  168684. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168685. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168686. /* In multi-pass modes, we need a virtual block array for each component. */
  168687. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168688. #endif
  168689. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168690. /* When doing block smoothing, we latch coefficient Al values here */
  168691. int * coef_bits_latch;
  168692. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168693. #endif
  168694. } my_coef_controller3;
  168695. typedef my_coef_controller3 * my_coef_ptr3;
  168696. /* Forward declarations */
  168697. METHODDEF(int) decompress_onepass
  168698. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168699. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168700. METHODDEF(int) decompress_data
  168701. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168702. #endif
  168703. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168704. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168705. METHODDEF(int) decompress_smooth_data
  168706. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168707. #endif
  168708. LOCAL(void)
  168709. start_iMCU_row3 (j_decompress_ptr cinfo)
  168710. /* Reset within-iMCU-row counters for a new row (input side) */
  168711. {
  168712. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168713. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168714. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168715. * But at the bottom of the image, process only what's left.
  168716. */
  168717. if (cinfo->comps_in_scan > 1) {
  168718. coef->MCU_rows_per_iMCU_row = 1;
  168719. } else {
  168720. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168721. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168722. else
  168723. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168724. }
  168725. coef->MCU_ctr = 0;
  168726. coef->MCU_vert_offset = 0;
  168727. }
  168728. /*
  168729. * Initialize for an input processing pass.
  168730. */
  168731. METHODDEF(void)
  168732. start_input_pass (j_decompress_ptr cinfo)
  168733. {
  168734. cinfo->input_iMCU_row = 0;
  168735. start_iMCU_row3(cinfo);
  168736. }
  168737. /*
  168738. * Initialize for an output processing pass.
  168739. */
  168740. METHODDEF(void)
  168741. start_output_pass (j_decompress_ptr cinfo)
  168742. {
  168743. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168744. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168745. /* If multipass, check to see whether to use block smoothing on this pass */
  168746. if (coef->pub.coef_arrays != NULL) {
  168747. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168748. coef->pub.decompress_data = decompress_smooth_data;
  168749. else
  168750. coef->pub.decompress_data = decompress_data;
  168751. }
  168752. #endif
  168753. cinfo->output_iMCU_row = 0;
  168754. }
  168755. /*
  168756. * Decompress and return some data in the single-pass case.
  168757. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168758. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168759. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168760. *
  168761. * NB: output_buf contains a plane for each component in image,
  168762. * which we index according to the component's SOF position.
  168763. */
  168764. METHODDEF(int)
  168765. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168766. {
  168767. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168768. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168769. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168770. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168771. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168772. JSAMPARRAY output_ptr;
  168773. JDIMENSION start_col, output_col;
  168774. jpeg_component_info *compptr;
  168775. inverse_DCT_method_ptr inverse_DCT;
  168776. /* Loop to process as much as one whole iMCU row */
  168777. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168778. yoffset++) {
  168779. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168780. MCU_col_num++) {
  168781. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168782. jzero_far((void FAR *) coef->MCU_buffer[0],
  168783. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168784. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168785. /* Suspension forced; update state counters and exit */
  168786. coef->MCU_vert_offset = yoffset;
  168787. coef->MCU_ctr = MCU_col_num;
  168788. return JPEG_SUSPENDED;
  168789. }
  168790. /* Determine where data should go in output_buf and do the IDCT thing.
  168791. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168792. * incremented past them!). Note the inner loop relies on having
  168793. * allocated the MCU_buffer[] blocks sequentially.
  168794. */
  168795. blkn = 0; /* index of current DCT block within MCU */
  168796. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168797. compptr = cinfo->cur_comp_info[ci];
  168798. /* Don't bother to IDCT an uninteresting component. */
  168799. if (! compptr->component_needed) {
  168800. blkn += compptr->MCU_blocks;
  168801. continue;
  168802. }
  168803. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168804. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168805. : compptr->last_col_width;
  168806. output_ptr = output_buf[compptr->component_index] +
  168807. yoffset * compptr->DCT_scaled_size;
  168808. start_col = MCU_col_num * compptr->MCU_sample_width;
  168809. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168810. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168811. yoffset+yindex < compptr->last_row_height) {
  168812. output_col = start_col;
  168813. for (xindex = 0; xindex < useful_width; xindex++) {
  168814. (*inverse_DCT) (cinfo, compptr,
  168815. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168816. output_ptr, output_col);
  168817. output_col += compptr->DCT_scaled_size;
  168818. }
  168819. }
  168820. blkn += compptr->MCU_width;
  168821. output_ptr += compptr->DCT_scaled_size;
  168822. }
  168823. }
  168824. }
  168825. /* Completed an MCU row, but perhaps not an iMCU row */
  168826. coef->MCU_ctr = 0;
  168827. }
  168828. /* Completed the iMCU row, advance counters for next one */
  168829. cinfo->output_iMCU_row++;
  168830. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168831. start_iMCU_row3(cinfo);
  168832. return JPEG_ROW_COMPLETED;
  168833. }
  168834. /* Completed the scan */
  168835. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168836. return JPEG_SCAN_COMPLETED;
  168837. }
  168838. /*
  168839. * Dummy consume-input routine for single-pass operation.
  168840. */
  168841. METHODDEF(int)
  168842. dummy_consume_data (j_decompress_ptr)
  168843. {
  168844. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168845. }
  168846. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168847. /*
  168848. * Consume input data and store it in the full-image coefficient buffer.
  168849. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168850. * ie, v_samp_factor block rows for each component in the scan.
  168851. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168852. */
  168853. METHODDEF(int)
  168854. consume_data (j_decompress_ptr cinfo)
  168855. {
  168856. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168857. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168858. int blkn, ci, xindex, yindex, yoffset;
  168859. JDIMENSION start_col;
  168860. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168861. JBLOCKROW buffer_ptr;
  168862. jpeg_component_info *compptr;
  168863. /* Align the virtual buffers for the components used in this scan. */
  168864. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168865. compptr = cinfo->cur_comp_info[ci];
  168866. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168867. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168868. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168869. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168870. /* Note: entropy decoder expects buffer to be zeroed,
  168871. * but this is handled automatically by the memory manager
  168872. * because we requested a pre-zeroed array.
  168873. */
  168874. }
  168875. /* Loop to process one whole iMCU row */
  168876. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168877. yoffset++) {
  168878. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168879. MCU_col_num++) {
  168880. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168881. blkn = 0; /* index of current DCT block within MCU */
  168882. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168883. compptr = cinfo->cur_comp_info[ci];
  168884. start_col = MCU_col_num * compptr->MCU_width;
  168885. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168886. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168887. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168888. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168889. }
  168890. }
  168891. }
  168892. /* Try to fetch the MCU. */
  168893. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168894. /* Suspension forced; update state counters and exit */
  168895. coef->MCU_vert_offset = yoffset;
  168896. coef->MCU_ctr = MCU_col_num;
  168897. return JPEG_SUSPENDED;
  168898. }
  168899. }
  168900. /* Completed an MCU row, but perhaps not an iMCU row */
  168901. coef->MCU_ctr = 0;
  168902. }
  168903. /* Completed the iMCU row, advance counters for next one */
  168904. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168905. start_iMCU_row3(cinfo);
  168906. return JPEG_ROW_COMPLETED;
  168907. }
  168908. /* Completed the scan */
  168909. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168910. return JPEG_SCAN_COMPLETED;
  168911. }
  168912. /*
  168913. * Decompress and return some data in the multi-pass case.
  168914. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168915. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168916. *
  168917. * NB: output_buf contains a plane for each component in image.
  168918. */
  168919. METHODDEF(int)
  168920. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168921. {
  168922. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168923. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168924. JDIMENSION block_num;
  168925. int ci, block_row, block_rows;
  168926. JBLOCKARRAY buffer;
  168927. JBLOCKROW buffer_ptr;
  168928. JSAMPARRAY output_ptr;
  168929. JDIMENSION output_col;
  168930. jpeg_component_info *compptr;
  168931. inverse_DCT_method_ptr inverse_DCT;
  168932. /* Force some input to be done if we are getting ahead of the input. */
  168933. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168934. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168935. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168936. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168937. return JPEG_SUSPENDED;
  168938. }
  168939. /* OK, output from the virtual arrays. */
  168940. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168941. ci++, compptr++) {
  168942. /* Don't bother to IDCT an uninteresting component. */
  168943. if (! compptr->component_needed)
  168944. continue;
  168945. /* Align the virtual buffer for this component. */
  168946. buffer = (*cinfo->mem->access_virt_barray)
  168947. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168948. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168949. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168950. /* Count non-dummy DCT block rows in this iMCU row. */
  168951. if (cinfo->output_iMCU_row < last_iMCU_row)
  168952. block_rows = compptr->v_samp_factor;
  168953. else {
  168954. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168955. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168956. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168957. }
  168958. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168959. output_ptr = output_buf[ci];
  168960. /* Loop over all DCT blocks to be processed. */
  168961. for (block_row = 0; block_row < block_rows; block_row++) {
  168962. buffer_ptr = buffer[block_row];
  168963. output_col = 0;
  168964. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168965. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168966. output_ptr, output_col);
  168967. buffer_ptr++;
  168968. output_col += compptr->DCT_scaled_size;
  168969. }
  168970. output_ptr += compptr->DCT_scaled_size;
  168971. }
  168972. }
  168973. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168974. return JPEG_ROW_COMPLETED;
  168975. return JPEG_SCAN_COMPLETED;
  168976. }
  168977. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168978. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168979. /*
  168980. * This code applies interblock smoothing as described by section K.8
  168981. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168982. * the DC values of a DCT block and its 8 neighboring blocks.
  168983. * We apply smoothing only for progressive JPEG decoding, and only if
  168984. * the coefficients it can estimate are not yet known to full precision.
  168985. */
  168986. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168987. #define Q01_POS 1
  168988. #define Q10_POS 8
  168989. #define Q20_POS 16
  168990. #define Q11_POS 9
  168991. #define Q02_POS 2
  168992. /*
  168993. * Determine whether block smoothing is applicable and safe.
  168994. * We also latch the current states of the coef_bits[] entries for the
  168995. * AC coefficients; otherwise, if the input side of the decompressor
  168996. * advances into a new scan, we might think the coefficients are known
  168997. * more accurately than they really are.
  168998. */
  168999. LOCAL(boolean)
  169000. smoothing_ok (j_decompress_ptr cinfo)
  169001. {
  169002. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169003. boolean smoothing_useful = FALSE;
  169004. int ci, coefi;
  169005. jpeg_component_info *compptr;
  169006. JQUANT_TBL * qtable;
  169007. int * coef_bits;
  169008. int * coef_bits_latch;
  169009. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  169010. return FALSE;
  169011. /* Allocate latch area if not already done */
  169012. if (coef->coef_bits_latch == NULL)
  169013. coef->coef_bits_latch = (int *)
  169014. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169015. cinfo->num_components *
  169016. (SAVED_COEFS * SIZEOF(int)));
  169017. coef_bits_latch = coef->coef_bits_latch;
  169018. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169019. ci++, compptr++) {
  169020. /* All components' quantization values must already be latched. */
  169021. if ((qtable = compptr->quant_table) == NULL)
  169022. return FALSE;
  169023. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  169024. if (qtable->quantval[0] == 0 ||
  169025. qtable->quantval[Q01_POS] == 0 ||
  169026. qtable->quantval[Q10_POS] == 0 ||
  169027. qtable->quantval[Q20_POS] == 0 ||
  169028. qtable->quantval[Q11_POS] == 0 ||
  169029. qtable->quantval[Q02_POS] == 0)
  169030. return FALSE;
  169031. /* DC values must be at least partly known for all components. */
  169032. coef_bits = cinfo->coef_bits[ci];
  169033. if (coef_bits[0] < 0)
  169034. return FALSE;
  169035. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  169036. for (coefi = 1; coefi <= 5; coefi++) {
  169037. coef_bits_latch[coefi] = coef_bits[coefi];
  169038. if (coef_bits[coefi] != 0)
  169039. smoothing_useful = TRUE;
  169040. }
  169041. coef_bits_latch += SAVED_COEFS;
  169042. }
  169043. return smoothing_useful;
  169044. }
  169045. /*
  169046. * Variant of decompress_data for use when doing block smoothing.
  169047. */
  169048. METHODDEF(int)
  169049. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169050. {
  169051. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169052. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169053. JDIMENSION block_num, last_block_column;
  169054. int ci, block_row, block_rows, access_rows;
  169055. JBLOCKARRAY buffer;
  169056. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  169057. JSAMPARRAY output_ptr;
  169058. JDIMENSION output_col;
  169059. jpeg_component_info *compptr;
  169060. inverse_DCT_method_ptr inverse_DCT;
  169061. boolean first_row, last_row;
  169062. JBLOCK workspace;
  169063. int *coef_bits;
  169064. JQUANT_TBL *quanttbl;
  169065. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  169066. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  169067. int Al, pred;
  169068. /* Force some input to be done if we are getting ahead of the input. */
  169069. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  169070. ! cinfo->inputctl->eoi_reached) {
  169071. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  169072. /* If input is working on current scan, we ordinarily want it to
  169073. * have completed the current row. But if input scan is DC,
  169074. * we want it to keep one row ahead so that next block row's DC
  169075. * values are up to date.
  169076. */
  169077. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  169078. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  169079. break;
  169080. }
  169081. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169082. return JPEG_SUSPENDED;
  169083. }
  169084. /* OK, output from the virtual arrays. */
  169085. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169086. ci++, compptr++) {
  169087. /* Don't bother to IDCT an uninteresting component. */
  169088. if (! compptr->component_needed)
  169089. continue;
  169090. /* Count non-dummy DCT block rows in this iMCU row. */
  169091. if (cinfo->output_iMCU_row < last_iMCU_row) {
  169092. block_rows = compptr->v_samp_factor;
  169093. access_rows = block_rows * 2; /* this and next iMCU row */
  169094. last_row = FALSE;
  169095. } else {
  169096. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169097. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169098. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169099. access_rows = block_rows; /* this iMCU row only */
  169100. last_row = TRUE;
  169101. }
  169102. /* Align the virtual buffer for this component. */
  169103. if (cinfo->output_iMCU_row > 0) {
  169104. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  169105. buffer = (*cinfo->mem->access_virt_barray)
  169106. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169107. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  169108. (JDIMENSION) access_rows, FALSE);
  169109. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  169110. first_row = FALSE;
  169111. } else {
  169112. buffer = (*cinfo->mem->access_virt_barray)
  169113. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169114. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  169115. first_row = TRUE;
  169116. }
  169117. /* Fetch component-dependent info */
  169118. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  169119. quanttbl = compptr->quant_table;
  169120. Q00 = quanttbl->quantval[0];
  169121. Q01 = quanttbl->quantval[Q01_POS];
  169122. Q10 = quanttbl->quantval[Q10_POS];
  169123. Q20 = quanttbl->quantval[Q20_POS];
  169124. Q11 = quanttbl->quantval[Q11_POS];
  169125. Q02 = quanttbl->quantval[Q02_POS];
  169126. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169127. output_ptr = output_buf[ci];
  169128. /* Loop over all DCT blocks to be processed. */
  169129. for (block_row = 0; block_row < block_rows; block_row++) {
  169130. buffer_ptr = buffer[block_row];
  169131. if (first_row && block_row == 0)
  169132. prev_block_row = buffer_ptr;
  169133. else
  169134. prev_block_row = buffer[block_row-1];
  169135. if (last_row && block_row == block_rows-1)
  169136. next_block_row = buffer_ptr;
  169137. else
  169138. next_block_row = buffer[block_row+1];
  169139. /* We fetch the surrounding DC values using a sliding-register approach.
  169140. * Initialize all nine here so as to do the right thing on narrow pics.
  169141. */
  169142. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169143. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169144. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169145. output_col = 0;
  169146. last_block_column = compptr->width_in_blocks - 1;
  169147. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169148. /* Fetch current DCT block into workspace so we can modify it. */
  169149. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169150. /* Update DC values */
  169151. if (block_num < last_block_column) {
  169152. DC3 = (int) prev_block_row[1][0];
  169153. DC6 = (int) buffer_ptr[1][0];
  169154. DC9 = (int) next_block_row[1][0];
  169155. }
  169156. /* Compute coefficient estimates per K.8.
  169157. * An estimate is applied only if coefficient is still zero,
  169158. * and is not known to be fully accurate.
  169159. */
  169160. /* AC01 */
  169161. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169162. num = 36 * Q00 * (DC4 - DC6);
  169163. if (num >= 0) {
  169164. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169165. if (Al > 0 && pred >= (1<<Al))
  169166. pred = (1<<Al)-1;
  169167. } else {
  169168. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169169. if (Al > 0 && pred >= (1<<Al))
  169170. pred = (1<<Al)-1;
  169171. pred = -pred;
  169172. }
  169173. workspace[1] = (JCOEF) pred;
  169174. }
  169175. /* AC10 */
  169176. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169177. num = 36 * Q00 * (DC2 - DC8);
  169178. if (num >= 0) {
  169179. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169180. if (Al > 0 && pred >= (1<<Al))
  169181. pred = (1<<Al)-1;
  169182. } else {
  169183. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169184. if (Al > 0 && pred >= (1<<Al))
  169185. pred = (1<<Al)-1;
  169186. pred = -pred;
  169187. }
  169188. workspace[8] = (JCOEF) pred;
  169189. }
  169190. /* AC20 */
  169191. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169192. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169193. if (num >= 0) {
  169194. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169195. if (Al > 0 && pred >= (1<<Al))
  169196. pred = (1<<Al)-1;
  169197. } else {
  169198. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169199. if (Al > 0 && pred >= (1<<Al))
  169200. pred = (1<<Al)-1;
  169201. pred = -pred;
  169202. }
  169203. workspace[16] = (JCOEF) pred;
  169204. }
  169205. /* AC11 */
  169206. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169207. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169208. if (num >= 0) {
  169209. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169210. if (Al > 0 && pred >= (1<<Al))
  169211. pred = (1<<Al)-1;
  169212. } else {
  169213. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169214. if (Al > 0 && pred >= (1<<Al))
  169215. pred = (1<<Al)-1;
  169216. pred = -pred;
  169217. }
  169218. workspace[9] = (JCOEF) pred;
  169219. }
  169220. /* AC02 */
  169221. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169222. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169223. if (num >= 0) {
  169224. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169225. if (Al > 0 && pred >= (1<<Al))
  169226. pred = (1<<Al)-1;
  169227. } else {
  169228. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169229. if (Al > 0 && pred >= (1<<Al))
  169230. pred = (1<<Al)-1;
  169231. pred = -pred;
  169232. }
  169233. workspace[2] = (JCOEF) pred;
  169234. }
  169235. /* OK, do the IDCT */
  169236. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169237. output_ptr, output_col);
  169238. /* Advance for next column */
  169239. DC1 = DC2; DC2 = DC3;
  169240. DC4 = DC5; DC5 = DC6;
  169241. DC7 = DC8; DC8 = DC9;
  169242. buffer_ptr++, prev_block_row++, next_block_row++;
  169243. output_col += compptr->DCT_scaled_size;
  169244. }
  169245. output_ptr += compptr->DCT_scaled_size;
  169246. }
  169247. }
  169248. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169249. return JPEG_ROW_COMPLETED;
  169250. return JPEG_SCAN_COMPLETED;
  169251. }
  169252. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169253. /*
  169254. * Initialize coefficient buffer controller.
  169255. */
  169256. GLOBAL(void)
  169257. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169258. {
  169259. my_coef_ptr3 coef;
  169260. coef = (my_coef_ptr3)
  169261. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169262. SIZEOF(my_coef_controller3));
  169263. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169264. coef->pub.start_input_pass = start_input_pass;
  169265. coef->pub.start_output_pass = start_output_pass;
  169266. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169267. coef->coef_bits_latch = NULL;
  169268. #endif
  169269. /* Create the coefficient buffer. */
  169270. if (need_full_buffer) {
  169271. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169272. /* Allocate a full-image virtual array for each component, */
  169273. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169274. /* Note we ask for a pre-zeroed array. */
  169275. int ci, access_rows;
  169276. jpeg_component_info *compptr;
  169277. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169278. ci++, compptr++) {
  169279. access_rows = compptr->v_samp_factor;
  169280. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169281. /* If block smoothing could be used, need a bigger window */
  169282. if (cinfo->progressive_mode)
  169283. access_rows *= 3;
  169284. #endif
  169285. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169286. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169287. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169288. (long) compptr->h_samp_factor),
  169289. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169290. (long) compptr->v_samp_factor),
  169291. (JDIMENSION) access_rows);
  169292. }
  169293. coef->pub.consume_data = consume_data;
  169294. coef->pub.decompress_data = decompress_data;
  169295. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169296. #else
  169297. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169298. #endif
  169299. } else {
  169300. /* We only need a single-MCU buffer. */
  169301. JBLOCKROW buffer;
  169302. int i;
  169303. buffer = (JBLOCKROW)
  169304. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169305. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169306. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169307. coef->MCU_buffer[i] = buffer + i;
  169308. }
  169309. coef->pub.consume_data = dummy_consume_data;
  169310. coef->pub.decompress_data = decompress_onepass;
  169311. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169312. }
  169313. }
  169314. /*** End of inlined file: jdcoefct.c ***/
  169315. #undef FIX
  169316. /*** Start of inlined file: jdcolor.c ***/
  169317. #define JPEG_INTERNALS
  169318. /* Private subobject */
  169319. typedef struct {
  169320. struct jpeg_color_deconverter pub; /* public fields */
  169321. /* Private state for YCC->RGB conversion */
  169322. int * Cr_r_tab; /* => table for Cr to R conversion */
  169323. int * Cb_b_tab; /* => table for Cb to B conversion */
  169324. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169325. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169326. } my_color_deconverter2;
  169327. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169328. /**************** YCbCr -> RGB conversion: most common case **************/
  169329. /*
  169330. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169331. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169332. * The conversion equations to be implemented are therefore
  169333. * R = Y + 1.40200 * Cr
  169334. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169335. * B = Y + 1.77200 * Cb
  169336. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169337. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169338. *
  169339. * To avoid floating-point arithmetic, we represent the fractional constants
  169340. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169341. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169342. * Notice that Y, being an integral input, does not contribute any fraction
  169343. * so it need not participate in the rounding.
  169344. *
  169345. * For even more speed, we avoid doing any multiplications in the inner loop
  169346. * by precalculating the constants times Cb and Cr for all possible values.
  169347. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169348. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169349. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169350. * colorspace anyway.
  169351. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169352. * values for the G calculation are left scaled up, since we must add them
  169353. * together before rounding.
  169354. */
  169355. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169356. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169357. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169358. /*
  169359. * Initialize tables for YCC->RGB colorspace conversion.
  169360. */
  169361. LOCAL(void)
  169362. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169363. {
  169364. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169365. int i;
  169366. INT32 x;
  169367. SHIFT_TEMPS
  169368. cconvert->Cr_r_tab = (int *)
  169369. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169370. (MAXJSAMPLE+1) * SIZEOF(int));
  169371. cconvert->Cb_b_tab = (int *)
  169372. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169373. (MAXJSAMPLE+1) * SIZEOF(int));
  169374. cconvert->Cr_g_tab = (INT32 *)
  169375. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169376. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169377. cconvert->Cb_g_tab = (INT32 *)
  169378. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169379. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169380. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169381. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169382. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169383. /* Cr=>R value is nearest int to 1.40200 * x */
  169384. cconvert->Cr_r_tab[i] = (int)
  169385. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169386. /* Cb=>B value is nearest int to 1.77200 * x */
  169387. cconvert->Cb_b_tab[i] = (int)
  169388. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169389. /* Cr=>G value is scaled-up -0.71414 * x */
  169390. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169391. /* Cb=>G value is scaled-up -0.34414 * x */
  169392. /* We also add in ONE_HALF so that need not do it in inner loop */
  169393. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169394. }
  169395. }
  169396. /*
  169397. * Convert some rows of samples to the output colorspace.
  169398. *
  169399. * Note that we change from noninterleaved, one-plane-per-component format
  169400. * to interleaved-pixel format. The output buffer is therefore three times
  169401. * as wide as the input buffer.
  169402. * A starting row offset is provided only for the input buffer. The caller
  169403. * can easily adjust the passed output_buf value to accommodate any row
  169404. * offset required on that side.
  169405. */
  169406. METHODDEF(void)
  169407. ycc_rgb_convert (j_decompress_ptr cinfo,
  169408. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169409. JSAMPARRAY output_buf, int num_rows)
  169410. {
  169411. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169412. register int y, cb, cr;
  169413. register JSAMPROW outptr;
  169414. register JSAMPROW inptr0, inptr1, inptr2;
  169415. register JDIMENSION col;
  169416. JDIMENSION num_cols = cinfo->output_width;
  169417. /* copy these pointers into registers if possible */
  169418. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169419. register int * Crrtab = cconvert->Cr_r_tab;
  169420. register int * Cbbtab = cconvert->Cb_b_tab;
  169421. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169422. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169423. SHIFT_TEMPS
  169424. while (--num_rows >= 0) {
  169425. inptr0 = input_buf[0][input_row];
  169426. inptr1 = input_buf[1][input_row];
  169427. inptr2 = input_buf[2][input_row];
  169428. input_row++;
  169429. outptr = *output_buf++;
  169430. for (col = 0; col < num_cols; col++) {
  169431. y = GETJSAMPLE(inptr0[col]);
  169432. cb = GETJSAMPLE(inptr1[col]);
  169433. cr = GETJSAMPLE(inptr2[col]);
  169434. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169435. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169436. outptr[RGB_GREEN] = range_limit[y +
  169437. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169438. SCALEBITS))];
  169439. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169440. outptr += RGB_PIXELSIZE;
  169441. }
  169442. }
  169443. }
  169444. /**************** Cases other than YCbCr -> RGB **************/
  169445. /*
  169446. * Color conversion for no colorspace change: just copy the data,
  169447. * converting from separate-planes to interleaved representation.
  169448. */
  169449. METHODDEF(void)
  169450. null_convert2 (j_decompress_ptr cinfo,
  169451. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169452. JSAMPARRAY output_buf, int num_rows)
  169453. {
  169454. register JSAMPROW inptr, outptr;
  169455. register JDIMENSION count;
  169456. register int num_components = cinfo->num_components;
  169457. JDIMENSION num_cols = cinfo->output_width;
  169458. int ci;
  169459. while (--num_rows >= 0) {
  169460. for (ci = 0; ci < num_components; ci++) {
  169461. inptr = input_buf[ci][input_row];
  169462. outptr = output_buf[0] + ci;
  169463. for (count = num_cols; count > 0; count--) {
  169464. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169465. outptr += num_components;
  169466. }
  169467. }
  169468. input_row++;
  169469. output_buf++;
  169470. }
  169471. }
  169472. /*
  169473. * Color conversion for grayscale: just copy the data.
  169474. * This also works for YCbCr -> grayscale conversion, in which
  169475. * we just copy the Y (luminance) component and ignore chrominance.
  169476. */
  169477. METHODDEF(void)
  169478. grayscale_convert2 (j_decompress_ptr cinfo,
  169479. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169480. JSAMPARRAY output_buf, int num_rows)
  169481. {
  169482. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169483. num_rows, cinfo->output_width);
  169484. }
  169485. /*
  169486. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169487. * This is provided to support applications that don't want to cope
  169488. * with grayscale as a separate case.
  169489. */
  169490. METHODDEF(void)
  169491. gray_rgb_convert (j_decompress_ptr cinfo,
  169492. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169493. JSAMPARRAY output_buf, int num_rows)
  169494. {
  169495. register JSAMPROW inptr, outptr;
  169496. register JDIMENSION col;
  169497. JDIMENSION num_cols = cinfo->output_width;
  169498. while (--num_rows >= 0) {
  169499. inptr = input_buf[0][input_row++];
  169500. outptr = *output_buf++;
  169501. for (col = 0; col < num_cols; col++) {
  169502. /* We can dispense with GETJSAMPLE() here */
  169503. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169504. outptr += RGB_PIXELSIZE;
  169505. }
  169506. }
  169507. }
  169508. /*
  169509. * Adobe-style YCCK->CMYK conversion.
  169510. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169511. * conversion as above, while passing K (black) unchanged.
  169512. * We assume build_ycc_rgb_table has been called.
  169513. */
  169514. METHODDEF(void)
  169515. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169516. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169517. JSAMPARRAY output_buf, int num_rows)
  169518. {
  169519. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169520. register int y, cb, cr;
  169521. register JSAMPROW outptr;
  169522. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169523. register JDIMENSION col;
  169524. JDIMENSION num_cols = cinfo->output_width;
  169525. /* copy these pointers into registers if possible */
  169526. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169527. register int * Crrtab = cconvert->Cr_r_tab;
  169528. register int * Cbbtab = cconvert->Cb_b_tab;
  169529. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169530. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169531. SHIFT_TEMPS
  169532. while (--num_rows >= 0) {
  169533. inptr0 = input_buf[0][input_row];
  169534. inptr1 = input_buf[1][input_row];
  169535. inptr2 = input_buf[2][input_row];
  169536. inptr3 = input_buf[3][input_row];
  169537. input_row++;
  169538. outptr = *output_buf++;
  169539. for (col = 0; col < num_cols; col++) {
  169540. y = GETJSAMPLE(inptr0[col]);
  169541. cb = GETJSAMPLE(inptr1[col]);
  169542. cr = GETJSAMPLE(inptr2[col]);
  169543. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169544. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169545. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169546. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169547. SCALEBITS)))];
  169548. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169549. /* K passes through unchanged */
  169550. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169551. outptr += 4;
  169552. }
  169553. }
  169554. }
  169555. /*
  169556. * Empty method for start_pass.
  169557. */
  169558. METHODDEF(void)
  169559. start_pass_dcolor (j_decompress_ptr)
  169560. {
  169561. /* no work needed */
  169562. }
  169563. /*
  169564. * Module initialization routine for output colorspace conversion.
  169565. */
  169566. GLOBAL(void)
  169567. jinit_color_deconverter (j_decompress_ptr cinfo)
  169568. {
  169569. my_cconvert_ptr2 cconvert;
  169570. int ci;
  169571. cconvert = (my_cconvert_ptr2)
  169572. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169573. SIZEOF(my_color_deconverter2));
  169574. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169575. cconvert->pub.start_pass = start_pass_dcolor;
  169576. /* Make sure num_components agrees with jpeg_color_space */
  169577. switch (cinfo->jpeg_color_space) {
  169578. case JCS_GRAYSCALE:
  169579. if (cinfo->num_components != 1)
  169580. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169581. break;
  169582. case JCS_RGB:
  169583. case JCS_YCbCr:
  169584. if (cinfo->num_components != 3)
  169585. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169586. break;
  169587. case JCS_CMYK:
  169588. case JCS_YCCK:
  169589. if (cinfo->num_components != 4)
  169590. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169591. break;
  169592. default: /* JCS_UNKNOWN can be anything */
  169593. if (cinfo->num_components < 1)
  169594. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169595. break;
  169596. }
  169597. /* Set out_color_components and conversion method based on requested space.
  169598. * Also clear the component_needed flags for any unused components,
  169599. * so that earlier pipeline stages can avoid useless computation.
  169600. */
  169601. switch (cinfo->out_color_space) {
  169602. case JCS_GRAYSCALE:
  169603. cinfo->out_color_components = 1;
  169604. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169605. cinfo->jpeg_color_space == JCS_YCbCr) {
  169606. cconvert->pub.color_convert = grayscale_convert2;
  169607. /* For color->grayscale conversion, only the Y (0) component is needed */
  169608. for (ci = 1; ci < cinfo->num_components; ci++)
  169609. cinfo->comp_info[ci].component_needed = FALSE;
  169610. } else
  169611. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169612. break;
  169613. case JCS_RGB:
  169614. cinfo->out_color_components = RGB_PIXELSIZE;
  169615. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169616. cconvert->pub.color_convert = ycc_rgb_convert;
  169617. build_ycc_rgb_table(cinfo);
  169618. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169619. cconvert->pub.color_convert = gray_rgb_convert;
  169620. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169621. cconvert->pub.color_convert = null_convert2;
  169622. } else
  169623. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169624. break;
  169625. case JCS_CMYK:
  169626. cinfo->out_color_components = 4;
  169627. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169628. cconvert->pub.color_convert = ycck_cmyk_convert;
  169629. build_ycc_rgb_table(cinfo);
  169630. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169631. cconvert->pub.color_convert = null_convert2;
  169632. } else
  169633. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169634. break;
  169635. default:
  169636. /* Permit null conversion to same output space */
  169637. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169638. cinfo->out_color_components = cinfo->num_components;
  169639. cconvert->pub.color_convert = null_convert2;
  169640. } else /* unsupported non-null conversion */
  169641. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169642. break;
  169643. }
  169644. if (cinfo->quantize_colors)
  169645. cinfo->output_components = 1; /* single colormapped output component */
  169646. else
  169647. cinfo->output_components = cinfo->out_color_components;
  169648. }
  169649. /*** End of inlined file: jdcolor.c ***/
  169650. #undef FIX
  169651. /*** Start of inlined file: jddctmgr.c ***/
  169652. #define JPEG_INTERNALS
  169653. /*
  169654. * The decompressor input side (jdinput.c) saves away the appropriate
  169655. * quantization table for each component at the start of the first scan
  169656. * involving that component. (This is necessary in order to correctly
  169657. * decode files that reuse Q-table slots.)
  169658. * When we are ready to make an output pass, the saved Q-table is converted
  169659. * to a multiplier table that will actually be used by the IDCT routine.
  169660. * The multiplier table contents are IDCT-method-dependent. To support
  169661. * application changes in IDCT method between scans, we can remake the
  169662. * multiplier tables if necessary.
  169663. * In buffered-image mode, the first output pass may occur before any data
  169664. * has been seen for some components, and thus before their Q-tables have
  169665. * been saved away. To handle this case, multiplier tables are preset
  169666. * to zeroes; the result of the IDCT will be a neutral gray level.
  169667. */
  169668. /* Private subobject for this module */
  169669. typedef struct {
  169670. struct jpeg_inverse_dct pub; /* public fields */
  169671. /* This array contains the IDCT method code that each multiplier table
  169672. * is currently set up for, or -1 if it's not yet set up.
  169673. * The actual multiplier tables are pointed to by dct_table in the
  169674. * per-component comp_info structures.
  169675. */
  169676. int cur_method[MAX_COMPONENTS];
  169677. } my_idct_controller;
  169678. typedef my_idct_controller * my_idct_ptr;
  169679. /* Allocated multiplier tables: big enough for any supported variant */
  169680. typedef union {
  169681. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169682. #ifdef DCT_IFAST_SUPPORTED
  169683. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169684. #endif
  169685. #ifdef DCT_FLOAT_SUPPORTED
  169686. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169687. #endif
  169688. } multiplier_table;
  169689. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169690. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169691. */
  169692. #ifdef DCT_ISLOW_SUPPORTED
  169693. #define PROVIDE_ISLOW_TABLES
  169694. #else
  169695. #ifdef IDCT_SCALING_SUPPORTED
  169696. #define PROVIDE_ISLOW_TABLES
  169697. #endif
  169698. #endif
  169699. /*
  169700. * Prepare for an output pass.
  169701. * Here we select the proper IDCT routine for each component and build
  169702. * a matching multiplier table.
  169703. */
  169704. METHODDEF(void)
  169705. start_pass (j_decompress_ptr cinfo)
  169706. {
  169707. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169708. int ci, i;
  169709. jpeg_component_info *compptr;
  169710. int method = 0;
  169711. inverse_DCT_method_ptr method_ptr = NULL;
  169712. JQUANT_TBL * qtbl;
  169713. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169714. ci++, compptr++) {
  169715. /* Select the proper IDCT routine for this component's scaling */
  169716. switch (compptr->DCT_scaled_size) {
  169717. #ifdef IDCT_SCALING_SUPPORTED
  169718. case 1:
  169719. method_ptr = jpeg_idct_1x1;
  169720. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169721. break;
  169722. case 2:
  169723. method_ptr = jpeg_idct_2x2;
  169724. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169725. break;
  169726. case 4:
  169727. method_ptr = jpeg_idct_4x4;
  169728. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169729. break;
  169730. #endif
  169731. case DCTSIZE:
  169732. switch (cinfo->dct_method) {
  169733. #ifdef DCT_ISLOW_SUPPORTED
  169734. case JDCT_ISLOW:
  169735. method_ptr = jpeg_idct_islow;
  169736. method = JDCT_ISLOW;
  169737. break;
  169738. #endif
  169739. #ifdef DCT_IFAST_SUPPORTED
  169740. case JDCT_IFAST:
  169741. method_ptr = jpeg_idct_ifast;
  169742. method = JDCT_IFAST;
  169743. break;
  169744. #endif
  169745. #ifdef DCT_FLOAT_SUPPORTED
  169746. case JDCT_FLOAT:
  169747. method_ptr = jpeg_idct_float;
  169748. method = JDCT_FLOAT;
  169749. break;
  169750. #endif
  169751. default:
  169752. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169753. break;
  169754. }
  169755. break;
  169756. default:
  169757. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169758. break;
  169759. }
  169760. idct->pub.inverse_DCT[ci] = method_ptr;
  169761. /* Create multiplier table from quant table.
  169762. * However, we can skip this if the component is uninteresting
  169763. * or if we already built the table. Also, if no quant table
  169764. * has yet been saved for the component, we leave the
  169765. * multiplier table all-zero; we'll be reading zeroes from the
  169766. * coefficient controller's buffer anyway.
  169767. */
  169768. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169769. continue;
  169770. qtbl = compptr->quant_table;
  169771. if (qtbl == NULL) /* happens if no data yet for component */
  169772. continue;
  169773. idct->cur_method[ci] = method;
  169774. switch (method) {
  169775. #ifdef PROVIDE_ISLOW_TABLES
  169776. case JDCT_ISLOW:
  169777. {
  169778. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169779. * coefficients, but are stored as ints to ensure access efficiency.
  169780. */
  169781. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169782. for (i = 0; i < DCTSIZE2; i++) {
  169783. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169784. }
  169785. }
  169786. break;
  169787. #endif
  169788. #ifdef DCT_IFAST_SUPPORTED
  169789. case JDCT_IFAST:
  169790. {
  169791. /* For AA&N IDCT method, multipliers are equal to quantization
  169792. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169793. * scalefactor[0] = 1
  169794. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169795. * For integer operation, the multiplier table is to be scaled by
  169796. * IFAST_SCALE_BITS.
  169797. */
  169798. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169799. #define CONST_BITS 14
  169800. static const INT16 aanscales[DCTSIZE2] = {
  169801. /* precomputed values scaled up by 14 bits */
  169802. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169803. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169804. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169805. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169806. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169807. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169808. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169809. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169810. };
  169811. SHIFT_TEMPS
  169812. for (i = 0; i < DCTSIZE2; i++) {
  169813. ifmtbl[i] = (IFAST_MULT_TYPE)
  169814. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169815. (INT32) aanscales[i]),
  169816. CONST_BITS-IFAST_SCALE_BITS);
  169817. }
  169818. }
  169819. break;
  169820. #endif
  169821. #ifdef DCT_FLOAT_SUPPORTED
  169822. case JDCT_FLOAT:
  169823. {
  169824. /* For float AA&N IDCT method, multipliers are equal to quantization
  169825. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169826. * scalefactor[0] = 1
  169827. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169828. */
  169829. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169830. int row, col;
  169831. static const double aanscalefactor[DCTSIZE] = {
  169832. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169833. 1.0, 0.785694958, 0.541196100, 0.275899379
  169834. };
  169835. i = 0;
  169836. for (row = 0; row < DCTSIZE; row++) {
  169837. for (col = 0; col < DCTSIZE; col++) {
  169838. fmtbl[i] = (FLOAT_MULT_TYPE)
  169839. ((double) qtbl->quantval[i] *
  169840. aanscalefactor[row] * aanscalefactor[col]);
  169841. i++;
  169842. }
  169843. }
  169844. }
  169845. break;
  169846. #endif
  169847. default:
  169848. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169849. break;
  169850. }
  169851. }
  169852. }
  169853. /*
  169854. * Initialize IDCT manager.
  169855. */
  169856. GLOBAL(void)
  169857. jinit_inverse_dct (j_decompress_ptr cinfo)
  169858. {
  169859. my_idct_ptr idct;
  169860. int ci;
  169861. jpeg_component_info *compptr;
  169862. idct = (my_idct_ptr)
  169863. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169864. SIZEOF(my_idct_controller));
  169865. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169866. idct->pub.start_pass = start_pass;
  169867. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169868. ci++, compptr++) {
  169869. /* Allocate and pre-zero a multiplier table for each component */
  169870. compptr->dct_table =
  169871. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169872. SIZEOF(multiplier_table));
  169873. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169874. /* Mark multiplier table not yet set up for any method */
  169875. idct->cur_method[ci] = -1;
  169876. }
  169877. }
  169878. /*** End of inlined file: jddctmgr.c ***/
  169879. #undef CONST_BITS
  169880. #undef ASSIGN_STATE
  169881. /*** Start of inlined file: jdhuff.c ***/
  169882. #define JPEG_INTERNALS
  169883. /*** Start of inlined file: jdhuff.h ***/
  169884. /* Short forms of external names for systems with brain-damaged linkers. */
  169885. #ifndef __jdhuff_h__
  169886. #define __jdhuff_h__
  169887. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169888. #define jpeg_make_d_derived_tbl jMkDDerived
  169889. #define jpeg_fill_bit_buffer jFilBitBuf
  169890. #define jpeg_huff_decode jHufDecode
  169891. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169892. /* Derived data constructed for each Huffman table */
  169893. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169894. typedef struct {
  169895. /* Basic tables: (element [0] of each array is unused) */
  169896. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169897. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169898. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169899. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169900. * the smallest code of length k; so given a code of length k, the
  169901. * corresponding symbol is huffval[code + valoffset[k]]
  169902. */
  169903. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169904. JHUFF_TBL *pub;
  169905. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169906. * the input data stream. If the next Huffman code is no more
  169907. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169908. * the corresponding symbol directly from these tables.
  169909. */
  169910. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169911. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169912. } d_derived_tbl;
  169913. /* Expand a Huffman table definition into the derived format */
  169914. EXTERN(void) jpeg_make_d_derived_tbl
  169915. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169916. d_derived_tbl ** pdtbl));
  169917. /*
  169918. * Fetching the next N bits from the input stream is a time-critical operation
  169919. * for the Huffman decoders. We implement it with a combination of inline
  169920. * macros and out-of-line subroutines. Note that N (the number of bits
  169921. * demanded at one time) never exceeds 15 for JPEG use.
  169922. *
  169923. * We read source bytes into get_buffer and dole out bits as needed.
  169924. * If get_buffer already contains enough bits, they are fetched in-line
  169925. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169926. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169927. * as full as possible (not just to the number of bits needed; this
  169928. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169929. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169930. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169931. * at least the requested number of bits --- dummy zeroes are inserted if
  169932. * necessary.
  169933. */
  169934. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169935. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169936. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169937. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169938. * appropriately should be a win. Unfortunately we can't define the size
  169939. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169940. * because not all machines measure sizeof in 8-bit bytes.
  169941. */
  169942. typedef struct { /* Bitreading state saved across MCUs */
  169943. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169944. int bits_left; /* # of unused bits in it */
  169945. } bitread_perm_state;
  169946. typedef struct { /* Bitreading working state within an MCU */
  169947. /* Current data source location */
  169948. /* We need a copy, rather than munging the original, in case of suspension */
  169949. const JOCTET * next_input_byte; /* => next byte to read from source */
  169950. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169951. /* Bit input buffer --- note these values are kept in register variables,
  169952. * not in this struct, inside the inner loops.
  169953. */
  169954. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169955. int bits_left; /* # of unused bits in it */
  169956. /* Pointer needed by jpeg_fill_bit_buffer. */
  169957. j_decompress_ptr cinfo; /* back link to decompress master record */
  169958. } bitread_working_state;
  169959. /* Macros to declare and load/save bitread local variables. */
  169960. #define BITREAD_STATE_VARS \
  169961. register bit_buf_type get_buffer; \
  169962. register int bits_left; \
  169963. bitread_working_state br_state
  169964. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169965. br_state.cinfo = cinfop; \
  169966. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169967. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169968. get_buffer = permstate.get_buffer; \
  169969. bits_left = permstate.bits_left;
  169970. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169971. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169972. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169973. permstate.get_buffer = get_buffer; \
  169974. permstate.bits_left = bits_left
  169975. /*
  169976. * These macros provide the in-line portion of bit fetching.
  169977. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169978. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169979. * The variables get_buffer and bits_left are assumed to be locals,
  169980. * but the state struct might not be (jpeg_huff_decode needs this).
  169981. * CHECK_BIT_BUFFER(state,n,action);
  169982. * Ensure there are N bits in get_buffer; if suspend, take action.
  169983. * val = GET_BITS(n);
  169984. * Fetch next N bits.
  169985. * val = PEEK_BITS(n);
  169986. * Fetch next N bits without removing them from the buffer.
  169987. * DROP_BITS(n);
  169988. * Discard next N bits.
  169989. * The value N should be a simple variable, not an expression, because it
  169990. * is evaluated multiple times.
  169991. */
  169992. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169993. { if (bits_left < (nbits)) { \
  169994. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169995. { action; } \
  169996. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169997. #define GET_BITS(nbits) \
  169998. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169999. #define PEEK_BITS(nbits) \
  170000. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  170001. #define DROP_BITS(nbits) \
  170002. (bits_left -= (nbits))
  170003. /* Load up the bit buffer to a depth of at least nbits */
  170004. EXTERN(boolean) jpeg_fill_bit_buffer
  170005. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170006. register int bits_left, int nbits));
  170007. /*
  170008. * Code for extracting next Huffman-coded symbol from input bit stream.
  170009. * Again, this is time-critical and we make the main paths be macros.
  170010. *
  170011. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  170012. * without looping. Usually, more than 95% of the Huffman codes will be 8
  170013. * or fewer bits long. The few overlength codes are handled with a loop,
  170014. * which need not be inline code.
  170015. *
  170016. * Notes about the HUFF_DECODE macro:
  170017. * 1. Near the end of the data segment, we may fail to get enough bits
  170018. * for a lookahead. In that case, we do it the hard way.
  170019. * 2. If the lookahead table contains no entry, the next code must be
  170020. * more than HUFF_LOOKAHEAD bits long.
  170021. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  170022. */
  170023. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  170024. { register int nb, look; \
  170025. if (bits_left < HUFF_LOOKAHEAD) { \
  170026. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  170027. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170028. if (bits_left < HUFF_LOOKAHEAD) { \
  170029. nb = 1; goto slowlabel; \
  170030. } \
  170031. } \
  170032. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  170033. if ((nb = htbl->look_nbits[look]) != 0) { \
  170034. DROP_BITS(nb); \
  170035. result = htbl->look_sym[look]; \
  170036. } else { \
  170037. nb = HUFF_LOOKAHEAD+1; \
  170038. slowlabel: \
  170039. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  170040. { failaction; } \
  170041. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170042. } \
  170043. }
  170044. /* Out-of-line case for Huffman code fetching */
  170045. EXTERN(int) jpeg_huff_decode
  170046. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170047. register int bits_left, d_derived_tbl * htbl, int min_bits));
  170048. #endif
  170049. /*** End of inlined file: jdhuff.h ***/
  170050. /* Declarations shared with jdphuff.c */
  170051. /*
  170052. * Expanded entropy decoder object for Huffman decoding.
  170053. *
  170054. * The savable_state subrecord contains fields that change within an MCU,
  170055. * but must not be updated permanently until we complete the MCU.
  170056. */
  170057. typedef struct {
  170058. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  170059. } savable_state2;
  170060. /* This macro is to work around compilers with missing or broken
  170061. * structure assignment. You'll need to fix this code if you have
  170062. * such a compiler and you change MAX_COMPS_IN_SCAN.
  170063. */
  170064. #ifndef NO_STRUCT_ASSIGN
  170065. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  170066. #else
  170067. #if MAX_COMPS_IN_SCAN == 4
  170068. #define ASSIGN_STATE(dest,src) \
  170069. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  170070. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170071. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170072. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170073. #endif
  170074. #endif
  170075. typedef struct {
  170076. struct jpeg_entropy_decoder pub; /* public fields */
  170077. /* These fields are loaded into local variables at start of each MCU.
  170078. * In case of suspension, we exit WITHOUT updating them.
  170079. */
  170080. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170081. savable_state2 saved; /* Other state at start of MCU */
  170082. /* These fields are NOT loaded into local working state. */
  170083. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170084. /* Pointers to derived tables (these workspaces have image lifespan) */
  170085. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  170086. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  170087. /* Precalculated info set up by start_pass for use in decode_mcu: */
  170088. /* Pointers to derived tables to be used for each block within an MCU */
  170089. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170090. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170091. /* Whether we care about the DC and AC coefficient values for each block */
  170092. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  170093. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  170094. } huff_entropy_decoder2;
  170095. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  170096. /*
  170097. * Initialize for a Huffman-compressed scan.
  170098. */
  170099. METHODDEF(void)
  170100. start_pass_huff_decoder (j_decompress_ptr cinfo)
  170101. {
  170102. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170103. int ci, blkn, dctbl, actbl;
  170104. jpeg_component_info * compptr;
  170105. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  170106. * This ought to be an error condition, but we make it a warning because
  170107. * there are some baseline files out there with all zeroes in these bytes.
  170108. */
  170109. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  170110. cinfo->Ah != 0 || cinfo->Al != 0)
  170111. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  170112. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170113. compptr = cinfo->cur_comp_info[ci];
  170114. dctbl = compptr->dc_tbl_no;
  170115. actbl = compptr->ac_tbl_no;
  170116. /* Compute derived values for Huffman tables */
  170117. /* We may do this more than once for a table, but it's not expensive */
  170118. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  170119. & entropy->dc_derived_tbls[dctbl]);
  170120. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  170121. & entropy->ac_derived_tbls[actbl]);
  170122. /* Initialize DC predictions to 0 */
  170123. entropy->saved.last_dc_val[ci] = 0;
  170124. }
  170125. /* Precalculate decoding info for each block in an MCU of this scan */
  170126. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170127. ci = cinfo->MCU_membership[blkn];
  170128. compptr = cinfo->cur_comp_info[ci];
  170129. /* Precalculate which table to use for each block */
  170130. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  170131. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  170132. /* Decide whether we really care about the coefficient values */
  170133. if (compptr->component_needed) {
  170134. entropy->dc_needed[blkn] = TRUE;
  170135. /* we don't need the ACs if producing a 1/8th-size image */
  170136. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  170137. } else {
  170138. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  170139. }
  170140. }
  170141. /* Initialize bitread state variables */
  170142. entropy->bitstate.bits_left = 0;
  170143. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170144. entropy->pub.insufficient_data = FALSE;
  170145. /* Initialize restart counter */
  170146. entropy->restarts_to_go = cinfo->restart_interval;
  170147. }
  170148. /*
  170149. * Compute the derived values for a Huffman table.
  170150. * This routine also performs some validation checks on the table.
  170151. *
  170152. * Note this is also used by jdphuff.c.
  170153. */
  170154. GLOBAL(void)
  170155. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170156. d_derived_tbl ** pdtbl)
  170157. {
  170158. JHUFF_TBL *htbl;
  170159. d_derived_tbl *dtbl;
  170160. int p, i, l, si, numsymbols;
  170161. int lookbits, ctr;
  170162. char huffsize[257];
  170163. unsigned int huffcode[257];
  170164. unsigned int code;
  170165. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170166. * paralleling the order of the symbols themselves in htbl->huffval[].
  170167. */
  170168. /* Find the input Huffman table */
  170169. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170170. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170171. htbl =
  170172. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170173. if (htbl == NULL)
  170174. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170175. /* Allocate a workspace if we haven't already done so. */
  170176. if (*pdtbl == NULL)
  170177. *pdtbl = (d_derived_tbl *)
  170178. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170179. SIZEOF(d_derived_tbl));
  170180. dtbl = *pdtbl;
  170181. dtbl->pub = htbl; /* fill in back link */
  170182. /* Figure C.1: make table of Huffman code length for each symbol */
  170183. p = 0;
  170184. for (l = 1; l <= 16; l++) {
  170185. i = (int) htbl->bits[l];
  170186. if (i < 0 || p + i > 256) /* protect against table overrun */
  170187. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170188. while (i--)
  170189. huffsize[p++] = (char) l;
  170190. }
  170191. huffsize[p] = 0;
  170192. numsymbols = p;
  170193. /* Figure C.2: generate the codes themselves */
  170194. /* We also validate that the counts represent a legal Huffman code tree. */
  170195. code = 0;
  170196. si = huffsize[0];
  170197. p = 0;
  170198. while (huffsize[p]) {
  170199. while (((int) huffsize[p]) == si) {
  170200. huffcode[p++] = code;
  170201. code++;
  170202. }
  170203. /* code is now 1 more than the last code used for codelength si; but
  170204. * it must still fit in si bits, since no code is allowed to be all ones.
  170205. */
  170206. if (((INT32) code) >= (((INT32) 1) << si))
  170207. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170208. code <<= 1;
  170209. si++;
  170210. }
  170211. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170212. p = 0;
  170213. for (l = 1; l <= 16; l++) {
  170214. if (htbl->bits[l]) {
  170215. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170216. * minus the minimum code of length l
  170217. */
  170218. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170219. p += htbl->bits[l];
  170220. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170221. } else {
  170222. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170223. }
  170224. }
  170225. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170226. /* Compute lookahead tables to speed up decoding.
  170227. * First we set all the table entries to 0, indicating "too long";
  170228. * then we iterate through the Huffman codes that are short enough and
  170229. * fill in all the entries that correspond to bit sequences starting
  170230. * with that code.
  170231. */
  170232. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170233. p = 0;
  170234. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170235. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170236. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170237. /* Generate left-justified code followed by all possible bit sequences */
  170238. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170239. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170240. dtbl->look_nbits[lookbits] = l;
  170241. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170242. lookbits++;
  170243. }
  170244. }
  170245. }
  170246. /* Validate symbols as being reasonable.
  170247. * For AC tables, we make no check, but accept all byte values 0..255.
  170248. * For DC tables, we require the symbols to be in range 0..15.
  170249. * (Tighter bounds could be applied depending on the data depth and mode,
  170250. * but this is sufficient to ensure safe decoding.)
  170251. */
  170252. if (isDC) {
  170253. for (i = 0; i < numsymbols; i++) {
  170254. int sym = htbl->huffval[i];
  170255. if (sym < 0 || sym > 15)
  170256. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170257. }
  170258. }
  170259. }
  170260. /*
  170261. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170262. * See jdhuff.h for info about usage.
  170263. * Note: current values of get_buffer and bits_left are passed as parameters,
  170264. * but are returned in the corresponding fields of the state struct.
  170265. *
  170266. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170267. * of get_buffer to be used. (On machines with wider words, an even larger
  170268. * buffer could be used.) However, on some machines 32-bit shifts are
  170269. * quite slow and take time proportional to the number of places shifted.
  170270. * (This is true with most PC compilers, for instance.) In this case it may
  170271. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170272. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170273. */
  170274. #ifdef SLOW_SHIFT_32
  170275. #define MIN_GET_BITS 15 /* minimum allowable value */
  170276. #else
  170277. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170278. #endif
  170279. GLOBAL(boolean)
  170280. jpeg_fill_bit_buffer (bitread_working_state * state,
  170281. register bit_buf_type get_buffer, register int bits_left,
  170282. int nbits)
  170283. /* Load up the bit buffer to a depth of at least nbits */
  170284. {
  170285. /* Copy heavily used state fields into locals (hopefully registers) */
  170286. register const JOCTET * next_input_byte = state->next_input_byte;
  170287. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170288. j_decompress_ptr cinfo = state->cinfo;
  170289. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170290. /* (It is assumed that no request will be for more than that many bits.) */
  170291. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170292. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170293. while (bits_left < MIN_GET_BITS) {
  170294. register int c;
  170295. /* Attempt to read a byte */
  170296. if (bytes_in_buffer == 0) {
  170297. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170298. return FALSE;
  170299. next_input_byte = cinfo->src->next_input_byte;
  170300. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170301. }
  170302. bytes_in_buffer--;
  170303. c = GETJOCTET(*next_input_byte++);
  170304. /* If it's 0xFF, check and discard stuffed zero byte */
  170305. if (c == 0xFF) {
  170306. /* Loop here to discard any padding FF's on terminating marker,
  170307. * so that we can save a valid unread_marker value. NOTE: we will
  170308. * accept multiple FF's followed by a 0 as meaning a single FF data
  170309. * byte. This data pattern is not valid according to the standard.
  170310. */
  170311. do {
  170312. if (bytes_in_buffer == 0) {
  170313. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170314. return FALSE;
  170315. next_input_byte = cinfo->src->next_input_byte;
  170316. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170317. }
  170318. bytes_in_buffer--;
  170319. c = GETJOCTET(*next_input_byte++);
  170320. } while (c == 0xFF);
  170321. if (c == 0) {
  170322. /* Found FF/00, which represents an FF data byte */
  170323. c = 0xFF;
  170324. } else {
  170325. /* Oops, it's actually a marker indicating end of compressed data.
  170326. * Save the marker code for later use.
  170327. * Fine point: it might appear that we should save the marker into
  170328. * bitread working state, not straight into permanent state. But
  170329. * once we have hit a marker, we cannot need to suspend within the
  170330. * current MCU, because we will read no more bytes from the data
  170331. * source. So it is OK to update permanent state right away.
  170332. */
  170333. cinfo->unread_marker = c;
  170334. /* See if we need to insert some fake zero bits. */
  170335. goto no_more_bytes;
  170336. }
  170337. }
  170338. /* OK, load c into get_buffer */
  170339. get_buffer = (get_buffer << 8) | c;
  170340. bits_left += 8;
  170341. } /* end while */
  170342. } else {
  170343. no_more_bytes:
  170344. /* We get here if we've read the marker that terminates the compressed
  170345. * data segment. There should be enough bits in the buffer register
  170346. * to satisfy the request; if so, no problem.
  170347. */
  170348. if (nbits > bits_left) {
  170349. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170350. * the data stream, so that we can produce some kind of image.
  170351. * We use a nonvolatile flag to ensure that only one warning message
  170352. * appears per data segment.
  170353. */
  170354. if (! cinfo->entropy->insufficient_data) {
  170355. WARNMS(cinfo, JWRN_HIT_MARKER);
  170356. cinfo->entropy->insufficient_data = TRUE;
  170357. }
  170358. /* Fill the buffer with zero bits */
  170359. get_buffer <<= MIN_GET_BITS - bits_left;
  170360. bits_left = MIN_GET_BITS;
  170361. }
  170362. }
  170363. /* Unload the local registers */
  170364. state->next_input_byte = next_input_byte;
  170365. state->bytes_in_buffer = bytes_in_buffer;
  170366. state->get_buffer = get_buffer;
  170367. state->bits_left = bits_left;
  170368. return TRUE;
  170369. }
  170370. /*
  170371. * Out-of-line code for Huffman code decoding.
  170372. * See jdhuff.h for info about usage.
  170373. */
  170374. GLOBAL(int)
  170375. jpeg_huff_decode (bitread_working_state * state,
  170376. register bit_buf_type get_buffer, register int bits_left,
  170377. d_derived_tbl * htbl, int min_bits)
  170378. {
  170379. register int l = min_bits;
  170380. register INT32 code;
  170381. /* HUFF_DECODE has determined that the code is at least min_bits */
  170382. /* bits long, so fetch that many bits in one swoop. */
  170383. CHECK_BIT_BUFFER(*state, l, return -1);
  170384. code = GET_BITS(l);
  170385. /* Collect the rest of the Huffman code one bit at a time. */
  170386. /* This is per Figure F.16 in the JPEG spec. */
  170387. while (code > htbl->maxcode[l]) {
  170388. code <<= 1;
  170389. CHECK_BIT_BUFFER(*state, 1, return -1);
  170390. code |= GET_BITS(1);
  170391. l++;
  170392. }
  170393. /* Unload the local registers */
  170394. state->get_buffer = get_buffer;
  170395. state->bits_left = bits_left;
  170396. /* With garbage input we may reach the sentinel value l = 17. */
  170397. if (l > 16) {
  170398. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170399. return 0; /* fake a zero as the safest result */
  170400. }
  170401. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170402. }
  170403. /*
  170404. * Check for a restart marker & resynchronize decoder.
  170405. * Returns FALSE if must suspend.
  170406. */
  170407. LOCAL(boolean)
  170408. process_restart (j_decompress_ptr cinfo)
  170409. {
  170410. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170411. int ci;
  170412. /* Throw away any unused bits remaining in bit buffer; */
  170413. /* include any full bytes in next_marker's count of discarded bytes */
  170414. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170415. entropy->bitstate.bits_left = 0;
  170416. /* Advance past the RSTn marker */
  170417. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170418. return FALSE;
  170419. /* Re-initialize DC predictions to 0 */
  170420. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170421. entropy->saved.last_dc_val[ci] = 0;
  170422. /* Reset restart counter */
  170423. entropy->restarts_to_go = cinfo->restart_interval;
  170424. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170425. * against a marker. In that case we will end up treating the next data
  170426. * segment as empty, and we can avoid producing bogus output pixels by
  170427. * leaving the flag set.
  170428. */
  170429. if (cinfo->unread_marker == 0)
  170430. entropy->pub.insufficient_data = FALSE;
  170431. return TRUE;
  170432. }
  170433. /*
  170434. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170435. * The coefficients are reordered from zigzag order into natural array order,
  170436. * but are not dequantized.
  170437. *
  170438. * The i'th block of the MCU is stored into the block pointed to by
  170439. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170440. * (Wholesale zeroing is usually a little faster than retail...)
  170441. *
  170442. * Returns FALSE if data source requested suspension. In that case no
  170443. * changes have been made to permanent state. (Exception: some output
  170444. * coefficients may already have been assigned. This is harmless for
  170445. * this module, since we'll just re-assign them on the next call.)
  170446. */
  170447. METHODDEF(boolean)
  170448. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170449. {
  170450. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170451. int blkn;
  170452. BITREAD_STATE_VARS;
  170453. savable_state2 state;
  170454. /* Process restart marker if needed; may have to suspend */
  170455. if (cinfo->restart_interval) {
  170456. if (entropy->restarts_to_go == 0)
  170457. if (! process_restart(cinfo))
  170458. return FALSE;
  170459. }
  170460. /* If we've run out of data, just leave the MCU set to zeroes.
  170461. * This way, we return uniform gray for the remainder of the segment.
  170462. */
  170463. if (! entropy->pub.insufficient_data) {
  170464. /* Load up working state */
  170465. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170466. ASSIGN_STATE(state, entropy->saved);
  170467. /* Outer loop handles each block in the MCU */
  170468. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170469. JBLOCKROW block = MCU_data[blkn];
  170470. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170471. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170472. register int s, k, r;
  170473. /* Decode a single block's worth of coefficients */
  170474. /* Section F.2.2.1: decode the DC coefficient difference */
  170475. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170476. if (s) {
  170477. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170478. r = GET_BITS(s);
  170479. s = HUFF_EXTEND(r, s);
  170480. }
  170481. if (entropy->dc_needed[blkn]) {
  170482. /* Convert DC difference to actual value, update last_dc_val */
  170483. int ci = cinfo->MCU_membership[blkn];
  170484. s += state.last_dc_val[ci];
  170485. state.last_dc_val[ci] = s;
  170486. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170487. (*block)[0] = (JCOEF) s;
  170488. }
  170489. if (entropy->ac_needed[blkn]) {
  170490. /* Section F.2.2.2: decode the AC coefficients */
  170491. /* Since zeroes are skipped, output area must be cleared beforehand */
  170492. for (k = 1; k < DCTSIZE2; k++) {
  170493. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170494. r = s >> 4;
  170495. s &= 15;
  170496. if (s) {
  170497. k += r;
  170498. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170499. r = GET_BITS(s);
  170500. s = HUFF_EXTEND(r, s);
  170501. /* Output coefficient in natural (dezigzagged) order.
  170502. * Note: the extra entries in jpeg_natural_order[] will save us
  170503. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170504. */
  170505. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170506. } else {
  170507. if (r != 15)
  170508. break;
  170509. k += 15;
  170510. }
  170511. }
  170512. } else {
  170513. /* Section F.2.2.2: decode the AC coefficients */
  170514. /* In this path we just discard the values */
  170515. for (k = 1; k < DCTSIZE2; k++) {
  170516. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170517. r = s >> 4;
  170518. s &= 15;
  170519. if (s) {
  170520. k += r;
  170521. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170522. DROP_BITS(s);
  170523. } else {
  170524. if (r != 15)
  170525. break;
  170526. k += 15;
  170527. }
  170528. }
  170529. }
  170530. }
  170531. /* Completed MCU, so update state */
  170532. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170533. ASSIGN_STATE(entropy->saved, state);
  170534. }
  170535. /* Account for restart interval (no-op if not using restarts) */
  170536. entropy->restarts_to_go--;
  170537. return TRUE;
  170538. }
  170539. /*
  170540. * Module initialization routine for Huffman entropy decoding.
  170541. */
  170542. GLOBAL(void)
  170543. jinit_huff_decoder (j_decompress_ptr cinfo)
  170544. {
  170545. huff_entropy_ptr2 entropy;
  170546. int i;
  170547. entropy = (huff_entropy_ptr2)
  170548. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170549. SIZEOF(huff_entropy_decoder2));
  170550. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170551. entropy->pub.start_pass = start_pass_huff_decoder;
  170552. entropy->pub.decode_mcu = decode_mcu;
  170553. /* Mark tables unallocated */
  170554. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170555. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170556. }
  170557. }
  170558. /*** End of inlined file: jdhuff.c ***/
  170559. /*** Start of inlined file: jdinput.c ***/
  170560. #define JPEG_INTERNALS
  170561. /* Private state */
  170562. typedef struct {
  170563. struct jpeg_input_controller pub; /* public fields */
  170564. boolean inheaders; /* TRUE until first SOS is reached */
  170565. } my_input_controller;
  170566. typedef my_input_controller * my_inputctl_ptr;
  170567. /* Forward declarations */
  170568. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170569. /*
  170570. * Routines to calculate various quantities related to the size of the image.
  170571. */
  170572. LOCAL(void)
  170573. initial_setup2 (j_decompress_ptr cinfo)
  170574. /* Called once, when first SOS marker is reached */
  170575. {
  170576. int ci;
  170577. jpeg_component_info *compptr;
  170578. /* Make sure image isn't bigger than I can handle */
  170579. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170580. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170581. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170582. /* For now, precision must match compiled-in value... */
  170583. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170584. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170585. /* Check that number of components won't exceed internal array sizes */
  170586. if (cinfo->num_components > MAX_COMPONENTS)
  170587. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170588. MAX_COMPONENTS);
  170589. /* Compute maximum sampling factors; check factor validity */
  170590. cinfo->max_h_samp_factor = 1;
  170591. cinfo->max_v_samp_factor = 1;
  170592. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170593. ci++, compptr++) {
  170594. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170595. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170596. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170597. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170598. compptr->h_samp_factor);
  170599. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170600. compptr->v_samp_factor);
  170601. }
  170602. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170603. * In the full decompressor, this will be overridden by jdmaster.c;
  170604. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170605. */
  170606. cinfo->min_DCT_scaled_size = DCTSIZE;
  170607. /* Compute dimensions of components */
  170608. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170609. ci++, compptr++) {
  170610. compptr->DCT_scaled_size = DCTSIZE;
  170611. /* Size in DCT blocks */
  170612. compptr->width_in_blocks = (JDIMENSION)
  170613. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170614. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170615. compptr->height_in_blocks = (JDIMENSION)
  170616. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170617. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170618. /* downsampled_width and downsampled_height will also be overridden by
  170619. * jdmaster.c if we are doing full decompression. The transcoder library
  170620. * doesn't use these values, but the calling application might.
  170621. */
  170622. /* Size in samples */
  170623. compptr->downsampled_width = (JDIMENSION)
  170624. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170625. (long) cinfo->max_h_samp_factor);
  170626. compptr->downsampled_height = (JDIMENSION)
  170627. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170628. (long) cinfo->max_v_samp_factor);
  170629. /* Mark component needed, until color conversion says otherwise */
  170630. compptr->component_needed = TRUE;
  170631. /* Mark no quantization table yet saved for component */
  170632. compptr->quant_table = NULL;
  170633. }
  170634. /* Compute number of fully interleaved MCU rows. */
  170635. cinfo->total_iMCU_rows = (JDIMENSION)
  170636. jdiv_round_up((long) cinfo->image_height,
  170637. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170638. /* Decide whether file contains multiple scans */
  170639. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170640. cinfo->inputctl->has_multiple_scans = TRUE;
  170641. else
  170642. cinfo->inputctl->has_multiple_scans = FALSE;
  170643. }
  170644. LOCAL(void)
  170645. per_scan_setup2 (j_decompress_ptr cinfo)
  170646. /* Do computations that are needed before processing a JPEG scan */
  170647. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170648. {
  170649. int ci, mcublks, tmp;
  170650. jpeg_component_info *compptr;
  170651. if (cinfo->comps_in_scan == 1) {
  170652. /* Noninterleaved (single-component) scan */
  170653. compptr = cinfo->cur_comp_info[0];
  170654. /* Overall image size in MCUs */
  170655. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170656. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170657. /* For noninterleaved scan, always one block per MCU */
  170658. compptr->MCU_width = 1;
  170659. compptr->MCU_height = 1;
  170660. compptr->MCU_blocks = 1;
  170661. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170662. compptr->last_col_width = 1;
  170663. /* For noninterleaved scans, it is convenient to define last_row_height
  170664. * as the number of block rows present in the last iMCU row.
  170665. */
  170666. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170667. if (tmp == 0) tmp = compptr->v_samp_factor;
  170668. compptr->last_row_height = tmp;
  170669. /* Prepare array describing MCU composition */
  170670. cinfo->blocks_in_MCU = 1;
  170671. cinfo->MCU_membership[0] = 0;
  170672. } else {
  170673. /* Interleaved (multi-component) scan */
  170674. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170675. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170676. MAX_COMPS_IN_SCAN);
  170677. /* Overall image size in MCUs */
  170678. cinfo->MCUs_per_row = (JDIMENSION)
  170679. jdiv_round_up((long) cinfo->image_width,
  170680. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170681. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170682. jdiv_round_up((long) cinfo->image_height,
  170683. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170684. cinfo->blocks_in_MCU = 0;
  170685. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170686. compptr = cinfo->cur_comp_info[ci];
  170687. /* Sampling factors give # of blocks of component in each MCU */
  170688. compptr->MCU_width = compptr->h_samp_factor;
  170689. compptr->MCU_height = compptr->v_samp_factor;
  170690. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170691. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170692. /* Figure number of non-dummy blocks in last MCU column & row */
  170693. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170694. if (tmp == 0) tmp = compptr->MCU_width;
  170695. compptr->last_col_width = tmp;
  170696. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170697. if (tmp == 0) tmp = compptr->MCU_height;
  170698. compptr->last_row_height = tmp;
  170699. /* Prepare array describing MCU composition */
  170700. mcublks = compptr->MCU_blocks;
  170701. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170702. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170703. while (mcublks-- > 0) {
  170704. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170705. }
  170706. }
  170707. }
  170708. }
  170709. /*
  170710. * Save away a copy of the Q-table referenced by each component present
  170711. * in the current scan, unless already saved during a prior scan.
  170712. *
  170713. * In a multiple-scan JPEG file, the encoder could assign different components
  170714. * the same Q-table slot number, but change table definitions between scans
  170715. * so that each component uses a different Q-table. (The IJG encoder is not
  170716. * currently capable of doing this, but other encoders might.) Since we want
  170717. * to be able to dequantize all the components at the end of the file, this
  170718. * means that we have to save away the table actually used for each component.
  170719. * We do this by copying the table at the start of the first scan containing
  170720. * the component.
  170721. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170722. * slot between scans of a component using that slot. If the encoder does so
  170723. * anyway, this decoder will simply use the Q-table values that were current
  170724. * at the start of the first scan for the component.
  170725. *
  170726. * The decompressor output side looks only at the saved quant tables,
  170727. * not at the current Q-table slots.
  170728. */
  170729. LOCAL(void)
  170730. latch_quant_tables (j_decompress_ptr cinfo)
  170731. {
  170732. int ci, qtblno;
  170733. jpeg_component_info *compptr;
  170734. JQUANT_TBL * qtbl;
  170735. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170736. compptr = cinfo->cur_comp_info[ci];
  170737. /* No work if we already saved Q-table for this component */
  170738. if (compptr->quant_table != NULL)
  170739. continue;
  170740. /* Make sure specified quantization table is present */
  170741. qtblno = compptr->quant_tbl_no;
  170742. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170743. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170744. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170745. /* OK, save away the quantization table */
  170746. qtbl = (JQUANT_TBL *)
  170747. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170748. SIZEOF(JQUANT_TBL));
  170749. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170750. compptr->quant_table = qtbl;
  170751. }
  170752. }
  170753. /*
  170754. * Initialize the input modules to read a scan of compressed data.
  170755. * The first call to this is done by jdmaster.c after initializing
  170756. * the entire decompressor (during jpeg_start_decompress).
  170757. * Subsequent calls come from consume_markers, below.
  170758. */
  170759. METHODDEF(void)
  170760. start_input_pass2 (j_decompress_ptr cinfo)
  170761. {
  170762. per_scan_setup2(cinfo);
  170763. latch_quant_tables(cinfo);
  170764. (*cinfo->entropy->start_pass) (cinfo);
  170765. (*cinfo->coef->start_input_pass) (cinfo);
  170766. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170767. }
  170768. /*
  170769. * Finish up after inputting a compressed-data scan.
  170770. * This is called by the coefficient controller after it's read all
  170771. * the expected data of the scan.
  170772. */
  170773. METHODDEF(void)
  170774. finish_input_pass (j_decompress_ptr cinfo)
  170775. {
  170776. cinfo->inputctl->consume_input = consume_markers;
  170777. }
  170778. /*
  170779. * Read JPEG markers before, between, or after compressed-data scans.
  170780. * Change state as necessary when a new scan is reached.
  170781. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170782. *
  170783. * The consume_input method pointer points either here or to the
  170784. * coefficient controller's consume_data routine, depending on whether
  170785. * we are reading a compressed data segment or inter-segment markers.
  170786. */
  170787. METHODDEF(int)
  170788. consume_markers (j_decompress_ptr cinfo)
  170789. {
  170790. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170791. int val;
  170792. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170793. return JPEG_REACHED_EOI;
  170794. val = (*cinfo->marker->read_markers) (cinfo);
  170795. switch (val) {
  170796. case JPEG_REACHED_SOS: /* Found SOS */
  170797. if (inputctl->inheaders) { /* 1st SOS */
  170798. initial_setup2(cinfo);
  170799. inputctl->inheaders = FALSE;
  170800. /* Note: start_input_pass must be called by jdmaster.c
  170801. * before any more input can be consumed. jdapimin.c is
  170802. * responsible for enforcing this sequencing.
  170803. */
  170804. } else { /* 2nd or later SOS marker */
  170805. if (! inputctl->pub.has_multiple_scans)
  170806. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170807. start_input_pass2(cinfo);
  170808. }
  170809. break;
  170810. case JPEG_REACHED_EOI: /* Found EOI */
  170811. inputctl->pub.eoi_reached = TRUE;
  170812. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170813. if (cinfo->marker->saw_SOF)
  170814. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170815. } else {
  170816. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170817. * if user set output_scan_number larger than number of scans.
  170818. */
  170819. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170820. cinfo->output_scan_number = cinfo->input_scan_number;
  170821. }
  170822. break;
  170823. case JPEG_SUSPENDED:
  170824. break;
  170825. }
  170826. return val;
  170827. }
  170828. /*
  170829. * Reset state to begin a fresh datastream.
  170830. */
  170831. METHODDEF(void)
  170832. reset_input_controller (j_decompress_ptr cinfo)
  170833. {
  170834. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170835. inputctl->pub.consume_input = consume_markers;
  170836. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170837. inputctl->pub.eoi_reached = FALSE;
  170838. inputctl->inheaders = TRUE;
  170839. /* Reset other modules */
  170840. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170841. (*cinfo->marker->reset_marker_reader) (cinfo);
  170842. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170843. cinfo->coef_bits = NULL;
  170844. }
  170845. /*
  170846. * Initialize the input controller module.
  170847. * This is called only once, when the decompression object is created.
  170848. */
  170849. GLOBAL(void)
  170850. jinit_input_controller (j_decompress_ptr cinfo)
  170851. {
  170852. my_inputctl_ptr inputctl;
  170853. /* Create subobject in permanent pool */
  170854. inputctl = (my_inputctl_ptr)
  170855. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170856. SIZEOF(my_input_controller));
  170857. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170858. /* Initialize method pointers */
  170859. inputctl->pub.consume_input = consume_markers;
  170860. inputctl->pub.reset_input_controller = reset_input_controller;
  170861. inputctl->pub.start_input_pass = start_input_pass2;
  170862. inputctl->pub.finish_input_pass = finish_input_pass;
  170863. /* Initialize state: can't use reset_input_controller since we don't
  170864. * want to try to reset other modules yet.
  170865. */
  170866. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170867. inputctl->pub.eoi_reached = FALSE;
  170868. inputctl->inheaders = TRUE;
  170869. }
  170870. /*** End of inlined file: jdinput.c ***/
  170871. /*** Start of inlined file: jdmainct.c ***/
  170872. #define JPEG_INTERNALS
  170873. /*
  170874. * In the current system design, the main buffer need never be a full-image
  170875. * buffer; any full-height buffers will be found inside the coefficient or
  170876. * postprocessing controllers. Nonetheless, the main controller is not
  170877. * trivial. Its responsibility is to provide context rows for upsampling/
  170878. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170879. *
  170880. * Postprocessor input data is counted in "row groups". A row group
  170881. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170882. * sample rows of each component. (We require DCT_scaled_size values to be
  170883. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170884. * values will likely be powers of two, so we actually have the stronger
  170885. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170886. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170887. * row group (times any additional scale factor that the upsampler is
  170888. * applying).
  170889. *
  170890. * The coefficient controller will deliver data to us one iMCU row at a time;
  170891. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170892. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170893. * to one row of MCUs when the image is fully interleaved.) Note that the
  170894. * number of sample rows varies across components, but the number of row
  170895. * groups does not. Some garbage sample rows may be included in the last iMCU
  170896. * row at the bottom of the image.
  170897. *
  170898. * Depending on the vertical scaling algorithm used, the upsampler may need
  170899. * access to the sample row(s) above and below its current input row group.
  170900. * The upsampler is required to set need_context_rows TRUE at global selection
  170901. * time if so. When need_context_rows is FALSE, this controller can simply
  170902. * obtain one iMCU row at a time from the coefficient controller and dole it
  170903. * out as row groups to the postprocessor.
  170904. *
  170905. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170906. * passed to postprocessing contains at least one row group's worth of samples
  170907. * above and below the row group(s) being processed. Note that the context
  170908. * rows "above" the first passed row group appear at negative row offsets in
  170909. * the passed buffer. At the top and bottom of the image, the required
  170910. * context rows are manufactured by duplicating the first or last real sample
  170911. * row; this avoids having special cases in the upsampling inner loops.
  170912. *
  170913. * The amount of context is fixed at one row group just because that's a
  170914. * convenient number for this controller to work with. The existing
  170915. * upsamplers really only need one sample row of context. An upsampler
  170916. * supporting arbitrary output rescaling might wish for more than one row
  170917. * group of context when shrinking the image; tough, we don't handle that.
  170918. * (This is justified by the assumption that downsizing will be handled mostly
  170919. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170920. * the upsample step needn't be much less than one.)
  170921. *
  170922. * To provide the desired context, we have to retain the last two row groups
  170923. * of one iMCU row while reading in the next iMCU row. (The last row group
  170924. * can't be processed until we have another row group for its below-context,
  170925. * and so we have to save the next-to-last group too for its above-context.)
  170926. * We could do this most simply by copying data around in our buffer, but
  170927. * that'd be very slow. We can avoid copying any data by creating a rather
  170928. * strange pointer structure. Here's how it works. We allocate a workspace
  170929. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170930. * of row groups per iMCU row). We create two sets of redundant pointers to
  170931. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170932. * pointer lists look like this:
  170933. * M+1 M-1
  170934. * master pointer --> 0 master pointer --> 0
  170935. * 1 1
  170936. * ... ...
  170937. * M-3 M-3
  170938. * M-2 M
  170939. * M-1 M+1
  170940. * M M-2
  170941. * M+1 M-1
  170942. * 0 0
  170943. * We read alternate iMCU rows using each master pointer; thus the last two
  170944. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170945. * The pointer lists are set up so that the required context rows appear to
  170946. * be adjacent to the proper places when we pass the pointer lists to the
  170947. * upsampler.
  170948. *
  170949. * The above pictures describe the normal state of the pointer lists.
  170950. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170951. * the first or last sample row as necessary (this is cheaper than copying
  170952. * sample rows around).
  170953. *
  170954. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170955. * situation each iMCU row provides only one row group so the buffering logic
  170956. * must be different (eg, we must read two iMCU rows before we can emit the
  170957. * first row group). For now, we simply do not support providing context
  170958. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170959. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170960. * want it quick and dirty, so a context-free upsampler is sufficient.
  170961. */
  170962. /* Private buffer controller object */
  170963. typedef struct {
  170964. struct jpeg_d_main_controller pub; /* public fields */
  170965. /* Pointer to allocated workspace (M or M+2 row groups). */
  170966. JSAMPARRAY buffer[MAX_COMPONENTS];
  170967. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170968. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170969. /* Remaining fields are only used in the context case. */
  170970. /* These are the master pointers to the funny-order pointer lists. */
  170971. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170972. int whichptr; /* indicates which pointer set is now in use */
  170973. int context_state; /* process_data state machine status */
  170974. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170975. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170976. } my_main_controller4;
  170977. typedef my_main_controller4 * my_main_ptr4;
  170978. /* context_state values: */
  170979. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170980. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170981. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170982. /* Forward declarations */
  170983. METHODDEF(void) process_data_simple_main2
  170984. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170985. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170986. METHODDEF(void) process_data_context_main
  170987. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170988. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170989. #ifdef QUANT_2PASS_SUPPORTED
  170990. METHODDEF(void) process_data_crank_post
  170991. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170992. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170993. #endif
  170994. LOCAL(void)
  170995. alloc_funny_pointers (j_decompress_ptr cinfo)
  170996. /* Allocate space for the funny pointer lists.
  170997. * This is done only once, not once per pass.
  170998. */
  170999. {
  171000. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171001. int ci, rgroup;
  171002. int M = cinfo->min_DCT_scaled_size;
  171003. jpeg_component_info *compptr;
  171004. JSAMPARRAY xbuf;
  171005. /* Get top-level space for component array pointers.
  171006. * We alloc both arrays with one call to save a few cycles.
  171007. */
  171008. main_->xbuffer[0] = (JSAMPIMAGE)
  171009. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171010. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  171011. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  171012. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171013. ci++, compptr++) {
  171014. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171015. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171016. /* Get space for pointer lists --- M+4 row groups in each list.
  171017. * We alloc both pointer lists with one call to save a few cycles.
  171018. */
  171019. xbuf = (JSAMPARRAY)
  171020. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171021. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  171022. xbuf += rgroup; /* want one row group at negative offsets */
  171023. main_->xbuffer[0][ci] = xbuf;
  171024. xbuf += rgroup * (M + 4);
  171025. main_->xbuffer[1][ci] = xbuf;
  171026. }
  171027. }
  171028. LOCAL(void)
  171029. make_funny_pointers (j_decompress_ptr cinfo)
  171030. /* Create the funny pointer lists discussed in the comments above.
  171031. * The actual workspace is already allocated (in main->buffer),
  171032. * and the space for the pointer lists is allocated too.
  171033. * This routine just fills in the curiously ordered lists.
  171034. * This will be repeated at the beginning of each pass.
  171035. */
  171036. {
  171037. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171038. int ci, i, rgroup;
  171039. int M = cinfo->min_DCT_scaled_size;
  171040. jpeg_component_info *compptr;
  171041. JSAMPARRAY buf, xbuf0, xbuf1;
  171042. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171043. ci++, compptr++) {
  171044. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171045. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171046. xbuf0 = main_->xbuffer[0][ci];
  171047. xbuf1 = main_->xbuffer[1][ci];
  171048. /* First copy the workspace pointers as-is */
  171049. buf = main_->buffer[ci];
  171050. for (i = 0; i < rgroup * (M + 2); i++) {
  171051. xbuf0[i] = xbuf1[i] = buf[i];
  171052. }
  171053. /* In the second list, put the last four row groups in swapped order */
  171054. for (i = 0; i < rgroup * 2; i++) {
  171055. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  171056. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  171057. }
  171058. /* The wraparound pointers at top and bottom will be filled later
  171059. * (see set_wraparound_pointers, below). Initially we want the "above"
  171060. * pointers to duplicate the first actual data line. This only needs
  171061. * to happen in xbuffer[0].
  171062. */
  171063. for (i = 0; i < rgroup; i++) {
  171064. xbuf0[i - rgroup] = xbuf0[0];
  171065. }
  171066. }
  171067. }
  171068. LOCAL(void)
  171069. set_wraparound_pointers (j_decompress_ptr cinfo)
  171070. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  171071. * This changes the pointer list state from top-of-image to the normal state.
  171072. */
  171073. {
  171074. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171075. int ci, i, rgroup;
  171076. int M = cinfo->min_DCT_scaled_size;
  171077. jpeg_component_info *compptr;
  171078. JSAMPARRAY xbuf0, xbuf1;
  171079. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171080. ci++, compptr++) {
  171081. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171082. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171083. xbuf0 = main_->xbuffer[0][ci];
  171084. xbuf1 = main_->xbuffer[1][ci];
  171085. for (i = 0; i < rgroup; i++) {
  171086. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  171087. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  171088. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  171089. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  171090. }
  171091. }
  171092. }
  171093. LOCAL(void)
  171094. set_bottom_pointers (j_decompress_ptr cinfo)
  171095. /* Change the pointer lists to duplicate the last sample row at the bottom
  171096. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  171097. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  171098. */
  171099. {
  171100. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171101. int ci, i, rgroup, iMCUheight, rows_left;
  171102. jpeg_component_info *compptr;
  171103. JSAMPARRAY xbuf;
  171104. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171105. ci++, compptr++) {
  171106. /* Count sample rows in one iMCU row and in one row group */
  171107. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  171108. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  171109. /* Count nondummy sample rows remaining for this component */
  171110. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  171111. if (rows_left == 0) rows_left = iMCUheight;
  171112. /* Count nondummy row groups. Should get same answer for each component,
  171113. * so we need only do it once.
  171114. */
  171115. if (ci == 0) {
  171116. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  171117. }
  171118. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  171119. * last partial rowgroup and ensures at least one full rowgroup of context.
  171120. */
  171121. xbuf = main_->xbuffer[main_->whichptr][ci];
  171122. for (i = 0; i < rgroup * 2; i++) {
  171123. xbuf[rows_left + i] = xbuf[rows_left-1];
  171124. }
  171125. }
  171126. }
  171127. /*
  171128. * Initialize for a processing pass.
  171129. */
  171130. METHODDEF(void)
  171131. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  171132. {
  171133. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171134. switch (pass_mode) {
  171135. case JBUF_PASS_THRU:
  171136. if (cinfo->upsample->need_context_rows) {
  171137. main_->pub.process_data = process_data_context_main;
  171138. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  171139. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  171140. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171141. main_->iMCU_row_ctr = 0;
  171142. } else {
  171143. /* Simple case with no context needed */
  171144. main_->pub.process_data = process_data_simple_main2;
  171145. }
  171146. main_->buffer_full = FALSE; /* Mark buffer empty */
  171147. main_->rowgroup_ctr = 0;
  171148. break;
  171149. #ifdef QUANT_2PASS_SUPPORTED
  171150. case JBUF_CRANK_DEST:
  171151. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171152. main_->pub.process_data = process_data_crank_post;
  171153. break;
  171154. #endif
  171155. default:
  171156. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171157. break;
  171158. }
  171159. }
  171160. /*
  171161. * Process some data.
  171162. * This handles the simple case where no context is required.
  171163. */
  171164. METHODDEF(void)
  171165. process_data_simple_main2 (j_decompress_ptr cinfo,
  171166. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171167. JDIMENSION out_rows_avail)
  171168. {
  171169. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171170. JDIMENSION rowgroups_avail;
  171171. /* Read input data if we haven't filled the main buffer yet */
  171172. if (! main_->buffer_full) {
  171173. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171174. return; /* suspension forced, can do nothing more */
  171175. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171176. }
  171177. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171178. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171179. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171180. * to the postprocessor. The postprocessor has to check for bottom
  171181. * of image anyway (at row resolution), so no point in us doing it too.
  171182. */
  171183. /* Feed the postprocessor */
  171184. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171185. &main_->rowgroup_ctr, rowgroups_avail,
  171186. output_buf, out_row_ctr, out_rows_avail);
  171187. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171188. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171189. main_->buffer_full = FALSE;
  171190. main_->rowgroup_ctr = 0;
  171191. }
  171192. }
  171193. /*
  171194. * Process some data.
  171195. * This handles the case where context rows must be provided.
  171196. */
  171197. METHODDEF(void)
  171198. process_data_context_main (j_decompress_ptr cinfo,
  171199. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171200. JDIMENSION out_rows_avail)
  171201. {
  171202. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171203. /* Read input data if we haven't filled the main buffer yet */
  171204. if (! main_->buffer_full) {
  171205. if (! (*cinfo->coef->decompress_data) (cinfo,
  171206. main_->xbuffer[main_->whichptr]))
  171207. return; /* suspension forced, can do nothing more */
  171208. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171209. main_->iMCU_row_ctr++; /* count rows received */
  171210. }
  171211. /* Postprocessor typically will not swallow all the input data it is handed
  171212. * in one call (due to filling the output buffer first). Must be prepared
  171213. * to exit and restart. This switch lets us keep track of how far we got.
  171214. * Note that each case falls through to the next on successful completion.
  171215. */
  171216. switch (main_->context_state) {
  171217. case CTX_POSTPONED_ROW:
  171218. /* Call postprocessor using previously set pointers for postponed row */
  171219. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171220. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171221. output_buf, out_row_ctr, out_rows_avail);
  171222. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171223. return; /* Need to suspend */
  171224. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171225. if (*out_row_ctr >= out_rows_avail)
  171226. return; /* Postprocessor exactly filled output buf */
  171227. /*FALLTHROUGH*/
  171228. case CTX_PREPARE_FOR_IMCU:
  171229. /* Prepare to process first M-1 row groups of this iMCU row */
  171230. main_->rowgroup_ctr = 0;
  171231. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171232. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171233. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171234. */
  171235. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171236. set_bottom_pointers(cinfo);
  171237. main_->context_state = CTX_PROCESS_IMCU;
  171238. /*FALLTHROUGH*/
  171239. case CTX_PROCESS_IMCU:
  171240. /* Call postprocessor using previously set pointers */
  171241. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171242. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171243. output_buf, out_row_ctr, out_rows_avail);
  171244. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171245. return; /* Need to suspend */
  171246. /* After the first iMCU, change wraparound pointers to normal state */
  171247. if (main_->iMCU_row_ctr == 1)
  171248. set_wraparound_pointers(cinfo);
  171249. /* Prepare to load new iMCU row using other xbuffer list */
  171250. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171251. main_->buffer_full = FALSE;
  171252. /* Still need to process last row group of this iMCU row, */
  171253. /* which is saved at index M+1 of the other xbuffer */
  171254. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171255. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171256. main_->context_state = CTX_POSTPONED_ROW;
  171257. }
  171258. }
  171259. /*
  171260. * Process some data.
  171261. * Final pass of two-pass quantization: just call the postprocessor.
  171262. * Source data will be the postprocessor controller's internal buffer.
  171263. */
  171264. #ifdef QUANT_2PASS_SUPPORTED
  171265. METHODDEF(void)
  171266. process_data_crank_post (j_decompress_ptr cinfo,
  171267. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171268. JDIMENSION out_rows_avail)
  171269. {
  171270. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171271. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171272. output_buf, out_row_ctr, out_rows_avail);
  171273. }
  171274. #endif /* QUANT_2PASS_SUPPORTED */
  171275. /*
  171276. * Initialize main buffer controller.
  171277. */
  171278. GLOBAL(void)
  171279. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171280. {
  171281. my_main_ptr4 main_;
  171282. int ci, rgroup, ngroups;
  171283. jpeg_component_info *compptr;
  171284. main_ = (my_main_ptr4)
  171285. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171286. SIZEOF(my_main_controller4));
  171287. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171288. main_->pub.start_pass = start_pass_main2;
  171289. if (need_full_buffer) /* shouldn't happen */
  171290. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171291. /* Allocate the workspace.
  171292. * ngroups is the number of row groups we need.
  171293. */
  171294. if (cinfo->upsample->need_context_rows) {
  171295. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171296. ERREXIT(cinfo, JERR_NOTIMPL);
  171297. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171298. ngroups = cinfo->min_DCT_scaled_size + 2;
  171299. } else {
  171300. ngroups = cinfo->min_DCT_scaled_size;
  171301. }
  171302. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171303. ci++, compptr++) {
  171304. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171305. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171306. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171307. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171308. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171309. (JDIMENSION) (rgroup * ngroups));
  171310. }
  171311. }
  171312. /*** End of inlined file: jdmainct.c ***/
  171313. /*** Start of inlined file: jdmarker.c ***/
  171314. #define JPEG_INTERNALS
  171315. /* Private state */
  171316. typedef struct {
  171317. struct jpeg_marker_reader pub; /* public fields */
  171318. /* Application-overridable marker processing methods */
  171319. jpeg_marker_parser_method process_COM;
  171320. jpeg_marker_parser_method process_APPn[16];
  171321. /* Limit on marker data length to save for each marker type */
  171322. unsigned int length_limit_COM;
  171323. unsigned int length_limit_APPn[16];
  171324. /* Status of COM/APPn marker saving */
  171325. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171326. unsigned int bytes_read; /* data bytes read so far in marker */
  171327. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171328. } my_marker_reader;
  171329. typedef my_marker_reader * my_marker_ptr2;
  171330. /*
  171331. * Macros for fetching data from the data source module.
  171332. *
  171333. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171334. * the current restart point; we update them only when we have reached a
  171335. * suitable place to restart if a suspension occurs.
  171336. */
  171337. /* Declare and initialize local copies of input pointer/count */
  171338. #define INPUT_VARS(cinfo) \
  171339. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171340. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171341. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171342. /* Unload the local copies --- do this only at a restart boundary */
  171343. #define INPUT_SYNC(cinfo) \
  171344. ( datasrc->next_input_byte = next_input_byte, \
  171345. datasrc->bytes_in_buffer = bytes_in_buffer )
  171346. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171347. #define INPUT_RELOAD(cinfo) \
  171348. ( next_input_byte = datasrc->next_input_byte, \
  171349. bytes_in_buffer = datasrc->bytes_in_buffer )
  171350. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171351. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171352. * but we must reload the local copies after a successful fill.
  171353. */
  171354. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171355. if (bytes_in_buffer == 0) { \
  171356. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171357. { action; } \
  171358. INPUT_RELOAD(cinfo); \
  171359. }
  171360. /* Read a byte into variable V.
  171361. * If must suspend, take the specified action (typically "return FALSE").
  171362. */
  171363. #define INPUT_BYTE(cinfo,V,action) \
  171364. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171365. bytes_in_buffer--; \
  171366. V = GETJOCTET(*next_input_byte++); )
  171367. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171368. * V should be declared unsigned int or perhaps INT32.
  171369. */
  171370. #define INPUT_2BYTES(cinfo,V,action) \
  171371. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171372. bytes_in_buffer--; \
  171373. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171374. MAKE_BYTE_AVAIL(cinfo,action); \
  171375. bytes_in_buffer--; \
  171376. V += GETJOCTET(*next_input_byte++); )
  171377. /*
  171378. * Routines to process JPEG markers.
  171379. *
  171380. * Entry condition: JPEG marker itself has been read and its code saved
  171381. * in cinfo->unread_marker; input restart point is just after the marker.
  171382. *
  171383. * Exit: if return TRUE, have read and processed any parameters, and have
  171384. * updated the restart point to point after the parameters.
  171385. * If return FALSE, was forced to suspend before reaching end of
  171386. * marker parameters; restart point has not been moved. Same routine
  171387. * will be called again after application supplies more input data.
  171388. *
  171389. * This approach to suspension assumes that all of a marker's parameters
  171390. * can fit into a single input bufferload. This should hold for "normal"
  171391. * markers. Some COM/APPn markers might have large parameter segments
  171392. * that might not fit. If we are simply dropping such a marker, we use
  171393. * skip_input_data to get past it, and thereby put the problem on the
  171394. * source manager's shoulders. If we are saving the marker's contents
  171395. * into memory, we use a slightly different convention: when forced to
  171396. * suspend, the marker processor updates the restart point to the end of
  171397. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171398. * On resumption, cinfo->unread_marker still contains the marker code,
  171399. * but the data source will point to the next chunk of marker data.
  171400. * The marker processor must retain internal state to deal with this.
  171401. *
  171402. * Note that we don't bother to avoid duplicate trace messages if a
  171403. * suspension occurs within marker parameters. Other side effects
  171404. * require more care.
  171405. */
  171406. LOCAL(boolean)
  171407. get_soi (j_decompress_ptr cinfo)
  171408. /* Process an SOI marker */
  171409. {
  171410. int i;
  171411. TRACEMS(cinfo, 1, JTRC_SOI);
  171412. if (cinfo->marker->saw_SOI)
  171413. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171414. /* Reset all parameters that are defined to be reset by SOI */
  171415. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171416. cinfo->arith_dc_L[i] = 0;
  171417. cinfo->arith_dc_U[i] = 1;
  171418. cinfo->arith_ac_K[i] = 5;
  171419. }
  171420. cinfo->restart_interval = 0;
  171421. /* Set initial assumptions for colorspace etc */
  171422. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171423. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171424. cinfo->saw_JFIF_marker = FALSE;
  171425. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171426. cinfo->JFIF_minor_version = 1;
  171427. cinfo->density_unit = 0;
  171428. cinfo->X_density = 1;
  171429. cinfo->Y_density = 1;
  171430. cinfo->saw_Adobe_marker = FALSE;
  171431. cinfo->Adobe_transform = 0;
  171432. cinfo->marker->saw_SOI = TRUE;
  171433. return TRUE;
  171434. }
  171435. LOCAL(boolean)
  171436. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171437. /* Process a SOFn marker */
  171438. {
  171439. INT32 length;
  171440. int c, ci;
  171441. jpeg_component_info * compptr;
  171442. INPUT_VARS(cinfo);
  171443. cinfo->progressive_mode = is_prog;
  171444. cinfo->arith_code = is_arith;
  171445. INPUT_2BYTES(cinfo, length, return FALSE);
  171446. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171447. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171448. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171449. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171450. length -= 8;
  171451. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171452. (int) cinfo->image_width, (int) cinfo->image_height,
  171453. cinfo->num_components);
  171454. if (cinfo->marker->saw_SOF)
  171455. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171456. /* We don't support files in which the image height is initially specified */
  171457. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171458. /* might as well have a general sanity check. */
  171459. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171460. || cinfo->num_components <= 0)
  171461. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171462. if (length != (cinfo->num_components * 3))
  171463. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171464. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171465. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171466. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171467. cinfo->num_components * SIZEOF(jpeg_component_info));
  171468. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171469. ci++, compptr++) {
  171470. compptr->component_index = ci;
  171471. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171472. INPUT_BYTE(cinfo, c, return FALSE);
  171473. compptr->h_samp_factor = (c >> 4) & 15;
  171474. compptr->v_samp_factor = (c ) & 15;
  171475. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171476. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171477. compptr->component_id, compptr->h_samp_factor,
  171478. compptr->v_samp_factor, compptr->quant_tbl_no);
  171479. }
  171480. cinfo->marker->saw_SOF = TRUE;
  171481. INPUT_SYNC(cinfo);
  171482. return TRUE;
  171483. }
  171484. LOCAL(boolean)
  171485. get_sos (j_decompress_ptr cinfo)
  171486. /* Process a SOS marker */
  171487. {
  171488. INT32 length;
  171489. int i, ci, n, c, cc;
  171490. jpeg_component_info * compptr;
  171491. INPUT_VARS(cinfo);
  171492. if (! cinfo->marker->saw_SOF)
  171493. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171494. INPUT_2BYTES(cinfo, length, return FALSE);
  171495. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171496. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171497. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171498. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171499. cinfo->comps_in_scan = n;
  171500. /* Collect the component-spec parameters */
  171501. for (i = 0; i < n; i++) {
  171502. INPUT_BYTE(cinfo, cc, return FALSE);
  171503. INPUT_BYTE(cinfo, c, return FALSE);
  171504. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171505. ci++, compptr++) {
  171506. if (cc == compptr->component_id)
  171507. goto id_found;
  171508. }
  171509. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171510. id_found:
  171511. cinfo->cur_comp_info[i] = compptr;
  171512. compptr->dc_tbl_no = (c >> 4) & 15;
  171513. compptr->ac_tbl_no = (c ) & 15;
  171514. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171515. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171516. }
  171517. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171518. INPUT_BYTE(cinfo, c, return FALSE);
  171519. cinfo->Ss = c;
  171520. INPUT_BYTE(cinfo, c, return FALSE);
  171521. cinfo->Se = c;
  171522. INPUT_BYTE(cinfo, c, return FALSE);
  171523. cinfo->Ah = (c >> 4) & 15;
  171524. cinfo->Al = (c ) & 15;
  171525. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171526. cinfo->Ah, cinfo->Al);
  171527. /* Prepare to scan data & restart markers */
  171528. cinfo->marker->next_restart_num = 0;
  171529. /* Count another SOS marker */
  171530. cinfo->input_scan_number++;
  171531. INPUT_SYNC(cinfo);
  171532. return TRUE;
  171533. }
  171534. #ifdef D_ARITH_CODING_SUPPORTED
  171535. LOCAL(boolean)
  171536. get_dac (j_decompress_ptr cinfo)
  171537. /* Process a DAC marker */
  171538. {
  171539. INT32 length;
  171540. int index, val;
  171541. INPUT_VARS(cinfo);
  171542. INPUT_2BYTES(cinfo, length, return FALSE);
  171543. length -= 2;
  171544. while (length > 0) {
  171545. INPUT_BYTE(cinfo, index, return FALSE);
  171546. INPUT_BYTE(cinfo, val, return FALSE);
  171547. length -= 2;
  171548. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171549. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171550. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171551. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171552. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171553. } else { /* define DC table */
  171554. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171555. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171556. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171557. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171558. }
  171559. }
  171560. if (length != 0)
  171561. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171562. INPUT_SYNC(cinfo);
  171563. return TRUE;
  171564. }
  171565. #else /* ! D_ARITH_CODING_SUPPORTED */
  171566. #define get_dac(cinfo) skip_variable(cinfo)
  171567. #endif /* D_ARITH_CODING_SUPPORTED */
  171568. LOCAL(boolean)
  171569. get_dht (j_decompress_ptr cinfo)
  171570. /* Process a DHT marker */
  171571. {
  171572. INT32 length;
  171573. UINT8 bits[17];
  171574. UINT8 huffval[256];
  171575. int i, index, count;
  171576. JHUFF_TBL **htblptr;
  171577. INPUT_VARS(cinfo);
  171578. INPUT_2BYTES(cinfo, length, return FALSE);
  171579. length -= 2;
  171580. while (length > 16) {
  171581. INPUT_BYTE(cinfo, index, return FALSE);
  171582. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171583. bits[0] = 0;
  171584. count = 0;
  171585. for (i = 1; i <= 16; i++) {
  171586. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171587. count += bits[i];
  171588. }
  171589. length -= 1 + 16;
  171590. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171591. bits[1], bits[2], bits[3], bits[4],
  171592. bits[5], bits[6], bits[7], bits[8]);
  171593. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171594. bits[9], bits[10], bits[11], bits[12],
  171595. bits[13], bits[14], bits[15], bits[16]);
  171596. /* Here we just do minimal validation of the counts to avoid walking
  171597. * off the end of our table space. jdhuff.c will check more carefully.
  171598. */
  171599. if (count > 256 || ((INT32) count) > length)
  171600. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171601. for (i = 0; i < count; i++)
  171602. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171603. length -= count;
  171604. if (index & 0x10) { /* AC table definition */
  171605. index -= 0x10;
  171606. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171607. } else { /* DC table definition */
  171608. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171609. }
  171610. if (index < 0 || index >= NUM_HUFF_TBLS)
  171611. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171612. if (*htblptr == NULL)
  171613. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171614. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171615. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171616. }
  171617. if (length != 0)
  171618. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171619. INPUT_SYNC(cinfo);
  171620. return TRUE;
  171621. }
  171622. LOCAL(boolean)
  171623. get_dqt (j_decompress_ptr cinfo)
  171624. /* Process a DQT marker */
  171625. {
  171626. INT32 length;
  171627. int n, i, prec;
  171628. unsigned int tmp;
  171629. JQUANT_TBL *quant_ptr;
  171630. INPUT_VARS(cinfo);
  171631. INPUT_2BYTES(cinfo, length, return FALSE);
  171632. length -= 2;
  171633. while (length > 0) {
  171634. INPUT_BYTE(cinfo, n, return FALSE);
  171635. prec = n >> 4;
  171636. n &= 0x0F;
  171637. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171638. if (n >= NUM_QUANT_TBLS)
  171639. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171640. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171641. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171642. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171643. for (i = 0; i < DCTSIZE2; i++) {
  171644. if (prec)
  171645. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171646. else
  171647. INPUT_BYTE(cinfo, tmp, return FALSE);
  171648. /* We convert the zigzag-order table to natural array order. */
  171649. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171650. }
  171651. if (cinfo->err->trace_level >= 2) {
  171652. for (i = 0; i < DCTSIZE2; i += 8) {
  171653. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171654. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171655. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171656. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171657. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171658. }
  171659. }
  171660. length -= DCTSIZE2+1;
  171661. if (prec) length -= DCTSIZE2;
  171662. }
  171663. if (length != 0)
  171664. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171665. INPUT_SYNC(cinfo);
  171666. return TRUE;
  171667. }
  171668. LOCAL(boolean)
  171669. get_dri (j_decompress_ptr cinfo)
  171670. /* Process a DRI marker */
  171671. {
  171672. INT32 length;
  171673. unsigned int tmp;
  171674. INPUT_VARS(cinfo);
  171675. INPUT_2BYTES(cinfo, length, return FALSE);
  171676. if (length != 4)
  171677. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171678. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171679. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171680. cinfo->restart_interval = tmp;
  171681. INPUT_SYNC(cinfo);
  171682. return TRUE;
  171683. }
  171684. /*
  171685. * Routines for processing APPn and COM markers.
  171686. * These are either saved in memory or discarded, per application request.
  171687. * APP0 and APP14 are specially checked to see if they are
  171688. * JFIF and Adobe markers, respectively.
  171689. */
  171690. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171691. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171692. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171693. LOCAL(void)
  171694. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171695. unsigned int datalen, INT32 remaining)
  171696. /* Examine first few bytes from an APP0.
  171697. * Take appropriate action if it is a JFIF marker.
  171698. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171699. */
  171700. {
  171701. INT32 totallen = (INT32) datalen + remaining;
  171702. if (datalen >= APP0_DATA_LEN &&
  171703. GETJOCTET(data[0]) == 0x4A &&
  171704. GETJOCTET(data[1]) == 0x46 &&
  171705. GETJOCTET(data[2]) == 0x49 &&
  171706. GETJOCTET(data[3]) == 0x46 &&
  171707. GETJOCTET(data[4]) == 0) {
  171708. /* Found JFIF APP0 marker: save info */
  171709. cinfo->saw_JFIF_marker = TRUE;
  171710. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171711. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171712. cinfo->density_unit = GETJOCTET(data[7]);
  171713. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171714. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171715. /* Check version.
  171716. * Major version must be 1, anything else signals an incompatible change.
  171717. * (We used to treat this as an error, but now it's a nonfatal warning,
  171718. * because some bozo at Hijaak couldn't read the spec.)
  171719. * Minor version should be 0..2, but process anyway if newer.
  171720. */
  171721. if (cinfo->JFIF_major_version != 1)
  171722. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171723. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171724. /* Generate trace messages */
  171725. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171726. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171727. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171728. /* Validate thumbnail dimensions and issue appropriate messages */
  171729. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171730. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171731. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171732. totallen -= APP0_DATA_LEN;
  171733. if (totallen !=
  171734. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171735. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171736. } else if (datalen >= 6 &&
  171737. GETJOCTET(data[0]) == 0x4A &&
  171738. GETJOCTET(data[1]) == 0x46 &&
  171739. GETJOCTET(data[2]) == 0x58 &&
  171740. GETJOCTET(data[3]) == 0x58 &&
  171741. GETJOCTET(data[4]) == 0) {
  171742. /* Found JFIF "JFXX" extension APP0 marker */
  171743. /* The library doesn't actually do anything with these,
  171744. * but we try to produce a helpful trace message.
  171745. */
  171746. switch (GETJOCTET(data[5])) {
  171747. case 0x10:
  171748. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171749. break;
  171750. case 0x11:
  171751. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171752. break;
  171753. case 0x13:
  171754. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171755. break;
  171756. default:
  171757. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171758. GETJOCTET(data[5]), (int) totallen);
  171759. break;
  171760. }
  171761. } else {
  171762. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171763. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171764. }
  171765. }
  171766. LOCAL(void)
  171767. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171768. unsigned int datalen, INT32 remaining)
  171769. /* Examine first few bytes from an APP14.
  171770. * Take appropriate action if it is an Adobe marker.
  171771. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171772. */
  171773. {
  171774. unsigned int version, flags0, flags1, transform;
  171775. if (datalen >= APP14_DATA_LEN &&
  171776. GETJOCTET(data[0]) == 0x41 &&
  171777. GETJOCTET(data[1]) == 0x64 &&
  171778. GETJOCTET(data[2]) == 0x6F &&
  171779. GETJOCTET(data[3]) == 0x62 &&
  171780. GETJOCTET(data[4]) == 0x65) {
  171781. /* Found Adobe APP14 marker */
  171782. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171783. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171784. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171785. transform = GETJOCTET(data[11]);
  171786. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171787. cinfo->saw_Adobe_marker = TRUE;
  171788. cinfo->Adobe_transform = (UINT8) transform;
  171789. } else {
  171790. /* Start of APP14 does not match "Adobe", or too short */
  171791. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171792. }
  171793. }
  171794. METHODDEF(boolean)
  171795. get_interesting_appn (j_decompress_ptr cinfo)
  171796. /* Process an APP0 or APP14 marker without saving it */
  171797. {
  171798. INT32 length;
  171799. JOCTET b[APPN_DATA_LEN];
  171800. unsigned int i, numtoread;
  171801. INPUT_VARS(cinfo);
  171802. INPUT_2BYTES(cinfo, length, return FALSE);
  171803. length -= 2;
  171804. /* get the interesting part of the marker data */
  171805. if (length >= APPN_DATA_LEN)
  171806. numtoread = APPN_DATA_LEN;
  171807. else if (length > 0)
  171808. numtoread = (unsigned int) length;
  171809. else
  171810. numtoread = 0;
  171811. for (i = 0; i < numtoread; i++)
  171812. INPUT_BYTE(cinfo, b[i], return FALSE);
  171813. length -= numtoread;
  171814. /* process it */
  171815. switch (cinfo->unread_marker) {
  171816. case M_APP0:
  171817. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171818. break;
  171819. case M_APP14:
  171820. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171821. break;
  171822. default:
  171823. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171824. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171825. break;
  171826. }
  171827. /* skip any remaining data -- could be lots */
  171828. INPUT_SYNC(cinfo);
  171829. if (length > 0)
  171830. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171831. return TRUE;
  171832. }
  171833. #ifdef SAVE_MARKERS_SUPPORTED
  171834. METHODDEF(boolean)
  171835. save_marker (j_decompress_ptr cinfo)
  171836. /* Save an APPn or COM marker into the marker list */
  171837. {
  171838. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171839. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171840. unsigned int bytes_read, data_length;
  171841. JOCTET FAR * data;
  171842. INT32 length = 0;
  171843. INPUT_VARS(cinfo);
  171844. if (cur_marker == NULL) {
  171845. /* begin reading a marker */
  171846. INPUT_2BYTES(cinfo, length, return FALSE);
  171847. length -= 2;
  171848. if (length >= 0) { /* watch out for bogus length word */
  171849. /* figure out how much we want to save */
  171850. unsigned int limit;
  171851. if (cinfo->unread_marker == (int) M_COM)
  171852. limit = marker->length_limit_COM;
  171853. else
  171854. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171855. if ((unsigned int) length < limit)
  171856. limit = (unsigned int) length;
  171857. /* allocate and initialize the marker item */
  171858. cur_marker = (jpeg_saved_marker_ptr)
  171859. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171860. SIZEOF(struct jpeg_marker_struct) + limit);
  171861. cur_marker->next = NULL;
  171862. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171863. cur_marker->original_length = (unsigned int) length;
  171864. cur_marker->data_length = limit;
  171865. /* data area is just beyond the jpeg_marker_struct */
  171866. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171867. marker->cur_marker = cur_marker;
  171868. marker->bytes_read = 0;
  171869. bytes_read = 0;
  171870. data_length = limit;
  171871. } else {
  171872. /* deal with bogus length word */
  171873. bytes_read = data_length = 0;
  171874. data = NULL;
  171875. }
  171876. } else {
  171877. /* resume reading a marker */
  171878. bytes_read = marker->bytes_read;
  171879. data_length = cur_marker->data_length;
  171880. data = cur_marker->data + bytes_read;
  171881. }
  171882. while (bytes_read < data_length) {
  171883. INPUT_SYNC(cinfo); /* move the restart point to here */
  171884. marker->bytes_read = bytes_read;
  171885. /* If there's not at least one byte in buffer, suspend */
  171886. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171887. /* Copy bytes with reasonable rapidity */
  171888. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171889. *data++ = *next_input_byte++;
  171890. bytes_in_buffer--;
  171891. bytes_read++;
  171892. }
  171893. }
  171894. /* Done reading what we want to read */
  171895. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171896. /* Add new marker to end of list */
  171897. if (cinfo->marker_list == NULL) {
  171898. cinfo->marker_list = cur_marker;
  171899. } else {
  171900. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171901. while (prev->next != NULL)
  171902. prev = prev->next;
  171903. prev->next = cur_marker;
  171904. }
  171905. /* Reset pointer & calc remaining data length */
  171906. data = cur_marker->data;
  171907. length = cur_marker->original_length - data_length;
  171908. }
  171909. /* Reset to initial state for next marker */
  171910. marker->cur_marker = NULL;
  171911. /* Process the marker if interesting; else just make a generic trace msg */
  171912. switch (cinfo->unread_marker) {
  171913. case M_APP0:
  171914. examine_app0(cinfo, data, data_length, length);
  171915. break;
  171916. case M_APP14:
  171917. examine_app14(cinfo, data, data_length, length);
  171918. break;
  171919. default:
  171920. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171921. (int) (data_length + length));
  171922. break;
  171923. }
  171924. /* skip any remaining data -- could be lots */
  171925. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171926. if (length > 0)
  171927. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171928. return TRUE;
  171929. }
  171930. #endif /* SAVE_MARKERS_SUPPORTED */
  171931. METHODDEF(boolean)
  171932. skip_variable (j_decompress_ptr cinfo)
  171933. /* Skip over an unknown or uninteresting variable-length marker */
  171934. {
  171935. INT32 length;
  171936. INPUT_VARS(cinfo);
  171937. INPUT_2BYTES(cinfo, length, return FALSE);
  171938. length -= 2;
  171939. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171940. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171941. if (length > 0)
  171942. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171943. return TRUE;
  171944. }
  171945. /*
  171946. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171947. * Returns FALSE if had to suspend before reaching a marker;
  171948. * in that case cinfo->unread_marker is unchanged.
  171949. *
  171950. * Note that the result might not be a valid marker code,
  171951. * but it will never be 0 or FF.
  171952. */
  171953. LOCAL(boolean)
  171954. next_marker (j_decompress_ptr cinfo)
  171955. {
  171956. int c;
  171957. INPUT_VARS(cinfo);
  171958. for (;;) {
  171959. INPUT_BYTE(cinfo, c, return FALSE);
  171960. /* Skip any non-FF bytes.
  171961. * This may look a bit inefficient, but it will not occur in a valid file.
  171962. * We sync after each discarded byte so that a suspending data source
  171963. * can discard the byte from its buffer.
  171964. */
  171965. while (c != 0xFF) {
  171966. cinfo->marker->discarded_bytes++;
  171967. INPUT_SYNC(cinfo);
  171968. INPUT_BYTE(cinfo, c, return FALSE);
  171969. }
  171970. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171971. * pad bytes, so don't count them in discarded_bytes. We assume there
  171972. * will not be so many consecutive FF bytes as to overflow a suspending
  171973. * data source's input buffer.
  171974. */
  171975. do {
  171976. INPUT_BYTE(cinfo, c, return FALSE);
  171977. } while (c == 0xFF);
  171978. if (c != 0)
  171979. break; /* found a valid marker, exit loop */
  171980. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171981. * Discard it and loop back to try again.
  171982. */
  171983. cinfo->marker->discarded_bytes += 2;
  171984. INPUT_SYNC(cinfo);
  171985. }
  171986. if (cinfo->marker->discarded_bytes != 0) {
  171987. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171988. cinfo->marker->discarded_bytes = 0;
  171989. }
  171990. cinfo->unread_marker = c;
  171991. INPUT_SYNC(cinfo);
  171992. return TRUE;
  171993. }
  171994. LOCAL(boolean)
  171995. first_marker (j_decompress_ptr cinfo)
  171996. /* Like next_marker, but used to obtain the initial SOI marker. */
  171997. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171998. * we might well scan an entire input file before realizing it ain't JPEG.
  171999. * If an application wants to process non-JFIF files, it must seek to the
  172000. * SOI before calling the JPEG library.
  172001. */
  172002. {
  172003. int c, c2;
  172004. INPUT_VARS(cinfo);
  172005. INPUT_BYTE(cinfo, c, return FALSE);
  172006. INPUT_BYTE(cinfo, c2, return FALSE);
  172007. if (c != 0xFF || c2 != (int) M_SOI)
  172008. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  172009. cinfo->unread_marker = c2;
  172010. INPUT_SYNC(cinfo);
  172011. return TRUE;
  172012. }
  172013. /*
  172014. * Read markers until SOS or EOI.
  172015. *
  172016. * Returns same codes as are defined for jpeg_consume_input:
  172017. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  172018. */
  172019. METHODDEF(int)
  172020. read_markers (j_decompress_ptr cinfo)
  172021. {
  172022. /* Outer loop repeats once for each marker. */
  172023. for (;;) {
  172024. /* Collect the marker proper, unless we already did. */
  172025. /* NB: first_marker() enforces the requirement that SOI appear first. */
  172026. if (cinfo->unread_marker == 0) {
  172027. if (! cinfo->marker->saw_SOI) {
  172028. if (! first_marker(cinfo))
  172029. return JPEG_SUSPENDED;
  172030. } else {
  172031. if (! next_marker(cinfo))
  172032. return JPEG_SUSPENDED;
  172033. }
  172034. }
  172035. /* At this point cinfo->unread_marker contains the marker code and the
  172036. * input point is just past the marker proper, but before any parameters.
  172037. * A suspension will cause us to return with this state still true.
  172038. */
  172039. switch (cinfo->unread_marker) {
  172040. case M_SOI:
  172041. if (! get_soi(cinfo))
  172042. return JPEG_SUSPENDED;
  172043. break;
  172044. case M_SOF0: /* Baseline */
  172045. case M_SOF1: /* Extended sequential, Huffman */
  172046. if (! get_sof(cinfo, FALSE, FALSE))
  172047. return JPEG_SUSPENDED;
  172048. break;
  172049. case M_SOF2: /* Progressive, Huffman */
  172050. if (! get_sof(cinfo, TRUE, FALSE))
  172051. return JPEG_SUSPENDED;
  172052. break;
  172053. case M_SOF9: /* Extended sequential, arithmetic */
  172054. if (! get_sof(cinfo, FALSE, TRUE))
  172055. return JPEG_SUSPENDED;
  172056. break;
  172057. case M_SOF10: /* Progressive, arithmetic */
  172058. if (! get_sof(cinfo, TRUE, TRUE))
  172059. return JPEG_SUSPENDED;
  172060. break;
  172061. /* Currently unsupported SOFn types */
  172062. case M_SOF3: /* Lossless, Huffman */
  172063. case M_SOF5: /* Differential sequential, Huffman */
  172064. case M_SOF6: /* Differential progressive, Huffman */
  172065. case M_SOF7: /* Differential lossless, Huffman */
  172066. case M_JPG: /* Reserved for JPEG extensions */
  172067. case M_SOF11: /* Lossless, arithmetic */
  172068. case M_SOF13: /* Differential sequential, arithmetic */
  172069. case M_SOF14: /* Differential progressive, arithmetic */
  172070. case M_SOF15: /* Differential lossless, arithmetic */
  172071. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  172072. break;
  172073. case M_SOS:
  172074. if (! get_sos(cinfo))
  172075. return JPEG_SUSPENDED;
  172076. cinfo->unread_marker = 0; /* processed the marker */
  172077. return JPEG_REACHED_SOS;
  172078. case M_EOI:
  172079. TRACEMS(cinfo, 1, JTRC_EOI);
  172080. cinfo->unread_marker = 0; /* processed the marker */
  172081. return JPEG_REACHED_EOI;
  172082. case M_DAC:
  172083. if (! get_dac(cinfo))
  172084. return JPEG_SUSPENDED;
  172085. break;
  172086. case M_DHT:
  172087. if (! get_dht(cinfo))
  172088. return JPEG_SUSPENDED;
  172089. break;
  172090. case M_DQT:
  172091. if (! get_dqt(cinfo))
  172092. return JPEG_SUSPENDED;
  172093. break;
  172094. case M_DRI:
  172095. if (! get_dri(cinfo))
  172096. return JPEG_SUSPENDED;
  172097. break;
  172098. case M_APP0:
  172099. case M_APP1:
  172100. case M_APP2:
  172101. case M_APP3:
  172102. case M_APP4:
  172103. case M_APP5:
  172104. case M_APP6:
  172105. case M_APP7:
  172106. case M_APP8:
  172107. case M_APP9:
  172108. case M_APP10:
  172109. case M_APP11:
  172110. case M_APP12:
  172111. case M_APP13:
  172112. case M_APP14:
  172113. case M_APP15:
  172114. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  172115. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  172116. return JPEG_SUSPENDED;
  172117. break;
  172118. case M_COM:
  172119. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  172120. return JPEG_SUSPENDED;
  172121. break;
  172122. case M_RST0: /* these are all parameterless */
  172123. case M_RST1:
  172124. case M_RST2:
  172125. case M_RST3:
  172126. case M_RST4:
  172127. case M_RST5:
  172128. case M_RST6:
  172129. case M_RST7:
  172130. case M_TEM:
  172131. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  172132. break;
  172133. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  172134. if (! skip_variable(cinfo))
  172135. return JPEG_SUSPENDED;
  172136. break;
  172137. default: /* must be DHP, EXP, JPGn, or RESn */
  172138. /* For now, we treat the reserved markers as fatal errors since they are
  172139. * likely to be used to signal incompatible JPEG Part 3 extensions.
  172140. * Once the JPEG 3 version-number marker is well defined, this code
  172141. * ought to change!
  172142. */
  172143. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172144. break;
  172145. }
  172146. /* Successfully processed marker, so reset state variable */
  172147. cinfo->unread_marker = 0;
  172148. } /* end loop */
  172149. }
  172150. /*
  172151. * Read a restart marker, which is expected to appear next in the datastream;
  172152. * if the marker is not there, take appropriate recovery action.
  172153. * Returns FALSE if suspension is required.
  172154. *
  172155. * This is called by the entropy decoder after it has read an appropriate
  172156. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172157. * has already read a marker from the data source. Under normal conditions
  172158. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172159. * it holds a marker which the decoder will be unable to read past.
  172160. */
  172161. METHODDEF(boolean)
  172162. read_restart_marker (j_decompress_ptr cinfo)
  172163. {
  172164. /* Obtain a marker unless we already did. */
  172165. /* Note that next_marker will complain if it skips any data. */
  172166. if (cinfo->unread_marker == 0) {
  172167. if (! next_marker(cinfo))
  172168. return FALSE;
  172169. }
  172170. if (cinfo->unread_marker ==
  172171. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172172. /* Normal case --- swallow the marker and let entropy decoder continue */
  172173. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172174. cinfo->unread_marker = 0;
  172175. } else {
  172176. /* Uh-oh, the restart markers have been messed up. */
  172177. /* Let the data source manager determine how to resync. */
  172178. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172179. cinfo->marker->next_restart_num))
  172180. return FALSE;
  172181. }
  172182. /* Update next-restart state */
  172183. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172184. return TRUE;
  172185. }
  172186. /*
  172187. * This is the default resync_to_restart method for data source managers
  172188. * to use if they don't have any better approach. Some data source managers
  172189. * may be able to back up, or may have additional knowledge about the data
  172190. * which permits a more intelligent recovery strategy; such managers would
  172191. * presumably supply their own resync method.
  172192. *
  172193. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172194. * the restart marker it was expecting. (This code is *not* used unless
  172195. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172196. * the marker code actually found (might be anything, except 0 or FF).
  172197. * The desired restart marker number (0..7) is passed as a parameter.
  172198. * This routine is supposed to apply whatever error recovery strategy seems
  172199. * appropriate in order to position the input stream to the next data segment.
  172200. * Note that cinfo->unread_marker is treated as a marker appearing before
  172201. * the current data-source input point; usually it should be reset to zero
  172202. * before returning.
  172203. * Returns FALSE if suspension is required.
  172204. *
  172205. * This implementation is substantially constrained by wanting to treat the
  172206. * input as a data stream; this means we can't back up. Therefore, we have
  172207. * only the following actions to work with:
  172208. * 1. Simply discard the marker and let the entropy decoder resume at next
  172209. * byte of file.
  172210. * 2. Read forward until we find another marker, discarding intervening
  172211. * data. (In theory we could look ahead within the current bufferload,
  172212. * without having to discard data if we don't find the desired marker.
  172213. * This idea is not implemented here, in part because it makes behavior
  172214. * dependent on buffer size and chance buffer-boundary positions.)
  172215. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172216. * This will cause the entropy decoder to process an empty data segment,
  172217. * inserting dummy zeroes, and then we will reprocess the marker.
  172218. *
  172219. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172220. * appropriate if the found marker is a future restart marker (indicating
  172221. * that we have missed the desired restart marker, probably because it got
  172222. * corrupted).
  172223. * We apply #2 or #3 if the found marker is a restart marker no more than
  172224. * two counts behind or ahead of the expected one. We also apply #2 if the
  172225. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172226. * If the found marker is a restart marker more than 2 counts away, we do #1
  172227. * (too much risk that the marker is erroneous; with luck we will be able to
  172228. * resync at some future point).
  172229. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172230. * overrunning the end of a scan. An implementation limited to single-scan
  172231. * files might find it better to apply #2 for markers other than EOI, since
  172232. * any other marker would have to be bogus data in that case.
  172233. */
  172234. GLOBAL(boolean)
  172235. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172236. {
  172237. int marker = cinfo->unread_marker;
  172238. int action = 1;
  172239. /* Always put up a warning. */
  172240. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172241. /* Outer loop handles repeated decision after scanning forward. */
  172242. for (;;) {
  172243. if (marker < (int) M_SOF0)
  172244. action = 2; /* invalid marker */
  172245. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172246. action = 3; /* valid non-restart marker */
  172247. else {
  172248. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172249. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172250. action = 3; /* one of the next two expected restarts */
  172251. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172252. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172253. action = 2; /* a prior restart, so advance */
  172254. else
  172255. action = 1; /* desired restart or too far away */
  172256. }
  172257. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172258. switch (action) {
  172259. case 1:
  172260. /* Discard marker and let entropy decoder resume processing. */
  172261. cinfo->unread_marker = 0;
  172262. return TRUE;
  172263. case 2:
  172264. /* Scan to the next marker, and repeat the decision loop. */
  172265. if (! next_marker(cinfo))
  172266. return FALSE;
  172267. marker = cinfo->unread_marker;
  172268. break;
  172269. case 3:
  172270. /* Return without advancing past this marker. */
  172271. /* Entropy decoder will be forced to process an empty segment. */
  172272. return TRUE;
  172273. }
  172274. } /* end loop */
  172275. }
  172276. /*
  172277. * Reset marker processing state to begin a fresh datastream.
  172278. */
  172279. METHODDEF(void)
  172280. reset_marker_reader (j_decompress_ptr cinfo)
  172281. {
  172282. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172283. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172284. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172285. cinfo->unread_marker = 0; /* no pending marker */
  172286. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172287. marker->pub.saw_SOF = FALSE;
  172288. marker->pub.discarded_bytes = 0;
  172289. marker->cur_marker = NULL;
  172290. }
  172291. /*
  172292. * Initialize the marker reader module.
  172293. * This is called only once, when the decompression object is created.
  172294. */
  172295. GLOBAL(void)
  172296. jinit_marker_reader (j_decompress_ptr cinfo)
  172297. {
  172298. my_marker_ptr2 marker;
  172299. int i;
  172300. /* Create subobject in permanent pool */
  172301. marker = (my_marker_ptr2)
  172302. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172303. SIZEOF(my_marker_reader));
  172304. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172305. /* Initialize public method pointers */
  172306. marker->pub.reset_marker_reader = reset_marker_reader;
  172307. marker->pub.read_markers = read_markers;
  172308. marker->pub.read_restart_marker = read_restart_marker;
  172309. /* Initialize COM/APPn processing.
  172310. * By default, we examine and then discard APP0 and APP14,
  172311. * but simply discard COM and all other APPn.
  172312. */
  172313. marker->process_COM = skip_variable;
  172314. marker->length_limit_COM = 0;
  172315. for (i = 0; i < 16; i++) {
  172316. marker->process_APPn[i] = skip_variable;
  172317. marker->length_limit_APPn[i] = 0;
  172318. }
  172319. marker->process_APPn[0] = get_interesting_appn;
  172320. marker->process_APPn[14] = get_interesting_appn;
  172321. /* Reset marker processing state */
  172322. reset_marker_reader(cinfo);
  172323. }
  172324. /*
  172325. * Control saving of COM and APPn markers into marker_list.
  172326. */
  172327. #ifdef SAVE_MARKERS_SUPPORTED
  172328. GLOBAL(void)
  172329. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172330. unsigned int length_limit)
  172331. {
  172332. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172333. long maxlength;
  172334. jpeg_marker_parser_method processor;
  172335. /* Length limit mustn't be larger than what we can allocate
  172336. * (should only be a concern in a 16-bit environment).
  172337. */
  172338. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172339. if (((long) length_limit) > maxlength)
  172340. length_limit = (unsigned int) maxlength;
  172341. /* Choose processor routine to use.
  172342. * APP0/APP14 have special requirements.
  172343. */
  172344. if (length_limit) {
  172345. processor = save_marker;
  172346. /* If saving APP0/APP14, save at least enough for our internal use. */
  172347. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172348. length_limit = APP0_DATA_LEN;
  172349. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172350. length_limit = APP14_DATA_LEN;
  172351. } else {
  172352. processor = skip_variable;
  172353. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172354. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172355. processor = get_interesting_appn;
  172356. }
  172357. if (marker_code == (int) M_COM) {
  172358. marker->process_COM = processor;
  172359. marker->length_limit_COM = length_limit;
  172360. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172361. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172362. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172363. } else
  172364. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172365. }
  172366. #endif /* SAVE_MARKERS_SUPPORTED */
  172367. /*
  172368. * Install a special processing method for COM or APPn markers.
  172369. */
  172370. GLOBAL(void)
  172371. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172372. jpeg_marker_parser_method routine)
  172373. {
  172374. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172375. if (marker_code == (int) M_COM)
  172376. marker->process_COM = routine;
  172377. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172378. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172379. else
  172380. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172381. }
  172382. /*** End of inlined file: jdmarker.c ***/
  172383. /*** Start of inlined file: jdmaster.c ***/
  172384. #define JPEG_INTERNALS
  172385. /* Private state */
  172386. typedef struct {
  172387. struct jpeg_decomp_master pub; /* public fields */
  172388. int pass_number; /* # of passes completed */
  172389. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172390. /* Saved references to initialized quantizer modules,
  172391. * in case we need to switch modes.
  172392. */
  172393. struct jpeg_color_quantizer * quantizer_1pass;
  172394. struct jpeg_color_quantizer * quantizer_2pass;
  172395. } my_decomp_master;
  172396. typedef my_decomp_master * my_master_ptr6;
  172397. /*
  172398. * Determine whether merged upsample/color conversion should be used.
  172399. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172400. */
  172401. LOCAL(boolean)
  172402. use_merged_upsample (j_decompress_ptr cinfo)
  172403. {
  172404. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172405. /* Merging is the equivalent of plain box-filter upsampling */
  172406. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172407. return FALSE;
  172408. /* jdmerge.c only supports YCC=>RGB color conversion */
  172409. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172410. cinfo->out_color_space != JCS_RGB ||
  172411. cinfo->out_color_components != RGB_PIXELSIZE)
  172412. return FALSE;
  172413. /* and it only handles 2h1v or 2h2v sampling ratios */
  172414. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172415. cinfo->comp_info[1].h_samp_factor != 1 ||
  172416. cinfo->comp_info[2].h_samp_factor != 1 ||
  172417. cinfo->comp_info[0].v_samp_factor > 2 ||
  172418. cinfo->comp_info[1].v_samp_factor != 1 ||
  172419. cinfo->comp_info[2].v_samp_factor != 1)
  172420. return FALSE;
  172421. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172422. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172423. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172424. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172425. return FALSE;
  172426. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172427. return TRUE; /* by golly, it'll work... */
  172428. #else
  172429. return FALSE;
  172430. #endif
  172431. }
  172432. /*
  172433. * Compute output image dimensions and related values.
  172434. * NOTE: this is exported for possible use by application.
  172435. * Hence it mustn't do anything that can't be done twice.
  172436. * Also note that it may be called before the master module is initialized!
  172437. */
  172438. GLOBAL(void)
  172439. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172440. /* Do computations that are needed before master selection phase */
  172441. {
  172442. #ifdef IDCT_SCALING_SUPPORTED
  172443. int ci;
  172444. jpeg_component_info *compptr;
  172445. #endif
  172446. /* Prevent application from calling me at wrong times */
  172447. if (cinfo->global_state != DSTATE_READY)
  172448. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172449. #ifdef IDCT_SCALING_SUPPORTED
  172450. /* Compute actual output image dimensions and DCT scaling choices. */
  172451. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172452. /* Provide 1/8 scaling */
  172453. cinfo->output_width = (JDIMENSION)
  172454. jdiv_round_up((long) cinfo->image_width, 8L);
  172455. cinfo->output_height = (JDIMENSION)
  172456. jdiv_round_up((long) cinfo->image_height, 8L);
  172457. cinfo->min_DCT_scaled_size = 1;
  172458. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172459. /* Provide 1/4 scaling */
  172460. cinfo->output_width = (JDIMENSION)
  172461. jdiv_round_up((long) cinfo->image_width, 4L);
  172462. cinfo->output_height = (JDIMENSION)
  172463. jdiv_round_up((long) cinfo->image_height, 4L);
  172464. cinfo->min_DCT_scaled_size = 2;
  172465. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172466. /* Provide 1/2 scaling */
  172467. cinfo->output_width = (JDIMENSION)
  172468. jdiv_round_up((long) cinfo->image_width, 2L);
  172469. cinfo->output_height = (JDIMENSION)
  172470. jdiv_round_up((long) cinfo->image_height, 2L);
  172471. cinfo->min_DCT_scaled_size = 4;
  172472. } else {
  172473. /* Provide 1/1 scaling */
  172474. cinfo->output_width = cinfo->image_width;
  172475. cinfo->output_height = cinfo->image_height;
  172476. cinfo->min_DCT_scaled_size = DCTSIZE;
  172477. }
  172478. /* In selecting the actual DCT scaling for each component, we try to
  172479. * scale up the chroma components via IDCT scaling rather than upsampling.
  172480. * This saves time if the upsampler gets to use 1:1 scaling.
  172481. * Note this code assumes that the supported DCT scalings are powers of 2.
  172482. */
  172483. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172484. ci++, compptr++) {
  172485. int ssize = cinfo->min_DCT_scaled_size;
  172486. while (ssize < DCTSIZE &&
  172487. (compptr->h_samp_factor * ssize * 2 <=
  172488. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172489. (compptr->v_samp_factor * ssize * 2 <=
  172490. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172491. ssize = ssize * 2;
  172492. }
  172493. compptr->DCT_scaled_size = ssize;
  172494. }
  172495. /* Recompute downsampled dimensions of components;
  172496. * application needs to know these if using raw downsampled data.
  172497. */
  172498. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172499. ci++, compptr++) {
  172500. /* Size in samples, after IDCT scaling */
  172501. compptr->downsampled_width = (JDIMENSION)
  172502. jdiv_round_up((long) cinfo->image_width *
  172503. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172504. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172505. compptr->downsampled_height = (JDIMENSION)
  172506. jdiv_round_up((long) cinfo->image_height *
  172507. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172508. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172509. }
  172510. #else /* !IDCT_SCALING_SUPPORTED */
  172511. /* Hardwire it to "no scaling" */
  172512. cinfo->output_width = cinfo->image_width;
  172513. cinfo->output_height = cinfo->image_height;
  172514. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172515. * and has computed unscaled downsampled_width and downsampled_height.
  172516. */
  172517. #endif /* IDCT_SCALING_SUPPORTED */
  172518. /* Report number of components in selected colorspace. */
  172519. /* Probably this should be in the color conversion module... */
  172520. switch (cinfo->out_color_space) {
  172521. case JCS_GRAYSCALE:
  172522. cinfo->out_color_components = 1;
  172523. break;
  172524. case JCS_RGB:
  172525. #if RGB_PIXELSIZE != 3
  172526. cinfo->out_color_components = RGB_PIXELSIZE;
  172527. break;
  172528. #endif /* else share code with YCbCr */
  172529. case JCS_YCbCr:
  172530. cinfo->out_color_components = 3;
  172531. break;
  172532. case JCS_CMYK:
  172533. case JCS_YCCK:
  172534. cinfo->out_color_components = 4;
  172535. break;
  172536. default: /* else must be same colorspace as in file */
  172537. cinfo->out_color_components = cinfo->num_components;
  172538. break;
  172539. }
  172540. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172541. cinfo->out_color_components);
  172542. /* See if upsampler will want to emit more than one row at a time */
  172543. if (use_merged_upsample(cinfo))
  172544. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172545. else
  172546. cinfo->rec_outbuf_height = 1;
  172547. }
  172548. /*
  172549. * Several decompression processes need to range-limit values to the range
  172550. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172551. * due to noise introduced by quantization, roundoff error, etc. These
  172552. * processes are inner loops and need to be as fast as possible. On most
  172553. * machines, particularly CPUs with pipelines or instruction prefetch,
  172554. * a (subscript-check-less) C table lookup
  172555. * x = sample_range_limit[x];
  172556. * is faster than explicit tests
  172557. * if (x < 0) x = 0;
  172558. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172559. * These processes all use a common table prepared by the routine below.
  172560. *
  172561. * For most steps we can mathematically guarantee that the initial value
  172562. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172563. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172564. * limiting step (just after the IDCT), a wildly out-of-range value is
  172565. * possible if the input data is corrupt. To avoid any chance of indexing
  172566. * off the end of memory and getting a bad-pointer trap, we perform the
  172567. * post-IDCT limiting thus:
  172568. * x = range_limit[x & MASK];
  172569. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172570. * samples. Under normal circumstances this is more than enough range and
  172571. * a correct output will be generated; with bogus input data the mask will
  172572. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172573. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172574. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172575. * So the post-IDCT limiting table ends up looking like this:
  172576. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172577. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172578. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172579. * 0,1,...,CENTERJSAMPLE-1
  172580. * Negative inputs select values from the upper half of the table after
  172581. * masking.
  172582. *
  172583. * We can save some space by overlapping the start of the post-IDCT table
  172584. * with the simpler range limiting table. The post-IDCT table begins at
  172585. * sample_range_limit + CENTERJSAMPLE.
  172586. *
  172587. * Note that the table is allocated in near data space on PCs; it's small
  172588. * enough and used often enough to justify this.
  172589. */
  172590. LOCAL(void)
  172591. prepare_range_limit_table (j_decompress_ptr cinfo)
  172592. /* Allocate and fill in the sample_range_limit table */
  172593. {
  172594. JSAMPLE * table;
  172595. int i;
  172596. table = (JSAMPLE *)
  172597. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172598. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172599. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172600. cinfo->sample_range_limit = table;
  172601. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172602. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172603. /* Main part of "simple" table: limit[x] = x */
  172604. for (i = 0; i <= MAXJSAMPLE; i++)
  172605. table[i] = (JSAMPLE) i;
  172606. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172607. /* End of simple table, rest of first half of post-IDCT table */
  172608. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172609. table[i] = MAXJSAMPLE;
  172610. /* Second half of post-IDCT table */
  172611. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172612. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172613. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172614. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172615. }
  172616. /*
  172617. * Master selection of decompression modules.
  172618. * This is done once at jpeg_start_decompress time. We determine
  172619. * which modules will be used and give them appropriate initialization calls.
  172620. * We also initialize the decompressor input side to begin consuming data.
  172621. *
  172622. * Since jpeg_read_header has finished, we know what is in the SOF
  172623. * and (first) SOS markers. We also have all the application parameter
  172624. * settings.
  172625. */
  172626. LOCAL(void)
  172627. master_selection (j_decompress_ptr cinfo)
  172628. {
  172629. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172630. boolean use_c_buffer;
  172631. long samplesperrow;
  172632. JDIMENSION jd_samplesperrow;
  172633. /* Initialize dimensions and other stuff */
  172634. jpeg_calc_output_dimensions(cinfo);
  172635. prepare_range_limit_table(cinfo);
  172636. /* Width of an output scanline must be representable as JDIMENSION. */
  172637. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172638. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172639. if ((long) jd_samplesperrow != samplesperrow)
  172640. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172641. /* Initialize my private state */
  172642. master->pass_number = 0;
  172643. master->using_merged_upsample = use_merged_upsample(cinfo);
  172644. /* Color quantizer selection */
  172645. master->quantizer_1pass = NULL;
  172646. master->quantizer_2pass = NULL;
  172647. /* No mode changes if not using buffered-image mode. */
  172648. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172649. cinfo->enable_1pass_quant = FALSE;
  172650. cinfo->enable_external_quant = FALSE;
  172651. cinfo->enable_2pass_quant = FALSE;
  172652. }
  172653. if (cinfo->quantize_colors) {
  172654. if (cinfo->raw_data_out)
  172655. ERREXIT(cinfo, JERR_NOTIMPL);
  172656. /* 2-pass quantizer only works in 3-component color space. */
  172657. if (cinfo->out_color_components != 3) {
  172658. cinfo->enable_1pass_quant = TRUE;
  172659. cinfo->enable_external_quant = FALSE;
  172660. cinfo->enable_2pass_quant = FALSE;
  172661. cinfo->colormap = NULL;
  172662. } else if (cinfo->colormap != NULL) {
  172663. cinfo->enable_external_quant = TRUE;
  172664. } else if (cinfo->two_pass_quantize) {
  172665. cinfo->enable_2pass_quant = TRUE;
  172666. } else {
  172667. cinfo->enable_1pass_quant = TRUE;
  172668. }
  172669. if (cinfo->enable_1pass_quant) {
  172670. #ifdef QUANT_1PASS_SUPPORTED
  172671. jinit_1pass_quantizer(cinfo);
  172672. master->quantizer_1pass = cinfo->cquantize;
  172673. #else
  172674. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172675. #endif
  172676. }
  172677. /* We use the 2-pass code to map to external colormaps. */
  172678. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172679. #ifdef QUANT_2PASS_SUPPORTED
  172680. jinit_2pass_quantizer(cinfo);
  172681. master->quantizer_2pass = cinfo->cquantize;
  172682. #else
  172683. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172684. #endif
  172685. }
  172686. /* If both quantizers are initialized, the 2-pass one is left active;
  172687. * this is necessary for starting with quantization to an external map.
  172688. */
  172689. }
  172690. /* Post-processing: in particular, color conversion first */
  172691. if (! cinfo->raw_data_out) {
  172692. if (master->using_merged_upsample) {
  172693. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172694. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172695. #else
  172696. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172697. #endif
  172698. } else {
  172699. jinit_color_deconverter(cinfo);
  172700. jinit_upsampler(cinfo);
  172701. }
  172702. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172703. }
  172704. /* Inverse DCT */
  172705. jinit_inverse_dct(cinfo);
  172706. /* Entropy decoding: either Huffman or arithmetic coding. */
  172707. if (cinfo->arith_code) {
  172708. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172709. } else {
  172710. if (cinfo->progressive_mode) {
  172711. #ifdef D_PROGRESSIVE_SUPPORTED
  172712. jinit_phuff_decoder(cinfo);
  172713. #else
  172714. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172715. #endif
  172716. } else
  172717. jinit_huff_decoder(cinfo);
  172718. }
  172719. /* Initialize principal buffer controllers. */
  172720. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172721. jinit_d_coef_controller(cinfo, use_c_buffer);
  172722. if (! cinfo->raw_data_out)
  172723. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172724. /* We can now tell the memory manager to allocate virtual arrays. */
  172725. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172726. /* Initialize input side of decompressor to consume first scan. */
  172727. (*cinfo->inputctl->start_input_pass) (cinfo);
  172728. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172729. /* If jpeg_start_decompress will read the whole file, initialize
  172730. * progress monitoring appropriately. The input step is counted
  172731. * as one pass.
  172732. */
  172733. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172734. cinfo->inputctl->has_multiple_scans) {
  172735. int nscans;
  172736. /* Estimate number of scans to set pass_limit. */
  172737. if (cinfo->progressive_mode) {
  172738. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172739. nscans = 2 + 3 * cinfo->num_components;
  172740. } else {
  172741. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172742. nscans = cinfo->num_components;
  172743. }
  172744. cinfo->progress->pass_counter = 0L;
  172745. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172746. cinfo->progress->completed_passes = 0;
  172747. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172748. /* Count the input pass as done */
  172749. master->pass_number++;
  172750. }
  172751. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172752. }
  172753. /*
  172754. * Per-pass setup.
  172755. * This is called at the beginning of each output pass. We determine which
  172756. * modules will be active during this pass and give them appropriate
  172757. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172758. * is a "real" output pass or a dummy pass for color quantization.
  172759. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172760. */
  172761. METHODDEF(void)
  172762. prepare_for_output_pass (j_decompress_ptr cinfo)
  172763. {
  172764. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172765. if (master->pub.is_dummy_pass) {
  172766. #ifdef QUANT_2PASS_SUPPORTED
  172767. /* Final pass of 2-pass quantization */
  172768. master->pub.is_dummy_pass = FALSE;
  172769. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172770. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172771. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172772. #else
  172773. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172774. #endif /* QUANT_2PASS_SUPPORTED */
  172775. } else {
  172776. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172777. /* Select new quantization method */
  172778. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172779. cinfo->cquantize = master->quantizer_2pass;
  172780. master->pub.is_dummy_pass = TRUE;
  172781. } else if (cinfo->enable_1pass_quant) {
  172782. cinfo->cquantize = master->quantizer_1pass;
  172783. } else {
  172784. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172785. }
  172786. }
  172787. (*cinfo->idct->start_pass) (cinfo);
  172788. (*cinfo->coef->start_output_pass) (cinfo);
  172789. if (! cinfo->raw_data_out) {
  172790. if (! master->using_merged_upsample)
  172791. (*cinfo->cconvert->start_pass) (cinfo);
  172792. (*cinfo->upsample->start_pass) (cinfo);
  172793. if (cinfo->quantize_colors)
  172794. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172795. (*cinfo->post->start_pass) (cinfo,
  172796. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172797. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172798. }
  172799. }
  172800. /* Set up progress monitor's pass info if present */
  172801. if (cinfo->progress != NULL) {
  172802. cinfo->progress->completed_passes = master->pass_number;
  172803. cinfo->progress->total_passes = master->pass_number +
  172804. (master->pub.is_dummy_pass ? 2 : 1);
  172805. /* In buffered-image mode, we assume one more output pass if EOI not
  172806. * yet reached, but no more passes if EOI has been reached.
  172807. */
  172808. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172809. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172810. }
  172811. }
  172812. }
  172813. /*
  172814. * Finish up at end of an output pass.
  172815. */
  172816. METHODDEF(void)
  172817. finish_output_pass (j_decompress_ptr cinfo)
  172818. {
  172819. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172820. if (cinfo->quantize_colors)
  172821. (*cinfo->cquantize->finish_pass) (cinfo);
  172822. master->pass_number++;
  172823. }
  172824. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172825. /*
  172826. * Switch to a new external colormap between output passes.
  172827. */
  172828. GLOBAL(void)
  172829. jpeg_new_colormap (j_decompress_ptr cinfo)
  172830. {
  172831. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172832. /* Prevent application from calling me at wrong times */
  172833. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172834. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172835. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172836. cinfo->colormap != NULL) {
  172837. /* Select 2-pass quantizer for external colormap use */
  172838. cinfo->cquantize = master->quantizer_2pass;
  172839. /* Notify quantizer of colormap change */
  172840. (*cinfo->cquantize->new_color_map) (cinfo);
  172841. master->pub.is_dummy_pass = FALSE; /* just in case */
  172842. } else
  172843. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172844. }
  172845. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172846. /*
  172847. * Initialize master decompression control and select active modules.
  172848. * This is performed at the start of jpeg_start_decompress.
  172849. */
  172850. GLOBAL(void)
  172851. jinit_master_decompress (j_decompress_ptr cinfo)
  172852. {
  172853. my_master_ptr6 master;
  172854. master = (my_master_ptr6)
  172855. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172856. SIZEOF(my_decomp_master));
  172857. cinfo->master = (struct jpeg_decomp_master *) master;
  172858. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172859. master->pub.finish_output_pass = finish_output_pass;
  172860. master->pub.is_dummy_pass = FALSE;
  172861. master_selection(cinfo);
  172862. }
  172863. /*** End of inlined file: jdmaster.c ***/
  172864. #undef FIX
  172865. /*** Start of inlined file: jdmerge.c ***/
  172866. #define JPEG_INTERNALS
  172867. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172868. /* Private subobject */
  172869. typedef struct {
  172870. struct jpeg_upsampler pub; /* public fields */
  172871. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172872. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172873. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172874. JSAMPARRAY output_buf));
  172875. /* Private state for YCC->RGB conversion */
  172876. int * Cr_r_tab; /* => table for Cr to R conversion */
  172877. int * Cb_b_tab; /* => table for Cb to B conversion */
  172878. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172879. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172880. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172881. * We need a "spare" row buffer to hold the second output row if the
  172882. * application provides just a one-row buffer; we also use the spare
  172883. * to discard the dummy last row if the image height is odd.
  172884. */
  172885. JSAMPROW spare_row;
  172886. boolean spare_full; /* T if spare buffer is occupied */
  172887. JDIMENSION out_row_width; /* samples per output row */
  172888. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172889. } my_upsampler;
  172890. typedef my_upsampler * my_upsample_ptr;
  172891. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172892. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172893. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172894. /*
  172895. * Initialize tables for YCC->RGB colorspace conversion.
  172896. * This is taken directly from jdcolor.c; see that file for more info.
  172897. */
  172898. LOCAL(void)
  172899. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172900. {
  172901. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172902. int i;
  172903. INT32 x;
  172904. SHIFT_TEMPS
  172905. upsample->Cr_r_tab = (int *)
  172906. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172907. (MAXJSAMPLE+1) * SIZEOF(int));
  172908. upsample->Cb_b_tab = (int *)
  172909. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172910. (MAXJSAMPLE+1) * SIZEOF(int));
  172911. upsample->Cr_g_tab = (INT32 *)
  172912. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172913. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172914. upsample->Cb_g_tab = (INT32 *)
  172915. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172916. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172917. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172918. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172919. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172920. /* Cr=>R value is nearest int to 1.40200 * x */
  172921. upsample->Cr_r_tab[i] = (int)
  172922. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172923. /* Cb=>B value is nearest int to 1.77200 * x */
  172924. upsample->Cb_b_tab[i] = (int)
  172925. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172926. /* Cr=>G value is scaled-up -0.71414 * x */
  172927. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172928. /* Cb=>G value is scaled-up -0.34414 * x */
  172929. /* We also add in ONE_HALF so that need not do it in inner loop */
  172930. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172931. }
  172932. }
  172933. /*
  172934. * Initialize for an upsampling pass.
  172935. */
  172936. METHODDEF(void)
  172937. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172938. {
  172939. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172940. /* Mark the spare buffer empty */
  172941. upsample->spare_full = FALSE;
  172942. /* Initialize total-height counter for detecting bottom of image */
  172943. upsample->rows_to_go = cinfo->output_height;
  172944. }
  172945. /*
  172946. * Control routine to do upsampling (and color conversion).
  172947. *
  172948. * The control routine just handles the row buffering considerations.
  172949. */
  172950. METHODDEF(void)
  172951. merged_2v_upsample (j_decompress_ptr cinfo,
  172952. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172953. JDIMENSION,
  172954. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172955. JDIMENSION out_rows_avail)
  172956. /* 2:1 vertical sampling case: may need a spare row. */
  172957. {
  172958. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172959. JSAMPROW work_ptrs[2];
  172960. JDIMENSION num_rows; /* number of rows returned to caller */
  172961. if (upsample->spare_full) {
  172962. /* If we have a spare row saved from a previous cycle, just return it. */
  172963. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172964. 1, upsample->out_row_width);
  172965. num_rows = 1;
  172966. upsample->spare_full = FALSE;
  172967. } else {
  172968. /* Figure number of rows to return to caller. */
  172969. num_rows = 2;
  172970. /* Not more than the distance to the end of the image. */
  172971. if (num_rows > upsample->rows_to_go)
  172972. num_rows = upsample->rows_to_go;
  172973. /* And not more than what the client can accept: */
  172974. out_rows_avail -= *out_row_ctr;
  172975. if (num_rows > out_rows_avail)
  172976. num_rows = out_rows_avail;
  172977. /* Create output pointer array for upsampler. */
  172978. work_ptrs[0] = output_buf[*out_row_ctr];
  172979. if (num_rows > 1) {
  172980. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172981. } else {
  172982. work_ptrs[1] = upsample->spare_row;
  172983. upsample->spare_full = TRUE;
  172984. }
  172985. /* Now do the upsampling. */
  172986. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172987. }
  172988. /* Adjust counts */
  172989. *out_row_ctr += num_rows;
  172990. upsample->rows_to_go -= num_rows;
  172991. /* When the buffer is emptied, declare this input row group consumed */
  172992. if (! upsample->spare_full)
  172993. (*in_row_group_ctr)++;
  172994. }
  172995. METHODDEF(void)
  172996. merged_1v_upsample (j_decompress_ptr cinfo,
  172997. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172998. JDIMENSION,
  172999. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173000. JDIMENSION)
  173001. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  173002. {
  173003. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173004. /* Just do the upsampling. */
  173005. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  173006. output_buf + *out_row_ctr);
  173007. /* Adjust counts */
  173008. (*out_row_ctr)++;
  173009. (*in_row_group_ctr)++;
  173010. }
  173011. /*
  173012. * These are the routines invoked by the control routines to do
  173013. * the actual upsampling/conversion. One row group is processed per call.
  173014. *
  173015. * Note: since we may be writing directly into application-supplied buffers,
  173016. * we have to be honest about the output width; we can't assume the buffer
  173017. * has been rounded up to an even width.
  173018. */
  173019. /*
  173020. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  173021. */
  173022. METHODDEF(void)
  173023. h2v1_merged_upsample (j_decompress_ptr cinfo,
  173024. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173025. JSAMPARRAY output_buf)
  173026. {
  173027. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173028. register int y, cred, cgreen, cblue;
  173029. int cb, cr;
  173030. register JSAMPROW outptr;
  173031. JSAMPROW inptr0, inptr1, inptr2;
  173032. JDIMENSION col;
  173033. /* copy these pointers into registers if possible */
  173034. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173035. int * Crrtab = upsample->Cr_r_tab;
  173036. int * Cbbtab = upsample->Cb_b_tab;
  173037. INT32 * Crgtab = upsample->Cr_g_tab;
  173038. INT32 * Cbgtab = upsample->Cb_g_tab;
  173039. SHIFT_TEMPS
  173040. inptr0 = input_buf[0][in_row_group_ctr];
  173041. inptr1 = input_buf[1][in_row_group_ctr];
  173042. inptr2 = input_buf[2][in_row_group_ctr];
  173043. outptr = output_buf[0];
  173044. /* Loop for each pair of output pixels */
  173045. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173046. /* Do the chroma part of the calculation */
  173047. cb = GETJSAMPLE(*inptr1++);
  173048. cr = GETJSAMPLE(*inptr2++);
  173049. cred = Crrtab[cr];
  173050. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173051. cblue = Cbbtab[cb];
  173052. /* Fetch 2 Y values and emit 2 pixels */
  173053. y = GETJSAMPLE(*inptr0++);
  173054. outptr[RGB_RED] = range_limit[y + cred];
  173055. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173056. outptr[RGB_BLUE] = range_limit[y + cblue];
  173057. outptr += RGB_PIXELSIZE;
  173058. y = GETJSAMPLE(*inptr0++);
  173059. outptr[RGB_RED] = range_limit[y + cred];
  173060. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173061. outptr[RGB_BLUE] = range_limit[y + cblue];
  173062. outptr += RGB_PIXELSIZE;
  173063. }
  173064. /* If image width is odd, do the last output column separately */
  173065. if (cinfo->output_width & 1) {
  173066. cb = GETJSAMPLE(*inptr1);
  173067. cr = GETJSAMPLE(*inptr2);
  173068. cred = Crrtab[cr];
  173069. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173070. cblue = Cbbtab[cb];
  173071. y = GETJSAMPLE(*inptr0);
  173072. outptr[RGB_RED] = range_limit[y + cred];
  173073. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173074. outptr[RGB_BLUE] = range_limit[y + cblue];
  173075. }
  173076. }
  173077. /*
  173078. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  173079. */
  173080. METHODDEF(void)
  173081. h2v2_merged_upsample (j_decompress_ptr cinfo,
  173082. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173083. JSAMPARRAY output_buf)
  173084. {
  173085. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173086. register int y, cred, cgreen, cblue;
  173087. int cb, cr;
  173088. register JSAMPROW outptr0, outptr1;
  173089. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  173090. JDIMENSION col;
  173091. /* copy these pointers into registers if possible */
  173092. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173093. int * Crrtab = upsample->Cr_r_tab;
  173094. int * Cbbtab = upsample->Cb_b_tab;
  173095. INT32 * Crgtab = upsample->Cr_g_tab;
  173096. INT32 * Cbgtab = upsample->Cb_g_tab;
  173097. SHIFT_TEMPS
  173098. inptr00 = input_buf[0][in_row_group_ctr*2];
  173099. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  173100. inptr1 = input_buf[1][in_row_group_ctr];
  173101. inptr2 = input_buf[2][in_row_group_ctr];
  173102. outptr0 = output_buf[0];
  173103. outptr1 = output_buf[1];
  173104. /* Loop for each group of output pixels */
  173105. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173106. /* Do the chroma part of the calculation */
  173107. cb = GETJSAMPLE(*inptr1++);
  173108. cr = GETJSAMPLE(*inptr2++);
  173109. cred = Crrtab[cr];
  173110. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173111. cblue = Cbbtab[cb];
  173112. /* Fetch 4 Y values and emit 4 pixels */
  173113. y = GETJSAMPLE(*inptr00++);
  173114. outptr0[RGB_RED] = range_limit[y + cred];
  173115. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173116. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173117. outptr0 += RGB_PIXELSIZE;
  173118. y = GETJSAMPLE(*inptr00++);
  173119. outptr0[RGB_RED] = range_limit[y + cred];
  173120. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173121. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173122. outptr0 += RGB_PIXELSIZE;
  173123. y = GETJSAMPLE(*inptr01++);
  173124. outptr1[RGB_RED] = range_limit[y + cred];
  173125. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173126. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173127. outptr1 += RGB_PIXELSIZE;
  173128. y = GETJSAMPLE(*inptr01++);
  173129. outptr1[RGB_RED] = range_limit[y + cred];
  173130. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173131. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173132. outptr1 += RGB_PIXELSIZE;
  173133. }
  173134. /* If image width is odd, do the last output column separately */
  173135. if (cinfo->output_width & 1) {
  173136. cb = GETJSAMPLE(*inptr1);
  173137. cr = GETJSAMPLE(*inptr2);
  173138. cred = Crrtab[cr];
  173139. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173140. cblue = Cbbtab[cb];
  173141. y = GETJSAMPLE(*inptr00);
  173142. outptr0[RGB_RED] = range_limit[y + cred];
  173143. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173144. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173145. y = GETJSAMPLE(*inptr01);
  173146. outptr1[RGB_RED] = range_limit[y + cred];
  173147. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173148. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173149. }
  173150. }
  173151. /*
  173152. * Module initialization routine for merged upsampling/color conversion.
  173153. *
  173154. * NB: this is called under the conditions determined by use_merged_upsample()
  173155. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173156. * of this module; no safety checks are made here.
  173157. */
  173158. GLOBAL(void)
  173159. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173160. {
  173161. my_upsample_ptr upsample;
  173162. upsample = (my_upsample_ptr)
  173163. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173164. SIZEOF(my_upsampler));
  173165. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173166. upsample->pub.start_pass = start_pass_merged_upsample;
  173167. upsample->pub.need_context_rows = FALSE;
  173168. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173169. if (cinfo->max_v_samp_factor == 2) {
  173170. upsample->pub.upsample = merged_2v_upsample;
  173171. upsample->upmethod = h2v2_merged_upsample;
  173172. /* Allocate a spare row buffer */
  173173. upsample->spare_row = (JSAMPROW)
  173174. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173175. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173176. } else {
  173177. upsample->pub.upsample = merged_1v_upsample;
  173178. upsample->upmethod = h2v1_merged_upsample;
  173179. /* No spare row needed */
  173180. upsample->spare_row = NULL;
  173181. }
  173182. build_ycc_rgb_table2(cinfo);
  173183. }
  173184. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173185. /*** End of inlined file: jdmerge.c ***/
  173186. #undef ASSIGN_STATE
  173187. /*** Start of inlined file: jdphuff.c ***/
  173188. #define JPEG_INTERNALS
  173189. #ifdef D_PROGRESSIVE_SUPPORTED
  173190. /*
  173191. * Expanded entropy decoder object for progressive Huffman decoding.
  173192. *
  173193. * The savable_state subrecord contains fields that change within an MCU,
  173194. * but must not be updated permanently until we complete the MCU.
  173195. */
  173196. typedef struct {
  173197. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173198. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173199. } savable_state3;
  173200. /* This macro is to work around compilers with missing or broken
  173201. * structure assignment. You'll need to fix this code if you have
  173202. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173203. */
  173204. #ifndef NO_STRUCT_ASSIGN
  173205. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173206. #else
  173207. #if MAX_COMPS_IN_SCAN == 4
  173208. #define ASSIGN_STATE(dest,src) \
  173209. ((dest).EOBRUN = (src).EOBRUN, \
  173210. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173211. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173212. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173213. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173214. #endif
  173215. #endif
  173216. typedef struct {
  173217. struct jpeg_entropy_decoder pub; /* public fields */
  173218. /* These fields are loaded into local variables at start of each MCU.
  173219. * In case of suspension, we exit WITHOUT updating them.
  173220. */
  173221. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173222. savable_state3 saved; /* Other state at start of MCU */
  173223. /* These fields are NOT loaded into local working state. */
  173224. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173225. /* Pointers to derived tables (these workspaces have image lifespan) */
  173226. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173227. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173228. } phuff_entropy_decoder;
  173229. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173230. /* Forward declarations */
  173231. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173232. JBLOCKROW *MCU_data));
  173233. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173234. JBLOCKROW *MCU_data));
  173235. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173236. JBLOCKROW *MCU_data));
  173237. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173238. JBLOCKROW *MCU_data));
  173239. /*
  173240. * Initialize for a Huffman-compressed scan.
  173241. */
  173242. METHODDEF(void)
  173243. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173244. {
  173245. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173246. boolean is_DC_band, bad;
  173247. int ci, coefi, tbl;
  173248. int *coef_bit_ptr;
  173249. jpeg_component_info * compptr;
  173250. is_DC_band = (cinfo->Ss == 0);
  173251. /* Validate scan parameters */
  173252. bad = FALSE;
  173253. if (is_DC_band) {
  173254. if (cinfo->Se != 0)
  173255. bad = TRUE;
  173256. } else {
  173257. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173258. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173259. bad = TRUE;
  173260. /* AC scans may have only one component */
  173261. if (cinfo->comps_in_scan != 1)
  173262. bad = TRUE;
  173263. }
  173264. if (cinfo->Ah != 0) {
  173265. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173266. if (cinfo->Al != cinfo->Ah-1)
  173267. bad = TRUE;
  173268. }
  173269. if (cinfo->Al > 13) /* need not check for < 0 */
  173270. bad = TRUE;
  173271. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173272. * but the spec doesn't say so, and we try to be liberal about what we
  173273. * accept. Note: large Al values could result in out-of-range DC
  173274. * coefficients during early scans, leading to bizarre displays due to
  173275. * overflows in the IDCT math. But we won't crash.
  173276. */
  173277. if (bad)
  173278. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173279. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173280. /* Update progression status, and verify that scan order is legal.
  173281. * Note that inter-scan inconsistencies are treated as warnings
  173282. * not fatal errors ... not clear if this is right way to behave.
  173283. */
  173284. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173285. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173286. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173287. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173288. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173289. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173290. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173291. if (cinfo->Ah != expected)
  173292. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173293. coef_bit_ptr[coefi] = cinfo->Al;
  173294. }
  173295. }
  173296. /* Select MCU decoding routine */
  173297. if (cinfo->Ah == 0) {
  173298. if (is_DC_band)
  173299. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173300. else
  173301. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173302. } else {
  173303. if (is_DC_band)
  173304. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173305. else
  173306. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173307. }
  173308. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173309. compptr = cinfo->cur_comp_info[ci];
  173310. /* Make sure requested tables are present, and compute derived tables.
  173311. * We may build same derived table more than once, but it's not expensive.
  173312. */
  173313. if (is_DC_band) {
  173314. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173315. tbl = compptr->dc_tbl_no;
  173316. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173317. & entropy->derived_tbls[tbl]);
  173318. }
  173319. } else {
  173320. tbl = compptr->ac_tbl_no;
  173321. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173322. & entropy->derived_tbls[tbl]);
  173323. /* remember the single active table */
  173324. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173325. }
  173326. /* Initialize DC predictions to 0 */
  173327. entropy->saved.last_dc_val[ci] = 0;
  173328. }
  173329. /* Initialize bitread state variables */
  173330. entropy->bitstate.bits_left = 0;
  173331. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173332. entropy->pub.insufficient_data = FALSE;
  173333. /* Initialize private state variables */
  173334. entropy->saved.EOBRUN = 0;
  173335. /* Initialize restart counter */
  173336. entropy->restarts_to_go = cinfo->restart_interval;
  173337. }
  173338. /*
  173339. * Check for a restart marker & resynchronize decoder.
  173340. * Returns FALSE if must suspend.
  173341. */
  173342. LOCAL(boolean)
  173343. process_restartp (j_decompress_ptr cinfo)
  173344. {
  173345. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173346. int ci;
  173347. /* Throw away any unused bits remaining in bit buffer; */
  173348. /* include any full bytes in next_marker's count of discarded bytes */
  173349. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173350. entropy->bitstate.bits_left = 0;
  173351. /* Advance past the RSTn marker */
  173352. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173353. return FALSE;
  173354. /* Re-initialize DC predictions to 0 */
  173355. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173356. entropy->saved.last_dc_val[ci] = 0;
  173357. /* Re-init EOB run count, too */
  173358. entropy->saved.EOBRUN = 0;
  173359. /* Reset restart counter */
  173360. entropy->restarts_to_go = cinfo->restart_interval;
  173361. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173362. * against a marker. In that case we will end up treating the next data
  173363. * segment as empty, and we can avoid producing bogus output pixels by
  173364. * leaving the flag set.
  173365. */
  173366. if (cinfo->unread_marker == 0)
  173367. entropy->pub.insufficient_data = FALSE;
  173368. return TRUE;
  173369. }
  173370. /*
  173371. * Huffman MCU decoding.
  173372. * Each of these routines decodes and returns one MCU's worth of
  173373. * Huffman-compressed coefficients.
  173374. * The coefficients are reordered from zigzag order into natural array order,
  173375. * but are not dequantized.
  173376. *
  173377. * The i'th block of the MCU is stored into the block pointed to by
  173378. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173379. *
  173380. * We return FALSE if data source requested suspension. In that case no
  173381. * changes have been made to permanent state. (Exception: some output
  173382. * coefficients may already have been assigned. This is harmless for
  173383. * spectral selection, since we'll just re-assign them on the next call.
  173384. * Successive approximation AC refinement has to be more careful, however.)
  173385. */
  173386. /*
  173387. * MCU decoding for DC initial scan (either spectral selection,
  173388. * or first pass of successive approximation).
  173389. */
  173390. METHODDEF(boolean)
  173391. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173392. {
  173393. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173394. int Al = cinfo->Al;
  173395. register int s, r;
  173396. int blkn, ci;
  173397. JBLOCKROW block;
  173398. BITREAD_STATE_VARS;
  173399. savable_state3 state;
  173400. d_derived_tbl * tbl;
  173401. jpeg_component_info * compptr;
  173402. /* Process restart marker if needed; may have to suspend */
  173403. if (cinfo->restart_interval) {
  173404. if (entropy->restarts_to_go == 0)
  173405. if (! process_restartp(cinfo))
  173406. return FALSE;
  173407. }
  173408. /* If we've run out of data, just leave the MCU set to zeroes.
  173409. * This way, we return uniform gray for the remainder of the segment.
  173410. */
  173411. if (! entropy->pub.insufficient_data) {
  173412. /* Load up working state */
  173413. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173414. ASSIGN_STATE(state, entropy->saved);
  173415. /* Outer loop handles each block in the MCU */
  173416. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173417. block = MCU_data[blkn];
  173418. ci = cinfo->MCU_membership[blkn];
  173419. compptr = cinfo->cur_comp_info[ci];
  173420. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173421. /* Decode a single block's worth of coefficients */
  173422. /* Section F.2.2.1: decode the DC coefficient difference */
  173423. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173424. if (s) {
  173425. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173426. r = GET_BITS(s);
  173427. s = HUFF_EXTEND(r, s);
  173428. }
  173429. /* Convert DC difference to actual value, update last_dc_val */
  173430. s += state.last_dc_val[ci];
  173431. state.last_dc_val[ci] = s;
  173432. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173433. (*block)[0] = (JCOEF) (s << Al);
  173434. }
  173435. /* Completed MCU, so update state */
  173436. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173437. ASSIGN_STATE(entropy->saved, state);
  173438. }
  173439. /* Account for restart interval (no-op if not using restarts) */
  173440. entropy->restarts_to_go--;
  173441. return TRUE;
  173442. }
  173443. /*
  173444. * MCU decoding for AC initial scan (either spectral selection,
  173445. * or first pass of successive approximation).
  173446. */
  173447. METHODDEF(boolean)
  173448. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173449. {
  173450. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173451. int Se = cinfo->Se;
  173452. int Al = cinfo->Al;
  173453. register int s, k, r;
  173454. unsigned int EOBRUN;
  173455. JBLOCKROW block;
  173456. BITREAD_STATE_VARS;
  173457. d_derived_tbl * tbl;
  173458. /* Process restart marker if needed; may have to suspend */
  173459. if (cinfo->restart_interval) {
  173460. if (entropy->restarts_to_go == 0)
  173461. if (! process_restartp(cinfo))
  173462. return FALSE;
  173463. }
  173464. /* If we've run out of data, just leave the MCU set to zeroes.
  173465. * This way, we return uniform gray for the remainder of the segment.
  173466. */
  173467. if (! entropy->pub.insufficient_data) {
  173468. /* Load up working state.
  173469. * We can avoid loading/saving bitread state if in an EOB run.
  173470. */
  173471. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173472. /* There is always only one block per MCU */
  173473. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173474. EOBRUN--; /* ...process it now (we do nothing) */
  173475. else {
  173476. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173477. block = MCU_data[0];
  173478. tbl = entropy->ac_derived_tbl;
  173479. for (k = cinfo->Ss; k <= Se; k++) {
  173480. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173481. r = s >> 4;
  173482. s &= 15;
  173483. if (s) {
  173484. k += r;
  173485. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173486. r = GET_BITS(s);
  173487. s = HUFF_EXTEND(r, s);
  173488. /* Scale and output coefficient in natural (dezigzagged) order */
  173489. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173490. } else {
  173491. if (r == 15) { /* ZRL */
  173492. k += 15; /* skip 15 zeroes in band */
  173493. } else { /* EOBr, run length is 2^r + appended bits */
  173494. EOBRUN = 1 << r;
  173495. if (r) { /* EOBr, r > 0 */
  173496. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173497. r = GET_BITS(r);
  173498. EOBRUN += r;
  173499. }
  173500. EOBRUN--; /* this band is processed at this moment */
  173501. break; /* force end-of-band */
  173502. }
  173503. }
  173504. }
  173505. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173506. }
  173507. /* Completed MCU, so update state */
  173508. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173509. }
  173510. /* Account for restart interval (no-op if not using restarts) */
  173511. entropy->restarts_to_go--;
  173512. return TRUE;
  173513. }
  173514. /*
  173515. * MCU decoding for DC successive approximation refinement scan.
  173516. * Note: we assume such scans can be multi-component, although the spec
  173517. * is not very clear on the point.
  173518. */
  173519. METHODDEF(boolean)
  173520. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173521. {
  173522. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173523. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173524. int blkn;
  173525. JBLOCKROW block;
  173526. BITREAD_STATE_VARS;
  173527. /* Process restart marker if needed; may have to suspend */
  173528. if (cinfo->restart_interval) {
  173529. if (entropy->restarts_to_go == 0)
  173530. if (! process_restartp(cinfo))
  173531. return FALSE;
  173532. }
  173533. /* Not worth the cycles to check insufficient_data here,
  173534. * since we will not change the data anyway if we read zeroes.
  173535. */
  173536. /* Load up working state */
  173537. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173538. /* Outer loop handles each block in the MCU */
  173539. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173540. block = MCU_data[blkn];
  173541. /* Encoded data is simply the next bit of the two's-complement DC value */
  173542. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173543. if (GET_BITS(1))
  173544. (*block)[0] |= p1;
  173545. /* Note: since we use |=, repeating the assignment later is safe */
  173546. }
  173547. /* Completed MCU, so update state */
  173548. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173549. /* Account for restart interval (no-op if not using restarts) */
  173550. entropy->restarts_to_go--;
  173551. return TRUE;
  173552. }
  173553. /*
  173554. * MCU decoding for AC successive approximation refinement scan.
  173555. */
  173556. METHODDEF(boolean)
  173557. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173558. {
  173559. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173560. int Se = cinfo->Se;
  173561. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173562. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173563. register int s, k, r;
  173564. unsigned int EOBRUN;
  173565. JBLOCKROW block;
  173566. JCOEFPTR thiscoef;
  173567. BITREAD_STATE_VARS;
  173568. d_derived_tbl * tbl;
  173569. int num_newnz;
  173570. int newnz_pos[DCTSIZE2];
  173571. /* Process restart marker if needed; may have to suspend */
  173572. if (cinfo->restart_interval) {
  173573. if (entropy->restarts_to_go == 0)
  173574. if (! process_restartp(cinfo))
  173575. return FALSE;
  173576. }
  173577. /* If we've run out of data, don't modify the MCU.
  173578. */
  173579. if (! entropy->pub.insufficient_data) {
  173580. /* Load up working state */
  173581. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173582. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173583. /* There is always only one block per MCU */
  173584. block = MCU_data[0];
  173585. tbl = entropy->ac_derived_tbl;
  173586. /* If we are forced to suspend, we must undo the assignments to any newly
  173587. * nonzero coefficients in the block, because otherwise we'd get confused
  173588. * next time about which coefficients were already nonzero.
  173589. * But we need not undo addition of bits to already-nonzero coefficients;
  173590. * instead, we can test the current bit to see if we already did it.
  173591. */
  173592. num_newnz = 0;
  173593. /* initialize coefficient loop counter to start of band */
  173594. k = cinfo->Ss;
  173595. if (EOBRUN == 0) {
  173596. for (; k <= Se; k++) {
  173597. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173598. r = s >> 4;
  173599. s &= 15;
  173600. if (s) {
  173601. if (s != 1) /* size of new coef should always be 1 */
  173602. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173603. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173604. if (GET_BITS(1))
  173605. s = p1; /* newly nonzero coef is positive */
  173606. else
  173607. s = m1; /* newly nonzero coef is negative */
  173608. } else {
  173609. if (r != 15) {
  173610. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173611. if (r) {
  173612. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173613. r = GET_BITS(r);
  173614. EOBRUN += r;
  173615. }
  173616. break; /* rest of block is handled by EOB logic */
  173617. }
  173618. /* note s = 0 for processing ZRL */
  173619. }
  173620. /* Advance over already-nonzero coefs and r still-zero coefs,
  173621. * appending correction bits to the nonzeroes. A correction bit is 1
  173622. * if the absolute value of the coefficient must be increased.
  173623. */
  173624. do {
  173625. thiscoef = *block + jpeg_natural_order[k];
  173626. if (*thiscoef != 0) {
  173627. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173628. if (GET_BITS(1)) {
  173629. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173630. if (*thiscoef >= 0)
  173631. *thiscoef += p1;
  173632. else
  173633. *thiscoef += m1;
  173634. }
  173635. }
  173636. } else {
  173637. if (--r < 0)
  173638. break; /* reached target zero coefficient */
  173639. }
  173640. k++;
  173641. } while (k <= Se);
  173642. if (s) {
  173643. int pos = jpeg_natural_order[k];
  173644. /* Output newly nonzero coefficient */
  173645. (*block)[pos] = (JCOEF) s;
  173646. /* Remember its position in case we have to suspend */
  173647. newnz_pos[num_newnz++] = pos;
  173648. }
  173649. }
  173650. }
  173651. if (EOBRUN > 0) {
  173652. /* Scan any remaining coefficient positions after the end-of-band
  173653. * (the last newly nonzero coefficient, if any). Append a correction
  173654. * bit to each already-nonzero coefficient. A correction bit is 1
  173655. * if the absolute value of the coefficient must be increased.
  173656. */
  173657. for (; k <= Se; k++) {
  173658. thiscoef = *block + jpeg_natural_order[k];
  173659. if (*thiscoef != 0) {
  173660. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173661. if (GET_BITS(1)) {
  173662. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173663. if (*thiscoef >= 0)
  173664. *thiscoef += p1;
  173665. else
  173666. *thiscoef += m1;
  173667. }
  173668. }
  173669. }
  173670. }
  173671. /* Count one block completed in EOB run */
  173672. EOBRUN--;
  173673. }
  173674. /* Completed MCU, so update state */
  173675. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173676. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173677. }
  173678. /* Account for restart interval (no-op if not using restarts) */
  173679. entropy->restarts_to_go--;
  173680. return TRUE;
  173681. undoit:
  173682. /* Re-zero any output coefficients that we made newly nonzero */
  173683. while (num_newnz > 0)
  173684. (*block)[newnz_pos[--num_newnz]] = 0;
  173685. return FALSE;
  173686. }
  173687. /*
  173688. * Module initialization routine for progressive Huffman entropy decoding.
  173689. */
  173690. GLOBAL(void)
  173691. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173692. {
  173693. phuff_entropy_ptr2 entropy;
  173694. int *coef_bit_ptr;
  173695. int ci, i;
  173696. entropy = (phuff_entropy_ptr2)
  173697. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173698. SIZEOF(phuff_entropy_decoder));
  173699. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173700. entropy->pub.start_pass = start_pass_phuff_decoder;
  173701. /* Mark derived tables unallocated */
  173702. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173703. entropy->derived_tbls[i] = NULL;
  173704. }
  173705. /* Create progression status table */
  173706. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173707. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173708. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173709. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173710. for (ci = 0; ci < cinfo->num_components; ci++)
  173711. for (i = 0; i < DCTSIZE2; i++)
  173712. *coef_bit_ptr++ = -1;
  173713. }
  173714. #endif /* D_PROGRESSIVE_SUPPORTED */
  173715. /*** End of inlined file: jdphuff.c ***/
  173716. /*** Start of inlined file: jdpostct.c ***/
  173717. #define JPEG_INTERNALS
  173718. /* Private buffer controller object */
  173719. typedef struct {
  173720. struct jpeg_d_post_controller pub; /* public fields */
  173721. /* Color quantization source buffer: this holds output data from
  173722. * the upsample/color conversion step to be passed to the quantizer.
  173723. * For two-pass color quantization, we need a full-image buffer;
  173724. * for one-pass operation, a strip buffer is sufficient.
  173725. */
  173726. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173727. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173728. JDIMENSION strip_height; /* buffer size in rows */
  173729. /* for two-pass mode only: */
  173730. JDIMENSION starting_row; /* row # of first row in current strip */
  173731. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173732. } my_post_controller;
  173733. typedef my_post_controller * my_post_ptr;
  173734. /* Forward declarations */
  173735. METHODDEF(void) post_process_1pass
  173736. JPP((j_decompress_ptr cinfo,
  173737. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173738. JDIMENSION in_row_groups_avail,
  173739. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173740. JDIMENSION out_rows_avail));
  173741. #ifdef QUANT_2PASS_SUPPORTED
  173742. METHODDEF(void) post_process_prepass
  173743. JPP((j_decompress_ptr cinfo,
  173744. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173745. JDIMENSION in_row_groups_avail,
  173746. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173747. JDIMENSION out_rows_avail));
  173748. METHODDEF(void) post_process_2pass
  173749. JPP((j_decompress_ptr cinfo,
  173750. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173751. JDIMENSION in_row_groups_avail,
  173752. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173753. JDIMENSION out_rows_avail));
  173754. #endif
  173755. /*
  173756. * Initialize for a processing pass.
  173757. */
  173758. METHODDEF(void)
  173759. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173760. {
  173761. my_post_ptr post = (my_post_ptr) cinfo->post;
  173762. switch (pass_mode) {
  173763. case JBUF_PASS_THRU:
  173764. if (cinfo->quantize_colors) {
  173765. /* Single-pass processing with color quantization. */
  173766. post->pub.post_process_data = post_process_1pass;
  173767. /* We could be doing buffered-image output before starting a 2-pass
  173768. * color quantization; in that case, jinit_d_post_controller did not
  173769. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173770. */
  173771. if (post->buffer == NULL) {
  173772. post->buffer = (*cinfo->mem->access_virt_sarray)
  173773. ((j_common_ptr) cinfo, post->whole_image,
  173774. (JDIMENSION) 0, post->strip_height, TRUE);
  173775. }
  173776. } else {
  173777. /* For single-pass processing without color quantization,
  173778. * I have no work to do; just call the upsampler directly.
  173779. */
  173780. post->pub.post_process_data = cinfo->upsample->upsample;
  173781. }
  173782. break;
  173783. #ifdef QUANT_2PASS_SUPPORTED
  173784. case JBUF_SAVE_AND_PASS:
  173785. /* First pass of 2-pass quantization */
  173786. if (post->whole_image == NULL)
  173787. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173788. post->pub.post_process_data = post_process_prepass;
  173789. break;
  173790. case JBUF_CRANK_DEST:
  173791. /* Second pass of 2-pass quantization */
  173792. if (post->whole_image == NULL)
  173793. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173794. post->pub.post_process_data = post_process_2pass;
  173795. break;
  173796. #endif /* QUANT_2PASS_SUPPORTED */
  173797. default:
  173798. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173799. break;
  173800. }
  173801. post->starting_row = post->next_row = 0;
  173802. }
  173803. /*
  173804. * Process some data in the one-pass (strip buffer) case.
  173805. * This is used for color precision reduction as well as one-pass quantization.
  173806. */
  173807. METHODDEF(void)
  173808. post_process_1pass (j_decompress_ptr cinfo,
  173809. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173810. JDIMENSION in_row_groups_avail,
  173811. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173812. JDIMENSION out_rows_avail)
  173813. {
  173814. my_post_ptr post = (my_post_ptr) cinfo->post;
  173815. JDIMENSION num_rows, max_rows;
  173816. /* Fill the buffer, but not more than what we can dump out in one go. */
  173817. /* Note we rely on the upsampler to detect bottom of image. */
  173818. max_rows = out_rows_avail - *out_row_ctr;
  173819. if (max_rows > post->strip_height)
  173820. max_rows = post->strip_height;
  173821. num_rows = 0;
  173822. (*cinfo->upsample->upsample) (cinfo,
  173823. input_buf, in_row_group_ctr, in_row_groups_avail,
  173824. post->buffer, &num_rows, max_rows);
  173825. /* Quantize and emit data. */
  173826. (*cinfo->cquantize->color_quantize) (cinfo,
  173827. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173828. *out_row_ctr += num_rows;
  173829. }
  173830. #ifdef QUANT_2PASS_SUPPORTED
  173831. /*
  173832. * Process some data in the first pass of 2-pass quantization.
  173833. */
  173834. METHODDEF(void)
  173835. post_process_prepass (j_decompress_ptr cinfo,
  173836. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173837. JDIMENSION in_row_groups_avail,
  173838. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173839. JDIMENSION)
  173840. {
  173841. my_post_ptr post = (my_post_ptr) cinfo->post;
  173842. JDIMENSION old_next_row, num_rows;
  173843. /* Reposition virtual buffer if at start of strip. */
  173844. if (post->next_row == 0) {
  173845. post->buffer = (*cinfo->mem->access_virt_sarray)
  173846. ((j_common_ptr) cinfo, post->whole_image,
  173847. post->starting_row, post->strip_height, TRUE);
  173848. }
  173849. /* Upsample some data (up to a strip height's worth). */
  173850. old_next_row = post->next_row;
  173851. (*cinfo->upsample->upsample) (cinfo,
  173852. input_buf, in_row_group_ctr, in_row_groups_avail,
  173853. post->buffer, &post->next_row, post->strip_height);
  173854. /* Allow quantizer to scan new data. No data is emitted, */
  173855. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173856. if (post->next_row > old_next_row) {
  173857. num_rows = post->next_row - old_next_row;
  173858. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173859. (JSAMPARRAY) NULL, (int) num_rows);
  173860. *out_row_ctr += num_rows;
  173861. }
  173862. /* Advance if we filled the strip. */
  173863. if (post->next_row >= post->strip_height) {
  173864. post->starting_row += post->strip_height;
  173865. post->next_row = 0;
  173866. }
  173867. }
  173868. /*
  173869. * Process some data in the second pass of 2-pass quantization.
  173870. */
  173871. METHODDEF(void)
  173872. post_process_2pass (j_decompress_ptr cinfo,
  173873. JSAMPIMAGE, JDIMENSION *,
  173874. JDIMENSION,
  173875. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173876. JDIMENSION out_rows_avail)
  173877. {
  173878. my_post_ptr post = (my_post_ptr) cinfo->post;
  173879. JDIMENSION num_rows, max_rows;
  173880. /* Reposition virtual buffer if at start of strip. */
  173881. if (post->next_row == 0) {
  173882. post->buffer = (*cinfo->mem->access_virt_sarray)
  173883. ((j_common_ptr) cinfo, post->whole_image,
  173884. post->starting_row, post->strip_height, FALSE);
  173885. }
  173886. /* Determine number of rows to emit. */
  173887. num_rows = post->strip_height - post->next_row; /* available in strip */
  173888. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173889. if (num_rows > max_rows)
  173890. num_rows = max_rows;
  173891. /* We have to check bottom of image here, can't depend on upsampler. */
  173892. max_rows = cinfo->output_height - post->starting_row;
  173893. if (num_rows > max_rows)
  173894. num_rows = max_rows;
  173895. /* Quantize and emit data. */
  173896. (*cinfo->cquantize->color_quantize) (cinfo,
  173897. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173898. (int) num_rows);
  173899. *out_row_ctr += num_rows;
  173900. /* Advance if we filled the strip. */
  173901. post->next_row += num_rows;
  173902. if (post->next_row >= post->strip_height) {
  173903. post->starting_row += post->strip_height;
  173904. post->next_row = 0;
  173905. }
  173906. }
  173907. #endif /* QUANT_2PASS_SUPPORTED */
  173908. /*
  173909. * Initialize postprocessing controller.
  173910. */
  173911. GLOBAL(void)
  173912. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173913. {
  173914. my_post_ptr post;
  173915. post = (my_post_ptr)
  173916. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173917. SIZEOF(my_post_controller));
  173918. cinfo->post = (struct jpeg_d_post_controller *) post;
  173919. post->pub.start_pass = start_pass_dpost;
  173920. post->whole_image = NULL; /* flag for no virtual arrays */
  173921. post->buffer = NULL; /* flag for no strip buffer */
  173922. /* Create the quantization buffer, if needed */
  173923. if (cinfo->quantize_colors) {
  173924. /* The buffer strip height is max_v_samp_factor, which is typically
  173925. * an efficient number of rows for upsampling to return.
  173926. * (In the presence of output rescaling, we might want to be smarter?)
  173927. */
  173928. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173929. if (need_full_buffer) {
  173930. /* Two-pass color quantization: need full-image storage. */
  173931. /* We round up the number of rows to a multiple of the strip height. */
  173932. #ifdef QUANT_2PASS_SUPPORTED
  173933. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173934. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173935. cinfo->output_width * cinfo->out_color_components,
  173936. (JDIMENSION) jround_up((long) cinfo->output_height,
  173937. (long) post->strip_height),
  173938. post->strip_height);
  173939. #else
  173940. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173941. #endif /* QUANT_2PASS_SUPPORTED */
  173942. } else {
  173943. /* One-pass color quantization: just make a strip buffer. */
  173944. post->buffer = (*cinfo->mem->alloc_sarray)
  173945. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173946. cinfo->output_width * cinfo->out_color_components,
  173947. post->strip_height);
  173948. }
  173949. }
  173950. }
  173951. /*** End of inlined file: jdpostct.c ***/
  173952. #undef FIX
  173953. /*** Start of inlined file: jdsample.c ***/
  173954. #define JPEG_INTERNALS
  173955. /* Pointer to routine to upsample a single component */
  173956. typedef JMETHOD(void, upsample1_ptr,
  173957. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173958. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173959. /* Private subobject */
  173960. typedef struct {
  173961. struct jpeg_upsampler pub; /* public fields */
  173962. /* Color conversion buffer. When using separate upsampling and color
  173963. * conversion steps, this buffer holds one upsampled row group until it
  173964. * has been color converted and output.
  173965. * Note: we do not allocate any storage for component(s) which are full-size,
  173966. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173967. * simply set to point to the input data array, thereby avoiding copying.
  173968. */
  173969. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173970. /* Per-component upsampling method pointers */
  173971. upsample1_ptr methods[MAX_COMPONENTS];
  173972. int next_row_out; /* counts rows emitted from color_buf */
  173973. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173974. /* Height of an input row group for each component. */
  173975. int rowgroup_height[MAX_COMPONENTS];
  173976. /* These arrays save pixel expansion factors so that int_expand need not
  173977. * recompute them each time. They are unused for other upsampling methods.
  173978. */
  173979. UINT8 h_expand[MAX_COMPONENTS];
  173980. UINT8 v_expand[MAX_COMPONENTS];
  173981. } my_upsampler2;
  173982. typedef my_upsampler2 * my_upsample_ptr2;
  173983. /*
  173984. * Initialize for an upsampling pass.
  173985. */
  173986. METHODDEF(void)
  173987. start_pass_upsample (j_decompress_ptr cinfo)
  173988. {
  173989. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173990. /* Mark the conversion buffer empty */
  173991. upsample->next_row_out = cinfo->max_v_samp_factor;
  173992. /* Initialize total-height counter for detecting bottom of image */
  173993. upsample->rows_to_go = cinfo->output_height;
  173994. }
  173995. /*
  173996. * Control routine to do upsampling (and color conversion).
  173997. *
  173998. * In this version we upsample each component independently.
  173999. * We upsample one row group into the conversion buffer, then apply
  174000. * color conversion a row at a time.
  174001. */
  174002. METHODDEF(void)
  174003. sep_upsample (j_decompress_ptr cinfo,
  174004. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174005. JDIMENSION,
  174006. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174007. JDIMENSION out_rows_avail)
  174008. {
  174009. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174010. int ci;
  174011. jpeg_component_info * compptr;
  174012. JDIMENSION num_rows;
  174013. /* Fill the conversion buffer, if it's empty */
  174014. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  174015. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174016. ci++, compptr++) {
  174017. /* Invoke per-component upsample method. Notice we pass a POINTER
  174018. * to color_buf[ci], so that fullsize_upsample can change it.
  174019. */
  174020. (*upsample->methods[ci]) (cinfo, compptr,
  174021. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  174022. upsample->color_buf + ci);
  174023. }
  174024. upsample->next_row_out = 0;
  174025. }
  174026. /* Color-convert and emit rows */
  174027. /* How many we have in the buffer: */
  174028. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  174029. /* Not more than the distance to the end of the image. Need this test
  174030. * in case the image height is not a multiple of max_v_samp_factor:
  174031. */
  174032. if (num_rows > upsample->rows_to_go)
  174033. num_rows = upsample->rows_to_go;
  174034. /* And not more than what the client can accept: */
  174035. out_rows_avail -= *out_row_ctr;
  174036. if (num_rows > out_rows_avail)
  174037. num_rows = out_rows_avail;
  174038. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  174039. (JDIMENSION) upsample->next_row_out,
  174040. output_buf + *out_row_ctr,
  174041. (int) num_rows);
  174042. /* Adjust counts */
  174043. *out_row_ctr += num_rows;
  174044. upsample->rows_to_go -= num_rows;
  174045. upsample->next_row_out += num_rows;
  174046. /* When the buffer is emptied, declare this input row group consumed */
  174047. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  174048. (*in_row_group_ctr)++;
  174049. }
  174050. /*
  174051. * These are the routines invoked by sep_upsample to upsample pixel values
  174052. * of a single component. One row group is processed per call.
  174053. */
  174054. /*
  174055. * For full-size components, we just make color_buf[ci] point at the
  174056. * input buffer, and thus avoid copying any data. Note that this is
  174057. * safe only because sep_upsample doesn't declare the input row group
  174058. * "consumed" until we are done color converting and emitting it.
  174059. */
  174060. METHODDEF(void)
  174061. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  174062. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174063. {
  174064. *output_data_ptr = input_data;
  174065. }
  174066. /*
  174067. * This is a no-op version used for "uninteresting" components.
  174068. * These components will not be referenced by color conversion.
  174069. */
  174070. METHODDEF(void)
  174071. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  174072. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  174073. {
  174074. *output_data_ptr = NULL; /* safety check */
  174075. }
  174076. /*
  174077. * This version handles any integral sampling ratios.
  174078. * This is not used for typical JPEG files, so it need not be fast.
  174079. * Nor, for that matter, is it particularly accurate: the algorithm is
  174080. * simple replication of the input pixel onto the corresponding output
  174081. * pixels. The hi-falutin sampling literature refers to this as a
  174082. * "box filter". A box filter tends to introduce visible artifacts,
  174083. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  174084. * you would be well advised to improve this code.
  174085. */
  174086. METHODDEF(void)
  174087. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174088. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174089. {
  174090. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174091. JSAMPARRAY output_data = *output_data_ptr;
  174092. register JSAMPROW inptr, outptr;
  174093. register JSAMPLE invalue;
  174094. register int h;
  174095. JSAMPROW outend;
  174096. int h_expand, v_expand;
  174097. int inrow, outrow;
  174098. h_expand = upsample->h_expand[compptr->component_index];
  174099. v_expand = upsample->v_expand[compptr->component_index];
  174100. inrow = outrow = 0;
  174101. while (outrow < cinfo->max_v_samp_factor) {
  174102. /* Generate one output row with proper horizontal expansion */
  174103. inptr = input_data[inrow];
  174104. outptr = output_data[outrow];
  174105. outend = outptr + cinfo->output_width;
  174106. while (outptr < outend) {
  174107. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174108. for (h = h_expand; h > 0; h--) {
  174109. *outptr++ = invalue;
  174110. }
  174111. }
  174112. /* Generate any additional output rows by duplicating the first one */
  174113. if (v_expand > 1) {
  174114. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174115. v_expand-1, cinfo->output_width);
  174116. }
  174117. inrow++;
  174118. outrow += v_expand;
  174119. }
  174120. }
  174121. /*
  174122. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  174123. * It's still a box filter.
  174124. */
  174125. METHODDEF(void)
  174126. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174127. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174128. {
  174129. JSAMPARRAY output_data = *output_data_ptr;
  174130. register JSAMPROW inptr, outptr;
  174131. register JSAMPLE invalue;
  174132. JSAMPROW outend;
  174133. int inrow;
  174134. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174135. inptr = input_data[inrow];
  174136. outptr = output_data[inrow];
  174137. outend = outptr + cinfo->output_width;
  174138. while (outptr < outend) {
  174139. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174140. *outptr++ = invalue;
  174141. *outptr++ = invalue;
  174142. }
  174143. }
  174144. }
  174145. /*
  174146. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174147. * It's still a box filter.
  174148. */
  174149. METHODDEF(void)
  174150. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174151. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174152. {
  174153. JSAMPARRAY output_data = *output_data_ptr;
  174154. register JSAMPROW inptr, outptr;
  174155. register JSAMPLE invalue;
  174156. JSAMPROW outend;
  174157. int inrow, outrow;
  174158. inrow = outrow = 0;
  174159. while (outrow < cinfo->max_v_samp_factor) {
  174160. inptr = input_data[inrow];
  174161. outptr = output_data[outrow];
  174162. outend = outptr + cinfo->output_width;
  174163. while (outptr < outend) {
  174164. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174165. *outptr++ = invalue;
  174166. *outptr++ = invalue;
  174167. }
  174168. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174169. 1, cinfo->output_width);
  174170. inrow++;
  174171. outrow += 2;
  174172. }
  174173. }
  174174. /*
  174175. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174176. *
  174177. * The upsampling algorithm is linear interpolation between pixel centers,
  174178. * also known as a "triangle filter". This is a good compromise between
  174179. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174180. * of the way between input pixel centers.
  174181. *
  174182. * A note about the "bias" calculations: when rounding fractional values to
  174183. * integer, we do not want to always round 0.5 up to the next integer.
  174184. * If we did that, we'd introduce a noticeable bias towards larger values.
  174185. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174186. * alternate pixel locations (a simple ordered dither pattern).
  174187. */
  174188. METHODDEF(void)
  174189. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174190. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174191. {
  174192. JSAMPARRAY output_data = *output_data_ptr;
  174193. register JSAMPROW inptr, outptr;
  174194. register int invalue;
  174195. register JDIMENSION colctr;
  174196. int inrow;
  174197. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174198. inptr = input_data[inrow];
  174199. outptr = output_data[inrow];
  174200. /* Special case for first column */
  174201. invalue = GETJSAMPLE(*inptr++);
  174202. *outptr++ = (JSAMPLE) invalue;
  174203. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174204. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174205. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174206. invalue = GETJSAMPLE(*inptr++) * 3;
  174207. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174208. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174209. }
  174210. /* Special case for last column */
  174211. invalue = GETJSAMPLE(*inptr);
  174212. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174213. *outptr++ = (JSAMPLE) invalue;
  174214. }
  174215. }
  174216. /*
  174217. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174218. * Again a triangle filter; see comments for h2v1 case, above.
  174219. *
  174220. * It is OK for us to reference the adjacent input rows because we demanded
  174221. * context from the main buffer controller (see initialization code).
  174222. */
  174223. METHODDEF(void)
  174224. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174225. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174226. {
  174227. JSAMPARRAY output_data = *output_data_ptr;
  174228. register JSAMPROW inptr0, inptr1, outptr;
  174229. #if BITS_IN_JSAMPLE == 8
  174230. register int thiscolsum, lastcolsum, nextcolsum;
  174231. #else
  174232. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174233. #endif
  174234. register JDIMENSION colctr;
  174235. int inrow, outrow, v;
  174236. inrow = outrow = 0;
  174237. while (outrow < cinfo->max_v_samp_factor) {
  174238. for (v = 0; v < 2; v++) {
  174239. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174240. inptr0 = input_data[inrow];
  174241. if (v == 0) /* next nearest is row above */
  174242. inptr1 = input_data[inrow-1];
  174243. else /* next nearest is row below */
  174244. inptr1 = input_data[inrow+1];
  174245. outptr = output_data[outrow++];
  174246. /* Special case for first column */
  174247. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174248. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174249. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174250. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174251. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174252. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174253. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174254. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174255. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174256. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174257. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174258. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174259. }
  174260. /* Special case for last column */
  174261. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174262. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174263. }
  174264. inrow++;
  174265. }
  174266. }
  174267. /*
  174268. * Module initialization routine for upsampling.
  174269. */
  174270. GLOBAL(void)
  174271. jinit_upsampler (j_decompress_ptr cinfo)
  174272. {
  174273. my_upsample_ptr2 upsample;
  174274. int ci;
  174275. jpeg_component_info * compptr;
  174276. boolean need_buffer, do_fancy;
  174277. int h_in_group, v_in_group, h_out_group, v_out_group;
  174278. upsample = (my_upsample_ptr2)
  174279. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174280. SIZEOF(my_upsampler2));
  174281. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174282. upsample->pub.start_pass = start_pass_upsample;
  174283. upsample->pub.upsample = sep_upsample;
  174284. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174285. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174286. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174287. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174288. * so don't ask for it.
  174289. */
  174290. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174291. /* Verify we can handle the sampling factors, select per-component methods,
  174292. * and create storage as needed.
  174293. */
  174294. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174295. ci++, compptr++) {
  174296. /* Compute size of an "input group" after IDCT scaling. This many samples
  174297. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174298. */
  174299. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174300. cinfo->min_DCT_scaled_size;
  174301. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174302. cinfo->min_DCT_scaled_size;
  174303. h_out_group = cinfo->max_h_samp_factor;
  174304. v_out_group = cinfo->max_v_samp_factor;
  174305. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174306. need_buffer = TRUE;
  174307. if (! compptr->component_needed) {
  174308. /* Don't bother to upsample an uninteresting component. */
  174309. upsample->methods[ci] = noop_upsample;
  174310. need_buffer = FALSE;
  174311. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174312. /* Fullsize components can be processed without any work. */
  174313. upsample->methods[ci] = fullsize_upsample;
  174314. need_buffer = FALSE;
  174315. } else if (h_in_group * 2 == h_out_group &&
  174316. v_in_group == v_out_group) {
  174317. /* Special cases for 2h1v upsampling */
  174318. if (do_fancy && compptr->downsampled_width > 2)
  174319. upsample->methods[ci] = h2v1_fancy_upsample;
  174320. else
  174321. upsample->methods[ci] = h2v1_upsample;
  174322. } else if (h_in_group * 2 == h_out_group &&
  174323. v_in_group * 2 == v_out_group) {
  174324. /* Special cases for 2h2v upsampling */
  174325. if (do_fancy && compptr->downsampled_width > 2) {
  174326. upsample->methods[ci] = h2v2_fancy_upsample;
  174327. upsample->pub.need_context_rows = TRUE;
  174328. } else
  174329. upsample->methods[ci] = h2v2_upsample;
  174330. } else if ((h_out_group % h_in_group) == 0 &&
  174331. (v_out_group % v_in_group) == 0) {
  174332. /* Generic integral-factors upsampling method */
  174333. upsample->methods[ci] = int_upsample;
  174334. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174335. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174336. } else
  174337. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174338. if (need_buffer) {
  174339. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174340. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174341. (JDIMENSION) jround_up((long) cinfo->output_width,
  174342. (long) cinfo->max_h_samp_factor),
  174343. (JDIMENSION) cinfo->max_v_samp_factor);
  174344. }
  174345. }
  174346. }
  174347. /*** End of inlined file: jdsample.c ***/
  174348. /*** Start of inlined file: jdtrans.c ***/
  174349. #define JPEG_INTERNALS
  174350. /* Forward declarations */
  174351. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174352. /*
  174353. * Read the coefficient arrays from a JPEG file.
  174354. * jpeg_read_header must be completed before calling this.
  174355. *
  174356. * The entire image is read into a set of virtual coefficient-block arrays,
  174357. * one per component. The return value is a pointer to the array of
  174358. * virtual-array descriptors. These can be manipulated directly via the
  174359. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174360. * To release the memory occupied by the virtual arrays, call
  174361. * jpeg_finish_decompress() when done with the data.
  174362. *
  174363. * An alternative usage is to simply obtain access to the coefficient arrays
  174364. * during a buffered-image-mode decompression operation. This is allowed
  174365. * after any jpeg_finish_output() call. The arrays can be accessed until
  174366. * jpeg_finish_decompress() is called. (Note that any call to the library
  174367. * may reposition the arrays, so don't rely on access_virt_barray() results
  174368. * to stay valid across library calls.)
  174369. *
  174370. * Returns NULL if suspended. This case need be checked only if
  174371. * a suspending data source is used.
  174372. */
  174373. GLOBAL(jvirt_barray_ptr *)
  174374. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174375. {
  174376. if (cinfo->global_state == DSTATE_READY) {
  174377. /* First call: initialize active modules */
  174378. transdecode_master_selection(cinfo);
  174379. cinfo->global_state = DSTATE_RDCOEFS;
  174380. }
  174381. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174382. /* Absorb whole file into the coef buffer */
  174383. for (;;) {
  174384. int retcode;
  174385. /* Call progress monitor hook if present */
  174386. if (cinfo->progress != NULL)
  174387. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174388. /* Absorb some more input */
  174389. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174390. if (retcode == JPEG_SUSPENDED)
  174391. return NULL;
  174392. if (retcode == JPEG_REACHED_EOI)
  174393. break;
  174394. /* Advance progress counter if appropriate */
  174395. if (cinfo->progress != NULL &&
  174396. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174397. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174398. /* startup underestimated number of scans; ratchet up one scan */
  174399. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174400. }
  174401. }
  174402. }
  174403. /* Set state so that jpeg_finish_decompress does the right thing */
  174404. cinfo->global_state = DSTATE_STOPPING;
  174405. }
  174406. /* At this point we should be in state DSTATE_STOPPING if being used
  174407. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174408. * to the coefficients during a full buffered-image-mode decompression.
  174409. */
  174410. if ((cinfo->global_state == DSTATE_STOPPING ||
  174411. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174412. return cinfo->coef->coef_arrays;
  174413. }
  174414. /* Oops, improper usage */
  174415. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174416. return NULL; /* keep compiler happy */
  174417. }
  174418. /*
  174419. * Master selection of decompression modules for transcoding.
  174420. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174421. */
  174422. LOCAL(void)
  174423. transdecode_master_selection (j_decompress_ptr cinfo)
  174424. {
  174425. /* This is effectively a buffered-image operation. */
  174426. cinfo->buffered_image = TRUE;
  174427. /* Entropy decoding: either Huffman or arithmetic coding. */
  174428. if (cinfo->arith_code) {
  174429. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174430. } else {
  174431. if (cinfo->progressive_mode) {
  174432. #ifdef D_PROGRESSIVE_SUPPORTED
  174433. jinit_phuff_decoder(cinfo);
  174434. #else
  174435. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174436. #endif
  174437. } else
  174438. jinit_huff_decoder(cinfo);
  174439. }
  174440. /* Always get a full-image coefficient buffer. */
  174441. jinit_d_coef_controller(cinfo, TRUE);
  174442. /* We can now tell the memory manager to allocate virtual arrays. */
  174443. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174444. /* Initialize input side of decompressor to consume first scan. */
  174445. (*cinfo->inputctl->start_input_pass) (cinfo);
  174446. /* Initialize progress monitoring. */
  174447. if (cinfo->progress != NULL) {
  174448. int nscans;
  174449. /* Estimate number of scans to set pass_limit. */
  174450. if (cinfo->progressive_mode) {
  174451. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174452. nscans = 2 + 3 * cinfo->num_components;
  174453. } else if (cinfo->inputctl->has_multiple_scans) {
  174454. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174455. nscans = cinfo->num_components;
  174456. } else {
  174457. nscans = 1;
  174458. }
  174459. cinfo->progress->pass_counter = 0L;
  174460. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174461. cinfo->progress->completed_passes = 0;
  174462. cinfo->progress->total_passes = 1;
  174463. }
  174464. }
  174465. /*** End of inlined file: jdtrans.c ***/
  174466. /*** Start of inlined file: jfdctflt.c ***/
  174467. #define JPEG_INTERNALS
  174468. #ifdef DCT_FLOAT_SUPPORTED
  174469. /*
  174470. * This module is specialized to the case DCTSIZE = 8.
  174471. */
  174472. #if DCTSIZE != 8
  174473. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174474. #endif
  174475. /*
  174476. * Perform the forward DCT on one block of samples.
  174477. */
  174478. GLOBAL(void)
  174479. jpeg_fdct_float (FAST_FLOAT * data)
  174480. {
  174481. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174482. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174483. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174484. FAST_FLOAT *dataptr;
  174485. int ctr;
  174486. /* Pass 1: process rows. */
  174487. dataptr = data;
  174488. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174489. tmp0 = dataptr[0] + dataptr[7];
  174490. tmp7 = dataptr[0] - dataptr[7];
  174491. tmp1 = dataptr[1] + dataptr[6];
  174492. tmp6 = dataptr[1] - dataptr[6];
  174493. tmp2 = dataptr[2] + dataptr[5];
  174494. tmp5 = dataptr[2] - dataptr[5];
  174495. tmp3 = dataptr[3] + dataptr[4];
  174496. tmp4 = dataptr[3] - dataptr[4];
  174497. /* Even part */
  174498. tmp10 = tmp0 + tmp3; /* phase 2 */
  174499. tmp13 = tmp0 - tmp3;
  174500. tmp11 = tmp1 + tmp2;
  174501. tmp12 = tmp1 - tmp2;
  174502. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174503. dataptr[4] = tmp10 - tmp11;
  174504. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174505. dataptr[2] = tmp13 + z1; /* phase 5 */
  174506. dataptr[6] = tmp13 - z1;
  174507. /* Odd part */
  174508. tmp10 = tmp4 + tmp5; /* phase 2 */
  174509. tmp11 = tmp5 + tmp6;
  174510. tmp12 = tmp6 + tmp7;
  174511. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174512. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174513. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174514. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174515. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174516. z11 = tmp7 + z3; /* phase 5 */
  174517. z13 = tmp7 - z3;
  174518. dataptr[5] = z13 + z2; /* phase 6 */
  174519. dataptr[3] = z13 - z2;
  174520. dataptr[1] = z11 + z4;
  174521. dataptr[7] = z11 - z4;
  174522. dataptr += DCTSIZE; /* advance pointer to next row */
  174523. }
  174524. /* Pass 2: process columns. */
  174525. dataptr = data;
  174526. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174527. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174528. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174529. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174530. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174531. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174532. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174533. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174534. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174535. /* Even part */
  174536. tmp10 = tmp0 + tmp3; /* phase 2 */
  174537. tmp13 = tmp0 - tmp3;
  174538. tmp11 = tmp1 + tmp2;
  174539. tmp12 = tmp1 - tmp2;
  174540. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174541. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174542. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174543. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174544. dataptr[DCTSIZE*6] = tmp13 - z1;
  174545. /* Odd part */
  174546. tmp10 = tmp4 + tmp5; /* phase 2 */
  174547. tmp11 = tmp5 + tmp6;
  174548. tmp12 = tmp6 + tmp7;
  174549. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174550. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174551. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174552. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174553. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174554. z11 = tmp7 + z3; /* phase 5 */
  174555. z13 = tmp7 - z3;
  174556. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174557. dataptr[DCTSIZE*3] = z13 - z2;
  174558. dataptr[DCTSIZE*1] = z11 + z4;
  174559. dataptr[DCTSIZE*7] = z11 - z4;
  174560. dataptr++; /* advance pointer to next column */
  174561. }
  174562. }
  174563. #endif /* DCT_FLOAT_SUPPORTED */
  174564. /*** End of inlined file: jfdctflt.c ***/
  174565. /*** Start of inlined file: jfdctint.c ***/
  174566. #define JPEG_INTERNALS
  174567. #ifdef DCT_ISLOW_SUPPORTED
  174568. /*
  174569. * This module is specialized to the case DCTSIZE = 8.
  174570. */
  174571. #if DCTSIZE != 8
  174572. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174573. #endif
  174574. /*
  174575. * The poop on this scaling stuff is as follows:
  174576. *
  174577. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174578. * larger than the true DCT outputs. The final outputs are therefore
  174579. * a factor of N larger than desired; since N=8 this can be cured by
  174580. * a simple right shift at the end of the algorithm. The advantage of
  174581. * this arrangement is that we save two multiplications per 1-D DCT,
  174582. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174583. * In the IJG code, this factor of 8 is removed by the quantization step
  174584. * (in jcdctmgr.c), NOT in this module.
  174585. *
  174586. * We have to do addition and subtraction of the integer inputs, which
  174587. * is no problem, and multiplication by fractional constants, which is
  174588. * a problem to do in integer arithmetic. We multiply all the constants
  174589. * by CONST_SCALE and convert them to integer constants (thus retaining
  174590. * CONST_BITS bits of precision in the constants). After doing a
  174591. * multiplication we have to divide the product by CONST_SCALE, with proper
  174592. * rounding, to produce the correct output. This division can be done
  174593. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174594. * as long as possible so that partial sums can be added together with
  174595. * full fractional precision.
  174596. *
  174597. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174598. * they are represented to better-than-integral precision. These outputs
  174599. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174600. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174601. * array is INT32 anyway.)
  174602. *
  174603. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174604. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174605. * shows that the values given below are the most effective.
  174606. */
  174607. #if BITS_IN_JSAMPLE == 8
  174608. #define CONST_BITS 13
  174609. #define PASS1_BITS 2
  174610. #else
  174611. #define CONST_BITS 13
  174612. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174613. #endif
  174614. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174615. * causing a lot of useless floating-point operations at run time.
  174616. * To get around this we use the following pre-calculated constants.
  174617. * If you change CONST_BITS you may want to add appropriate values.
  174618. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174619. */
  174620. #if CONST_BITS == 13
  174621. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174622. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174623. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174624. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174625. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174626. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174627. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174628. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174629. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174630. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174631. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174632. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174633. #else
  174634. #define FIX_0_298631336 FIX(0.298631336)
  174635. #define FIX_0_390180644 FIX(0.390180644)
  174636. #define FIX_0_541196100 FIX(0.541196100)
  174637. #define FIX_0_765366865 FIX(0.765366865)
  174638. #define FIX_0_899976223 FIX(0.899976223)
  174639. #define FIX_1_175875602 FIX(1.175875602)
  174640. #define FIX_1_501321110 FIX(1.501321110)
  174641. #define FIX_1_847759065 FIX(1.847759065)
  174642. #define FIX_1_961570560 FIX(1.961570560)
  174643. #define FIX_2_053119869 FIX(2.053119869)
  174644. #define FIX_2_562915447 FIX(2.562915447)
  174645. #define FIX_3_072711026 FIX(3.072711026)
  174646. #endif
  174647. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174648. * For 8-bit samples with the recommended scaling, all the variable
  174649. * and constant values involved are no more than 16 bits wide, so a
  174650. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174651. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174652. */
  174653. #if BITS_IN_JSAMPLE == 8
  174654. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174655. #else
  174656. #define MULTIPLY(var,const) ((var) * (const))
  174657. #endif
  174658. /*
  174659. * Perform the forward DCT on one block of samples.
  174660. */
  174661. GLOBAL(void)
  174662. jpeg_fdct_islow (DCTELEM * data)
  174663. {
  174664. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174665. INT32 tmp10, tmp11, tmp12, tmp13;
  174666. INT32 z1, z2, z3, z4, z5;
  174667. DCTELEM *dataptr;
  174668. int ctr;
  174669. SHIFT_TEMPS
  174670. /* Pass 1: process rows. */
  174671. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174672. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174673. dataptr = data;
  174674. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174675. tmp0 = dataptr[0] + dataptr[7];
  174676. tmp7 = dataptr[0] - dataptr[7];
  174677. tmp1 = dataptr[1] + dataptr[6];
  174678. tmp6 = dataptr[1] - dataptr[6];
  174679. tmp2 = dataptr[2] + dataptr[5];
  174680. tmp5 = dataptr[2] - dataptr[5];
  174681. tmp3 = dataptr[3] + dataptr[4];
  174682. tmp4 = dataptr[3] - dataptr[4];
  174683. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174684. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174685. */
  174686. tmp10 = tmp0 + tmp3;
  174687. tmp13 = tmp0 - tmp3;
  174688. tmp11 = tmp1 + tmp2;
  174689. tmp12 = tmp1 - tmp2;
  174690. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174691. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174692. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174693. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174694. CONST_BITS-PASS1_BITS);
  174695. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174696. CONST_BITS-PASS1_BITS);
  174697. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174698. * cK represents cos(K*pi/16).
  174699. * i0..i3 in the paper are tmp4..tmp7 here.
  174700. */
  174701. z1 = tmp4 + tmp7;
  174702. z2 = tmp5 + tmp6;
  174703. z3 = tmp4 + tmp6;
  174704. z4 = tmp5 + tmp7;
  174705. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174706. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174707. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174708. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174709. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174710. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174711. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174712. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174713. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174714. z3 += z5;
  174715. z4 += z5;
  174716. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174717. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174718. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174719. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174720. dataptr += DCTSIZE; /* advance pointer to next row */
  174721. }
  174722. /* Pass 2: process columns.
  174723. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174724. * by an overall factor of 8.
  174725. */
  174726. dataptr = data;
  174727. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174728. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174729. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174730. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174731. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174732. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174733. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174734. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174735. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174736. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174737. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174738. */
  174739. tmp10 = tmp0 + tmp3;
  174740. tmp13 = tmp0 - tmp3;
  174741. tmp11 = tmp1 + tmp2;
  174742. tmp12 = tmp1 - tmp2;
  174743. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174744. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174745. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174746. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174747. CONST_BITS+PASS1_BITS);
  174748. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174749. CONST_BITS+PASS1_BITS);
  174750. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174751. * cK represents cos(K*pi/16).
  174752. * i0..i3 in the paper are tmp4..tmp7 here.
  174753. */
  174754. z1 = tmp4 + tmp7;
  174755. z2 = tmp5 + tmp6;
  174756. z3 = tmp4 + tmp6;
  174757. z4 = tmp5 + tmp7;
  174758. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174759. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174760. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174761. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174762. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174763. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174764. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174765. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174766. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174767. z3 += z5;
  174768. z4 += z5;
  174769. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174770. CONST_BITS+PASS1_BITS);
  174771. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174772. CONST_BITS+PASS1_BITS);
  174773. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174774. CONST_BITS+PASS1_BITS);
  174775. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174776. CONST_BITS+PASS1_BITS);
  174777. dataptr++; /* advance pointer to next column */
  174778. }
  174779. }
  174780. #endif /* DCT_ISLOW_SUPPORTED */
  174781. /*** End of inlined file: jfdctint.c ***/
  174782. #undef CONST_BITS
  174783. #undef MULTIPLY
  174784. #undef FIX_0_541196100
  174785. /*** Start of inlined file: jfdctfst.c ***/
  174786. #define JPEG_INTERNALS
  174787. #ifdef DCT_IFAST_SUPPORTED
  174788. /*
  174789. * This module is specialized to the case DCTSIZE = 8.
  174790. */
  174791. #if DCTSIZE != 8
  174792. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174793. #endif
  174794. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174795. * see jfdctint.c for more details. However, we choose to descale
  174796. * (right shift) multiplication products as soon as they are formed,
  174797. * rather than carrying additional fractional bits into subsequent additions.
  174798. * This compromises accuracy slightly, but it lets us save a few shifts.
  174799. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174800. * everywhere except in the multiplications proper; this saves a good deal
  174801. * of work on 16-bit-int machines.
  174802. *
  174803. * Again to save a few shifts, the intermediate results between pass 1 and
  174804. * pass 2 are not upscaled, but are represented only to integral precision.
  174805. *
  174806. * A final compromise is to represent the multiplicative constants to only
  174807. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174808. * machines, and may also reduce the cost of multiplication (since there
  174809. * are fewer one-bits in the constants).
  174810. */
  174811. #define CONST_BITS 8
  174812. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174813. * causing a lot of useless floating-point operations at run time.
  174814. * To get around this we use the following pre-calculated constants.
  174815. * If you change CONST_BITS you may want to add appropriate values.
  174816. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174817. */
  174818. #if CONST_BITS == 8
  174819. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174820. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174821. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174822. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174823. #else
  174824. #define FIX_0_382683433 FIX(0.382683433)
  174825. #define FIX_0_541196100 FIX(0.541196100)
  174826. #define FIX_0_707106781 FIX(0.707106781)
  174827. #define FIX_1_306562965 FIX(1.306562965)
  174828. #endif
  174829. /* We can gain a little more speed, with a further compromise in accuracy,
  174830. * by omitting the addition in a descaling shift. This yields an incorrectly
  174831. * rounded result half the time...
  174832. */
  174833. #ifndef USE_ACCURATE_ROUNDING
  174834. #undef DESCALE
  174835. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174836. #endif
  174837. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174838. * descale to yield a DCTELEM result.
  174839. */
  174840. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174841. /*
  174842. * Perform the forward DCT on one block of samples.
  174843. */
  174844. GLOBAL(void)
  174845. jpeg_fdct_ifast (DCTELEM * data)
  174846. {
  174847. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174848. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174849. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174850. DCTELEM *dataptr;
  174851. int ctr;
  174852. SHIFT_TEMPS
  174853. /* Pass 1: process rows. */
  174854. dataptr = data;
  174855. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174856. tmp0 = dataptr[0] + dataptr[7];
  174857. tmp7 = dataptr[0] - dataptr[7];
  174858. tmp1 = dataptr[1] + dataptr[6];
  174859. tmp6 = dataptr[1] - dataptr[6];
  174860. tmp2 = dataptr[2] + dataptr[5];
  174861. tmp5 = dataptr[2] - dataptr[5];
  174862. tmp3 = dataptr[3] + dataptr[4];
  174863. tmp4 = dataptr[3] - dataptr[4];
  174864. /* Even part */
  174865. tmp10 = tmp0 + tmp3; /* phase 2 */
  174866. tmp13 = tmp0 - tmp3;
  174867. tmp11 = tmp1 + tmp2;
  174868. tmp12 = tmp1 - tmp2;
  174869. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174870. dataptr[4] = tmp10 - tmp11;
  174871. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174872. dataptr[2] = tmp13 + z1; /* phase 5 */
  174873. dataptr[6] = tmp13 - z1;
  174874. /* Odd part */
  174875. tmp10 = tmp4 + tmp5; /* phase 2 */
  174876. tmp11 = tmp5 + tmp6;
  174877. tmp12 = tmp6 + tmp7;
  174878. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174879. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174880. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174881. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174882. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174883. z11 = tmp7 + z3; /* phase 5 */
  174884. z13 = tmp7 - z3;
  174885. dataptr[5] = z13 + z2; /* phase 6 */
  174886. dataptr[3] = z13 - z2;
  174887. dataptr[1] = z11 + z4;
  174888. dataptr[7] = z11 - z4;
  174889. dataptr += DCTSIZE; /* advance pointer to next row */
  174890. }
  174891. /* Pass 2: process columns. */
  174892. dataptr = data;
  174893. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174894. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174895. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174896. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174897. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174898. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174899. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174900. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174901. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174902. /* Even part */
  174903. tmp10 = tmp0 + tmp3; /* phase 2 */
  174904. tmp13 = tmp0 - tmp3;
  174905. tmp11 = tmp1 + tmp2;
  174906. tmp12 = tmp1 - tmp2;
  174907. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174908. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174909. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174910. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174911. dataptr[DCTSIZE*6] = tmp13 - z1;
  174912. /* Odd part */
  174913. tmp10 = tmp4 + tmp5; /* phase 2 */
  174914. tmp11 = tmp5 + tmp6;
  174915. tmp12 = tmp6 + tmp7;
  174916. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174917. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174918. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174919. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174920. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174921. z11 = tmp7 + z3; /* phase 5 */
  174922. z13 = tmp7 - z3;
  174923. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174924. dataptr[DCTSIZE*3] = z13 - z2;
  174925. dataptr[DCTSIZE*1] = z11 + z4;
  174926. dataptr[DCTSIZE*7] = z11 - z4;
  174927. dataptr++; /* advance pointer to next column */
  174928. }
  174929. }
  174930. #endif /* DCT_IFAST_SUPPORTED */
  174931. /*** End of inlined file: jfdctfst.c ***/
  174932. #undef FIX_0_541196100
  174933. /*** Start of inlined file: jidctflt.c ***/
  174934. #define JPEG_INTERNALS
  174935. #ifdef DCT_FLOAT_SUPPORTED
  174936. /*
  174937. * This module is specialized to the case DCTSIZE = 8.
  174938. */
  174939. #if DCTSIZE != 8
  174940. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174941. #endif
  174942. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174943. * entry; produce a float result.
  174944. */
  174945. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174946. /*
  174947. * Perform dequantization and inverse DCT on one block of coefficients.
  174948. */
  174949. GLOBAL(void)
  174950. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174951. JCOEFPTR coef_block,
  174952. JSAMPARRAY output_buf, JDIMENSION output_col)
  174953. {
  174954. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174955. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174956. FAST_FLOAT z5, z10, z11, z12, z13;
  174957. JCOEFPTR inptr;
  174958. FLOAT_MULT_TYPE * quantptr;
  174959. FAST_FLOAT * wsptr;
  174960. JSAMPROW outptr;
  174961. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174962. int ctr;
  174963. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174964. SHIFT_TEMPS
  174965. /* Pass 1: process columns from input, store into work array. */
  174966. inptr = coef_block;
  174967. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174968. wsptr = workspace;
  174969. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174970. /* Due to quantization, we will usually find that many of the input
  174971. * coefficients are zero, especially the AC terms. We can exploit this
  174972. * by short-circuiting the IDCT calculation for any column in which all
  174973. * the AC terms are zero. In that case each output is equal to the
  174974. * DC coefficient (with scale factor as needed).
  174975. * With typical images and quantization tables, half or more of the
  174976. * column DCT calculations can be simplified this way.
  174977. */
  174978. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174979. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174980. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174981. inptr[DCTSIZE*7] == 0) {
  174982. /* AC terms all zero */
  174983. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174984. wsptr[DCTSIZE*0] = dcval;
  174985. wsptr[DCTSIZE*1] = dcval;
  174986. wsptr[DCTSIZE*2] = dcval;
  174987. wsptr[DCTSIZE*3] = dcval;
  174988. wsptr[DCTSIZE*4] = dcval;
  174989. wsptr[DCTSIZE*5] = dcval;
  174990. wsptr[DCTSIZE*6] = dcval;
  174991. wsptr[DCTSIZE*7] = dcval;
  174992. inptr++; /* advance pointers to next column */
  174993. quantptr++;
  174994. wsptr++;
  174995. continue;
  174996. }
  174997. /* Even part */
  174998. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174999. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175000. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175001. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175002. tmp10 = tmp0 + tmp2; /* phase 3 */
  175003. tmp11 = tmp0 - tmp2;
  175004. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175005. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  175006. tmp0 = tmp10 + tmp13; /* phase 2 */
  175007. tmp3 = tmp10 - tmp13;
  175008. tmp1 = tmp11 + tmp12;
  175009. tmp2 = tmp11 - tmp12;
  175010. /* Odd part */
  175011. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175012. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175013. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175014. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175015. z13 = tmp6 + tmp5; /* phase 6 */
  175016. z10 = tmp6 - tmp5;
  175017. z11 = tmp4 + tmp7;
  175018. z12 = tmp4 - tmp7;
  175019. tmp7 = z11 + z13; /* phase 5 */
  175020. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  175021. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175022. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175023. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175024. tmp6 = tmp12 - tmp7; /* phase 2 */
  175025. tmp5 = tmp11 - tmp6;
  175026. tmp4 = tmp10 + tmp5;
  175027. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  175028. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  175029. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  175030. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  175031. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  175032. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  175033. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  175034. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  175035. inptr++; /* advance pointers to next column */
  175036. quantptr++;
  175037. wsptr++;
  175038. }
  175039. /* Pass 2: process rows from work array, store into output array. */
  175040. /* Note that we must descale the results by a factor of 8 == 2**3. */
  175041. wsptr = workspace;
  175042. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175043. outptr = output_buf[ctr] + output_col;
  175044. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175045. * However, the column calculation has created many nonzero AC terms, so
  175046. * the simplification applies less often (typically 5% to 10% of the time).
  175047. * And testing floats for zero is relatively expensive, so we don't bother.
  175048. */
  175049. /* Even part */
  175050. tmp10 = wsptr[0] + wsptr[4];
  175051. tmp11 = wsptr[0] - wsptr[4];
  175052. tmp13 = wsptr[2] + wsptr[6];
  175053. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  175054. tmp0 = tmp10 + tmp13;
  175055. tmp3 = tmp10 - tmp13;
  175056. tmp1 = tmp11 + tmp12;
  175057. tmp2 = tmp11 - tmp12;
  175058. /* Odd part */
  175059. z13 = wsptr[5] + wsptr[3];
  175060. z10 = wsptr[5] - wsptr[3];
  175061. z11 = wsptr[1] + wsptr[7];
  175062. z12 = wsptr[1] - wsptr[7];
  175063. tmp7 = z11 + z13;
  175064. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  175065. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175066. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175067. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175068. tmp6 = tmp12 - tmp7;
  175069. tmp5 = tmp11 - tmp6;
  175070. tmp4 = tmp10 + tmp5;
  175071. /* Final output stage: scale down by a factor of 8 and range-limit */
  175072. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  175073. & RANGE_MASK];
  175074. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  175075. & RANGE_MASK];
  175076. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  175077. & RANGE_MASK];
  175078. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  175079. & RANGE_MASK];
  175080. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  175081. & RANGE_MASK];
  175082. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  175083. & RANGE_MASK];
  175084. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  175085. & RANGE_MASK];
  175086. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  175087. & RANGE_MASK];
  175088. wsptr += DCTSIZE; /* advance pointer to next row */
  175089. }
  175090. }
  175091. #endif /* DCT_FLOAT_SUPPORTED */
  175092. /*** End of inlined file: jidctflt.c ***/
  175093. #undef CONST_BITS
  175094. #undef FIX_1_847759065
  175095. #undef MULTIPLY
  175096. #undef DEQUANTIZE
  175097. #undef DESCALE
  175098. /*** Start of inlined file: jidctfst.c ***/
  175099. #define JPEG_INTERNALS
  175100. #ifdef DCT_IFAST_SUPPORTED
  175101. /*
  175102. * This module is specialized to the case DCTSIZE = 8.
  175103. */
  175104. #if DCTSIZE != 8
  175105. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175106. #endif
  175107. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175108. * see jidctint.c for more details. However, we choose to descale
  175109. * (right shift) multiplication products as soon as they are formed,
  175110. * rather than carrying additional fractional bits into subsequent additions.
  175111. * This compromises accuracy slightly, but it lets us save a few shifts.
  175112. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175113. * everywhere except in the multiplications proper; this saves a good deal
  175114. * of work on 16-bit-int machines.
  175115. *
  175116. * The dequantized coefficients are not integers because the AA&N scaling
  175117. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  175118. * so that the first and second IDCT rounds have the same input scaling.
  175119. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  175120. * avoid a descaling shift; this compromises accuracy rather drastically
  175121. * for small quantization table entries, but it saves a lot of shifts.
  175122. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  175123. * so we use a much larger scaling factor to preserve accuracy.
  175124. *
  175125. * A final compromise is to represent the multiplicative constants to only
  175126. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175127. * machines, and may also reduce the cost of multiplication (since there
  175128. * are fewer one-bits in the constants).
  175129. */
  175130. #if BITS_IN_JSAMPLE == 8
  175131. #define CONST_BITS 8
  175132. #define PASS1_BITS 2
  175133. #else
  175134. #define CONST_BITS 8
  175135. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175136. #endif
  175137. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175138. * causing a lot of useless floating-point operations at run time.
  175139. * To get around this we use the following pre-calculated constants.
  175140. * If you change CONST_BITS you may want to add appropriate values.
  175141. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175142. */
  175143. #if CONST_BITS == 8
  175144. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175145. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175146. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175147. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175148. #else
  175149. #define FIX_1_082392200 FIX(1.082392200)
  175150. #define FIX_1_414213562 FIX(1.414213562)
  175151. #define FIX_1_847759065 FIX(1.847759065)
  175152. #define FIX_2_613125930 FIX(2.613125930)
  175153. #endif
  175154. /* We can gain a little more speed, with a further compromise in accuracy,
  175155. * by omitting the addition in a descaling shift. This yields an incorrectly
  175156. * rounded result half the time...
  175157. */
  175158. #ifndef USE_ACCURATE_ROUNDING
  175159. #undef DESCALE
  175160. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175161. #endif
  175162. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175163. * descale to yield a DCTELEM result.
  175164. */
  175165. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175166. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175167. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175168. * multiplication will do. For 12-bit data, the multiplier table is
  175169. * declared INT32, so a 32-bit multiply will be used.
  175170. */
  175171. #if BITS_IN_JSAMPLE == 8
  175172. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175173. #else
  175174. #define DEQUANTIZE(coef,quantval) \
  175175. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175176. #endif
  175177. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175178. * We assume that int right shift is unsigned if INT32 right shift is.
  175179. */
  175180. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175181. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175182. #if BITS_IN_JSAMPLE == 8
  175183. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175184. #else
  175185. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175186. #endif
  175187. #define IRIGHT_SHIFT(x,shft) \
  175188. ((ishift_temp = (x)) < 0 ? \
  175189. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175190. (ishift_temp >> (shft)))
  175191. #else
  175192. #define ISHIFT_TEMPS
  175193. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175194. #endif
  175195. #ifdef USE_ACCURATE_ROUNDING
  175196. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175197. #else
  175198. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175199. #endif
  175200. /*
  175201. * Perform dequantization and inverse DCT on one block of coefficients.
  175202. */
  175203. GLOBAL(void)
  175204. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175205. JCOEFPTR coef_block,
  175206. JSAMPARRAY output_buf, JDIMENSION output_col)
  175207. {
  175208. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175209. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175210. DCTELEM z5, z10, z11, z12, z13;
  175211. JCOEFPTR inptr;
  175212. IFAST_MULT_TYPE * quantptr;
  175213. int * wsptr;
  175214. JSAMPROW outptr;
  175215. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175216. int ctr;
  175217. int workspace[DCTSIZE2]; /* buffers data between passes */
  175218. SHIFT_TEMPS /* for DESCALE */
  175219. ISHIFT_TEMPS /* for IDESCALE */
  175220. /* Pass 1: process columns from input, store into work array. */
  175221. inptr = coef_block;
  175222. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175223. wsptr = workspace;
  175224. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175225. /* Due to quantization, we will usually find that many of the input
  175226. * coefficients are zero, especially the AC terms. We can exploit this
  175227. * by short-circuiting the IDCT calculation for any column in which all
  175228. * the AC terms are zero. In that case each output is equal to the
  175229. * DC coefficient (with scale factor as needed).
  175230. * With typical images and quantization tables, half or more of the
  175231. * column DCT calculations can be simplified this way.
  175232. */
  175233. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175234. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175235. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175236. inptr[DCTSIZE*7] == 0) {
  175237. /* AC terms all zero */
  175238. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175239. wsptr[DCTSIZE*0] = dcval;
  175240. wsptr[DCTSIZE*1] = dcval;
  175241. wsptr[DCTSIZE*2] = dcval;
  175242. wsptr[DCTSIZE*3] = dcval;
  175243. wsptr[DCTSIZE*4] = dcval;
  175244. wsptr[DCTSIZE*5] = dcval;
  175245. wsptr[DCTSIZE*6] = dcval;
  175246. wsptr[DCTSIZE*7] = dcval;
  175247. inptr++; /* advance pointers to next column */
  175248. quantptr++;
  175249. wsptr++;
  175250. continue;
  175251. }
  175252. /* Even part */
  175253. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175254. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175255. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175256. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175257. tmp10 = tmp0 + tmp2; /* phase 3 */
  175258. tmp11 = tmp0 - tmp2;
  175259. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175260. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175261. tmp0 = tmp10 + tmp13; /* phase 2 */
  175262. tmp3 = tmp10 - tmp13;
  175263. tmp1 = tmp11 + tmp12;
  175264. tmp2 = tmp11 - tmp12;
  175265. /* Odd part */
  175266. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175267. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175268. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175269. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175270. z13 = tmp6 + tmp5; /* phase 6 */
  175271. z10 = tmp6 - tmp5;
  175272. z11 = tmp4 + tmp7;
  175273. z12 = tmp4 - tmp7;
  175274. tmp7 = z11 + z13; /* phase 5 */
  175275. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175276. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175277. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175278. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175279. tmp6 = tmp12 - tmp7; /* phase 2 */
  175280. tmp5 = tmp11 - tmp6;
  175281. tmp4 = tmp10 + tmp5;
  175282. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175283. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175284. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175285. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175286. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175287. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175288. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175289. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175290. inptr++; /* advance pointers to next column */
  175291. quantptr++;
  175292. wsptr++;
  175293. }
  175294. /* Pass 2: process rows from work array, store into output array. */
  175295. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175296. /* and also undo the PASS1_BITS scaling. */
  175297. wsptr = workspace;
  175298. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175299. outptr = output_buf[ctr] + output_col;
  175300. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175301. * However, the column calculation has created many nonzero AC terms, so
  175302. * the simplification applies less often (typically 5% to 10% of the time).
  175303. * On machines with very fast multiplication, it's possible that the
  175304. * test takes more time than it's worth. In that case this section
  175305. * may be commented out.
  175306. */
  175307. #ifndef NO_ZERO_ROW_TEST
  175308. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175309. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175310. /* AC terms all zero */
  175311. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175312. & RANGE_MASK];
  175313. outptr[0] = dcval;
  175314. outptr[1] = dcval;
  175315. outptr[2] = dcval;
  175316. outptr[3] = dcval;
  175317. outptr[4] = dcval;
  175318. outptr[5] = dcval;
  175319. outptr[6] = dcval;
  175320. outptr[7] = dcval;
  175321. wsptr += DCTSIZE; /* advance pointer to next row */
  175322. continue;
  175323. }
  175324. #endif
  175325. /* Even part */
  175326. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175327. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175328. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175329. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175330. - tmp13;
  175331. tmp0 = tmp10 + tmp13;
  175332. tmp3 = tmp10 - tmp13;
  175333. tmp1 = tmp11 + tmp12;
  175334. tmp2 = tmp11 - tmp12;
  175335. /* Odd part */
  175336. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175337. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175338. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175339. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175340. tmp7 = z11 + z13; /* phase 5 */
  175341. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175342. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175343. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175344. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175345. tmp6 = tmp12 - tmp7; /* phase 2 */
  175346. tmp5 = tmp11 - tmp6;
  175347. tmp4 = tmp10 + tmp5;
  175348. /* Final output stage: scale down by a factor of 8 and range-limit */
  175349. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175350. & RANGE_MASK];
  175351. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175352. & RANGE_MASK];
  175353. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175354. & RANGE_MASK];
  175355. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175356. & RANGE_MASK];
  175357. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175358. & RANGE_MASK];
  175359. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175360. & RANGE_MASK];
  175361. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175362. & RANGE_MASK];
  175363. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175364. & RANGE_MASK];
  175365. wsptr += DCTSIZE; /* advance pointer to next row */
  175366. }
  175367. }
  175368. #endif /* DCT_IFAST_SUPPORTED */
  175369. /*** End of inlined file: jidctfst.c ***/
  175370. #undef CONST_BITS
  175371. #undef FIX_1_847759065
  175372. #undef MULTIPLY
  175373. #undef DEQUANTIZE
  175374. /*** Start of inlined file: jidctint.c ***/
  175375. #define JPEG_INTERNALS
  175376. #ifdef DCT_ISLOW_SUPPORTED
  175377. /*
  175378. * This module is specialized to the case DCTSIZE = 8.
  175379. */
  175380. #if DCTSIZE != 8
  175381. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175382. #endif
  175383. /*
  175384. * The poop on this scaling stuff is as follows:
  175385. *
  175386. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175387. * larger than the true IDCT outputs. The final outputs are therefore
  175388. * a factor of N larger than desired; since N=8 this can be cured by
  175389. * a simple right shift at the end of the algorithm. The advantage of
  175390. * this arrangement is that we save two multiplications per 1-D IDCT,
  175391. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175392. *
  175393. * We have to do addition and subtraction of the integer inputs, which
  175394. * is no problem, and multiplication by fractional constants, which is
  175395. * a problem to do in integer arithmetic. We multiply all the constants
  175396. * by CONST_SCALE and convert them to integer constants (thus retaining
  175397. * CONST_BITS bits of precision in the constants). After doing a
  175398. * multiplication we have to divide the product by CONST_SCALE, with proper
  175399. * rounding, to produce the correct output. This division can be done
  175400. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175401. * as long as possible so that partial sums can be added together with
  175402. * full fractional precision.
  175403. *
  175404. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175405. * they are represented to better-than-integral precision. These outputs
  175406. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175407. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175408. * intermediate INT32 array would be needed.)
  175409. *
  175410. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175411. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175412. * shows that the values given below are the most effective.
  175413. */
  175414. #if BITS_IN_JSAMPLE == 8
  175415. #define CONST_BITS 13
  175416. #define PASS1_BITS 2
  175417. #else
  175418. #define CONST_BITS 13
  175419. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175420. #endif
  175421. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175422. * causing a lot of useless floating-point operations at run time.
  175423. * To get around this we use the following pre-calculated constants.
  175424. * If you change CONST_BITS you may want to add appropriate values.
  175425. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175426. */
  175427. #if CONST_BITS == 13
  175428. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175429. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175430. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175431. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175432. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175433. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175434. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175435. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175436. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175437. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175438. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175439. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175440. #else
  175441. #define FIX_0_298631336 FIX(0.298631336)
  175442. #define FIX_0_390180644 FIX(0.390180644)
  175443. #define FIX_0_541196100 FIX(0.541196100)
  175444. #define FIX_0_765366865 FIX(0.765366865)
  175445. #define FIX_0_899976223 FIX(0.899976223)
  175446. #define FIX_1_175875602 FIX(1.175875602)
  175447. #define FIX_1_501321110 FIX(1.501321110)
  175448. #define FIX_1_847759065 FIX(1.847759065)
  175449. #define FIX_1_961570560 FIX(1.961570560)
  175450. #define FIX_2_053119869 FIX(2.053119869)
  175451. #define FIX_2_562915447 FIX(2.562915447)
  175452. #define FIX_3_072711026 FIX(3.072711026)
  175453. #endif
  175454. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175455. * For 8-bit samples with the recommended scaling, all the variable
  175456. * and constant values involved are no more than 16 bits wide, so a
  175457. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175458. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175459. */
  175460. #if BITS_IN_JSAMPLE == 8
  175461. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175462. #else
  175463. #define MULTIPLY(var,const) ((var) * (const))
  175464. #endif
  175465. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175466. * entry; produce an int result. In this module, both inputs and result
  175467. * are 16 bits or less, so either int or short multiply will work.
  175468. */
  175469. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175470. /*
  175471. * Perform dequantization and inverse DCT on one block of coefficients.
  175472. */
  175473. GLOBAL(void)
  175474. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175475. JCOEFPTR coef_block,
  175476. JSAMPARRAY output_buf, JDIMENSION output_col)
  175477. {
  175478. INT32 tmp0, tmp1, tmp2, tmp3;
  175479. INT32 tmp10, tmp11, tmp12, tmp13;
  175480. INT32 z1, z2, z3, z4, z5;
  175481. JCOEFPTR inptr;
  175482. ISLOW_MULT_TYPE * quantptr;
  175483. int * wsptr;
  175484. JSAMPROW outptr;
  175485. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175486. int ctr;
  175487. int workspace[DCTSIZE2]; /* buffers data between passes */
  175488. SHIFT_TEMPS
  175489. /* Pass 1: process columns from input, store into work array. */
  175490. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175491. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175492. inptr = coef_block;
  175493. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175494. wsptr = workspace;
  175495. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175496. /* Due to quantization, we will usually find that many of the input
  175497. * coefficients are zero, especially the AC terms. We can exploit this
  175498. * by short-circuiting the IDCT calculation for any column in which all
  175499. * the AC terms are zero. In that case each output is equal to the
  175500. * DC coefficient (with scale factor as needed).
  175501. * With typical images and quantization tables, half or more of the
  175502. * column DCT calculations can be simplified this way.
  175503. */
  175504. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175505. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175506. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175507. inptr[DCTSIZE*7] == 0) {
  175508. /* AC terms all zero */
  175509. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175510. wsptr[DCTSIZE*0] = dcval;
  175511. wsptr[DCTSIZE*1] = dcval;
  175512. wsptr[DCTSIZE*2] = dcval;
  175513. wsptr[DCTSIZE*3] = dcval;
  175514. wsptr[DCTSIZE*4] = dcval;
  175515. wsptr[DCTSIZE*5] = dcval;
  175516. wsptr[DCTSIZE*6] = dcval;
  175517. wsptr[DCTSIZE*7] = dcval;
  175518. inptr++; /* advance pointers to next column */
  175519. quantptr++;
  175520. wsptr++;
  175521. continue;
  175522. }
  175523. /* Even part: reverse the even part of the forward DCT. */
  175524. /* The rotator is sqrt(2)*c(-6). */
  175525. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175526. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175527. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175528. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175529. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175530. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175531. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175532. tmp0 = (z2 + z3) << CONST_BITS;
  175533. tmp1 = (z2 - z3) << CONST_BITS;
  175534. tmp10 = tmp0 + tmp3;
  175535. tmp13 = tmp0 - tmp3;
  175536. tmp11 = tmp1 + tmp2;
  175537. tmp12 = tmp1 - tmp2;
  175538. /* Odd part per figure 8; the matrix is unitary and hence its
  175539. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175540. */
  175541. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175542. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175543. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175544. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175545. z1 = tmp0 + tmp3;
  175546. z2 = tmp1 + tmp2;
  175547. z3 = tmp0 + tmp2;
  175548. z4 = tmp1 + tmp3;
  175549. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175550. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175551. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175552. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175553. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175554. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175555. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175556. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175557. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175558. z3 += z5;
  175559. z4 += z5;
  175560. tmp0 += z1 + z3;
  175561. tmp1 += z2 + z4;
  175562. tmp2 += z2 + z3;
  175563. tmp3 += z1 + z4;
  175564. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175565. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175566. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175567. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175568. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175569. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175570. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175571. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175572. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175573. inptr++; /* advance pointers to next column */
  175574. quantptr++;
  175575. wsptr++;
  175576. }
  175577. /* Pass 2: process rows from work array, store into output array. */
  175578. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175579. /* and also undo the PASS1_BITS scaling. */
  175580. wsptr = workspace;
  175581. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175582. outptr = output_buf[ctr] + output_col;
  175583. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175584. * However, the column calculation has created many nonzero AC terms, so
  175585. * the simplification applies less often (typically 5% to 10% of the time).
  175586. * On machines with very fast multiplication, it's possible that the
  175587. * test takes more time than it's worth. In that case this section
  175588. * may be commented out.
  175589. */
  175590. #ifndef NO_ZERO_ROW_TEST
  175591. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175592. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175593. /* AC terms all zero */
  175594. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175595. & RANGE_MASK];
  175596. outptr[0] = dcval;
  175597. outptr[1] = dcval;
  175598. outptr[2] = dcval;
  175599. outptr[3] = dcval;
  175600. outptr[4] = dcval;
  175601. outptr[5] = dcval;
  175602. outptr[6] = dcval;
  175603. outptr[7] = dcval;
  175604. wsptr += DCTSIZE; /* advance pointer to next row */
  175605. continue;
  175606. }
  175607. #endif
  175608. /* Even part: reverse the even part of the forward DCT. */
  175609. /* The rotator is sqrt(2)*c(-6). */
  175610. z2 = (INT32) wsptr[2];
  175611. z3 = (INT32) wsptr[6];
  175612. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175613. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175614. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175615. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175616. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175617. tmp10 = tmp0 + tmp3;
  175618. tmp13 = tmp0 - tmp3;
  175619. tmp11 = tmp1 + tmp2;
  175620. tmp12 = tmp1 - tmp2;
  175621. /* Odd part per figure 8; the matrix is unitary and hence its
  175622. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175623. */
  175624. tmp0 = (INT32) wsptr[7];
  175625. tmp1 = (INT32) wsptr[5];
  175626. tmp2 = (INT32) wsptr[3];
  175627. tmp3 = (INT32) wsptr[1];
  175628. z1 = tmp0 + tmp3;
  175629. z2 = tmp1 + tmp2;
  175630. z3 = tmp0 + tmp2;
  175631. z4 = tmp1 + tmp3;
  175632. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175633. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175634. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175635. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175636. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175637. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175638. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175639. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175640. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175641. z3 += z5;
  175642. z4 += z5;
  175643. tmp0 += z1 + z3;
  175644. tmp1 += z2 + z4;
  175645. tmp2 += z2 + z3;
  175646. tmp3 += z1 + z4;
  175647. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175648. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175649. CONST_BITS+PASS1_BITS+3)
  175650. & RANGE_MASK];
  175651. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175652. CONST_BITS+PASS1_BITS+3)
  175653. & RANGE_MASK];
  175654. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175655. CONST_BITS+PASS1_BITS+3)
  175656. & RANGE_MASK];
  175657. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175658. CONST_BITS+PASS1_BITS+3)
  175659. & RANGE_MASK];
  175660. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175661. CONST_BITS+PASS1_BITS+3)
  175662. & RANGE_MASK];
  175663. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175664. CONST_BITS+PASS1_BITS+3)
  175665. & RANGE_MASK];
  175666. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175667. CONST_BITS+PASS1_BITS+3)
  175668. & RANGE_MASK];
  175669. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175670. CONST_BITS+PASS1_BITS+3)
  175671. & RANGE_MASK];
  175672. wsptr += DCTSIZE; /* advance pointer to next row */
  175673. }
  175674. }
  175675. #endif /* DCT_ISLOW_SUPPORTED */
  175676. /*** End of inlined file: jidctint.c ***/
  175677. /*** Start of inlined file: jidctred.c ***/
  175678. #define JPEG_INTERNALS
  175679. #ifdef IDCT_SCALING_SUPPORTED
  175680. /*
  175681. * This module is specialized to the case DCTSIZE = 8.
  175682. */
  175683. #if DCTSIZE != 8
  175684. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175685. #endif
  175686. /* Scaling is the same as in jidctint.c. */
  175687. #if BITS_IN_JSAMPLE == 8
  175688. #define CONST_BITS 13
  175689. #define PASS1_BITS 2
  175690. #else
  175691. #define CONST_BITS 13
  175692. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175693. #endif
  175694. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175695. * causing a lot of useless floating-point operations at run time.
  175696. * To get around this we use the following pre-calculated constants.
  175697. * If you change CONST_BITS you may want to add appropriate values.
  175698. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175699. */
  175700. #if CONST_BITS == 13
  175701. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175702. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175703. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175704. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175705. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175706. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175707. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175708. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175709. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175710. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175711. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175712. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175713. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175714. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175715. #else
  175716. #define FIX_0_211164243 FIX(0.211164243)
  175717. #define FIX_0_509795579 FIX(0.509795579)
  175718. #define FIX_0_601344887 FIX(0.601344887)
  175719. #define FIX_0_720959822 FIX(0.720959822)
  175720. #define FIX_0_765366865 FIX(0.765366865)
  175721. #define FIX_0_850430095 FIX(0.850430095)
  175722. #define FIX_0_899976223 FIX(0.899976223)
  175723. #define FIX_1_061594337 FIX(1.061594337)
  175724. #define FIX_1_272758580 FIX(1.272758580)
  175725. #define FIX_1_451774981 FIX(1.451774981)
  175726. #define FIX_1_847759065 FIX(1.847759065)
  175727. #define FIX_2_172734803 FIX(2.172734803)
  175728. #define FIX_2_562915447 FIX(2.562915447)
  175729. #define FIX_3_624509785 FIX(3.624509785)
  175730. #endif
  175731. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175732. * For 8-bit samples with the recommended scaling, all the variable
  175733. * and constant values involved are no more than 16 bits wide, so a
  175734. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175735. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175736. */
  175737. #if BITS_IN_JSAMPLE == 8
  175738. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175739. #else
  175740. #define MULTIPLY(var,const) ((var) * (const))
  175741. #endif
  175742. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175743. * entry; produce an int result. In this module, both inputs and result
  175744. * are 16 bits or less, so either int or short multiply will work.
  175745. */
  175746. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175747. /*
  175748. * Perform dequantization and inverse DCT on one block of coefficients,
  175749. * producing a reduced-size 4x4 output block.
  175750. */
  175751. GLOBAL(void)
  175752. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175753. JCOEFPTR coef_block,
  175754. JSAMPARRAY output_buf, JDIMENSION output_col)
  175755. {
  175756. INT32 tmp0, tmp2, tmp10, tmp12;
  175757. INT32 z1, z2, z3, z4;
  175758. JCOEFPTR inptr;
  175759. ISLOW_MULT_TYPE * quantptr;
  175760. int * wsptr;
  175761. JSAMPROW outptr;
  175762. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175763. int ctr;
  175764. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175765. SHIFT_TEMPS
  175766. /* Pass 1: process columns from input, store into work array. */
  175767. inptr = coef_block;
  175768. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175769. wsptr = workspace;
  175770. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175771. /* Don't bother to process column 4, because second pass won't use it */
  175772. if (ctr == DCTSIZE-4)
  175773. continue;
  175774. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175775. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175776. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175777. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175778. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175779. wsptr[DCTSIZE*0] = dcval;
  175780. wsptr[DCTSIZE*1] = dcval;
  175781. wsptr[DCTSIZE*2] = dcval;
  175782. wsptr[DCTSIZE*3] = dcval;
  175783. continue;
  175784. }
  175785. /* Even part */
  175786. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175787. tmp0 <<= (CONST_BITS+1);
  175788. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175789. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175790. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175791. tmp10 = tmp0 + tmp2;
  175792. tmp12 = tmp0 - tmp2;
  175793. /* Odd part */
  175794. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175795. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175796. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175797. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175798. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175799. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175800. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175801. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175802. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175803. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175804. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175805. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175806. /* Final output stage */
  175807. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175808. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175809. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175810. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175811. }
  175812. /* Pass 2: process 4 rows from work array, store into output array. */
  175813. wsptr = workspace;
  175814. for (ctr = 0; ctr < 4; ctr++) {
  175815. outptr = output_buf[ctr] + output_col;
  175816. /* It's not clear whether a zero row test is worthwhile here ... */
  175817. #ifndef NO_ZERO_ROW_TEST
  175818. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175819. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175820. /* AC terms all zero */
  175821. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175822. & RANGE_MASK];
  175823. outptr[0] = dcval;
  175824. outptr[1] = dcval;
  175825. outptr[2] = dcval;
  175826. outptr[3] = dcval;
  175827. wsptr += DCTSIZE; /* advance pointer to next row */
  175828. continue;
  175829. }
  175830. #endif
  175831. /* Even part */
  175832. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175833. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175834. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175835. tmp10 = tmp0 + tmp2;
  175836. tmp12 = tmp0 - tmp2;
  175837. /* Odd part */
  175838. z1 = (INT32) wsptr[7];
  175839. z2 = (INT32) wsptr[5];
  175840. z3 = (INT32) wsptr[3];
  175841. z4 = (INT32) wsptr[1];
  175842. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175843. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175844. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175845. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175846. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175847. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175848. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175849. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175850. /* Final output stage */
  175851. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175852. CONST_BITS+PASS1_BITS+3+1)
  175853. & RANGE_MASK];
  175854. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175855. CONST_BITS+PASS1_BITS+3+1)
  175856. & RANGE_MASK];
  175857. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175858. CONST_BITS+PASS1_BITS+3+1)
  175859. & RANGE_MASK];
  175860. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175861. CONST_BITS+PASS1_BITS+3+1)
  175862. & RANGE_MASK];
  175863. wsptr += DCTSIZE; /* advance pointer to next row */
  175864. }
  175865. }
  175866. /*
  175867. * Perform dequantization and inverse DCT on one block of coefficients,
  175868. * producing a reduced-size 2x2 output block.
  175869. */
  175870. GLOBAL(void)
  175871. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175872. JCOEFPTR coef_block,
  175873. JSAMPARRAY output_buf, JDIMENSION output_col)
  175874. {
  175875. INT32 tmp0, tmp10, z1;
  175876. JCOEFPTR inptr;
  175877. ISLOW_MULT_TYPE * quantptr;
  175878. int * wsptr;
  175879. JSAMPROW outptr;
  175880. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175881. int ctr;
  175882. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175883. SHIFT_TEMPS
  175884. /* Pass 1: process columns from input, store into work array. */
  175885. inptr = coef_block;
  175886. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175887. wsptr = workspace;
  175888. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175889. /* Don't bother to process columns 2,4,6 */
  175890. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175891. continue;
  175892. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175893. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175894. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175895. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175896. wsptr[DCTSIZE*0] = dcval;
  175897. wsptr[DCTSIZE*1] = dcval;
  175898. continue;
  175899. }
  175900. /* Even part */
  175901. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175902. tmp10 = z1 << (CONST_BITS+2);
  175903. /* Odd part */
  175904. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175905. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175906. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175907. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175908. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175909. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175910. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175911. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175912. /* Final output stage */
  175913. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175914. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175915. }
  175916. /* Pass 2: process 2 rows from work array, store into output array. */
  175917. wsptr = workspace;
  175918. for (ctr = 0; ctr < 2; ctr++) {
  175919. outptr = output_buf[ctr] + output_col;
  175920. /* It's not clear whether a zero row test is worthwhile here ... */
  175921. #ifndef NO_ZERO_ROW_TEST
  175922. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175923. /* AC terms all zero */
  175924. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175925. & RANGE_MASK];
  175926. outptr[0] = dcval;
  175927. outptr[1] = dcval;
  175928. wsptr += DCTSIZE; /* advance pointer to next row */
  175929. continue;
  175930. }
  175931. #endif
  175932. /* Even part */
  175933. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175934. /* Odd part */
  175935. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175936. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175937. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175938. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175939. /* Final output stage */
  175940. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175941. CONST_BITS+PASS1_BITS+3+2)
  175942. & RANGE_MASK];
  175943. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175944. CONST_BITS+PASS1_BITS+3+2)
  175945. & RANGE_MASK];
  175946. wsptr += DCTSIZE; /* advance pointer to next row */
  175947. }
  175948. }
  175949. /*
  175950. * Perform dequantization and inverse DCT on one block of coefficients,
  175951. * producing a reduced-size 1x1 output block.
  175952. */
  175953. GLOBAL(void)
  175954. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175955. JCOEFPTR coef_block,
  175956. JSAMPARRAY output_buf, JDIMENSION output_col)
  175957. {
  175958. int dcval;
  175959. ISLOW_MULT_TYPE * quantptr;
  175960. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175961. SHIFT_TEMPS
  175962. /* We hardly need an inverse DCT routine for this: just take the
  175963. * average pixel value, which is one-eighth of the DC coefficient.
  175964. */
  175965. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175966. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175967. dcval = (int) DESCALE((INT32) dcval, 3);
  175968. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175969. }
  175970. #endif /* IDCT_SCALING_SUPPORTED */
  175971. /*** End of inlined file: jidctred.c ***/
  175972. /*** Start of inlined file: jmemmgr.c ***/
  175973. #define JPEG_INTERNALS
  175974. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175975. /*** Start of inlined file: jmemsys.h ***/
  175976. #ifndef __jmemsys_h__
  175977. #define __jmemsys_h__
  175978. /* Short forms of external names for systems with brain-damaged linkers. */
  175979. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175980. #define jpeg_get_small jGetSmall
  175981. #define jpeg_free_small jFreeSmall
  175982. #define jpeg_get_large jGetLarge
  175983. #define jpeg_free_large jFreeLarge
  175984. #define jpeg_mem_available jMemAvail
  175985. #define jpeg_open_backing_store jOpenBackStore
  175986. #define jpeg_mem_init jMemInit
  175987. #define jpeg_mem_term jMemTerm
  175988. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175989. /*
  175990. * These two functions are used to allocate and release small chunks of
  175991. * memory. (Typically the total amount requested through jpeg_get_small is
  175992. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175993. * Behavior should be the same as for the standard library functions malloc
  175994. * and free; in particular, jpeg_get_small must return NULL on failure.
  175995. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175996. * size of the object being freed, just in case it's needed.
  175997. * On an 80x86 machine using small-data memory model, these manage near heap.
  175998. */
  175999. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  176000. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  176001. size_t sizeofobject));
  176002. /*
  176003. * These two functions are used to allocate and release large chunks of
  176004. * memory (up to the total free space designated by jpeg_mem_available).
  176005. * The interface is the same as above, except that on an 80x86 machine,
  176006. * far pointers are used. On most other machines these are identical to
  176007. * the jpeg_get/free_small routines; but we keep them separate anyway,
  176008. * in case a different allocation strategy is desirable for large chunks.
  176009. */
  176010. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  176011. size_t sizeofobject));
  176012. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  176013. size_t sizeofobject));
  176014. /*
  176015. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  176016. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  176017. * matter, but that case should never come into play). This macro is needed
  176018. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  176019. * On those machines, we expect that jconfig.h will provide a proper value.
  176020. * On machines with 32-bit flat address spaces, any large constant may be used.
  176021. *
  176022. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  176023. * size_t and will be a multiple of sizeof(align_type).
  176024. */
  176025. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  176026. #define MAX_ALLOC_CHUNK 1000000000L
  176027. #endif
  176028. /*
  176029. * This routine computes the total space still available for allocation by
  176030. * jpeg_get_large. If more space than this is needed, backing store will be
  176031. * used. NOTE: any memory already allocated must not be counted.
  176032. *
  176033. * There is a minimum space requirement, corresponding to the minimum
  176034. * feasible buffer sizes; jmemmgr.c will request that much space even if
  176035. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  176036. * all working storage in memory, is also passed in case it is useful.
  176037. * Finally, the total space already allocated is passed. If no better
  176038. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  176039. * is often a suitable calculation.
  176040. *
  176041. * It is OK for jpeg_mem_available to underestimate the space available
  176042. * (that'll just lead to more backing-store access than is really necessary).
  176043. * However, an overestimate will lead to failure. Hence it's wise to subtract
  176044. * a slop factor from the true available space. 5% should be enough.
  176045. *
  176046. * On machines with lots of virtual memory, any large constant may be returned.
  176047. * Conversely, zero may be returned to always use the minimum amount of memory.
  176048. */
  176049. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  176050. long min_bytes_needed,
  176051. long max_bytes_needed,
  176052. long already_allocated));
  176053. /*
  176054. * This structure holds whatever state is needed to access a single
  176055. * backing-store object. The read/write/close method pointers are called
  176056. * by jmemmgr.c to manipulate the backing-store object; all other fields
  176057. * are private to the system-dependent backing store routines.
  176058. */
  176059. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  176060. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  176061. typedef unsigned short XMSH; /* type of extended-memory handles */
  176062. typedef unsigned short EMSH; /* type of expanded-memory handles */
  176063. typedef union {
  176064. short file_handle; /* DOS file handle if it's a temp file */
  176065. XMSH xms_handle; /* handle if it's a chunk of XMS */
  176066. EMSH ems_handle; /* handle if it's a chunk of EMS */
  176067. } handle_union;
  176068. #endif /* USE_MSDOS_MEMMGR */
  176069. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  176070. #include <Files.h>
  176071. #endif /* USE_MAC_MEMMGR */
  176072. //typedef struct backing_store_struct * backing_store_ptr;
  176073. typedef struct backing_store_struct {
  176074. /* Methods for reading/writing/closing this backing-store object */
  176075. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  176076. struct backing_store_struct *info,
  176077. void FAR * buffer_address,
  176078. long file_offset, long byte_count));
  176079. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  176080. struct backing_store_struct *info,
  176081. void FAR * buffer_address,
  176082. long file_offset, long byte_count));
  176083. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  176084. struct backing_store_struct *info));
  176085. /* Private fields for system-dependent backing-store management */
  176086. #ifdef USE_MSDOS_MEMMGR
  176087. /* For the MS-DOS manager (jmemdos.c), we need: */
  176088. handle_union handle; /* reference to backing-store storage object */
  176089. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176090. #else
  176091. #ifdef USE_MAC_MEMMGR
  176092. /* For the Mac manager (jmemmac.c), we need: */
  176093. short temp_file; /* file reference number to temp file */
  176094. FSSpec tempSpec; /* the FSSpec for the temp file */
  176095. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176096. #else
  176097. /* For a typical implementation with temp files, we need: */
  176098. FILE * temp_file; /* stdio reference to temp file */
  176099. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  176100. #endif
  176101. #endif
  176102. } backing_store_info;
  176103. /*
  176104. * Initial opening of a backing-store object. This must fill in the
  176105. * read/write/close pointers in the object. The read/write routines
  176106. * may take an error exit if the specified maximum file size is exceeded.
  176107. * (If jpeg_mem_available always returns a large value, this routine can
  176108. * just take an error exit.)
  176109. */
  176110. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  176111. struct backing_store_struct *info,
  176112. long total_bytes_needed));
  176113. /*
  176114. * These routines take care of any system-dependent initialization and
  176115. * cleanup required. jpeg_mem_init will be called before anything is
  176116. * allocated (and, therefore, nothing in cinfo is of use except the error
  176117. * manager pointer). It should return a suitable default value for
  176118. * max_memory_to_use; this may subsequently be overridden by the surrounding
  176119. * application. (Note that max_memory_to_use is only important if
  176120. * jpeg_mem_available chooses to consult it ... no one else will.)
  176121. * jpeg_mem_term may assume that all requested memory has been freed and that
  176122. * all opened backing-store objects have been closed.
  176123. */
  176124. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  176125. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  176126. #endif
  176127. /*** End of inlined file: jmemsys.h ***/
  176128. /* import the system-dependent declarations */
  176129. #ifndef NO_GETENV
  176130. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  176131. extern char * getenv JPP((const char * name));
  176132. #endif
  176133. #endif
  176134. /*
  176135. * Some important notes:
  176136. * The allocation routines provided here must never return NULL.
  176137. * They should exit to error_exit if unsuccessful.
  176138. *
  176139. * It's not a good idea to try to merge the sarray and barray routines,
  176140. * even though they are textually almost the same, because samples are
  176141. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176142. * in machines where byte pointers have a different representation from
  176143. * word pointers, the resulting machine code could not be the same.
  176144. */
  176145. /*
  176146. * Many machines require storage alignment: longs must start on 4-byte
  176147. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176148. * always returns pointers that are multiples of the worst-case alignment
  176149. * requirement, and we had better do so too.
  176150. * There isn't any really portable way to determine the worst-case alignment
  176151. * requirement. This module assumes that the alignment requirement is
  176152. * multiples of sizeof(ALIGN_TYPE).
  176153. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176154. * workstations (where doubles really do need 8-byte alignment) and will work
  176155. * fine on nearly everything. If your machine has lesser alignment needs,
  176156. * you can save a few bytes by making ALIGN_TYPE smaller.
  176157. * The only place I know of where this will NOT work is certain Macintosh
  176158. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176159. * Doing 10-byte alignment is counterproductive because longwords won't be
  176160. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176161. * such a compiler.
  176162. */
  176163. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176164. #define ALIGN_TYPE double
  176165. #endif
  176166. /*
  176167. * We allocate objects from "pools", where each pool is gotten with a single
  176168. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176169. * overhead within a pool, except for alignment padding. Each pool has a
  176170. * header with a link to the next pool of the same class.
  176171. * Small and large pool headers are identical except that the latter's
  176172. * link pointer must be FAR on 80x86 machines.
  176173. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176174. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176175. * of the alignment requirement of ALIGN_TYPE.
  176176. */
  176177. typedef union small_pool_struct * small_pool_ptr;
  176178. typedef union small_pool_struct {
  176179. struct {
  176180. small_pool_ptr next; /* next in list of pools */
  176181. size_t bytes_used; /* how many bytes already used within pool */
  176182. size_t bytes_left; /* bytes still available in this pool */
  176183. } hdr;
  176184. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176185. } small_pool_hdr;
  176186. typedef union large_pool_struct FAR * large_pool_ptr;
  176187. typedef union large_pool_struct {
  176188. struct {
  176189. large_pool_ptr next; /* next in list of pools */
  176190. size_t bytes_used; /* how many bytes already used within pool */
  176191. size_t bytes_left; /* bytes still available in this pool */
  176192. } hdr;
  176193. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176194. } large_pool_hdr;
  176195. /*
  176196. * Here is the full definition of a memory manager object.
  176197. */
  176198. typedef struct {
  176199. struct jpeg_memory_mgr pub; /* public fields */
  176200. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176201. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176202. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176203. /* Since we only have one lifetime class of virtual arrays, only one
  176204. * linked list is necessary (for each datatype). Note that the virtual
  176205. * array control blocks being linked together are actually stored somewhere
  176206. * in the small-pool list.
  176207. */
  176208. jvirt_sarray_ptr virt_sarray_list;
  176209. jvirt_barray_ptr virt_barray_list;
  176210. /* This counts total space obtained from jpeg_get_small/large */
  176211. long total_space_allocated;
  176212. /* alloc_sarray and alloc_barray set this value for use by virtual
  176213. * array routines.
  176214. */
  176215. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176216. } my_memory_mgr;
  176217. typedef my_memory_mgr * my_mem_ptr;
  176218. /*
  176219. * The control blocks for virtual arrays.
  176220. * Note that these blocks are allocated in the "small" pool area.
  176221. * System-dependent info for the associated backing store (if any) is hidden
  176222. * inside the backing_store_info struct.
  176223. */
  176224. struct jvirt_sarray_control {
  176225. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176226. JDIMENSION rows_in_array; /* total virtual array height */
  176227. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176228. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176229. JDIMENSION rows_in_mem; /* height of memory buffer */
  176230. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176231. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176232. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176233. boolean pre_zero; /* pre-zero mode requested? */
  176234. boolean dirty; /* do current buffer contents need written? */
  176235. boolean b_s_open; /* is backing-store data valid? */
  176236. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176237. backing_store_info b_s_info; /* System-dependent control info */
  176238. };
  176239. struct jvirt_barray_control {
  176240. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176241. JDIMENSION rows_in_array; /* total virtual array height */
  176242. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176243. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176244. JDIMENSION rows_in_mem; /* height of memory buffer */
  176245. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176246. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176247. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176248. boolean pre_zero; /* pre-zero mode requested? */
  176249. boolean dirty; /* do current buffer contents need written? */
  176250. boolean b_s_open; /* is backing-store data valid? */
  176251. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176252. backing_store_info b_s_info; /* System-dependent control info */
  176253. };
  176254. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176255. LOCAL(void)
  176256. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176257. {
  176258. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176259. small_pool_ptr shdr_ptr;
  176260. large_pool_ptr lhdr_ptr;
  176261. /* Since this is only a debugging stub, we can cheat a little by using
  176262. * fprintf directly rather than going through the trace message code.
  176263. * This is helpful because message parm array can't handle longs.
  176264. */
  176265. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176266. pool_id, mem->total_space_allocated);
  176267. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176268. lhdr_ptr = lhdr_ptr->hdr.next) {
  176269. fprintf(stderr, " Large chunk used %ld\n",
  176270. (long) lhdr_ptr->hdr.bytes_used);
  176271. }
  176272. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176273. shdr_ptr = shdr_ptr->hdr.next) {
  176274. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176275. (long) shdr_ptr->hdr.bytes_used,
  176276. (long) shdr_ptr->hdr.bytes_left);
  176277. }
  176278. }
  176279. #endif /* MEM_STATS */
  176280. LOCAL(void)
  176281. out_of_memory (j_common_ptr cinfo, int which)
  176282. /* Report an out-of-memory error and stop execution */
  176283. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176284. {
  176285. #ifdef MEM_STATS
  176286. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176287. #endif
  176288. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176289. }
  176290. /*
  176291. * Allocation of "small" objects.
  176292. *
  176293. * For these, we use pooled storage. When a new pool must be created,
  176294. * we try to get enough space for the current request plus a "slop" factor,
  176295. * where the slop will be the amount of leftover space in the new pool.
  176296. * The speed vs. space tradeoff is largely determined by the slop values.
  176297. * A different slop value is provided for each pool class (lifetime),
  176298. * and we also distinguish the first pool of a class from later ones.
  176299. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176300. * machines, but may be too small if longs are 64 bits or more.
  176301. */
  176302. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176303. {
  176304. 1600, /* first PERMANENT pool */
  176305. 16000 /* first IMAGE pool */
  176306. };
  176307. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176308. {
  176309. 0, /* additional PERMANENT pools */
  176310. 5000 /* additional IMAGE pools */
  176311. };
  176312. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176313. METHODDEF(void *)
  176314. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176315. /* Allocate a "small" object */
  176316. {
  176317. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176318. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176319. char * data_ptr;
  176320. size_t odd_bytes, min_request, slop;
  176321. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176322. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176323. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176324. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176325. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176326. if (odd_bytes > 0)
  176327. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176328. /* See if space is available in any existing pool */
  176329. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176330. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176331. prev_hdr_ptr = NULL;
  176332. hdr_ptr = mem->small_list[pool_id];
  176333. while (hdr_ptr != NULL) {
  176334. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176335. break; /* found pool with enough space */
  176336. prev_hdr_ptr = hdr_ptr;
  176337. hdr_ptr = hdr_ptr->hdr.next;
  176338. }
  176339. /* Time to make a new pool? */
  176340. if (hdr_ptr == NULL) {
  176341. /* min_request is what we need now, slop is what will be leftover */
  176342. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176343. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176344. slop = first_pool_slop[pool_id];
  176345. else
  176346. slop = extra_pool_slop[pool_id];
  176347. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176348. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176349. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176350. /* Try to get space, if fail reduce slop and try again */
  176351. for (;;) {
  176352. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176353. if (hdr_ptr != NULL)
  176354. break;
  176355. slop /= 2;
  176356. if (slop < MIN_SLOP) /* give up when it gets real small */
  176357. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176358. }
  176359. mem->total_space_allocated += min_request + slop;
  176360. /* Success, initialize the new pool header and add to end of list */
  176361. hdr_ptr->hdr.next = NULL;
  176362. hdr_ptr->hdr.bytes_used = 0;
  176363. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176364. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176365. mem->small_list[pool_id] = hdr_ptr;
  176366. else
  176367. prev_hdr_ptr->hdr.next = hdr_ptr;
  176368. }
  176369. /* OK, allocate the object from the current pool */
  176370. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176371. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176372. hdr_ptr->hdr.bytes_used += sizeofobject;
  176373. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176374. return (void *) data_ptr;
  176375. }
  176376. /*
  176377. * Allocation of "large" objects.
  176378. *
  176379. * The external semantics of these are the same as "small" objects,
  176380. * except that FAR pointers are used on 80x86. However the pool
  176381. * management heuristics are quite different. We assume that each
  176382. * request is large enough that it may as well be passed directly to
  176383. * jpeg_get_large; the pool management just links everything together
  176384. * so that we can free it all on demand.
  176385. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176386. * structures. The routines that create these structures (see below)
  176387. * deliberately bunch rows together to ensure a large request size.
  176388. */
  176389. METHODDEF(void FAR *)
  176390. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176391. /* Allocate a "large" object */
  176392. {
  176393. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176394. large_pool_ptr hdr_ptr;
  176395. size_t odd_bytes;
  176396. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176397. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176398. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176399. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176400. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176401. if (odd_bytes > 0)
  176402. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176403. /* Always make a new pool */
  176404. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176405. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176406. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176407. SIZEOF(large_pool_hdr));
  176408. if (hdr_ptr == NULL)
  176409. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176410. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176411. /* Success, initialize the new pool header and add to list */
  176412. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176413. /* We maintain space counts in each pool header for statistical purposes,
  176414. * even though they are not needed for allocation.
  176415. */
  176416. hdr_ptr->hdr.bytes_used = sizeofobject;
  176417. hdr_ptr->hdr.bytes_left = 0;
  176418. mem->large_list[pool_id] = hdr_ptr;
  176419. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176420. }
  176421. /*
  176422. * Creation of 2-D sample arrays.
  176423. * The pointers are in near heap, the samples themselves in FAR heap.
  176424. *
  176425. * To minimize allocation overhead and to allow I/O of large contiguous
  176426. * blocks, we allocate the sample rows in groups of as many rows as possible
  176427. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176428. * NB: the virtual array control routines, later in this file, know about
  176429. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176430. * object so that it can be saved away if this sarray is the workspace for
  176431. * a virtual array.
  176432. */
  176433. METHODDEF(JSAMPARRAY)
  176434. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176435. JDIMENSION samplesperrow, JDIMENSION numrows)
  176436. /* Allocate a 2-D sample array */
  176437. {
  176438. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176439. JSAMPARRAY result;
  176440. JSAMPROW workspace;
  176441. JDIMENSION rowsperchunk, currow, i;
  176442. long ltemp;
  176443. /* Calculate max # of rows allowed in one allocation chunk */
  176444. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176445. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176446. if (ltemp <= 0)
  176447. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176448. if (ltemp < (long) numrows)
  176449. rowsperchunk = (JDIMENSION) ltemp;
  176450. else
  176451. rowsperchunk = numrows;
  176452. mem->last_rowsperchunk = rowsperchunk;
  176453. /* Get space for row pointers (small object) */
  176454. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176455. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176456. /* Get the rows themselves (large objects) */
  176457. currow = 0;
  176458. while (currow < numrows) {
  176459. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176460. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176461. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176462. * SIZEOF(JSAMPLE)));
  176463. for (i = rowsperchunk; i > 0; i--) {
  176464. result[currow++] = workspace;
  176465. workspace += samplesperrow;
  176466. }
  176467. }
  176468. return result;
  176469. }
  176470. /*
  176471. * Creation of 2-D coefficient-block arrays.
  176472. * This is essentially the same as the code for sample arrays, above.
  176473. */
  176474. METHODDEF(JBLOCKARRAY)
  176475. alloc_barray (j_common_ptr cinfo, int pool_id,
  176476. JDIMENSION blocksperrow, JDIMENSION numrows)
  176477. /* Allocate a 2-D coefficient-block array */
  176478. {
  176479. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176480. JBLOCKARRAY result;
  176481. JBLOCKROW workspace;
  176482. JDIMENSION rowsperchunk, currow, i;
  176483. long ltemp;
  176484. /* Calculate max # of rows allowed in one allocation chunk */
  176485. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176486. ((long) blocksperrow * SIZEOF(JBLOCK));
  176487. if (ltemp <= 0)
  176488. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176489. if (ltemp < (long) numrows)
  176490. rowsperchunk = (JDIMENSION) ltemp;
  176491. else
  176492. rowsperchunk = numrows;
  176493. mem->last_rowsperchunk = rowsperchunk;
  176494. /* Get space for row pointers (small object) */
  176495. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176496. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176497. /* Get the rows themselves (large objects) */
  176498. currow = 0;
  176499. while (currow < numrows) {
  176500. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176501. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176502. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176503. * SIZEOF(JBLOCK)));
  176504. for (i = rowsperchunk; i > 0; i--) {
  176505. result[currow++] = workspace;
  176506. workspace += blocksperrow;
  176507. }
  176508. }
  176509. return result;
  176510. }
  176511. /*
  176512. * About virtual array management:
  176513. *
  176514. * The above "normal" array routines are only used to allocate strip buffers
  176515. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176516. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176517. * time, but the memory manager must save the whole array for repeated
  176518. * accesses. The intended implementation is that there is a strip buffer in
  176519. * memory (as high as is possible given the desired memory limit), plus a
  176520. * backing file that holds the rest of the array.
  176521. *
  176522. * The request_virt_array routines are told the total size of the image and
  176523. * the maximum number of rows that will be accessed at once. The in-memory
  176524. * buffer must be at least as large as the maxaccess value.
  176525. *
  176526. * The request routines create control blocks but not the in-memory buffers.
  176527. * That is postponed until realize_virt_arrays is called. At that time the
  176528. * total amount of space needed is known (approximately, anyway), so free
  176529. * memory can be divided up fairly.
  176530. *
  176531. * The access_virt_array routines are responsible for making a specific strip
  176532. * area accessible (after reading or writing the backing file, if necessary).
  176533. * Note that the access routines are told whether the caller intends to modify
  176534. * the accessed strip; during a read-only pass this saves having to rewrite
  176535. * data to disk. The access routines are also responsible for pre-zeroing
  176536. * any newly accessed rows, if pre-zeroing was requested.
  176537. *
  176538. * In current usage, the access requests are usually for nonoverlapping
  176539. * strips; that is, successive access start_row numbers differ by exactly
  176540. * num_rows = maxaccess. This means we can get good performance with simple
  176541. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176542. * of the access height; then there will never be accesses across bufferload
  176543. * boundaries. The code will still work with overlapping access requests,
  176544. * but it doesn't handle bufferload overlaps very efficiently.
  176545. */
  176546. METHODDEF(jvirt_sarray_ptr)
  176547. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176548. JDIMENSION samplesperrow, JDIMENSION numrows,
  176549. JDIMENSION maxaccess)
  176550. /* Request a virtual 2-D sample array */
  176551. {
  176552. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176553. jvirt_sarray_ptr result;
  176554. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176555. if (pool_id != JPOOL_IMAGE)
  176556. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176557. /* get control block */
  176558. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176559. SIZEOF(struct jvirt_sarray_control));
  176560. result->mem_buffer = NULL; /* marks array not yet realized */
  176561. result->rows_in_array = numrows;
  176562. result->samplesperrow = samplesperrow;
  176563. result->maxaccess = maxaccess;
  176564. result->pre_zero = pre_zero;
  176565. result->b_s_open = FALSE; /* no associated backing-store object */
  176566. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176567. mem->virt_sarray_list = result;
  176568. return result;
  176569. }
  176570. METHODDEF(jvirt_barray_ptr)
  176571. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176572. JDIMENSION blocksperrow, JDIMENSION numrows,
  176573. JDIMENSION maxaccess)
  176574. /* Request a virtual 2-D coefficient-block array */
  176575. {
  176576. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176577. jvirt_barray_ptr result;
  176578. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176579. if (pool_id != JPOOL_IMAGE)
  176580. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176581. /* get control block */
  176582. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176583. SIZEOF(struct jvirt_barray_control));
  176584. result->mem_buffer = NULL; /* marks array not yet realized */
  176585. result->rows_in_array = numrows;
  176586. result->blocksperrow = blocksperrow;
  176587. result->maxaccess = maxaccess;
  176588. result->pre_zero = pre_zero;
  176589. result->b_s_open = FALSE; /* no associated backing-store object */
  176590. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176591. mem->virt_barray_list = result;
  176592. return result;
  176593. }
  176594. METHODDEF(void)
  176595. realize_virt_arrays (j_common_ptr cinfo)
  176596. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176597. {
  176598. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176599. long space_per_minheight, maximum_space, avail_mem;
  176600. long minheights, max_minheights;
  176601. jvirt_sarray_ptr sptr;
  176602. jvirt_barray_ptr bptr;
  176603. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176604. * and the maximum space needed (full image height in each buffer).
  176605. * These may be of use to the system-dependent jpeg_mem_available routine.
  176606. */
  176607. space_per_minheight = 0;
  176608. maximum_space = 0;
  176609. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176610. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176611. space_per_minheight += (long) sptr->maxaccess *
  176612. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176613. maximum_space += (long) sptr->rows_in_array *
  176614. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176615. }
  176616. }
  176617. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176618. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176619. space_per_minheight += (long) bptr->maxaccess *
  176620. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176621. maximum_space += (long) bptr->rows_in_array *
  176622. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176623. }
  176624. }
  176625. if (space_per_minheight <= 0)
  176626. return; /* no unrealized arrays, no work */
  176627. /* Determine amount of memory to actually use; this is system-dependent. */
  176628. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176629. mem->total_space_allocated);
  176630. /* If the maximum space needed is available, make all the buffers full
  176631. * height; otherwise parcel it out with the same number of minheights
  176632. * in each buffer.
  176633. */
  176634. if (avail_mem >= maximum_space)
  176635. max_minheights = 1000000000L;
  176636. else {
  176637. max_minheights = avail_mem / space_per_minheight;
  176638. /* If there doesn't seem to be enough space, try to get the minimum
  176639. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176640. */
  176641. if (max_minheights <= 0)
  176642. max_minheights = 1;
  176643. }
  176644. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176645. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176646. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176647. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176648. if (minheights <= max_minheights) {
  176649. /* This buffer fits in memory */
  176650. sptr->rows_in_mem = sptr->rows_in_array;
  176651. } else {
  176652. /* It doesn't fit in memory, create backing store. */
  176653. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176654. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176655. (long) sptr->rows_in_array *
  176656. (long) sptr->samplesperrow *
  176657. (long) SIZEOF(JSAMPLE));
  176658. sptr->b_s_open = TRUE;
  176659. }
  176660. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176661. sptr->samplesperrow, sptr->rows_in_mem);
  176662. sptr->rowsperchunk = mem->last_rowsperchunk;
  176663. sptr->cur_start_row = 0;
  176664. sptr->first_undef_row = 0;
  176665. sptr->dirty = FALSE;
  176666. }
  176667. }
  176668. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176669. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176670. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176671. if (minheights <= max_minheights) {
  176672. /* This buffer fits in memory */
  176673. bptr->rows_in_mem = bptr->rows_in_array;
  176674. } else {
  176675. /* It doesn't fit in memory, create backing store. */
  176676. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176677. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176678. (long) bptr->rows_in_array *
  176679. (long) bptr->blocksperrow *
  176680. (long) SIZEOF(JBLOCK));
  176681. bptr->b_s_open = TRUE;
  176682. }
  176683. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176684. bptr->blocksperrow, bptr->rows_in_mem);
  176685. bptr->rowsperchunk = mem->last_rowsperchunk;
  176686. bptr->cur_start_row = 0;
  176687. bptr->first_undef_row = 0;
  176688. bptr->dirty = FALSE;
  176689. }
  176690. }
  176691. }
  176692. LOCAL(void)
  176693. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176694. /* Do backing store read or write of a virtual sample array */
  176695. {
  176696. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176697. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176698. file_offset = ptr->cur_start_row * bytesperrow;
  176699. /* Loop to read or write each allocation chunk in mem_buffer */
  176700. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176701. /* One chunk, but check for short chunk at end of buffer */
  176702. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176703. /* Transfer no more than is currently defined */
  176704. thisrow = (long) ptr->cur_start_row + i;
  176705. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176706. /* Transfer no more than fits in file */
  176707. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176708. if (rows <= 0) /* this chunk might be past end of file! */
  176709. break;
  176710. byte_count = rows * bytesperrow;
  176711. if (writing)
  176712. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176713. (void FAR *) ptr->mem_buffer[i],
  176714. file_offset, byte_count);
  176715. else
  176716. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176717. (void FAR *) ptr->mem_buffer[i],
  176718. file_offset, byte_count);
  176719. file_offset += byte_count;
  176720. }
  176721. }
  176722. LOCAL(void)
  176723. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176724. /* Do backing store read or write of a virtual coefficient-block array */
  176725. {
  176726. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176727. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176728. file_offset = ptr->cur_start_row * bytesperrow;
  176729. /* Loop to read or write each allocation chunk in mem_buffer */
  176730. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176731. /* One chunk, but check for short chunk at end of buffer */
  176732. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176733. /* Transfer no more than is currently defined */
  176734. thisrow = (long) ptr->cur_start_row + i;
  176735. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176736. /* Transfer no more than fits in file */
  176737. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176738. if (rows <= 0) /* this chunk might be past end of file! */
  176739. break;
  176740. byte_count = rows * bytesperrow;
  176741. if (writing)
  176742. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176743. (void FAR *) ptr->mem_buffer[i],
  176744. file_offset, byte_count);
  176745. else
  176746. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176747. (void FAR *) ptr->mem_buffer[i],
  176748. file_offset, byte_count);
  176749. file_offset += byte_count;
  176750. }
  176751. }
  176752. METHODDEF(JSAMPARRAY)
  176753. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176754. JDIMENSION start_row, JDIMENSION num_rows,
  176755. boolean writable)
  176756. /* Access the part of a virtual sample array starting at start_row */
  176757. /* and extending for num_rows rows. writable is true if */
  176758. /* caller intends to modify the accessed area. */
  176759. {
  176760. JDIMENSION end_row = start_row + num_rows;
  176761. JDIMENSION undef_row;
  176762. /* debugging check */
  176763. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176764. ptr->mem_buffer == NULL)
  176765. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176766. /* Make the desired part of the virtual array accessible */
  176767. if (start_row < ptr->cur_start_row ||
  176768. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176769. if (! ptr->b_s_open)
  176770. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176771. /* Flush old buffer contents if necessary */
  176772. if (ptr->dirty) {
  176773. do_sarray_io(cinfo, ptr, TRUE);
  176774. ptr->dirty = FALSE;
  176775. }
  176776. /* Decide what part of virtual array to access.
  176777. * Algorithm: if target address > current window, assume forward scan,
  176778. * load starting at target address. If target address < current window,
  176779. * assume backward scan, load so that target area is top of window.
  176780. * Note that when switching from forward write to forward read, will have
  176781. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176782. */
  176783. if (start_row > ptr->cur_start_row) {
  176784. ptr->cur_start_row = start_row;
  176785. } else {
  176786. /* use long arithmetic here to avoid overflow & unsigned problems */
  176787. long ltemp;
  176788. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176789. if (ltemp < 0)
  176790. ltemp = 0; /* don't fall off front end of file */
  176791. ptr->cur_start_row = (JDIMENSION) ltemp;
  176792. }
  176793. /* Read in the selected part of the array.
  176794. * During the initial write pass, we will do no actual read
  176795. * because the selected part is all undefined.
  176796. */
  176797. do_sarray_io(cinfo, ptr, FALSE);
  176798. }
  176799. /* Ensure the accessed part of the array is defined; prezero if needed.
  176800. * To improve locality of access, we only prezero the part of the array
  176801. * that the caller is about to access, not the entire in-memory array.
  176802. */
  176803. if (ptr->first_undef_row < end_row) {
  176804. if (ptr->first_undef_row < start_row) {
  176805. if (writable) /* writer skipped over a section of array */
  176806. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176807. undef_row = start_row; /* but reader is allowed to read ahead */
  176808. } else {
  176809. undef_row = ptr->first_undef_row;
  176810. }
  176811. if (writable)
  176812. ptr->first_undef_row = end_row;
  176813. if (ptr->pre_zero) {
  176814. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176815. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176816. end_row -= ptr->cur_start_row;
  176817. while (undef_row < end_row) {
  176818. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176819. undef_row++;
  176820. }
  176821. } else {
  176822. if (! writable) /* reader looking at undefined data */
  176823. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176824. }
  176825. }
  176826. /* Flag the buffer dirty if caller will write in it */
  176827. if (writable)
  176828. ptr->dirty = TRUE;
  176829. /* Return address of proper part of the buffer */
  176830. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176831. }
  176832. METHODDEF(JBLOCKARRAY)
  176833. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176834. JDIMENSION start_row, JDIMENSION num_rows,
  176835. boolean writable)
  176836. /* Access the part of a virtual block array starting at start_row */
  176837. /* and extending for num_rows rows. writable is true if */
  176838. /* caller intends to modify the accessed area. */
  176839. {
  176840. JDIMENSION end_row = start_row + num_rows;
  176841. JDIMENSION undef_row;
  176842. /* debugging check */
  176843. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176844. ptr->mem_buffer == NULL)
  176845. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176846. /* Make the desired part of the virtual array accessible */
  176847. if (start_row < ptr->cur_start_row ||
  176848. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176849. if (! ptr->b_s_open)
  176850. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176851. /* Flush old buffer contents if necessary */
  176852. if (ptr->dirty) {
  176853. do_barray_io(cinfo, ptr, TRUE);
  176854. ptr->dirty = FALSE;
  176855. }
  176856. /* Decide what part of virtual array to access.
  176857. * Algorithm: if target address > current window, assume forward scan,
  176858. * load starting at target address. If target address < current window,
  176859. * assume backward scan, load so that target area is top of window.
  176860. * Note that when switching from forward write to forward read, will have
  176861. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176862. */
  176863. if (start_row > ptr->cur_start_row) {
  176864. ptr->cur_start_row = start_row;
  176865. } else {
  176866. /* use long arithmetic here to avoid overflow & unsigned problems */
  176867. long ltemp;
  176868. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176869. if (ltemp < 0)
  176870. ltemp = 0; /* don't fall off front end of file */
  176871. ptr->cur_start_row = (JDIMENSION) ltemp;
  176872. }
  176873. /* Read in the selected part of the array.
  176874. * During the initial write pass, we will do no actual read
  176875. * because the selected part is all undefined.
  176876. */
  176877. do_barray_io(cinfo, ptr, FALSE);
  176878. }
  176879. /* Ensure the accessed part of the array is defined; prezero if needed.
  176880. * To improve locality of access, we only prezero the part of the array
  176881. * that the caller is about to access, not the entire in-memory array.
  176882. */
  176883. if (ptr->first_undef_row < end_row) {
  176884. if (ptr->first_undef_row < start_row) {
  176885. if (writable) /* writer skipped over a section of array */
  176886. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176887. undef_row = start_row; /* but reader is allowed to read ahead */
  176888. } else {
  176889. undef_row = ptr->first_undef_row;
  176890. }
  176891. if (writable)
  176892. ptr->first_undef_row = end_row;
  176893. if (ptr->pre_zero) {
  176894. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176895. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176896. end_row -= ptr->cur_start_row;
  176897. while (undef_row < end_row) {
  176898. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176899. undef_row++;
  176900. }
  176901. } else {
  176902. if (! writable) /* reader looking at undefined data */
  176903. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176904. }
  176905. }
  176906. /* Flag the buffer dirty if caller will write in it */
  176907. if (writable)
  176908. ptr->dirty = TRUE;
  176909. /* Return address of proper part of the buffer */
  176910. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176911. }
  176912. /*
  176913. * Release all objects belonging to a specified pool.
  176914. */
  176915. METHODDEF(void)
  176916. free_pool (j_common_ptr cinfo, int pool_id)
  176917. {
  176918. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176919. small_pool_ptr shdr_ptr;
  176920. large_pool_ptr lhdr_ptr;
  176921. size_t space_freed;
  176922. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176923. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176924. #ifdef MEM_STATS
  176925. if (cinfo->err->trace_level > 1)
  176926. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176927. #endif
  176928. /* If freeing IMAGE pool, close any virtual arrays first */
  176929. if (pool_id == JPOOL_IMAGE) {
  176930. jvirt_sarray_ptr sptr;
  176931. jvirt_barray_ptr bptr;
  176932. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176933. if (sptr->b_s_open) { /* there may be no backing store */
  176934. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176935. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176936. }
  176937. }
  176938. mem->virt_sarray_list = NULL;
  176939. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176940. if (bptr->b_s_open) { /* there may be no backing store */
  176941. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176942. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176943. }
  176944. }
  176945. mem->virt_barray_list = NULL;
  176946. }
  176947. /* Release large objects */
  176948. lhdr_ptr = mem->large_list[pool_id];
  176949. mem->large_list[pool_id] = NULL;
  176950. while (lhdr_ptr != NULL) {
  176951. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176952. space_freed = lhdr_ptr->hdr.bytes_used +
  176953. lhdr_ptr->hdr.bytes_left +
  176954. SIZEOF(large_pool_hdr);
  176955. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176956. mem->total_space_allocated -= space_freed;
  176957. lhdr_ptr = next_lhdr_ptr;
  176958. }
  176959. /* Release small objects */
  176960. shdr_ptr = mem->small_list[pool_id];
  176961. mem->small_list[pool_id] = NULL;
  176962. while (shdr_ptr != NULL) {
  176963. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176964. space_freed = shdr_ptr->hdr.bytes_used +
  176965. shdr_ptr->hdr.bytes_left +
  176966. SIZEOF(small_pool_hdr);
  176967. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176968. mem->total_space_allocated -= space_freed;
  176969. shdr_ptr = next_shdr_ptr;
  176970. }
  176971. }
  176972. /*
  176973. * Close up shop entirely.
  176974. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176975. */
  176976. METHODDEF(void)
  176977. self_destruct (j_common_ptr cinfo)
  176978. {
  176979. int pool;
  176980. /* Close all backing store, release all memory.
  176981. * Releasing pools in reverse order might help avoid fragmentation
  176982. * with some (brain-damaged) malloc libraries.
  176983. */
  176984. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176985. free_pool(cinfo, pool);
  176986. }
  176987. /* Release the memory manager control block too. */
  176988. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176989. cinfo->mem = NULL; /* ensures I will be called only once */
  176990. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176991. }
  176992. /*
  176993. * Memory manager initialization.
  176994. * When this is called, only the error manager pointer is valid in cinfo!
  176995. */
  176996. GLOBAL(void)
  176997. jinit_memory_mgr (j_common_ptr cinfo)
  176998. {
  176999. my_mem_ptr mem;
  177000. long max_to_use;
  177001. int pool;
  177002. size_t test_mac;
  177003. cinfo->mem = NULL; /* for safety if init fails */
  177004. /* Check for configuration errors.
  177005. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  177006. * doesn't reflect any real hardware alignment requirement.
  177007. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  177008. * in common if and only if X is a power of 2, ie has only one one-bit.
  177009. * Some compilers may give an "unreachable code" warning here; ignore it.
  177010. */
  177011. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  177012. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  177013. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  177014. * a multiple of SIZEOF(ALIGN_TYPE).
  177015. * Again, an "unreachable code" warning may be ignored here.
  177016. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  177017. */
  177018. test_mac = (size_t) MAX_ALLOC_CHUNK;
  177019. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  177020. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  177021. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  177022. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  177023. /* Attempt to allocate memory manager's control block */
  177024. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  177025. if (mem == NULL) {
  177026. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177027. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  177028. }
  177029. /* OK, fill in the method pointers */
  177030. mem->pub.alloc_small = alloc_small;
  177031. mem->pub.alloc_large = alloc_large;
  177032. mem->pub.alloc_sarray = alloc_sarray;
  177033. mem->pub.alloc_barray = alloc_barray;
  177034. mem->pub.request_virt_sarray = request_virt_sarray;
  177035. mem->pub.request_virt_barray = request_virt_barray;
  177036. mem->pub.realize_virt_arrays = realize_virt_arrays;
  177037. mem->pub.access_virt_sarray = access_virt_sarray;
  177038. mem->pub.access_virt_barray = access_virt_barray;
  177039. mem->pub.free_pool = free_pool;
  177040. mem->pub.self_destruct = self_destruct;
  177041. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  177042. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  177043. /* Initialize working state */
  177044. mem->pub.max_memory_to_use = max_to_use;
  177045. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177046. mem->small_list[pool] = NULL;
  177047. mem->large_list[pool] = NULL;
  177048. }
  177049. mem->virt_sarray_list = NULL;
  177050. mem->virt_barray_list = NULL;
  177051. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  177052. /* Declare ourselves open for business */
  177053. cinfo->mem = & mem->pub;
  177054. /* Check for an environment variable JPEGMEM; if found, override the
  177055. * default max_memory setting from jpeg_mem_init. Note that the
  177056. * surrounding application may again override this value.
  177057. * If your system doesn't support getenv(), define NO_GETENV to disable
  177058. * this feature.
  177059. */
  177060. #ifndef NO_GETENV
  177061. { char * memenv;
  177062. if ((memenv = getenv("JPEGMEM")) != NULL) {
  177063. char ch = 'x';
  177064. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  177065. if (ch == 'm' || ch == 'M')
  177066. max_to_use *= 1000L;
  177067. mem->pub.max_memory_to_use = max_to_use * 1000L;
  177068. }
  177069. }
  177070. }
  177071. #endif
  177072. }
  177073. /*** End of inlined file: jmemmgr.c ***/
  177074. /*** Start of inlined file: jmemnobs.c ***/
  177075. #define JPEG_INTERNALS
  177076. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  177077. extern void * malloc JPP((size_t size));
  177078. extern void free JPP((void *ptr));
  177079. #endif
  177080. /*
  177081. * Memory allocation and freeing are controlled by the regular library
  177082. * routines malloc() and free().
  177083. */
  177084. GLOBAL(void *)
  177085. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  177086. {
  177087. return (void *) malloc(sizeofobject);
  177088. }
  177089. GLOBAL(void)
  177090. jpeg_free_small (j_common_ptr , void * object, size_t)
  177091. {
  177092. free(object);
  177093. }
  177094. /*
  177095. * "Large" objects are treated the same as "small" ones.
  177096. * NB: although we include FAR keywords in the routine declarations,
  177097. * this file won't actually work in 80x86 small/medium model; at least,
  177098. * you probably won't be able to process useful-size images in only 64KB.
  177099. */
  177100. GLOBAL(void FAR *)
  177101. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  177102. {
  177103. return (void FAR *) malloc(sizeofobject);
  177104. }
  177105. GLOBAL(void)
  177106. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  177107. {
  177108. free(object);
  177109. }
  177110. /*
  177111. * This routine computes the total memory space available for allocation.
  177112. * Here we always say, "we got all you want bud!"
  177113. */
  177114. GLOBAL(long)
  177115. jpeg_mem_available (j_common_ptr, long,
  177116. long max_bytes_needed, long)
  177117. {
  177118. return max_bytes_needed;
  177119. }
  177120. /*
  177121. * Backing store (temporary file) management.
  177122. * Since jpeg_mem_available always promised the moon,
  177123. * this should never be called and we can just error out.
  177124. */
  177125. GLOBAL(void)
  177126. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  177127. long )
  177128. {
  177129. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  177130. }
  177131. /*
  177132. * These routines take care of any system-dependent initialization and
  177133. * cleanup required. Here, there isn't any.
  177134. */
  177135. GLOBAL(long)
  177136. jpeg_mem_init (j_common_ptr)
  177137. {
  177138. return 0; /* just set max_memory_to_use to 0 */
  177139. }
  177140. GLOBAL(void)
  177141. jpeg_mem_term (j_common_ptr)
  177142. {
  177143. /* no work */
  177144. }
  177145. /*** End of inlined file: jmemnobs.c ***/
  177146. /*** Start of inlined file: jquant1.c ***/
  177147. #define JPEG_INTERNALS
  177148. #ifdef QUANT_1PASS_SUPPORTED
  177149. /*
  177150. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177151. * high quality, colormapped output capability. A 2-pass quantizer usually
  177152. * gives better visual quality; however, for quantized grayscale output this
  177153. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177154. * quantizer, though you can turn it off if you really want to.
  177155. *
  177156. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177157. * image. We use a map consisting of all combinations of Ncolors[i] color
  177158. * values for the i'th component. The Ncolors[] values are chosen so that
  177159. * their product, the total number of colors, is no more than that requested.
  177160. * (In most cases, the product will be somewhat less.)
  177161. *
  177162. * Since the colormap is orthogonal, the representative value for each color
  177163. * component can be determined without considering the other components;
  177164. * then these indexes can be combined into a colormap index by a standard
  177165. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177166. * can be precalculated and stored in the lookup table colorindex[].
  177167. * colorindex[i][j] maps pixel value j in component i to the nearest
  177168. * representative value (grid plane) for that component; this index is
  177169. * multiplied by the array stride for component i, so that the
  177170. * index of the colormap entry closest to a given pixel value is just
  177171. * sum( colorindex[component-number][pixel-component-value] )
  177172. * Aside from being fast, this scheme allows for variable spacing between
  177173. * representative values with no additional lookup cost.
  177174. *
  177175. * If gamma correction has been applied in color conversion, it might be wise
  177176. * to adjust the color grid spacing so that the representative colors are
  177177. * equidistant in linear space. At this writing, gamma correction is not
  177178. * implemented by jdcolor, so nothing is done here.
  177179. */
  177180. /* Declarations for ordered dithering.
  177181. *
  177182. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177183. * dithering is described in many references, for instance Dale Schumacher's
  177184. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177185. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177186. * "dither" value to the input pixel and then round the result to the nearest
  177187. * output value. The dither value is equivalent to (0.5 - threshold) times
  177188. * the distance between output values. For ordered dithering, we assume that
  177189. * the output colors are equally spaced; if not, results will probably be
  177190. * worse, since the dither may be too much or too little at a given point.
  177191. *
  177192. * The normal calculation would be to form pixel value + dither, range-limit
  177193. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177194. * We can skip the separate range-limiting step by extending the colorindex
  177195. * table in both directions.
  177196. */
  177197. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177198. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177199. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177200. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177201. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177202. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177203. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177204. /* Bayer's order-4 dither array. Generated by the code given in
  177205. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177206. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177207. */
  177208. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177209. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177210. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177211. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177212. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177213. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177214. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177215. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177216. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177217. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177218. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177219. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177220. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177221. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177222. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177223. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177224. };
  177225. /* Declarations for Floyd-Steinberg dithering.
  177226. *
  177227. * Errors are accumulated into the array fserrors[], at a resolution of
  177228. * 1/16th of a pixel count. The error at a given pixel is propagated
  177229. * to its not-yet-processed neighbors using the standard F-S fractions,
  177230. * ... (here) 7/16
  177231. * 3/16 5/16 1/16
  177232. * We work left-to-right on even rows, right-to-left on odd rows.
  177233. *
  177234. * We can get away with a single array (holding one row's worth of errors)
  177235. * by using it to store the current row's errors at pixel columns not yet
  177236. * processed, but the next row's errors at columns already processed. We
  177237. * need only a few extra variables to hold the errors immediately around the
  177238. * current column. (If we are lucky, those variables are in registers, but
  177239. * even if not, they're probably cheaper to access than array elements are.)
  177240. *
  177241. * The fserrors[] array is indexed [component#][position].
  177242. * We provide (#columns + 2) entries per component; the extra entry at each
  177243. * end saves us from special-casing the first and last pixels.
  177244. *
  177245. * Note: on a wide image, we might not have enough room in a PC's near data
  177246. * segment to hold the error array; so it is allocated with alloc_large.
  177247. */
  177248. #if BITS_IN_JSAMPLE == 8
  177249. typedef INT16 FSERROR; /* 16 bits should be enough */
  177250. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177251. #else
  177252. typedef INT32 FSERROR; /* may need more than 16 bits */
  177253. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177254. #endif
  177255. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177256. /* Private subobject */
  177257. #define MAX_Q_COMPS 4 /* max components I can handle */
  177258. typedef struct {
  177259. struct jpeg_color_quantizer pub; /* public fields */
  177260. /* Initially allocated colormap is saved here */
  177261. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177262. int sv_actual; /* number of entries in use */
  177263. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177264. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177265. * premultiplied as described above. Since colormap indexes must fit into
  177266. * JSAMPLEs, the entries of this array will too.
  177267. */
  177268. boolean is_padded; /* is the colorindex padded for odither? */
  177269. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177270. /* Variables for ordered dithering */
  177271. int row_index; /* cur row's vertical index in dither matrix */
  177272. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177273. /* Variables for Floyd-Steinberg dithering */
  177274. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177275. boolean on_odd_row; /* flag to remember which row we are on */
  177276. } my_cquantizer;
  177277. typedef my_cquantizer * my_cquantize_ptr;
  177278. /*
  177279. * Policy-making subroutines for create_colormap and create_colorindex.
  177280. * These routines determine the colormap to be used. The rest of the module
  177281. * only assumes that the colormap is orthogonal.
  177282. *
  177283. * * select_ncolors decides how to divvy up the available colors
  177284. * among the components.
  177285. * * output_value defines the set of representative values for a component.
  177286. * * largest_input_value defines the mapping from input values to
  177287. * representative values for a component.
  177288. * Note that the latter two routines may impose different policies for
  177289. * different components, though this is not currently done.
  177290. */
  177291. LOCAL(int)
  177292. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177293. /* Determine allocation of desired colors to components, */
  177294. /* and fill in Ncolors[] array to indicate choice. */
  177295. /* Return value is total number of colors (product of Ncolors[] values). */
  177296. {
  177297. int nc = cinfo->out_color_components; /* number of color components */
  177298. int max_colors = cinfo->desired_number_of_colors;
  177299. int total_colors, iroot, i, j;
  177300. boolean changed;
  177301. long temp;
  177302. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177303. /* We can allocate at least the nc'th root of max_colors per component. */
  177304. /* Compute floor(nc'th root of max_colors). */
  177305. iroot = 1;
  177306. do {
  177307. iroot++;
  177308. temp = iroot; /* set temp = iroot ** nc */
  177309. for (i = 1; i < nc; i++)
  177310. temp *= iroot;
  177311. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177312. iroot--; /* now iroot = floor(root) */
  177313. /* Must have at least 2 color values per component */
  177314. if (iroot < 2)
  177315. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177316. /* Initialize to iroot color values for each component */
  177317. total_colors = 1;
  177318. for (i = 0; i < nc; i++) {
  177319. Ncolors[i] = iroot;
  177320. total_colors *= iroot;
  177321. }
  177322. /* We may be able to increment the count for one or more components without
  177323. * exceeding max_colors, though we know not all can be incremented.
  177324. * Sometimes, the first component can be incremented more than once!
  177325. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177326. * In RGB colorspace, try to increment G first, then R, then B.
  177327. */
  177328. do {
  177329. changed = FALSE;
  177330. for (i = 0; i < nc; i++) {
  177331. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177332. /* calculate new total_colors if Ncolors[j] is incremented */
  177333. temp = total_colors / Ncolors[j];
  177334. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177335. if (temp > (long) max_colors)
  177336. break; /* won't fit, done with this pass */
  177337. Ncolors[j]++; /* OK, apply the increment */
  177338. total_colors = (int) temp;
  177339. changed = TRUE;
  177340. }
  177341. } while (changed);
  177342. return total_colors;
  177343. }
  177344. LOCAL(int)
  177345. output_value (j_decompress_ptr, int, int j, int maxj)
  177346. /* Return j'th output value, where j will range from 0 to maxj */
  177347. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177348. {
  177349. /* We always provide values 0 and MAXJSAMPLE for each component;
  177350. * any additional values are equally spaced between these limits.
  177351. * (Forcing the upper and lower values to the limits ensures that
  177352. * dithering can't produce a color outside the selected gamut.)
  177353. */
  177354. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177355. }
  177356. LOCAL(int)
  177357. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177358. /* Return largest input value that should map to j'th output value */
  177359. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177360. {
  177361. /* Breakpoints are halfway between values returned by output_value */
  177362. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177363. }
  177364. /*
  177365. * Create the colormap.
  177366. */
  177367. LOCAL(void)
  177368. create_colormap (j_decompress_ptr cinfo)
  177369. {
  177370. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177371. JSAMPARRAY colormap; /* Created colormap */
  177372. int total_colors; /* Number of distinct output colors */
  177373. int i,j,k, nci, blksize, blkdist, ptr, val;
  177374. /* Select number of colors for each component */
  177375. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177376. /* Report selected color counts */
  177377. if (cinfo->out_color_components == 3)
  177378. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177379. total_colors, cquantize->Ncolors[0],
  177380. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177381. else
  177382. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177383. /* Allocate and fill in the colormap. */
  177384. /* The colors are ordered in the map in standard row-major order, */
  177385. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177386. colormap = (*cinfo->mem->alloc_sarray)
  177387. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177388. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177389. /* blksize is number of adjacent repeated entries for a component */
  177390. /* blkdist is distance between groups of identical entries for a component */
  177391. blkdist = total_colors;
  177392. for (i = 0; i < cinfo->out_color_components; i++) {
  177393. /* fill in colormap entries for i'th color component */
  177394. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177395. blksize = blkdist / nci;
  177396. for (j = 0; j < nci; j++) {
  177397. /* Compute j'th output value (out of nci) for component */
  177398. val = output_value(cinfo, i, j, nci-1);
  177399. /* Fill in all colormap entries that have this value of this component */
  177400. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177401. /* fill in blksize entries beginning at ptr */
  177402. for (k = 0; k < blksize; k++)
  177403. colormap[i][ptr+k] = (JSAMPLE) val;
  177404. }
  177405. }
  177406. blkdist = blksize; /* blksize of this color is blkdist of next */
  177407. }
  177408. /* Save the colormap in private storage,
  177409. * where it will survive color quantization mode changes.
  177410. */
  177411. cquantize->sv_colormap = colormap;
  177412. cquantize->sv_actual = total_colors;
  177413. }
  177414. /*
  177415. * Create the color index table.
  177416. */
  177417. LOCAL(void)
  177418. create_colorindex (j_decompress_ptr cinfo)
  177419. {
  177420. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177421. JSAMPROW indexptr;
  177422. int i,j,k, nci, blksize, val, pad;
  177423. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177424. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177425. * This is not necessary in the other dithering modes. However, we
  177426. * flag whether it was done in case user changes dithering mode.
  177427. */
  177428. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177429. pad = MAXJSAMPLE*2;
  177430. cquantize->is_padded = TRUE;
  177431. } else {
  177432. pad = 0;
  177433. cquantize->is_padded = FALSE;
  177434. }
  177435. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177436. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177437. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177438. (JDIMENSION) cinfo->out_color_components);
  177439. /* blksize is number of adjacent repeated entries for a component */
  177440. blksize = cquantize->sv_actual;
  177441. for (i = 0; i < cinfo->out_color_components; i++) {
  177442. /* fill in colorindex entries for i'th color component */
  177443. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177444. blksize = blksize / nci;
  177445. /* adjust colorindex pointers to provide padding at negative indexes. */
  177446. if (pad)
  177447. cquantize->colorindex[i] += MAXJSAMPLE;
  177448. /* in loop, val = index of current output value, */
  177449. /* and k = largest j that maps to current val */
  177450. indexptr = cquantize->colorindex[i];
  177451. val = 0;
  177452. k = largest_input_value(cinfo, i, 0, nci-1);
  177453. for (j = 0; j <= MAXJSAMPLE; j++) {
  177454. while (j > k) /* advance val if past boundary */
  177455. k = largest_input_value(cinfo, i, ++val, nci-1);
  177456. /* premultiply so that no multiplication needed in main processing */
  177457. indexptr[j] = (JSAMPLE) (val * blksize);
  177458. }
  177459. /* Pad at both ends if necessary */
  177460. if (pad)
  177461. for (j = 1; j <= MAXJSAMPLE; j++) {
  177462. indexptr[-j] = indexptr[0];
  177463. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177464. }
  177465. }
  177466. }
  177467. /*
  177468. * Create an ordered-dither array for a component having ncolors
  177469. * distinct output values.
  177470. */
  177471. LOCAL(ODITHER_MATRIX_PTR)
  177472. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177473. {
  177474. ODITHER_MATRIX_PTR odither;
  177475. int j,k;
  177476. INT32 num,den;
  177477. odither = (ODITHER_MATRIX_PTR)
  177478. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177479. SIZEOF(ODITHER_MATRIX));
  177480. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177481. * Hence the dither value for the matrix cell with fill order f
  177482. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177483. * On 16-bit-int machine, be careful to avoid overflow.
  177484. */
  177485. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177486. for (j = 0; j < ODITHER_SIZE; j++) {
  177487. for (k = 0; k < ODITHER_SIZE; k++) {
  177488. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177489. * MAXJSAMPLE;
  177490. /* Ensure round towards zero despite C's lack of consistency
  177491. * about rounding negative values in integer division...
  177492. */
  177493. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177494. }
  177495. }
  177496. return odither;
  177497. }
  177498. /*
  177499. * Create the ordered-dither tables.
  177500. * Components having the same number of representative colors may
  177501. * share a dither table.
  177502. */
  177503. LOCAL(void)
  177504. create_odither_tables (j_decompress_ptr cinfo)
  177505. {
  177506. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177507. ODITHER_MATRIX_PTR odither;
  177508. int i, j, nci;
  177509. for (i = 0; i < cinfo->out_color_components; i++) {
  177510. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177511. odither = NULL; /* search for matching prior component */
  177512. for (j = 0; j < i; j++) {
  177513. if (nci == cquantize->Ncolors[j]) {
  177514. odither = cquantize->odither[j];
  177515. break;
  177516. }
  177517. }
  177518. if (odither == NULL) /* need a new table? */
  177519. odither = make_odither_array(cinfo, nci);
  177520. cquantize->odither[i] = odither;
  177521. }
  177522. }
  177523. /*
  177524. * Map some rows of pixels to the output colormapped representation.
  177525. */
  177526. METHODDEF(void)
  177527. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177528. JSAMPARRAY output_buf, int num_rows)
  177529. /* General case, no dithering */
  177530. {
  177531. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177532. JSAMPARRAY colorindex = cquantize->colorindex;
  177533. register int pixcode, ci;
  177534. register JSAMPROW ptrin, ptrout;
  177535. int row;
  177536. JDIMENSION col;
  177537. JDIMENSION width = cinfo->output_width;
  177538. register int nc = cinfo->out_color_components;
  177539. for (row = 0; row < num_rows; row++) {
  177540. ptrin = input_buf[row];
  177541. ptrout = output_buf[row];
  177542. for (col = width; col > 0; col--) {
  177543. pixcode = 0;
  177544. for (ci = 0; ci < nc; ci++) {
  177545. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177546. }
  177547. *ptrout++ = (JSAMPLE) pixcode;
  177548. }
  177549. }
  177550. }
  177551. METHODDEF(void)
  177552. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177553. JSAMPARRAY output_buf, int num_rows)
  177554. /* Fast path for out_color_components==3, no dithering */
  177555. {
  177556. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177557. register int pixcode;
  177558. register JSAMPROW ptrin, ptrout;
  177559. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177560. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177561. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177562. int row;
  177563. JDIMENSION col;
  177564. JDIMENSION width = cinfo->output_width;
  177565. for (row = 0; row < num_rows; row++) {
  177566. ptrin = input_buf[row];
  177567. ptrout = output_buf[row];
  177568. for (col = width; col > 0; col--) {
  177569. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177570. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177571. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177572. *ptrout++ = (JSAMPLE) pixcode;
  177573. }
  177574. }
  177575. }
  177576. METHODDEF(void)
  177577. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177578. JSAMPARRAY output_buf, int num_rows)
  177579. /* General case, with ordered dithering */
  177580. {
  177581. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177582. register JSAMPROW input_ptr;
  177583. register JSAMPROW output_ptr;
  177584. JSAMPROW colorindex_ci;
  177585. int * dither; /* points to active row of dither matrix */
  177586. int row_index, col_index; /* current indexes into dither matrix */
  177587. int nc = cinfo->out_color_components;
  177588. int ci;
  177589. int row;
  177590. JDIMENSION col;
  177591. JDIMENSION width = cinfo->output_width;
  177592. for (row = 0; row < num_rows; row++) {
  177593. /* Initialize output values to 0 so can process components separately */
  177594. jzero_far((void FAR *) output_buf[row],
  177595. (size_t) (width * SIZEOF(JSAMPLE)));
  177596. row_index = cquantize->row_index;
  177597. for (ci = 0; ci < nc; ci++) {
  177598. input_ptr = input_buf[row] + ci;
  177599. output_ptr = output_buf[row];
  177600. colorindex_ci = cquantize->colorindex[ci];
  177601. dither = cquantize->odither[ci][row_index];
  177602. col_index = 0;
  177603. for (col = width; col > 0; col--) {
  177604. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177605. * select output value, accumulate into output code for this pixel.
  177606. * Range-limiting need not be done explicitly, as we have extended
  177607. * the colorindex table to produce the right answers for out-of-range
  177608. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177609. * required amount of padding.
  177610. */
  177611. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177612. input_ptr += nc;
  177613. output_ptr++;
  177614. col_index = (col_index + 1) & ODITHER_MASK;
  177615. }
  177616. }
  177617. /* Advance row index for next row */
  177618. row_index = (row_index + 1) & ODITHER_MASK;
  177619. cquantize->row_index = row_index;
  177620. }
  177621. }
  177622. METHODDEF(void)
  177623. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177624. JSAMPARRAY output_buf, int num_rows)
  177625. /* Fast path for out_color_components==3, with ordered dithering */
  177626. {
  177627. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177628. register int pixcode;
  177629. register JSAMPROW input_ptr;
  177630. register JSAMPROW output_ptr;
  177631. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177632. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177633. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177634. int * dither0; /* points to active row of dither matrix */
  177635. int * dither1;
  177636. int * dither2;
  177637. int row_index, col_index; /* current indexes into dither matrix */
  177638. int row;
  177639. JDIMENSION col;
  177640. JDIMENSION width = cinfo->output_width;
  177641. for (row = 0; row < num_rows; row++) {
  177642. row_index = cquantize->row_index;
  177643. input_ptr = input_buf[row];
  177644. output_ptr = output_buf[row];
  177645. dither0 = cquantize->odither[0][row_index];
  177646. dither1 = cquantize->odither[1][row_index];
  177647. dither2 = cquantize->odither[2][row_index];
  177648. col_index = 0;
  177649. for (col = width; col > 0; col--) {
  177650. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177651. dither0[col_index]]);
  177652. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177653. dither1[col_index]]);
  177654. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177655. dither2[col_index]]);
  177656. *output_ptr++ = (JSAMPLE) pixcode;
  177657. col_index = (col_index + 1) & ODITHER_MASK;
  177658. }
  177659. row_index = (row_index + 1) & ODITHER_MASK;
  177660. cquantize->row_index = row_index;
  177661. }
  177662. }
  177663. METHODDEF(void)
  177664. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177665. JSAMPARRAY output_buf, int num_rows)
  177666. /* General case, with Floyd-Steinberg dithering */
  177667. {
  177668. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177669. register LOCFSERROR cur; /* current error or pixel value */
  177670. LOCFSERROR belowerr; /* error for pixel below cur */
  177671. LOCFSERROR bpreverr; /* error for below/prev col */
  177672. LOCFSERROR bnexterr; /* error for below/next col */
  177673. LOCFSERROR delta;
  177674. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177675. register JSAMPROW input_ptr;
  177676. register JSAMPROW output_ptr;
  177677. JSAMPROW colorindex_ci;
  177678. JSAMPROW colormap_ci;
  177679. int pixcode;
  177680. int nc = cinfo->out_color_components;
  177681. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177682. int dirnc; /* dir * nc */
  177683. int ci;
  177684. int row;
  177685. JDIMENSION col;
  177686. JDIMENSION width = cinfo->output_width;
  177687. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177688. SHIFT_TEMPS
  177689. for (row = 0; row < num_rows; row++) {
  177690. /* Initialize output values to 0 so can process components separately */
  177691. jzero_far((void FAR *) output_buf[row],
  177692. (size_t) (width * SIZEOF(JSAMPLE)));
  177693. for (ci = 0; ci < nc; ci++) {
  177694. input_ptr = input_buf[row] + ci;
  177695. output_ptr = output_buf[row];
  177696. if (cquantize->on_odd_row) {
  177697. /* work right to left in this row */
  177698. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177699. output_ptr += width-1;
  177700. dir = -1;
  177701. dirnc = -nc;
  177702. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177703. } else {
  177704. /* work left to right in this row */
  177705. dir = 1;
  177706. dirnc = nc;
  177707. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177708. }
  177709. colorindex_ci = cquantize->colorindex[ci];
  177710. colormap_ci = cquantize->sv_colormap[ci];
  177711. /* Preset error values: no error propagated to first pixel from left */
  177712. cur = 0;
  177713. /* and no error propagated to row below yet */
  177714. belowerr = bpreverr = 0;
  177715. for (col = width; col > 0; col--) {
  177716. /* cur holds the error propagated from the previous pixel on the
  177717. * current line. Add the error propagated from the previous line
  177718. * to form the complete error correction term for this pixel, and
  177719. * round the error term (which is expressed * 16) to an integer.
  177720. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177721. * for either sign of the error value.
  177722. * Note: errorptr points to *previous* column's array entry.
  177723. */
  177724. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177725. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177726. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177727. * of the range_limit array.
  177728. */
  177729. cur += GETJSAMPLE(*input_ptr);
  177730. cur = GETJSAMPLE(range_limit[cur]);
  177731. /* Select output value, accumulate into output code for this pixel */
  177732. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177733. *output_ptr += (JSAMPLE) pixcode;
  177734. /* Compute actual representation error at this pixel */
  177735. /* Note: we can do this even though we don't have the final */
  177736. /* pixel code, because the colormap is orthogonal. */
  177737. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177738. /* Compute error fractions to be propagated to adjacent pixels.
  177739. * Add these into the running sums, and simultaneously shift the
  177740. * next-line error sums left by 1 column.
  177741. */
  177742. bnexterr = cur;
  177743. delta = cur * 2;
  177744. cur += delta; /* form error * 3 */
  177745. errorptr[0] = (FSERROR) (bpreverr + cur);
  177746. cur += delta; /* form error * 5 */
  177747. bpreverr = belowerr + cur;
  177748. belowerr = bnexterr;
  177749. cur += delta; /* form error * 7 */
  177750. /* At this point cur contains the 7/16 error value to be propagated
  177751. * to the next pixel on the current line, and all the errors for the
  177752. * next line have been shifted over. We are therefore ready to move on.
  177753. */
  177754. input_ptr += dirnc; /* advance input ptr to next column */
  177755. output_ptr += dir; /* advance output ptr to next column */
  177756. errorptr += dir; /* advance errorptr to current column */
  177757. }
  177758. /* Post-loop cleanup: we must unload the final error value into the
  177759. * final fserrors[] entry. Note we need not unload belowerr because
  177760. * it is for the dummy column before or after the actual array.
  177761. */
  177762. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177763. }
  177764. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177765. }
  177766. }
  177767. /*
  177768. * Allocate workspace for Floyd-Steinberg errors.
  177769. */
  177770. LOCAL(void)
  177771. alloc_fs_workspace (j_decompress_ptr cinfo)
  177772. {
  177773. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177774. size_t arraysize;
  177775. int i;
  177776. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177777. for (i = 0; i < cinfo->out_color_components; i++) {
  177778. cquantize->fserrors[i] = (FSERRPTR)
  177779. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177780. }
  177781. }
  177782. /*
  177783. * Initialize for one-pass color quantization.
  177784. */
  177785. METHODDEF(void)
  177786. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177787. {
  177788. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177789. size_t arraysize;
  177790. int i;
  177791. /* Install my colormap. */
  177792. cinfo->colormap = cquantize->sv_colormap;
  177793. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177794. /* Initialize for desired dithering mode. */
  177795. switch (cinfo->dither_mode) {
  177796. case JDITHER_NONE:
  177797. if (cinfo->out_color_components == 3)
  177798. cquantize->pub.color_quantize = color_quantize3;
  177799. else
  177800. cquantize->pub.color_quantize = color_quantize;
  177801. break;
  177802. case JDITHER_ORDERED:
  177803. if (cinfo->out_color_components == 3)
  177804. cquantize->pub.color_quantize = quantize3_ord_dither;
  177805. else
  177806. cquantize->pub.color_quantize = quantize_ord_dither;
  177807. cquantize->row_index = 0; /* initialize state for ordered dither */
  177808. /* If user changed to ordered dither from another mode,
  177809. * we must recreate the color index table with padding.
  177810. * This will cost extra space, but probably isn't very likely.
  177811. */
  177812. if (! cquantize->is_padded)
  177813. create_colorindex(cinfo);
  177814. /* Create ordered-dither tables if we didn't already. */
  177815. if (cquantize->odither[0] == NULL)
  177816. create_odither_tables(cinfo);
  177817. break;
  177818. case JDITHER_FS:
  177819. cquantize->pub.color_quantize = quantize_fs_dither;
  177820. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177821. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177822. if (cquantize->fserrors[0] == NULL)
  177823. alloc_fs_workspace(cinfo);
  177824. /* Initialize the propagated errors to zero. */
  177825. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177826. for (i = 0; i < cinfo->out_color_components; i++)
  177827. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177828. break;
  177829. default:
  177830. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177831. break;
  177832. }
  177833. }
  177834. /*
  177835. * Finish up at the end of the pass.
  177836. */
  177837. METHODDEF(void)
  177838. finish_pass_1_quant (j_decompress_ptr)
  177839. {
  177840. /* no work in 1-pass case */
  177841. }
  177842. /*
  177843. * Switch to a new external colormap between output passes.
  177844. * Shouldn't get to this module!
  177845. */
  177846. METHODDEF(void)
  177847. new_color_map_1_quant (j_decompress_ptr cinfo)
  177848. {
  177849. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177850. }
  177851. /*
  177852. * Module initialization routine for 1-pass color quantization.
  177853. */
  177854. GLOBAL(void)
  177855. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177856. {
  177857. my_cquantize_ptr cquantize;
  177858. cquantize = (my_cquantize_ptr)
  177859. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177860. SIZEOF(my_cquantizer));
  177861. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177862. cquantize->pub.start_pass = start_pass_1_quant;
  177863. cquantize->pub.finish_pass = finish_pass_1_quant;
  177864. cquantize->pub.new_color_map = new_color_map_1_quant;
  177865. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177866. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177867. /* Make sure my internal arrays won't overflow */
  177868. if (cinfo->out_color_components > MAX_Q_COMPS)
  177869. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177870. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177871. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177872. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177873. /* Create the colormap and color index table. */
  177874. create_colormap(cinfo);
  177875. create_colorindex(cinfo);
  177876. /* Allocate Floyd-Steinberg workspace now if requested.
  177877. * We do this now since it is FAR storage and may affect the memory
  177878. * manager's space calculations. If the user changes to FS dither
  177879. * mode in a later pass, we will allocate the space then, and will
  177880. * possibly overrun the max_memory_to_use setting.
  177881. */
  177882. if (cinfo->dither_mode == JDITHER_FS)
  177883. alloc_fs_workspace(cinfo);
  177884. }
  177885. #endif /* QUANT_1PASS_SUPPORTED */
  177886. /*** End of inlined file: jquant1.c ***/
  177887. /*** Start of inlined file: jquant2.c ***/
  177888. #define JPEG_INTERNALS
  177889. #ifdef QUANT_2PASS_SUPPORTED
  177890. /*
  177891. * This module implements the well-known Heckbert paradigm for color
  177892. * quantization. Most of the ideas used here can be traced back to
  177893. * Heckbert's seminal paper
  177894. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177895. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177896. *
  177897. * In the first pass over the image, we accumulate a histogram showing the
  177898. * usage count of each possible color. To keep the histogram to a reasonable
  177899. * size, we reduce the precision of the input; typical practice is to retain
  177900. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177901. * in the same histogram cell.
  177902. *
  177903. * Next, the color-selection step begins with a box representing the whole
  177904. * color space, and repeatedly splits the "largest" remaining box until we
  177905. * have as many boxes as desired colors. Then the mean color in each
  177906. * remaining box becomes one of the possible output colors.
  177907. *
  177908. * The second pass over the image maps each input pixel to the closest output
  177909. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177910. * This mapping is logically trivial, but making it go fast enough requires
  177911. * considerable care.
  177912. *
  177913. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177914. * the "largest" box and deciding where to cut it. The particular policies
  177915. * used here have proved out well in experimental comparisons, but better ones
  177916. * may yet be found.
  177917. *
  177918. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177919. * space, processing the raw upsampled data without a color conversion step.
  177920. * This allowed the color conversion math to be done only once per colormap
  177921. * entry, not once per pixel. However, that optimization precluded other
  177922. * useful optimizations (such as merging color conversion with upsampling)
  177923. * and it also interfered with desired capabilities such as quantizing to an
  177924. * externally-supplied colormap. We have therefore abandoned that approach.
  177925. * The present code works in the post-conversion color space, typically RGB.
  177926. *
  177927. * To improve the visual quality of the results, we actually work in scaled
  177928. * RGB space, giving G distances more weight than R, and R in turn more than
  177929. * B. To do everything in integer math, we must use integer scale factors.
  177930. * The 2/3/1 scale factors used here correspond loosely to the relative
  177931. * weights of the colors in the NTSC grayscale equation.
  177932. * If you want to use this code to quantize a non-RGB color space, you'll
  177933. * probably need to change these scale factors.
  177934. */
  177935. #define R_SCALE 2 /* scale R distances by this much */
  177936. #define G_SCALE 3 /* scale G distances by this much */
  177937. #define B_SCALE 1 /* and B by this much */
  177938. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177939. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177940. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177941. * you'll get compile errors until you extend this logic. In that case
  177942. * you'll probably want to tweak the histogram sizes too.
  177943. */
  177944. #if RGB_RED == 0
  177945. #define C0_SCALE R_SCALE
  177946. #endif
  177947. #if RGB_BLUE == 0
  177948. #define C0_SCALE B_SCALE
  177949. #endif
  177950. #if RGB_GREEN == 1
  177951. #define C1_SCALE G_SCALE
  177952. #endif
  177953. #if RGB_RED == 2
  177954. #define C2_SCALE R_SCALE
  177955. #endif
  177956. #if RGB_BLUE == 2
  177957. #define C2_SCALE B_SCALE
  177958. #endif
  177959. /*
  177960. * First we have the histogram data structure and routines for creating it.
  177961. *
  177962. * The number of bits of precision can be adjusted by changing these symbols.
  177963. * We recommend keeping 6 bits for G and 5 each for R and B.
  177964. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177965. * better results; if you are short of memory, 5 bits all around will save
  177966. * some space but degrade the results.
  177967. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177968. * (preferably unsigned long) for each cell. In practice this is overkill;
  177969. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177970. * and clamping those that do overflow to the maximum value will give close-
  177971. * enough results. This reduces the recommended histogram size from 256Kb
  177972. * to 128Kb, which is a useful savings on PC-class machines.
  177973. * (In the second pass the histogram space is re-used for pixel mapping data;
  177974. * in that capacity, each cell must be able to store zero to the number of
  177975. * desired colors. 16 bits/cell is plenty for that too.)
  177976. * Since the JPEG code is intended to run in small memory model on 80x86
  177977. * machines, we can't just allocate the histogram in one chunk. Instead
  177978. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177979. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177980. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177981. * on 80x86 machines, the pointer row is in near memory but the actual
  177982. * arrays are in far memory (same arrangement as we use for image arrays).
  177983. */
  177984. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177985. /* These will do the right thing for either R,G,B or B,G,R color order,
  177986. * but you may not like the results for other color orders.
  177987. */
  177988. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177989. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177990. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177991. /* Number of elements along histogram axes. */
  177992. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177993. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177994. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177995. /* These are the amounts to shift an input value to get a histogram index. */
  177996. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177997. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177998. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177999. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  178000. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  178001. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  178002. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  178003. typedef hist2d * hist3d; /* type for top-level pointer */
  178004. /* Declarations for Floyd-Steinberg dithering.
  178005. *
  178006. * Errors are accumulated into the array fserrors[], at a resolution of
  178007. * 1/16th of a pixel count. The error at a given pixel is propagated
  178008. * to its not-yet-processed neighbors using the standard F-S fractions,
  178009. * ... (here) 7/16
  178010. * 3/16 5/16 1/16
  178011. * We work left-to-right on even rows, right-to-left on odd rows.
  178012. *
  178013. * We can get away with a single array (holding one row's worth of errors)
  178014. * by using it to store the current row's errors at pixel columns not yet
  178015. * processed, but the next row's errors at columns already processed. We
  178016. * need only a few extra variables to hold the errors immediately around the
  178017. * current column. (If we are lucky, those variables are in registers, but
  178018. * even if not, they're probably cheaper to access than array elements are.)
  178019. *
  178020. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  178021. * each end saves us from special-casing the first and last pixels.
  178022. * Each entry is three values long, one value for each color component.
  178023. *
  178024. * Note: on a wide image, we might not have enough room in a PC's near data
  178025. * segment to hold the error array; so it is allocated with alloc_large.
  178026. */
  178027. #if BITS_IN_JSAMPLE == 8
  178028. typedef INT16 FSERROR; /* 16 bits should be enough */
  178029. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  178030. #else
  178031. typedef INT32 FSERROR; /* may need more than 16 bits */
  178032. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  178033. #endif
  178034. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  178035. /* Private subobject */
  178036. typedef struct {
  178037. struct jpeg_color_quantizer pub; /* public fields */
  178038. /* Space for the eventually created colormap is stashed here */
  178039. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  178040. int desired; /* desired # of colors = size of colormap */
  178041. /* Variables for accumulating image statistics */
  178042. hist3d histogram; /* pointer to the histogram */
  178043. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  178044. /* Variables for Floyd-Steinberg dithering */
  178045. FSERRPTR fserrors; /* accumulated errors */
  178046. boolean on_odd_row; /* flag to remember which row we are on */
  178047. int * error_limiter; /* table for clamping the applied error */
  178048. } my_cquantizer2;
  178049. typedef my_cquantizer2 * my_cquantize_ptr2;
  178050. /*
  178051. * Prescan some rows of pixels.
  178052. * In this module the prescan simply updates the histogram, which has been
  178053. * initialized to zeroes by start_pass.
  178054. * An output_buf parameter is required by the method signature, but no data
  178055. * is actually output (in fact the buffer controller is probably passing a
  178056. * NULL pointer).
  178057. */
  178058. METHODDEF(void)
  178059. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178060. JSAMPARRAY, int num_rows)
  178061. {
  178062. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178063. register JSAMPROW ptr;
  178064. register histptr histp;
  178065. register hist3d histogram = cquantize->histogram;
  178066. int row;
  178067. JDIMENSION col;
  178068. JDIMENSION width = cinfo->output_width;
  178069. for (row = 0; row < num_rows; row++) {
  178070. ptr = input_buf[row];
  178071. for (col = width; col > 0; col--) {
  178072. /* get pixel value and index into the histogram */
  178073. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  178074. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  178075. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  178076. /* increment, check for overflow and undo increment if so. */
  178077. if (++(*histp) <= 0)
  178078. (*histp)--;
  178079. ptr += 3;
  178080. }
  178081. }
  178082. }
  178083. /*
  178084. * Next we have the really interesting routines: selection of a colormap
  178085. * given the completed histogram.
  178086. * These routines work with a list of "boxes", each representing a rectangular
  178087. * subset of the input color space (to histogram precision).
  178088. */
  178089. typedef struct {
  178090. /* The bounds of the box (inclusive); expressed as histogram indexes */
  178091. int c0min, c0max;
  178092. int c1min, c1max;
  178093. int c2min, c2max;
  178094. /* The volume (actually 2-norm) of the box */
  178095. INT32 volume;
  178096. /* The number of nonzero histogram cells within this box */
  178097. long colorcount;
  178098. } box;
  178099. typedef box * boxptr;
  178100. LOCAL(boxptr)
  178101. find_biggest_color_pop (boxptr boxlist, int numboxes)
  178102. /* Find the splittable box with the largest color population */
  178103. /* Returns NULL if no splittable boxes remain */
  178104. {
  178105. register boxptr boxp;
  178106. register int i;
  178107. register long maxc = 0;
  178108. boxptr which = NULL;
  178109. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178110. if (boxp->colorcount > maxc && boxp->volume > 0) {
  178111. which = boxp;
  178112. maxc = boxp->colorcount;
  178113. }
  178114. }
  178115. return which;
  178116. }
  178117. LOCAL(boxptr)
  178118. find_biggest_volume (boxptr boxlist, int numboxes)
  178119. /* Find the splittable box with the largest (scaled) volume */
  178120. /* Returns NULL if no splittable boxes remain */
  178121. {
  178122. register boxptr boxp;
  178123. register int i;
  178124. register INT32 maxv = 0;
  178125. boxptr which = NULL;
  178126. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178127. if (boxp->volume > maxv) {
  178128. which = boxp;
  178129. maxv = boxp->volume;
  178130. }
  178131. }
  178132. return which;
  178133. }
  178134. LOCAL(void)
  178135. update_box (j_decompress_ptr cinfo, boxptr boxp)
  178136. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  178137. /* and recompute its volume and population */
  178138. {
  178139. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178140. hist3d histogram = cquantize->histogram;
  178141. histptr histp;
  178142. int c0,c1,c2;
  178143. int c0min,c0max,c1min,c1max,c2min,c2max;
  178144. INT32 dist0,dist1,dist2;
  178145. long ccount;
  178146. c0min = boxp->c0min; c0max = boxp->c0max;
  178147. c1min = boxp->c1min; c1max = boxp->c1max;
  178148. c2min = boxp->c2min; c2max = boxp->c2max;
  178149. if (c0max > c0min)
  178150. for (c0 = c0min; c0 <= c0max; c0++)
  178151. for (c1 = c1min; c1 <= c1max; c1++) {
  178152. histp = & histogram[c0][c1][c2min];
  178153. for (c2 = c2min; c2 <= c2max; c2++)
  178154. if (*histp++ != 0) {
  178155. boxp->c0min = c0min = c0;
  178156. goto have_c0min;
  178157. }
  178158. }
  178159. have_c0min:
  178160. if (c0max > c0min)
  178161. for (c0 = c0max; c0 >= c0min; c0--)
  178162. for (c1 = c1min; c1 <= c1max; c1++) {
  178163. histp = & histogram[c0][c1][c2min];
  178164. for (c2 = c2min; c2 <= c2max; c2++)
  178165. if (*histp++ != 0) {
  178166. boxp->c0max = c0max = c0;
  178167. goto have_c0max;
  178168. }
  178169. }
  178170. have_c0max:
  178171. if (c1max > c1min)
  178172. for (c1 = c1min; c1 <= c1max; c1++)
  178173. for (c0 = c0min; c0 <= c0max; c0++) {
  178174. histp = & histogram[c0][c1][c2min];
  178175. for (c2 = c2min; c2 <= c2max; c2++)
  178176. if (*histp++ != 0) {
  178177. boxp->c1min = c1min = c1;
  178178. goto have_c1min;
  178179. }
  178180. }
  178181. have_c1min:
  178182. if (c1max > c1min)
  178183. for (c1 = c1max; c1 >= c1min; c1--)
  178184. for (c0 = c0min; c0 <= c0max; c0++) {
  178185. histp = & histogram[c0][c1][c2min];
  178186. for (c2 = c2min; c2 <= c2max; c2++)
  178187. if (*histp++ != 0) {
  178188. boxp->c1max = c1max = c1;
  178189. goto have_c1max;
  178190. }
  178191. }
  178192. have_c1max:
  178193. if (c2max > c2min)
  178194. for (c2 = c2min; c2 <= c2max; c2++)
  178195. for (c0 = c0min; c0 <= c0max; c0++) {
  178196. histp = & histogram[c0][c1min][c2];
  178197. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178198. if (*histp != 0) {
  178199. boxp->c2min = c2min = c2;
  178200. goto have_c2min;
  178201. }
  178202. }
  178203. have_c2min:
  178204. if (c2max > c2min)
  178205. for (c2 = c2max; c2 >= c2min; c2--)
  178206. for (c0 = c0min; c0 <= c0max; c0++) {
  178207. histp = & histogram[c0][c1min][c2];
  178208. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178209. if (*histp != 0) {
  178210. boxp->c2max = c2max = c2;
  178211. goto have_c2max;
  178212. }
  178213. }
  178214. have_c2max:
  178215. /* Update box volume.
  178216. * We use 2-norm rather than real volume here; this biases the method
  178217. * against making long narrow boxes, and it has the side benefit that
  178218. * a box is splittable iff norm > 0.
  178219. * Since the differences are expressed in histogram-cell units,
  178220. * we have to shift back to JSAMPLE units to get consistent distances;
  178221. * after which, we scale according to the selected distance scale factors.
  178222. */
  178223. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178224. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178225. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178226. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178227. /* Now scan remaining volume of box and compute population */
  178228. ccount = 0;
  178229. for (c0 = c0min; c0 <= c0max; c0++)
  178230. for (c1 = c1min; c1 <= c1max; c1++) {
  178231. histp = & histogram[c0][c1][c2min];
  178232. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178233. if (*histp != 0) {
  178234. ccount++;
  178235. }
  178236. }
  178237. boxp->colorcount = ccount;
  178238. }
  178239. LOCAL(int)
  178240. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178241. int desired_colors)
  178242. /* Repeatedly select and split the largest box until we have enough boxes */
  178243. {
  178244. int n,lb;
  178245. int c0,c1,c2,cmax;
  178246. register boxptr b1,b2;
  178247. while (numboxes < desired_colors) {
  178248. /* Select box to split.
  178249. * Current algorithm: by population for first half, then by volume.
  178250. */
  178251. if (numboxes*2 <= desired_colors) {
  178252. b1 = find_biggest_color_pop(boxlist, numboxes);
  178253. } else {
  178254. b1 = find_biggest_volume(boxlist, numboxes);
  178255. }
  178256. if (b1 == NULL) /* no splittable boxes left! */
  178257. break;
  178258. b2 = &boxlist[numboxes]; /* where new box will go */
  178259. /* Copy the color bounds to the new box. */
  178260. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178261. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178262. /* Choose which axis to split the box on.
  178263. * Current algorithm: longest scaled axis.
  178264. * See notes in update_box about scaling distances.
  178265. */
  178266. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178267. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178268. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178269. /* We want to break any ties in favor of green, then red, blue last.
  178270. * This code does the right thing for R,G,B or B,G,R color orders only.
  178271. */
  178272. #if RGB_RED == 0
  178273. cmax = c1; n = 1;
  178274. if (c0 > cmax) { cmax = c0; n = 0; }
  178275. if (c2 > cmax) { n = 2; }
  178276. #else
  178277. cmax = c1; n = 1;
  178278. if (c2 > cmax) { cmax = c2; n = 2; }
  178279. if (c0 > cmax) { n = 0; }
  178280. #endif
  178281. /* Choose split point along selected axis, and update box bounds.
  178282. * Current algorithm: split at halfway point.
  178283. * (Since the box has been shrunk to minimum volume,
  178284. * any split will produce two nonempty subboxes.)
  178285. * Note that lb value is max for lower box, so must be < old max.
  178286. */
  178287. switch (n) {
  178288. case 0:
  178289. lb = (b1->c0max + b1->c0min) / 2;
  178290. b1->c0max = lb;
  178291. b2->c0min = lb+1;
  178292. break;
  178293. case 1:
  178294. lb = (b1->c1max + b1->c1min) / 2;
  178295. b1->c1max = lb;
  178296. b2->c1min = lb+1;
  178297. break;
  178298. case 2:
  178299. lb = (b1->c2max + b1->c2min) / 2;
  178300. b1->c2max = lb;
  178301. b2->c2min = lb+1;
  178302. break;
  178303. }
  178304. /* Update stats for boxes */
  178305. update_box(cinfo, b1);
  178306. update_box(cinfo, b2);
  178307. numboxes++;
  178308. }
  178309. return numboxes;
  178310. }
  178311. LOCAL(void)
  178312. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178313. /* Compute representative color for a box, put it in colormap[icolor] */
  178314. {
  178315. /* Current algorithm: mean weighted by pixels (not colors) */
  178316. /* Note it is important to get the rounding correct! */
  178317. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178318. hist3d histogram = cquantize->histogram;
  178319. histptr histp;
  178320. int c0,c1,c2;
  178321. int c0min,c0max,c1min,c1max,c2min,c2max;
  178322. long count;
  178323. long total = 0;
  178324. long c0total = 0;
  178325. long c1total = 0;
  178326. long c2total = 0;
  178327. c0min = boxp->c0min; c0max = boxp->c0max;
  178328. c1min = boxp->c1min; c1max = boxp->c1max;
  178329. c2min = boxp->c2min; c2max = boxp->c2max;
  178330. for (c0 = c0min; c0 <= c0max; c0++)
  178331. for (c1 = c1min; c1 <= c1max; c1++) {
  178332. histp = & histogram[c0][c1][c2min];
  178333. for (c2 = c2min; c2 <= c2max; c2++) {
  178334. if ((count = *histp++) != 0) {
  178335. total += count;
  178336. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178337. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178338. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178339. }
  178340. }
  178341. }
  178342. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178343. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178344. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178345. }
  178346. LOCAL(void)
  178347. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178348. /* Master routine for color selection */
  178349. {
  178350. boxptr boxlist;
  178351. int numboxes;
  178352. int i;
  178353. /* Allocate workspace for box list */
  178354. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178355. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178356. /* Initialize one box containing whole space */
  178357. numboxes = 1;
  178358. boxlist[0].c0min = 0;
  178359. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178360. boxlist[0].c1min = 0;
  178361. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178362. boxlist[0].c2min = 0;
  178363. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178364. /* Shrink it to actually-used volume and set its statistics */
  178365. update_box(cinfo, & boxlist[0]);
  178366. /* Perform median-cut to produce final box list */
  178367. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178368. /* Compute the representative color for each box, fill colormap */
  178369. for (i = 0; i < numboxes; i++)
  178370. compute_color(cinfo, & boxlist[i], i);
  178371. cinfo->actual_number_of_colors = numboxes;
  178372. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178373. }
  178374. /*
  178375. * These routines are concerned with the time-critical task of mapping input
  178376. * colors to the nearest color in the selected colormap.
  178377. *
  178378. * We re-use the histogram space as an "inverse color map", essentially a
  178379. * cache for the results of nearest-color searches. All colors within a
  178380. * histogram cell will be mapped to the same colormap entry, namely the one
  178381. * closest to the cell's center. This may not be quite the closest entry to
  178382. * the actual input color, but it's almost as good. A zero in the cache
  178383. * indicates we haven't found the nearest color for that cell yet; the array
  178384. * is cleared to zeroes before starting the mapping pass. When we find the
  178385. * nearest color for a cell, its colormap index plus one is recorded in the
  178386. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178387. * when they need to use an unfilled entry in the cache.
  178388. *
  178389. * Our method of efficiently finding nearest colors is based on the "locally
  178390. * sorted search" idea described by Heckbert and on the incremental distance
  178391. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178392. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178393. * the distances from a given colormap entry to each cell of the histogram can
  178394. * be computed quickly using an incremental method: the differences between
  178395. * distances to adjacent cells themselves differ by a constant. This allows a
  178396. * fairly fast implementation of the "brute force" approach of computing the
  178397. * distance from every colormap entry to every histogram cell. Unfortunately,
  178398. * it needs a work array to hold the best-distance-so-far for each histogram
  178399. * cell (because the inner loop has to be over cells, not colormap entries).
  178400. * The work array elements have to be INT32s, so the work array would need
  178401. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178402. *
  178403. * To get around these problems, we apply Thomas' method to compute the
  178404. * nearest colors for only the cells within a small subbox of the histogram.
  178405. * The work array need be only as big as the subbox, so the memory usage
  178406. * problem is solved. Furthermore, we need not fill subboxes that are never
  178407. * referenced in pass2; many images use only part of the color gamut, so a
  178408. * fair amount of work is saved. An additional advantage of this
  178409. * approach is that we can apply Heckbert's locality criterion to quickly
  178410. * eliminate colormap entries that are far away from the subbox; typically
  178411. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178412. * and we need not compute their distances to individual cells in the subbox.
  178413. * The speed of this approach is heavily influenced by the subbox size: too
  178414. * small means too much overhead, too big loses because Heckbert's criterion
  178415. * can't eliminate as many colormap entries. Empirically the best subbox
  178416. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178417. *
  178418. * Thomas' article also describes a refined method which is asymptotically
  178419. * faster than the brute-force method, but it is also far more complex and
  178420. * cannot efficiently be applied to small subboxes. It is therefore not
  178421. * useful for programs intended to be portable to DOS machines. On machines
  178422. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178423. * refined method might be faster than the present code --- but then again,
  178424. * it might not be any faster, and it's certainly more complicated.
  178425. */
  178426. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178427. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178428. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178429. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178430. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178431. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178432. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178433. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178434. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178435. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178436. /*
  178437. * The next three routines implement inverse colormap filling. They could
  178438. * all be folded into one big routine, but splitting them up this way saves
  178439. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178440. * and may allow some compilers to produce better code by registerizing more
  178441. * inner-loop variables.
  178442. */
  178443. LOCAL(int)
  178444. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178445. JSAMPLE colorlist[])
  178446. /* Locate the colormap entries close enough to an update box to be candidates
  178447. * for the nearest entry to some cell(s) in the update box. The update box
  178448. * is specified by the center coordinates of its first cell. The number of
  178449. * candidate colormap entries is returned, and their colormap indexes are
  178450. * placed in colorlist[].
  178451. * This routine uses Heckbert's "locally sorted search" criterion to select
  178452. * the colors that need further consideration.
  178453. */
  178454. {
  178455. int numcolors = cinfo->actual_number_of_colors;
  178456. int maxc0, maxc1, maxc2;
  178457. int centerc0, centerc1, centerc2;
  178458. int i, x, ncolors;
  178459. INT32 minmaxdist, min_dist, max_dist, tdist;
  178460. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178461. /* Compute true coordinates of update box's upper corner and center.
  178462. * Actually we compute the coordinates of the center of the upper-corner
  178463. * histogram cell, which are the upper bounds of the volume we care about.
  178464. * Note that since ">>" rounds down, the "center" values may be closer to
  178465. * min than to max; hence comparisons to them must be "<=", not "<".
  178466. */
  178467. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178468. centerc0 = (minc0 + maxc0) >> 1;
  178469. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178470. centerc1 = (minc1 + maxc1) >> 1;
  178471. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178472. centerc2 = (minc2 + maxc2) >> 1;
  178473. /* For each color in colormap, find:
  178474. * 1. its minimum squared-distance to any point in the update box
  178475. * (zero if color is within update box);
  178476. * 2. its maximum squared-distance to any point in the update box.
  178477. * Both of these can be found by considering only the corners of the box.
  178478. * We save the minimum distance for each color in mindist[];
  178479. * only the smallest maximum distance is of interest.
  178480. */
  178481. minmaxdist = 0x7FFFFFFFL;
  178482. for (i = 0; i < numcolors; i++) {
  178483. /* We compute the squared-c0-distance term, then add in the other two. */
  178484. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178485. if (x < minc0) {
  178486. tdist = (x - minc0) * C0_SCALE;
  178487. min_dist = tdist*tdist;
  178488. tdist = (x - maxc0) * C0_SCALE;
  178489. max_dist = tdist*tdist;
  178490. } else if (x > maxc0) {
  178491. tdist = (x - maxc0) * C0_SCALE;
  178492. min_dist = tdist*tdist;
  178493. tdist = (x - minc0) * C0_SCALE;
  178494. max_dist = tdist*tdist;
  178495. } else {
  178496. /* within cell range so no contribution to min_dist */
  178497. min_dist = 0;
  178498. if (x <= centerc0) {
  178499. tdist = (x - maxc0) * C0_SCALE;
  178500. max_dist = tdist*tdist;
  178501. } else {
  178502. tdist = (x - minc0) * C0_SCALE;
  178503. max_dist = tdist*tdist;
  178504. }
  178505. }
  178506. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178507. if (x < minc1) {
  178508. tdist = (x - minc1) * C1_SCALE;
  178509. min_dist += tdist*tdist;
  178510. tdist = (x - maxc1) * C1_SCALE;
  178511. max_dist += tdist*tdist;
  178512. } else if (x > maxc1) {
  178513. tdist = (x - maxc1) * C1_SCALE;
  178514. min_dist += tdist*tdist;
  178515. tdist = (x - minc1) * C1_SCALE;
  178516. max_dist += tdist*tdist;
  178517. } else {
  178518. /* within cell range so no contribution to min_dist */
  178519. if (x <= centerc1) {
  178520. tdist = (x - maxc1) * C1_SCALE;
  178521. max_dist += tdist*tdist;
  178522. } else {
  178523. tdist = (x - minc1) * C1_SCALE;
  178524. max_dist += tdist*tdist;
  178525. }
  178526. }
  178527. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178528. if (x < minc2) {
  178529. tdist = (x - minc2) * C2_SCALE;
  178530. min_dist += tdist*tdist;
  178531. tdist = (x - maxc2) * C2_SCALE;
  178532. max_dist += tdist*tdist;
  178533. } else if (x > maxc2) {
  178534. tdist = (x - maxc2) * C2_SCALE;
  178535. min_dist += tdist*tdist;
  178536. tdist = (x - minc2) * C2_SCALE;
  178537. max_dist += tdist*tdist;
  178538. } else {
  178539. /* within cell range so no contribution to min_dist */
  178540. if (x <= centerc2) {
  178541. tdist = (x - maxc2) * C2_SCALE;
  178542. max_dist += tdist*tdist;
  178543. } else {
  178544. tdist = (x - minc2) * C2_SCALE;
  178545. max_dist += tdist*tdist;
  178546. }
  178547. }
  178548. mindist[i] = min_dist; /* save away the results */
  178549. if (max_dist < minmaxdist)
  178550. minmaxdist = max_dist;
  178551. }
  178552. /* Now we know that no cell in the update box is more than minmaxdist
  178553. * away from some colormap entry. Therefore, only colors that are
  178554. * within minmaxdist of some part of the box need be considered.
  178555. */
  178556. ncolors = 0;
  178557. for (i = 0; i < numcolors; i++) {
  178558. if (mindist[i] <= minmaxdist)
  178559. colorlist[ncolors++] = (JSAMPLE) i;
  178560. }
  178561. return ncolors;
  178562. }
  178563. LOCAL(void)
  178564. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178565. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178566. /* Find the closest colormap entry for each cell in the update box,
  178567. * given the list of candidate colors prepared by find_nearby_colors.
  178568. * Return the indexes of the closest entries in the bestcolor[] array.
  178569. * This routine uses Thomas' incremental distance calculation method to
  178570. * find the distance from a colormap entry to successive cells in the box.
  178571. */
  178572. {
  178573. int ic0, ic1, ic2;
  178574. int i, icolor;
  178575. register INT32 * bptr; /* pointer into bestdist[] array */
  178576. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178577. INT32 dist0, dist1; /* initial distance values */
  178578. register INT32 dist2; /* current distance in inner loop */
  178579. INT32 xx0, xx1; /* distance increments */
  178580. register INT32 xx2;
  178581. INT32 inc0, inc1, inc2; /* initial values for increments */
  178582. /* This array holds the distance to the nearest-so-far color for each cell */
  178583. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178584. /* Initialize best-distance for each cell of the update box */
  178585. bptr = bestdist;
  178586. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178587. *bptr++ = 0x7FFFFFFFL;
  178588. /* For each color selected by find_nearby_colors,
  178589. * compute its distance to the center of each cell in the box.
  178590. * If that's less than best-so-far, update best distance and color number.
  178591. */
  178592. /* Nominal steps between cell centers ("x" in Thomas article) */
  178593. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178594. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178595. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178596. for (i = 0; i < numcolors; i++) {
  178597. icolor = GETJSAMPLE(colorlist[i]);
  178598. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178599. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178600. dist0 = inc0*inc0;
  178601. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178602. dist0 += inc1*inc1;
  178603. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178604. dist0 += inc2*inc2;
  178605. /* Form the initial difference increments */
  178606. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178607. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178608. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178609. /* Now loop over all cells in box, updating distance per Thomas method */
  178610. bptr = bestdist;
  178611. cptr = bestcolor;
  178612. xx0 = inc0;
  178613. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178614. dist1 = dist0;
  178615. xx1 = inc1;
  178616. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178617. dist2 = dist1;
  178618. xx2 = inc2;
  178619. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178620. if (dist2 < *bptr) {
  178621. *bptr = dist2;
  178622. *cptr = (JSAMPLE) icolor;
  178623. }
  178624. dist2 += xx2;
  178625. xx2 += 2 * STEP_C2 * STEP_C2;
  178626. bptr++;
  178627. cptr++;
  178628. }
  178629. dist1 += xx1;
  178630. xx1 += 2 * STEP_C1 * STEP_C1;
  178631. }
  178632. dist0 += xx0;
  178633. xx0 += 2 * STEP_C0 * STEP_C0;
  178634. }
  178635. }
  178636. }
  178637. LOCAL(void)
  178638. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178639. /* Fill the inverse-colormap entries in the update box that contains */
  178640. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178641. /* we can fill as many others as we wish.) */
  178642. {
  178643. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178644. hist3d histogram = cquantize->histogram;
  178645. int minc0, minc1, minc2; /* lower left corner of update box */
  178646. int ic0, ic1, ic2;
  178647. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178648. register histptr cachep; /* pointer into main cache array */
  178649. /* This array lists the candidate colormap indexes. */
  178650. JSAMPLE colorlist[MAXNUMCOLORS];
  178651. int numcolors; /* number of candidate colors */
  178652. /* This array holds the actually closest colormap index for each cell. */
  178653. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178654. /* Convert cell coordinates to update box ID */
  178655. c0 >>= BOX_C0_LOG;
  178656. c1 >>= BOX_C1_LOG;
  178657. c2 >>= BOX_C2_LOG;
  178658. /* Compute true coordinates of update box's origin corner.
  178659. * Actually we compute the coordinates of the center of the corner
  178660. * histogram cell, which are the lower bounds of the volume we care about.
  178661. */
  178662. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178663. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178664. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178665. /* Determine which colormap entries are close enough to be candidates
  178666. * for the nearest entry to some cell in the update box.
  178667. */
  178668. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178669. /* Determine the actually nearest colors. */
  178670. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178671. bestcolor);
  178672. /* Save the best color numbers (plus 1) in the main cache array */
  178673. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178674. c1 <<= BOX_C1_LOG;
  178675. c2 <<= BOX_C2_LOG;
  178676. cptr = bestcolor;
  178677. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178678. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178679. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178680. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178681. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178682. }
  178683. }
  178684. }
  178685. }
  178686. /*
  178687. * Map some rows of pixels to the output colormapped representation.
  178688. */
  178689. METHODDEF(void)
  178690. pass2_no_dither (j_decompress_ptr cinfo,
  178691. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178692. /* This version performs no dithering */
  178693. {
  178694. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178695. hist3d histogram = cquantize->histogram;
  178696. register JSAMPROW inptr, outptr;
  178697. register histptr cachep;
  178698. register int c0, c1, c2;
  178699. int row;
  178700. JDIMENSION col;
  178701. JDIMENSION width = cinfo->output_width;
  178702. for (row = 0; row < num_rows; row++) {
  178703. inptr = input_buf[row];
  178704. outptr = output_buf[row];
  178705. for (col = width; col > 0; col--) {
  178706. /* get pixel value and index into the cache */
  178707. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178708. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178709. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178710. cachep = & histogram[c0][c1][c2];
  178711. /* If we have not seen this color before, find nearest colormap entry */
  178712. /* and update the cache */
  178713. if (*cachep == 0)
  178714. fill_inverse_cmap(cinfo, c0,c1,c2);
  178715. /* Now emit the colormap index for this cell */
  178716. *outptr++ = (JSAMPLE) (*cachep - 1);
  178717. }
  178718. }
  178719. }
  178720. METHODDEF(void)
  178721. pass2_fs_dither (j_decompress_ptr cinfo,
  178722. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178723. /* This version performs Floyd-Steinberg dithering */
  178724. {
  178725. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178726. hist3d histogram = cquantize->histogram;
  178727. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178728. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178729. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178730. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178731. JSAMPROW inptr; /* => current input pixel */
  178732. JSAMPROW outptr; /* => current output pixel */
  178733. histptr cachep;
  178734. int dir; /* +1 or -1 depending on direction */
  178735. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178736. int row;
  178737. JDIMENSION col;
  178738. JDIMENSION width = cinfo->output_width;
  178739. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178740. int *error_limit = cquantize->error_limiter;
  178741. JSAMPROW colormap0 = cinfo->colormap[0];
  178742. JSAMPROW colormap1 = cinfo->colormap[1];
  178743. JSAMPROW colormap2 = cinfo->colormap[2];
  178744. SHIFT_TEMPS
  178745. for (row = 0; row < num_rows; row++) {
  178746. inptr = input_buf[row];
  178747. outptr = output_buf[row];
  178748. if (cquantize->on_odd_row) {
  178749. /* work right to left in this row */
  178750. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178751. outptr += width-1;
  178752. dir = -1;
  178753. dir3 = -3;
  178754. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178755. cquantize->on_odd_row = FALSE; /* flip for next time */
  178756. } else {
  178757. /* work left to right in this row */
  178758. dir = 1;
  178759. dir3 = 3;
  178760. errorptr = cquantize->fserrors; /* => entry before first real column */
  178761. cquantize->on_odd_row = TRUE; /* flip for next time */
  178762. }
  178763. /* Preset error values: no error propagated to first pixel from left */
  178764. cur0 = cur1 = cur2 = 0;
  178765. /* and no error propagated to row below yet */
  178766. belowerr0 = belowerr1 = belowerr2 = 0;
  178767. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178768. for (col = width; col > 0; col--) {
  178769. /* curN holds the error propagated from the previous pixel on the
  178770. * current line. Add the error propagated from the previous line
  178771. * to form the complete error correction term for this pixel, and
  178772. * round the error term (which is expressed * 16) to an integer.
  178773. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178774. * for either sign of the error value.
  178775. * Note: errorptr points to *previous* column's array entry.
  178776. */
  178777. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178778. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178779. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178780. /* Limit the error using transfer function set by init_error_limit.
  178781. * See comments with init_error_limit for rationale.
  178782. */
  178783. cur0 = error_limit[cur0];
  178784. cur1 = error_limit[cur1];
  178785. cur2 = error_limit[cur2];
  178786. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178787. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178788. * this sets the required size of the range_limit array.
  178789. */
  178790. cur0 += GETJSAMPLE(inptr[0]);
  178791. cur1 += GETJSAMPLE(inptr[1]);
  178792. cur2 += GETJSAMPLE(inptr[2]);
  178793. cur0 = GETJSAMPLE(range_limit[cur0]);
  178794. cur1 = GETJSAMPLE(range_limit[cur1]);
  178795. cur2 = GETJSAMPLE(range_limit[cur2]);
  178796. /* Index into the cache with adjusted pixel value */
  178797. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178798. /* If we have not seen this color before, find nearest colormap */
  178799. /* entry and update the cache */
  178800. if (*cachep == 0)
  178801. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178802. /* Now emit the colormap index for this cell */
  178803. { register int pixcode = *cachep - 1;
  178804. *outptr = (JSAMPLE) pixcode;
  178805. /* Compute representation error for this pixel */
  178806. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178807. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178808. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178809. }
  178810. /* Compute error fractions to be propagated to adjacent pixels.
  178811. * Add these into the running sums, and simultaneously shift the
  178812. * next-line error sums left by 1 column.
  178813. */
  178814. { register LOCFSERROR bnexterr, delta;
  178815. bnexterr = cur0; /* Process component 0 */
  178816. delta = cur0 * 2;
  178817. cur0 += delta; /* form error * 3 */
  178818. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178819. cur0 += delta; /* form error * 5 */
  178820. bpreverr0 = belowerr0 + cur0;
  178821. belowerr0 = bnexterr;
  178822. cur0 += delta; /* form error * 7 */
  178823. bnexterr = cur1; /* Process component 1 */
  178824. delta = cur1 * 2;
  178825. cur1 += delta; /* form error * 3 */
  178826. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178827. cur1 += delta; /* form error * 5 */
  178828. bpreverr1 = belowerr1 + cur1;
  178829. belowerr1 = bnexterr;
  178830. cur1 += delta; /* form error * 7 */
  178831. bnexterr = cur2; /* Process component 2 */
  178832. delta = cur2 * 2;
  178833. cur2 += delta; /* form error * 3 */
  178834. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178835. cur2 += delta; /* form error * 5 */
  178836. bpreverr2 = belowerr2 + cur2;
  178837. belowerr2 = bnexterr;
  178838. cur2 += delta; /* form error * 7 */
  178839. }
  178840. /* At this point curN contains the 7/16 error value to be propagated
  178841. * to the next pixel on the current line, and all the errors for the
  178842. * next line have been shifted over. We are therefore ready to move on.
  178843. */
  178844. inptr += dir3; /* Advance pixel pointers to next column */
  178845. outptr += dir;
  178846. errorptr += dir3; /* advance errorptr to current column */
  178847. }
  178848. /* Post-loop cleanup: we must unload the final error values into the
  178849. * final fserrors[] entry. Note we need not unload belowerrN because
  178850. * it is for the dummy column before or after the actual array.
  178851. */
  178852. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178853. errorptr[1] = (FSERROR) bpreverr1;
  178854. errorptr[2] = (FSERROR) bpreverr2;
  178855. }
  178856. }
  178857. /*
  178858. * Initialize the error-limiting transfer function (lookup table).
  178859. * The raw F-S error computation can potentially compute error values of up to
  178860. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178861. * much less, otherwise obviously wrong pixels will be created. (Typical
  178862. * effects include weird fringes at color-area boundaries, isolated bright
  178863. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178864. * is to ensure that the "corners" of the color cube are allocated as output
  178865. * colors; then repeated errors in the same direction cannot cause cascading
  178866. * error buildup. However, that only prevents the error from getting
  178867. * completely out of hand; Aaron Giles reports that error limiting improves
  178868. * the results even with corner colors allocated.
  178869. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178870. * well, but the smoother transfer function used below is even better. Thanks
  178871. * to Aaron Giles for this idea.
  178872. */
  178873. LOCAL(void)
  178874. init_error_limit (j_decompress_ptr cinfo)
  178875. /* Allocate and fill in the error_limiter table */
  178876. {
  178877. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178878. int * table;
  178879. int in, out;
  178880. table = (int *) (*cinfo->mem->alloc_small)
  178881. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178882. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178883. cquantize->error_limiter = table;
  178884. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178885. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178886. out = 0;
  178887. for (in = 0; in < STEPSIZE; in++, out++) {
  178888. table[in] = out; table[-in] = -out;
  178889. }
  178890. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178891. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178892. table[in] = out; table[-in] = -out;
  178893. }
  178894. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178895. for (; in <= MAXJSAMPLE; in++) {
  178896. table[in] = out; table[-in] = -out;
  178897. }
  178898. #undef STEPSIZE
  178899. }
  178900. /*
  178901. * Finish up at the end of each pass.
  178902. */
  178903. METHODDEF(void)
  178904. finish_pass1 (j_decompress_ptr cinfo)
  178905. {
  178906. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178907. /* Select the representative colors and fill in cinfo->colormap */
  178908. cinfo->colormap = cquantize->sv_colormap;
  178909. select_colors(cinfo, cquantize->desired);
  178910. /* Force next pass to zero the color index table */
  178911. cquantize->needs_zeroed = TRUE;
  178912. }
  178913. METHODDEF(void)
  178914. finish_pass2 (j_decompress_ptr)
  178915. {
  178916. /* no work */
  178917. }
  178918. /*
  178919. * Initialize for each processing pass.
  178920. */
  178921. METHODDEF(void)
  178922. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178923. {
  178924. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178925. hist3d histogram = cquantize->histogram;
  178926. int i;
  178927. /* Only F-S dithering or no dithering is supported. */
  178928. /* If user asks for ordered dither, give him F-S. */
  178929. if (cinfo->dither_mode != JDITHER_NONE)
  178930. cinfo->dither_mode = JDITHER_FS;
  178931. if (is_pre_scan) {
  178932. /* Set up method pointers */
  178933. cquantize->pub.color_quantize = prescan_quantize;
  178934. cquantize->pub.finish_pass = finish_pass1;
  178935. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178936. } else {
  178937. /* Set up method pointers */
  178938. if (cinfo->dither_mode == JDITHER_FS)
  178939. cquantize->pub.color_quantize = pass2_fs_dither;
  178940. else
  178941. cquantize->pub.color_quantize = pass2_no_dither;
  178942. cquantize->pub.finish_pass = finish_pass2;
  178943. /* Make sure color count is acceptable */
  178944. i = cinfo->actual_number_of_colors;
  178945. if (i < 1)
  178946. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178947. if (i > MAXNUMCOLORS)
  178948. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178949. if (cinfo->dither_mode == JDITHER_FS) {
  178950. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178951. (3 * SIZEOF(FSERROR)));
  178952. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178953. if (cquantize->fserrors == NULL)
  178954. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178955. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178956. /* Initialize the propagated errors to zero. */
  178957. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178958. /* Make the error-limit table if we didn't already. */
  178959. if (cquantize->error_limiter == NULL)
  178960. init_error_limit(cinfo);
  178961. cquantize->on_odd_row = FALSE;
  178962. }
  178963. }
  178964. /* Zero the histogram or inverse color map, if necessary */
  178965. if (cquantize->needs_zeroed) {
  178966. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178967. jzero_far((void FAR *) histogram[i],
  178968. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178969. }
  178970. cquantize->needs_zeroed = FALSE;
  178971. }
  178972. }
  178973. /*
  178974. * Switch to a new external colormap between output passes.
  178975. */
  178976. METHODDEF(void)
  178977. new_color_map_2_quant (j_decompress_ptr cinfo)
  178978. {
  178979. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178980. /* Reset the inverse color map */
  178981. cquantize->needs_zeroed = TRUE;
  178982. }
  178983. /*
  178984. * Module initialization routine for 2-pass color quantization.
  178985. */
  178986. GLOBAL(void)
  178987. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178988. {
  178989. my_cquantize_ptr2 cquantize;
  178990. int i;
  178991. cquantize = (my_cquantize_ptr2)
  178992. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178993. SIZEOF(my_cquantizer2));
  178994. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178995. cquantize->pub.start_pass = start_pass_2_quant;
  178996. cquantize->pub.new_color_map = new_color_map_2_quant;
  178997. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178998. cquantize->error_limiter = NULL;
  178999. /* Make sure jdmaster didn't give me a case I can't handle */
  179000. if (cinfo->out_color_components != 3)
  179001. ERREXIT(cinfo, JERR_NOTIMPL);
  179002. /* Allocate the histogram/inverse colormap storage */
  179003. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  179004. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  179005. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179006. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  179007. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179008. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179009. }
  179010. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  179011. /* Allocate storage for the completed colormap, if required.
  179012. * We do this now since it is FAR storage and may affect
  179013. * the memory manager's space calculations.
  179014. */
  179015. if (cinfo->enable_2pass_quant) {
  179016. /* Make sure color count is acceptable */
  179017. int desired = cinfo->desired_number_of_colors;
  179018. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  179019. if (desired < 8)
  179020. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  179021. /* Make sure colormap indexes can be represented by JSAMPLEs */
  179022. if (desired > MAXNUMCOLORS)
  179023. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  179024. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  179025. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  179026. cquantize->desired = desired;
  179027. } else
  179028. cquantize->sv_colormap = NULL;
  179029. /* Only F-S dithering or no dithering is supported. */
  179030. /* If user asks for ordered dither, give him F-S. */
  179031. if (cinfo->dither_mode != JDITHER_NONE)
  179032. cinfo->dither_mode = JDITHER_FS;
  179033. /* Allocate Floyd-Steinberg workspace if necessary.
  179034. * This isn't really needed until pass 2, but again it is FAR storage.
  179035. * Although we will cope with a later change in dither_mode,
  179036. * we do not promise to honor max_memory_to_use if dither_mode changes.
  179037. */
  179038. if (cinfo->dither_mode == JDITHER_FS) {
  179039. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179040. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179041. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  179042. /* Might as well create the error-limiting table too. */
  179043. init_error_limit(cinfo);
  179044. }
  179045. }
  179046. #endif /* QUANT_2PASS_SUPPORTED */
  179047. /*** End of inlined file: jquant2.c ***/
  179048. /*** Start of inlined file: jutils.c ***/
  179049. #define JPEG_INTERNALS
  179050. /*
  179051. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  179052. * of a DCT block read in natural order (left to right, top to bottom).
  179053. */
  179054. #if 0 /* This table is not actually needed in v6a */
  179055. const int jpeg_zigzag_order[DCTSIZE2] = {
  179056. 0, 1, 5, 6, 14, 15, 27, 28,
  179057. 2, 4, 7, 13, 16, 26, 29, 42,
  179058. 3, 8, 12, 17, 25, 30, 41, 43,
  179059. 9, 11, 18, 24, 31, 40, 44, 53,
  179060. 10, 19, 23, 32, 39, 45, 52, 54,
  179061. 20, 22, 33, 38, 46, 51, 55, 60,
  179062. 21, 34, 37, 47, 50, 56, 59, 61,
  179063. 35, 36, 48, 49, 57, 58, 62, 63
  179064. };
  179065. #endif
  179066. /*
  179067. * jpeg_natural_order[i] is the natural-order position of the i'th element
  179068. * of zigzag order.
  179069. *
  179070. * When reading corrupted data, the Huffman decoders could attempt
  179071. * to reference an entry beyond the end of this array (if the decoded
  179072. * zero run length reaches past the end of the block). To prevent
  179073. * wild stores without adding an inner-loop test, we put some extra
  179074. * "63"s after the real entries. This will cause the extra coefficient
  179075. * to be stored in location 63 of the block, not somewhere random.
  179076. * The worst case would be a run-length of 15, which means we need 16
  179077. * fake entries.
  179078. */
  179079. const int jpeg_natural_order[DCTSIZE2+16] = {
  179080. 0, 1, 8, 16, 9, 2, 3, 10,
  179081. 17, 24, 32, 25, 18, 11, 4, 5,
  179082. 12, 19, 26, 33, 40, 48, 41, 34,
  179083. 27, 20, 13, 6, 7, 14, 21, 28,
  179084. 35, 42, 49, 56, 57, 50, 43, 36,
  179085. 29, 22, 15, 23, 30, 37, 44, 51,
  179086. 58, 59, 52, 45, 38, 31, 39, 46,
  179087. 53, 60, 61, 54, 47, 55, 62, 63,
  179088. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  179089. 63, 63, 63, 63, 63, 63, 63, 63
  179090. };
  179091. /*
  179092. * Arithmetic utilities
  179093. */
  179094. GLOBAL(long)
  179095. jdiv_round_up (long a, long b)
  179096. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  179097. /* Assumes a >= 0, b > 0 */
  179098. {
  179099. return (a + b - 1L) / b;
  179100. }
  179101. GLOBAL(long)
  179102. jround_up (long a, long b)
  179103. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  179104. /* Assumes a >= 0, b > 0 */
  179105. {
  179106. a += b - 1L;
  179107. return a - (a % b);
  179108. }
  179109. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  179110. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  179111. * are FAR and we're assuming a small-pointer memory model. However, some
  179112. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  179113. * in the small-model libraries. These will be used if USE_FMEM is defined.
  179114. * Otherwise, the routines below do it the hard way. (The performance cost
  179115. * is not all that great, because these routines aren't very heavily used.)
  179116. */
  179117. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  179118. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  179119. #define FMEMZERO(target,size) MEMZERO(target,size)
  179120. #else /* 80x86 case, define if we can */
  179121. #ifdef USE_FMEM
  179122. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  179123. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  179124. #endif
  179125. #endif
  179126. GLOBAL(void)
  179127. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  179128. JSAMPARRAY output_array, int dest_row,
  179129. int num_rows, JDIMENSION num_cols)
  179130. /* Copy some rows of samples from one place to another.
  179131. * num_rows rows are copied from input_array[source_row++]
  179132. * to output_array[dest_row++]; these areas may overlap for duplication.
  179133. * The source and destination arrays must be at least as wide as num_cols.
  179134. */
  179135. {
  179136. register JSAMPROW inptr, outptr;
  179137. #ifdef FMEMCOPY
  179138. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  179139. #else
  179140. register JDIMENSION count;
  179141. #endif
  179142. register int row;
  179143. input_array += source_row;
  179144. output_array += dest_row;
  179145. for (row = num_rows; row > 0; row--) {
  179146. inptr = *input_array++;
  179147. outptr = *output_array++;
  179148. #ifdef FMEMCOPY
  179149. FMEMCOPY(outptr, inptr, count);
  179150. #else
  179151. for (count = num_cols; count > 0; count--)
  179152. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179153. #endif
  179154. }
  179155. }
  179156. GLOBAL(void)
  179157. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179158. JDIMENSION num_blocks)
  179159. /* Copy a row of coefficient blocks from one place to another. */
  179160. {
  179161. #ifdef FMEMCOPY
  179162. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179163. #else
  179164. register JCOEFPTR inptr, outptr;
  179165. register long count;
  179166. inptr = (JCOEFPTR) input_row;
  179167. outptr = (JCOEFPTR) output_row;
  179168. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179169. *outptr++ = *inptr++;
  179170. }
  179171. #endif
  179172. }
  179173. GLOBAL(void)
  179174. jzero_far (void FAR * target, size_t bytestozero)
  179175. /* Zero out a chunk of FAR memory. */
  179176. /* This might be sample-array data, block-array data, or alloc_large data. */
  179177. {
  179178. #ifdef FMEMZERO
  179179. FMEMZERO(target, bytestozero);
  179180. #else
  179181. register char FAR * ptr = (char FAR *) target;
  179182. register size_t count;
  179183. for (count = bytestozero; count > 0; count--) {
  179184. *ptr++ = 0;
  179185. }
  179186. #endif
  179187. }
  179188. /*** End of inlined file: jutils.c ***/
  179189. /*** Start of inlined file: transupp.c ***/
  179190. /* Although this file really shouldn't have access to the library internals,
  179191. * it's helpful to let it call jround_up() and jcopy_block_row().
  179192. */
  179193. #define JPEG_INTERNALS
  179194. /*** Start of inlined file: transupp.h ***/
  179195. /* If you happen not to want the image transform support, disable it here */
  179196. #ifndef TRANSFORMS_SUPPORTED
  179197. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179198. #endif
  179199. /* Short forms of external names for systems with brain-damaged linkers. */
  179200. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179201. #define jtransform_request_workspace jTrRequest
  179202. #define jtransform_adjust_parameters jTrAdjust
  179203. #define jtransform_execute_transformation jTrExec
  179204. #define jcopy_markers_setup jCMrkSetup
  179205. #define jcopy_markers_execute jCMrkExec
  179206. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179207. /*
  179208. * Codes for supported types of image transformations.
  179209. */
  179210. typedef enum {
  179211. JXFORM_NONE, /* no transformation */
  179212. JXFORM_FLIP_H, /* horizontal flip */
  179213. JXFORM_FLIP_V, /* vertical flip */
  179214. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179215. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179216. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179217. JXFORM_ROT_180, /* 180-degree rotation */
  179218. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179219. } JXFORM_CODE;
  179220. /*
  179221. * Although rotating and flipping data expressed as DCT coefficients is not
  179222. * hard, there is an asymmetry in the JPEG format specification for images
  179223. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179224. * image edges are padded out to the next iMCU boundary with junk data; but
  179225. * no padding is possible at the top and left edges. If we were to flip
  179226. * the whole image including the pad data, then pad garbage would become
  179227. * visible at the top and/or left, and real pixels would disappear into the
  179228. * pad margins --- perhaps permanently, since encoders & decoders may not
  179229. * bother to preserve DCT blocks that appear to be completely outside the
  179230. * nominal image area. So, we have to exclude any partial iMCUs from the
  179231. * basic transformation.
  179232. *
  179233. * Transpose is the only transformation that can handle partial iMCUs at the
  179234. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179235. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179236. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179237. * The other transforms are defined as combinations of these basic transforms
  179238. * and process edge blocks in a way that preserves the equivalence.
  179239. *
  179240. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179241. * this is not strictly lossless, but it usually gives the best-looking
  179242. * result for odd-size images. Note that when this option is active,
  179243. * the expected mathematical equivalences between the transforms may not hold.
  179244. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179245. * followed by -rot 180 -trim trims both edges.)
  179246. *
  179247. * We also offer a "force to grayscale" option, which simply discards the
  179248. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179249. * the luminance channel is preserved exactly. It's not the same kind of
  179250. * thing as the rotate/flip transformations, but it's convenient to handle it
  179251. * as part of this package, mainly because the transformation routines have to
  179252. * be aware of the option to know how many components to work on.
  179253. */
  179254. typedef struct {
  179255. /* Options: set by caller */
  179256. JXFORM_CODE transform; /* image transform operator */
  179257. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179258. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179259. /* Internal workspace: caller should not touch these */
  179260. int num_components; /* # of components in workspace */
  179261. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179262. } jpeg_transform_info;
  179263. #if TRANSFORMS_SUPPORTED
  179264. /* Request any required workspace */
  179265. EXTERN(void) jtransform_request_workspace
  179266. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179267. /* Adjust output image parameters */
  179268. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179269. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179270. jvirt_barray_ptr *src_coef_arrays,
  179271. jpeg_transform_info *info));
  179272. /* Execute the actual transformation, if any */
  179273. EXTERN(void) jtransform_execute_transformation
  179274. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179275. jvirt_barray_ptr *src_coef_arrays,
  179276. jpeg_transform_info *info));
  179277. #endif /* TRANSFORMS_SUPPORTED */
  179278. /*
  179279. * Support for copying optional markers from source to destination file.
  179280. */
  179281. typedef enum {
  179282. JCOPYOPT_NONE, /* copy no optional markers */
  179283. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179284. JCOPYOPT_ALL /* copy all optional markers */
  179285. } JCOPY_OPTION;
  179286. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179287. /* Setup decompression object to save desired markers in memory */
  179288. EXTERN(void) jcopy_markers_setup
  179289. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179290. /* Copy markers saved in the given source object to the destination object */
  179291. EXTERN(void) jcopy_markers_execute
  179292. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179293. JCOPY_OPTION option));
  179294. /*** End of inlined file: transupp.h ***/
  179295. /* My own external interface */
  179296. #if TRANSFORMS_SUPPORTED
  179297. /*
  179298. * Lossless image transformation routines. These routines work on DCT
  179299. * coefficient arrays and thus do not require any lossy decompression
  179300. * or recompression of the image.
  179301. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179302. *
  179303. * Horizontal flipping is done in-place, using a single top-to-bottom
  179304. * pass through the virtual source array. It will thus be much the
  179305. * fastest option for images larger than main memory.
  179306. *
  179307. * The other routines require a set of destination virtual arrays, so they
  179308. * need twice as much memory as jpegtran normally does. The destination
  179309. * arrays are always written in normal scan order (top to bottom) because
  179310. * the virtual array manager expects this. The source arrays will be scanned
  179311. * in the corresponding order, which means multiple passes through the source
  179312. * arrays for most of the transforms. That could result in much thrashing
  179313. * if the image is larger than main memory.
  179314. *
  179315. * Some notes about the operating environment of the individual transform
  179316. * routines:
  179317. * 1. Both the source and destination virtual arrays are allocated from the
  179318. * source JPEG object, and therefore should be manipulated by calling the
  179319. * source's memory manager.
  179320. * 2. The destination's component count should be used. It may be smaller
  179321. * than the source's when forcing to grayscale.
  179322. * 3. Likewise the destination's sampling factors should be used. When
  179323. * forcing to grayscale the destination's sampling factors will be all 1,
  179324. * and we may as well take that as the effective iMCU size.
  179325. * 4. When "trim" is in effect, the destination's dimensions will be the
  179326. * trimmed values but the source's will be untrimmed.
  179327. * 5. All the routines assume that the source and destination buffers are
  179328. * padded out to a full iMCU boundary. This is true, although for the
  179329. * source buffer it is an undocumented property of jdcoefct.c.
  179330. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179331. * dimensions and ignore the source's.
  179332. */
  179333. LOCAL(void)
  179334. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179335. jvirt_barray_ptr *src_coef_arrays)
  179336. /* Horizontal flip; done in-place, so no separate dest array is required */
  179337. {
  179338. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179339. int ci, k, offset_y;
  179340. JBLOCKARRAY buffer;
  179341. JCOEFPTR ptr1, ptr2;
  179342. JCOEF temp1, temp2;
  179343. jpeg_component_info *compptr;
  179344. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179345. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179346. * mirroring by changing the signs of odd-numbered columns.
  179347. * Partial iMCUs at the right edge are left untouched.
  179348. */
  179349. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179350. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179351. compptr = dstinfo->comp_info + ci;
  179352. comp_width = MCU_cols * compptr->h_samp_factor;
  179353. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179354. blk_y += compptr->v_samp_factor) {
  179355. buffer = (*srcinfo->mem->access_virt_barray)
  179356. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179357. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179358. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179359. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179360. ptr1 = buffer[offset_y][blk_x];
  179361. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179362. /* this unrolled loop doesn't need to know which row it's on... */
  179363. for (k = 0; k < DCTSIZE2; k += 2) {
  179364. temp1 = *ptr1; /* swap even column */
  179365. temp2 = *ptr2;
  179366. *ptr1++ = temp2;
  179367. *ptr2++ = temp1;
  179368. temp1 = *ptr1; /* swap odd column with sign change */
  179369. temp2 = *ptr2;
  179370. *ptr1++ = -temp2;
  179371. *ptr2++ = -temp1;
  179372. }
  179373. }
  179374. }
  179375. }
  179376. }
  179377. }
  179378. LOCAL(void)
  179379. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179380. jvirt_barray_ptr *src_coef_arrays,
  179381. jvirt_barray_ptr *dst_coef_arrays)
  179382. /* Vertical flip */
  179383. {
  179384. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179385. int ci, i, j, offset_y;
  179386. JBLOCKARRAY src_buffer, dst_buffer;
  179387. JBLOCKROW src_row_ptr, dst_row_ptr;
  179388. JCOEFPTR src_ptr, dst_ptr;
  179389. jpeg_component_info *compptr;
  179390. /* We output into a separate array because we can't touch different
  179391. * rows of the source virtual array simultaneously. Otherwise, this
  179392. * is a pretty straightforward analog of horizontal flip.
  179393. * Within a DCT block, vertical mirroring is done by changing the signs
  179394. * of odd-numbered rows.
  179395. * Partial iMCUs at the bottom edge are copied verbatim.
  179396. */
  179397. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179398. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179399. compptr = dstinfo->comp_info + ci;
  179400. comp_height = MCU_rows * compptr->v_samp_factor;
  179401. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179402. dst_blk_y += compptr->v_samp_factor) {
  179403. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179404. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179405. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179406. if (dst_blk_y < comp_height) {
  179407. /* Row is within the mirrorable area. */
  179408. src_buffer = (*srcinfo->mem->access_virt_barray)
  179409. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179410. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179411. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179412. } else {
  179413. /* Bottom-edge blocks will be copied verbatim. */
  179414. src_buffer = (*srcinfo->mem->access_virt_barray)
  179415. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179416. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179417. }
  179418. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179419. if (dst_blk_y < comp_height) {
  179420. /* Row is within the mirrorable area. */
  179421. dst_row_ptr = dst_buffer[offset_y];
  179422. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179423. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179424. dst_blk_x++) {
  179425. dst_ptr = dst_row_ptr[dst_blk_x];
  179426. src_ptr = src_row_ptr[dst_blk_x];
  179427. for (i = 0; i < DCTSIZE; i += 2) {
  179428. /* copy even row */
  179429. for (j = 0; j < DCTSIZE; j++)
  179430. *dst_ptr++ = *src_ptr++;
  179431. /* copy odd row with sign change */
  179432. for (j = 0; j < DCTSIZE; j++)
  179433. *dst_ptr++ = - *src_ptr++;
  179434. }
  179435. }
  179436. } else {
  179437. /* Just copy row verbatim. */
  179438. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179439. compptr->width_in_blocks);
  179440. }
  179441. }
  179442. }
  179443. }
  179444. }
  179445. LOCAL(void)
  179446. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179447. jvirt_barray_ptr *src_coef_arrays,
  179448. jvirt_barray_ptr *dst_coef_arrays)
  179449. /* Transpose source into destination */
  179450. {
  179451. JDIMENSION dst_blk_x, dst_blk_y;
  179452. int ci, i, j, offset_x, offset_y;
  179453. JBLOCKARRAY src_buffer, dst_buffer;
  179454. JCOEFPTR src_ptr, dst_ptr;
  179455. jpeg_component_info *compptr;
  179456. /* Transposing pixels within a block just requires transposing the
  179457. * DCT coefficients.
  179458. * Partial iMCUs at the edges require no special treatment; we simply
  179459. * process all the available DCT blocks for every component.
  179460. */
  179461. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179462. compptr = dstinfo->comp_info + ci;
  179463. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179464. dst_blk_y += compptr->v_samp_factor) {
  179465. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179466. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179467. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179468. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179469. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179470. dst_blk_x += compptr->h_samp_factor) {
  179471. src_buffer = (*srcinfo->mem->access_virt_barray)
  179472. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179473. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179474. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179475. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179476. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179477. for (i = 0; i < DCTSIZE; i++)
  179478. for (j = 0; j < DCTSIZE; j++)
  179479. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179480. }
  179481. }
  179482. }
  179483. }
  179484. }
  179485. }
  179486. LOCAL(void)
  179487. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179488. jvirt_barray_ptr *src_coef_arrays,
  179489. jvirt_barray_ptr *dst_coef_arrays)
  179490. /* 90 degree rotation is equivalent to
  179491. * 1. Transposing the image;
  179492. * 2. Horizontal mirroring.
  179493. * These two steps are merged into a single processing routine.
  179494. */
  179495. {
  179496. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179497. int ci, i, j, offset_x, offset_y;
  179498. JBLOCKARRAY src_buffer, dst_buffer;
  179499. JCOEFPTR src_ptr, dst_ptr;
  179500. jpeg_component_info *compptr;
  179501. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179502. * at the (output) right edge properly. They just get transposed and
  179503. * not mirrored.
  179504. */
  179505. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179506. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179507. compptr = dstinfo->comp_info + ci;
  179508. comp_width = MCU_cols * compptr->h_samp_factor;
  179509. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179510. dst_blk_y += compptr->v_samp_factor) {
  179511. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179512. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179513. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179514. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179515. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179516. dst_blk_x += compptr->h_samp_factor) {
  179517. src_buffer = (*srcinfo->mem->access_virt_barray)
  179518. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179519. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179520. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179521. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179522. if (dst_blk_x < comp_width) {
  179523. /* Block is within the mirrorable area. */
  179524. dst_ptr = dst_buffer[offset_y]
  179525. [comp_width - dst_blk_x - offset_x - 1];
  179526. for (i = 0; i < DCTSIZE; i++) {
  179527. for (j = 0; j < DCTSIZE; j++)
  179528. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179529. i++;
  179530. for (j = 0; j < DCTSIZE; j++)
  179531. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179532. }
  179533. } else {
  179534. /* Edge blocks are transposed but not mirrored. */
  179535. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179536. for (i = 0; i < DCTSIZE; i++)
  179537. for (j = 0; j < DCTSIZE; j++)
  179538. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179539. }
  179540. }
  179541. }
  179542. }
  179543. }
  179544. }
  179545. }
  179546. LOCAL(void)
  179547. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179548. jvirt_barray_ptr *src_coef_arrays,
  179549. jvirt_barray_ptr *dst_coef_arrays)
  179550. /* 270 degree rotation is equivalent to
  179551. * 1. Horizontal mirroring;
  179552. * 2. Transposing the image.
  179553. * These two steps are merged into a single processing routine.
  179554. */
  179555. {
  179556. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179557. int ci, i, j, offset_x, offset_y;
  179558. JBLOCKARRAY src_buffer, dst_buffer;
  179559. JCOEFPTR src_ptr, dst_ptr;
  179560. jpeg_component_info *compptr;
  179561. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179562. * at the (output) bottom edge properly. They just get transposed and
  179563. * not mirrored.
  179564. */
  179565. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179566. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179567. compptr = dstinfo->comp_info + ci;
  179568. comp_height = MCU_rows * compptr->v_samp_factor;
  179569. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179570. dst_blk_y += compptr->v_samp_factor) {
  179571. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179572. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179573. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179574. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179575. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179576. dst_blk_x += compptr->h_samp_factor) {
  179577. src_buffer = (*srcinfo->mem->access_virt_barray)
  179578. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179579. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179580. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179581. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179582. if (dst_blk_y < comp_height) {
  179583. /* Block is within the mirrorable area. */
  179584. src_ptr = src_buffer[offset_x]
  179585. [comp_height - dst_blk_y - offset_y - 1];
  179586. for (i = 0; i < DCTSIZE; i++) {
  179587. for (j = 0; j < DCTSIZE; j++) {
  179588. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179589. j++;
  179590. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179591. }
  179592. }
  179593. } else {
  179594. /* Edge blocks are transposed but not mirrored. */
  179595. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179596. for (i = 0; i < DCTSIZE; i++)
  179597. for (j = 0; j < DCTSIZE; j++)
  179598. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179599. }
  179600. }
  179601. }
  179602. }
  179603. }
  179604. }
  179605. }
  179606. LOCAL(void)
  179607. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179608. jvirt_barray_ptr *src_coef_arrays,
  179609. jvirt_barray_ptr *dst_coef_arrays)
  179610. /* 180 degree rotation is equivalent to
  179611. * 1. Vertical mirroring;
  179612. * 2. Horizontal mirroring.
  179613. * These two steps are merged into a single processing routine.
  179614. */
  179615. {
  179616. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179617. int ci, i, j, offset_y;
  179618. JBLOCKARRAY src_buffer, dst_buffer;
  179619. JBLOCKROW src_row_ptr, dst_row_ptr;
  179620. JCOEFPTR src_ptr, dst_ptr;
  179621. jpeg_component_info *compptr;
  179622. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179623. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179624. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179625. compptr = dstinfo->comp_info + ci;
  179626. comp_width = MCU_cols * compptr->h_samp_factor;
  179627. comp_height = MCU_rows * compptr->v_samp_factor;
  179628. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179629. dst_blk_y += compptr->v_samp_factor) {
  179630. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179631. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179632. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179633. if (dst_blk_y < comp_height) {
  179634. /* Row is within the vertically mirrorable area. */
  179635. src_buffer = (*srcinfo->mem->access_virt_barray)
  179636. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179637. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179638. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179639. } else {
  179640. /* Bottom-edge rows are only mirrored horizontally. */
  179641. src_buffer = (*srcinfo->mem->access_virt_barray)
  179642. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179643. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179644. }
  179645. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179646. if (dst_blk_y < comp_height) {
  179647. /* Row is within the mirrorable area. */
  179648. dst_row_ptr = dst_buffer[offset_y];
  179649. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179650. /* Process the blocks that can be mirrored both ways. */
  179651. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179652. dst_ptr = dst_row_ptr[dst_blk_x];
  179653. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179654. for (i = 0; i < DCTSIZE; i += 2) {
  179655. /* For even row, negate every odd column. */
  179656. for (j = 0; j < DCTSIZE; j += 2) {
  179657. *dst_ptr++ = *src_ptr++;
  179658. *dst_ptr++ = - *src_ptr++;
  179659. }
  179660. /* For odd row, negate every even column. */
  179661. for (j = 0; j < DCTSIZE; j += 2) {
  179662. *dst_ptr++ = - *src_ptr++;
  179663. *dst_ptr++ = *src_ptr++;
  179664. }
  179665. }
  179666. }
  179667. /* Any remaining right-edge blocks are only mirrored vertically. */
  179668. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179669. dst_ptr = dst_row_ptr[dst_blk_x];
  179670. src_ptr = src_row_ptr[dst_blk_x];
  179671. for (i = 0; i < DCTSIZE; i += 2) {
  179672. for (j = 0; j < DCTSIZE; j++)
  179673. *dst_ptr++ = *src_ptr++;
  179674. for (j = 0; j < DCTSIZE; j++)
  179675. *dst_ptr++ = - *src_ptr++;
  179676. }
  179677. }
  179678. } else {
  179679. /* Remaining rows are just mirrored horizontally. */
  179680. dst_row_ptr = dst_buffer[offset_y];
  179681. src_row_ptr = src_buffer[offset_y];
  179682. /* Process the blocks that can be mirrored. */
  179683. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179684. dst_ptr = dst_row_ptr[dst_blk_x];
  179685. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179686. for (i = 0; i < DCTSIZE2; i += 2) {
  179687. *dst_ptr++ = *src_ptr++;
  179688. *dst_ptr++ = - *src_ptr++;
  179689. }
  179690. }
  179691. /* Any remaining right-edge blocks are only copied. */
  179692. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179693. dst_ptr = dst_row_ptr[dst_blk_x];
  179694. src_ptr = src_row_ptr[dst_blk_x];
  179695. for (i = 0; i < DCTSIZE2; i++)
  179696. *dst_ptr++ = *src_ptr++;
  179697. }
  179698. }
  179699. }
  179700. }
  179701. }
  179702. }
  179703. LOCAL(void)
  179704. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179705. jvirt_barray_ptr *src_coef_arrays,
  179706. jvirt_barray_ptr *dst_coef_arrays)
  179707. /* Transverse transpose is equivalent to
  179708. * 1. 180 degree rotation;
  179709. * 2. Transposition;
  179710. * or
  179711. * 1. Horizontal mirroring;
  179712. * 2. Transposition;
  179713. * 3. Horizontal mirroring.
  179714. * These steps are merged into a single processing routine.
  179715. */
  179716. {
  179717. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179718. int ci, i, j, offset_x, offset_y;
  179719. JBLOCKARRAY src_buffer, dst_buffer;
  179720. JCOEFPTR src_ptr, dst_ptr;
  179721. jpeg_component_info *compptr;
  179722. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179723. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179724. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179725. compptr = dstinfo->comp_info + ci;
  179726. comp_width = MCU_cols * compptr->h_samp_factor;
  179727. comp_height = MCU_rows * compptr->v_samp_factor;
  179728. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179729. dst_blk_y += compptr->v_samp_factor) {
  179730. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179731. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179732. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179733. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179734. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179735. dst_blk_x += compptr->h_samp_factor) {
  179736. src_buffer = (*srcinfo->mem->access_virt_barray)
  179737. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179738. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179739. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179740. if (dst_blk_y < comp_height) {
  179741. src_ptr = src_buffer[offset_x]
  179742. [comp_height - dst_blk_y - offset_y - 1];
  179743. if (dst_blk_x < comp_width) {
  179744. /* Block is within the mirrorable area. */
  179745. dst_ptr = dst_buffer[offset_y]
  179746. [comp_width - dst_blk_x - offset_x - 1];
  179747. for (i = 0; i < DCTSIZE; i++) {
  179748. for (j = 0; j < DCTSIZE; j++) {
  179749. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179750. j++;
  179751. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179752. }
  179753. i++;
  179754. for (j = 0; j < DCTSIZE; j++) {
  179755. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179756. j++;
  179757. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179758. }
  179759. }
  179760. } else {
  179761. /* Right-edge blocks are mirrored in y only */
  179762. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179763. for (i = 0; i < DCTSIZE; i++) {
  179764. for (j = 0; j < DCTSIZE; j++) {
  179765. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179766. j++;
  179767. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179768. }
  179769. }
  179770. }
  179771. } else {
  179772. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179773. if (dst_blk_x < comp_width) {
  179774. /* Bottom-edge blocks are mirrored in x only */
  179775. dst_ptr = dst_buffer[offset_y]
  179776. [comp_width - dst_blk_x - offset_x - 1];
  179777. for (i = 0; i < DCTSIZE; i++) {
  179778. for (j = 0; j < DCTSIZE; j++)
  179779. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179780. i++;
  179781. for (j = 0; j < DCTSIZE; j++)
  179782. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179783. }
  179784. } else {
  179785. /* At lower right corner, just transpose, no mirroring */
  179786. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179787. for (i = 0; i < DCTSIZE; i++)
  179788. for (j = 0; j < DCTSIZE; j++)
  179789. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179790. }
  179791. }
  179792. }
  179793. }
  179794. }
  179795. }
  179796. }
  179797. }
  179798. /* Request any required workspace.
  179799. *
  179800. * We allocate the workspace virtual arrays from the source decompression
  179801. * object, so that all the arrays (both the original data and the workspace)
  179802. * will be taken into account while making memory management decisions.
  179803. * Hence, this routine must be called after jpeg_read_header (which reads
  179804. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179805. * the source's virtual arrays).
  179806. */
  179807. GLOBAL(void)
  179808. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179809. jpeg_transform_info *info)
  179810. {
  179811. jvirt_barray_ptr *coef_arrays = NULL;
  179812. jpeg_component_info *compptr;
  179813. int ci;
  179814. if (info->force_grayscale &&
  179815. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179816. srcinfo->num_components == 3) {
  179817. /* We'll only process the first component */
  179818. info->num_components = 1;
  179819. } else {
  179820. /* Process all the components */
  179821. info->num_components = srcinfo->num_components;
  179822. }
  179823. switch (info->transform) {
  179824. case JXFORM_NONE:
  179825. case JXFORM_FLIP_H:
  179826. /* Don't need a workspace array */
  179827. break;
  179828. case JXFORM_FLIP_V:
  179829. case JXFORM_ROT_180:
  179830. /* Need workspace arrays having same dimensions as source image.
  179831. * Note that we allocate arrays padded out to the next iMCU boundary,
  179832. * so that transform routines need not worry about missing edge blocks.
  179833. */
  179834. coef_arrays = (jvirt_barray_ptr *)
  179835. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179836. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179837. for (ci = 0; ci < info->num_components; ci++) {
  179838. compptr = srcinfo->comp_info + ci;
  179839. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179840. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179841. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179842. (long) compptr->h_samp_factor),
  179843. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179844. (long) compptr->v_samp_factor),
  179845. (JDIMENSION) compptr->v_samp_factor);
  179846. }
  179847. break;
  179848. case JXFORM_TRANSPOSE:
  179849. case JXFORM_TRANSVERSE:
  179850. case JXFORM_ROT_90:
  179851. case JXFORM_ROT_270:
  179852. /* Need workspace arrays having transposed dimensions.
  179853. * Note that we allocate arrays padded out to the next iMCU boundary,
  179854. * so that transform routines need not worry about missing edge blocks.
  179855. */
  179856. coef_arrays = (jvirt_barray_ptr *)
  179857. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179858. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179859. for (ci = 0; ci < info->num_components; ci++) {
  179860. compptr = srcinfo->comp_info + ci;
  179861. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179862. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179863. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179864. (long) compptr->v_samp_factor),
  179865. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179866. (long) compptr->h_samp_factor),
  179867. (JDIMENSION) compptr->h_samp_factor);
  179868. }
  179869. break;
  179870. }
  179871. info->workspace_coef_arrays = coef_arrays;
  179872. }
  179873. /* Transpose destination image parameters */
  179874. LOCAL(void)
  179875. transpose_critical_parameters (j_compress_ptr dstinfo)
  179876. {
  179877. int tblno, i, j, ci, itemp;
  179878. jpeg_component_info *compptr;
  179879. JQUANT_TBL *qtblptr;
  179880. JDIMENSION dtemp;
  179881. UINT16 qtemp;
  179882. /* Transpose basic image dimensions */
  179883. dtemp = dstinfo->image_width;
  179884. dstinfo->image_width = dstinfo->image_height;
  179885. dstinfo->image_height = dtemp;
  179886. /* Transpose sampling factors */
  179887. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179888. compptr = dstinfo->comp_info + ci;
  179889. itemp = compptr->h_samp_factor;
  179890. compptr->h_samp_factor = compptr->v_samp_factor;
  179891. compptr->v_samp_factor = itemp;
  179892. }
  179893. /* Transpose quantization tables */
  179894. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179895. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179896. if (qtblptr != NULL) {
  179897. for (i = 0; i < DCTSIZE; i++) {
  179898. for (j = 0; j < i; j++) {
  179899. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179900. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179901. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179902. }
  179903. }
  179904. }
  179905. }
  179906. }
  179907. /* Trim off any partial iMCUs on the indicated destination edge */
  179908. LOCAL(void)
  179909. trim_right_edge (j_compress_ptr dstinfo)
  179910. {
  179911. int ci, max_h_samp_factor;
  179912. JDIMENSION MCU_cols;
  179913. /* We have to compute max_h_samp_factor ourselves,
  179914. * because it hasn't been set yet in the destination
  179915. * (and we don't want to use the source's value).
  179916. */
  179917. max_h_samp_factor = 1;
  179918. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179919. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179920. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179921. }
  179922. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179923. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179924. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179925. }
  179926. LOCAL(void)
  179927. trim_bottom_edge (j_compress_ptr dstinfo)
  179928. {
  179929. int ci, max_v_samp_factor;
  179930. JDIMENSION MCU_rows;
  179931. /* We have to compute max_v_samp_factor ourselves,
  179932. * because it hasn't been set yet in the destination
  179933. * (and we don't want to use the source's value).
  179934. */
  179935. max_v_samp_factor = 1;
  179936. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179937. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179938. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179939. }
  179940. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179941. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179942. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179943. }
  179944. /* Adjust output image parameters as needed.
  179945. *
  179946. * This must be called after jpeg_copy_critical_parameters()
  179947. * and before jpeg_write_coefficients().
  179948. *
  179949. * The return value is the set of virtual coefficient arrays to be written
  179950. * (either the ones allocated by jtransform_request_workspace, or the
  179951. * original source data arrays). The caller will need to pass this value
  179952. * to jpeg_write_coefficients().
  179953. */
  179954. GLOBAL(jvirt_barray_ptr *)
  179955. jtransform_adjust_parameters (j_decompress_ptr,
  179956. j_compress_ptr dstinfo,
  179957. jvirt_barray_ptr *src_coef_arrays,
  179958. jpeg_transform_info *info)
  179959. {
  179960. /* If force-to-grayscale is requested, adjust destination parameters */
  179961. if (info->force_grayscale) {
  179962. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179963. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179964. * will get set to 1, which typically won't match the source.
  179965. * In fact we do this even if the source is already grayscale; that
  179966. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179967. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179968. */
  179969. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179970. dstinfo->num_components == 3) ||
  179971. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179972. dstinfo->num_components == 1)) {
  179973. /* We have to preserve the source's quantization table number. */
  179974. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179975. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179976. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179977. } else {
  179978. /* Sorry, can't do it */
  179979. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179980. }
  179981. }
  179982. /* Correct the destination's image dimensions etc if necessary */
  179983. switch (info->transform) {
  179984. case JXFORM_NONE:
  179985. /* Nothing to do */
  179986. break;
  179987. case JXFORM_FLIP_H:
  179988. if (info->trim)
  179989. trim_right_edge(dstinfo);
  179990. break;
  179991. case JXFORM_FLIP_V:
  179992. if (info->trim)
  179993. trim_bottom_edge(dstinfo);
  179994. break;
  179995. case JXFORM_TRANSPOSE:
  179996. transpose_critical_parameters(dstinfo);
  179997. /* transpose does NOT have to trim anything */
  179998. break;
  179999. case JXFORM_TRANSVERSE:
  180000. transpose_critical_parameters(dstinfo);
  180001. if (info->trim) {
  180002. trim_right_edge(dstinfo);
  180003. trim_bottom_edge(dstinfo);
  180004. }
  180005. break;
  180006. case JXFORM_ROT_90:
  180007. transpose_critical_parameters(dstinfo);
  180008. if (info->trim)
  180009. trim_right_edge(dstinfo);
  180010. break;
  180011. case JXFORM_ROT_180:
  180012. if (info->trim) {
  180013. trim_right_edge(dstinfo);
  180014. trim_bottom_edge(dstinfo);
  180015. }
  180016. break;
  180017. case JXFORM_ROT_270:
  180018. transpose_critical_parameters(dstinfo);
  180019. if (info->trim)
  180020. trim_bottom_edge(dstinfo);
  180021. break;
  180022. }
  180023. /* Return the appropriate output data set */
  180024. if (info->workspace_coef_arrays != NULL)
  180025. return info->workspace_coef_arrays;
  180026. return src_coef_arrays;
  180027. }
  180028. /* Execute the actual transformation, if any.
  180029. *
  180030. * This must be called *after* jpeg_write_coefficients, because it depends
  180031. * on jpeg_write_coefficients to have computed subsidiary values such as
  180032. * the per-component width and height fields in the destination object.
  180033. *
  180034. * Note that some transformations will modify the source data arrays!
  180035. */
  180036. GLOBAL(void)
  180037. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  180038. j_compress_ptr dstinfo,
  180039. jvirt_barray_ptr *src_coef_arrays,
  180040. jpeg_transform_info *info)
  180041. {
  180042. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  180043. switch (info->transform) {
  180044. case JXFORM_NONE:
  180045. break;
  180046. case JXFORM_FLIP_H:
  180047. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  180048. break;
  180049. case JXFORM_FLIP_V:
  180050. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180051. break;
  180052. case JXFORM_TRANSPOSE:
  180053. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180054. break;
  180055. case JXFORM_TRANSVERSE:
  180056. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180057. break;
  180058. case JXFORM_ROT_90:
  180059. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180060. break;
  180061. case JXFORM_ROT_180:
  180062. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180063. break;
  180064. case JXFORM_ROT_270:
  180065. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180066. break;
  180067. }
  180068. }
  180069. #endif /* TRANSFORMS_SUPPORTED */
  180070. /* Setup decompression object to save desired markers in memory.
  180071. * This must be called before jpeg_read_header() to have the desired effect.
  180072. */
  180073. GLOBAL(void)
  180074. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  180075. {
  180076. #ifdef SAVE_MARKERS_SUPPORTED
  180077. int m;
  180078. /* Save comments except under NONE option */
  180079. if (option != JCOPYOPT_NONE) {
  180080. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  180081. }
  180082. /* Save all types of APPn markers iff ALL option */
  180083. if (option == JCOPYOPT_ALL) {
  180084. for (m = 0; m < 16; m++)
  180085. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  180086. }
  180087. #endif /* SAVE_MARKERS_SUPPORTED */
  180088. }
  180089. /* Copy markers saved in the given source object to the destination object.
  180090. * This should be called just after jpeg_start_compress() or
  180091. * jpeg_write_coefficients().
  180092. * Note that those routines will have written the SOI, and also the
  180093. * JFIF APP0 or Adobe APP14 markers if selected.
  180094. */
  180095. GLOBAL(void)
  180096. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180097. JCOPY_OPTION)
  180098. {
  180099. jpeg_saved_marker_ptr marker;
  180100. /* In the current implementation, we don't actually need to examine the
  180101. * option flag here; we just copy everything that got saved.
  180102. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  180103. * if the encoder library already wrote one.
  180104. */
  180105. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  180106. if (dstinfo->write_JFIF_header &&
  180107. marker->marker == JPEG_APP0 &&
  180108. marker->data_length >= 5 &&
  180109. GETJOCTET(marker->data[0]) == 0x4A &&
  180110. GETJOCTET(marker->data[1]) == 0x46 &&
  180111. GETJOCTET(marker->data[2]) == 0x49 &&
  180112. GETJOCTET(marker->data[3]) == 0x46 &&
  180113. GETJOCTET(marker->data[4]) == 0)
  180114. continue; /* reject duplicate JFIF */
  180115. if (dstinfo->write_Adobe_marker &&
  180116. marker->marker == JPEG_APP0+14 &&
  180117. marker->data_length >= 5 &&
  180118. GETJOCTET(marker->data[0]) == 0x41 &&
  180119. GETJOCTET(marker->data[1]) == 0x64 &&
  180120. GETJOCTET(marker->data[2]) == 0x6F &&
  180121. GETJOCTET(marker->data[3]) == 0x62 &&
  180122. GETJOCTET(marker->data[4]) == 0x65)
  180123. continue; /* reject duplicate Adobe */
  180124. #ifdef NEED_FAR_POINTERS
  180125. /* We could use jpeg_write_marker if the data weren't FAR... */
  180126. {
  180127. unsigned int i;
  180128. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  180129. for (i = 0; i < marker->data_length; i++)
  180130. jpeg_write_m_byte(dstinfo, marker->data[i]);
  180131. }
  180132. #else
  180133. jpeg_write_marker(dstinfo, marker->marker,
  180134. marker->data, marker->data_length);
  180135. #endif
  180136. }
  180137. }
  180138. /*** End of inlined file: transupp.c ***/
  180139. #else
  180140. #define JPEG_INTERNALS
  180141. #undef FAR
  180142. #include <jpeglib.h>
  180143. #endif
  180144. }
  180145. #undef max
  180146. #undef min
  180147. #if JUCE_MSVC
  180148. #pragma warning (pop)
  180149. #endif
  180150. BEGIN_JUCE_NAMESPACE
  180151. namespace JPEGHelpers
  180152. {
  180153. using namespace jpeglibNamespace;
  180154. #if ! JUCE_MSVC
  180155. using jpeglibNamespace::boolean;
  180156. #endif
  180157. struct JPEGDecodingFailure {};
  180158. void fatalErrorHandler (j_common_ptr)
  180159. {
  180160. throw JPEGDecodingFailure();
  180161. }
  180162. void silentErrorCallback1 (j_common_ptr) {}
  180163. void silentErrorCallback2 (j_common_ptr, int) {}
  180164. void silentErrorCallback3 (j_common_ptr, char*) {}
  180165. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180166. {
  180167. zerostruct (err);
  180168. err.error_exit = fatalErrorHandler;
  180169. err.emit_message = silentErrorCallback2;
  180170. err.output_message = silentErrorCallback1;
  180171. err.format_message = silentErrorCallback3;
  180172. err.reset_error_mgr = silentErrorCallback1;
  180173. }
  180174. void dummyCallback1 (j_decompress_ptr)
  180175. {
  180176. }
  180177. void jpegSkip (j_decompress_ptr decompStruct, long num)
  180178. {
  180179. decompStruct->src->next_input_byte += num;
  180180. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180181. decompStruct->src->bytes_in_buffer -= num;
  180182. }
  180183. boolean jpegFill (j_decompress_ptr)
  180184. {
  180185. return 0;
  180186. }
  180187. const int jpegBufferSize = 512;
  180188. struct JuceJpegDest : public jpeg_destination_mgr
  180189. {
  180190. OutputStream* output;
  180191. char* buffer;
  180192. };
  180193. void jpegWriteInit (j_compress_ptr)
  180194. {
  180195. }
  180196. void jpegWriteTerminate (j_compress_ptr cinfo)
  180197. {
  180198. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180199. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180200. dest->output->write (dest->buffer, (int) numToWrite);
  180201. }
  180202. boolean jpegWriteFlush (j_compress_ptr cinfo)
  180203. {
  180204. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180205. const int numToWrite = jpegBufferSize;
  180206. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180207. dest->free_in_buffer = jpegBufferSize;
  180208. return dest->output->write (dest->buffer, numToWrite);
  180209. }
  180210. }
  180211. JPEGImageFormat::JPEGImageFormat()
  180212. : quality (-1.0f)
  180213. {
  180214. }
  180215. JPEGImageFormat::~JPEGImageFormat() {}
  180216. void JPEGImageFormat::setQuality (const float newQuality)
  180217. {
  180218. quality = newQuality;
  180219. }
  180220. const String JPEGImageFormat::getFormatName()
  180221. {
  180222. return "JPEG";
  180223. }
  180224. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180225. {
  180226. const int bytesNeeded = 10;
  180227. uint8 header [bytesNeeded];
  180228. if (in.read (header, bytesNeeded) == bytesNeeded)
  180229. {
  180230. return header[0] == 0xff
  180231. && header[1] == 0xd8
  180232. && header[2] == 0xff
  180233. && (header[3] == 0xe0 || header[3] == 0xe1);
  180234. }
  180235. return false;
  180236. }
  180237. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180238. const Image juce_loadWithCoreImage (InputStream& input);
  180239. #endif
  180240. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180241. {
  180242. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180243. return juce_loadWithCoreImage (in);
  180244. #else
  180245. using namespace jpeglibNamespace;
  180246. using namespace JPEGHelpers;
  180247. MemoryOutputStream mb;
  180248. mb.writeFromInputStream (in, -1);
  180249. Image image;
  180250. if (mb.getDataSize() > 16)
  180251. {
  180252. struct jpeg_decompress_struct jpegDecompStruct;
  180253. struct jpeg_error_mgr jerr;
  180254. setupSilentErrorHandler (jerr);
  180255. jpegDecompStruct.err = &jerr;
  180256. jpeg_create_decompress (&jpegDecompStruct);
  180257. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180258. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180259. jpegDecompStruct.src->init_source = dummyCallback1;
  180260. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180261. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180262. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180263. jpegDecompStruct.src->term_source = dummyCallback1;
  180264. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180265. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180266. try
  180267. {
  180268. jpeg_read_header (&jpegDecompStruct, TRUE);
  180269. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180270. const int width = jpegDecompStruct.output_width;
  180271. const int height = jpegDecompStruct.output_height;
  180272. jpegDecompStruct.out_color_space = JCS_RGB;
  180273. JSAMPARRAY buffer
  180274. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180275. JPOOL_IMAGE,
  180276. width * 3, 1);
  180277. if (jpeg_start_decompress (&jpegDecompStruct))
  180278. {
  180279. image = Image (Image::RGB, width, height, false);
  180280. image.getProperties()->set ("originalImageHadAlpha", false);
  180281. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180282. const Image::BitmapData destData (image, Image::BitmapData::writeOnly);
  180283. for (int y = 0; y < height; ++y)
  180284. {
  180285. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180286. const uint8* src = *buffer;
  180287. uint8* dest = destData.getLinePointer (y);
  180288. if (hasAlphaChan)
  180289. {
  180290. for (int i = width; --i >= 0;)
  180291. {
  180292. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180293. ((PixelARGB*) dest)->premultiply();
  180294. dest += destData.pixelStride;
  180295. src += 3;
  180296. }
  180297. }
  180298. else
  180299. {
  180300. for (int i = width; --i >= 0;)
  180301. {
  180302. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180303. dest += destData.pixelStride;
  180304. src += 3;
  180305. }
  180306. }
  180307. }
  180308. jpeg_finish_decompress (&jpegDecompStruct);
  180309. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180310. }
  180311. jpeg_destroy_decompress (&jpegDecompStruct);
  180312. }
  180313. catch (...)
  180314. {}
  180315. }
  180316. return image;
  180317. #endif
  180318. }
  180319. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180320. {
  180321. using namespace jpeglibNamespace;
  180322. using namespace JPEGHelpers;
  180323. if (image.hasAlphaChannel())
  180324. {
  180325. // this method could fill the background in white and still save the image..
  180326. jassertfalse;
  180327. return true;
  180328. }
  180329. struct jpeg_compress_struct jpegCompStruct;
  180330. struct jpeg_error_mgr jerr;
  180331. setupSilentErrorHandler (jerr);
  180332. jpegCompStruct.err = &jerr;
  180333. jpeg_create_compress (&jpegCompStruct);
  180334. JuceJpegDest dest;
  180335. jpegCompStruct.dest = &dest;
  180336. dest.output = &out;
  180337. HeapBlock <char> tempBuffer (jpegBufferSize);
  180338. dest.buffer = tempBuffer;
  180339. dest.next_output_byte = (JOCTET*) dest.buffer;
  180340. dest.free_in_buffer = jpegBufferSize;
  180341. dest.init_destination = jpegWriteInit;
  180342. dest.empty_output_buffer = jpegWriteFlush;
  180343. dest.term_destination = jpegWriteTerminate;
  180344. jpegCompStruct.image_width = image.getWidth();
  180345. jpegCompStruct.image_height = image.getHeight();
  180346. jpegCompStruct.input_components = 3;
  180347. jpegCompStruct.in_color_space = JCS_RGB;
  180348. jpegCompStruct.write_JFIF_header = 1;
  180349. jpegCompStruct.X_density = 72;
  180350. jpegCompStruct.Y_density = 72;
  180351. jpeg_set_defaults (&jpegCompStruct);
  180352. jpegCompStruct.dct_method = JDCT_FLOAT;
  180353. jpegCompStruct.optimize_coding = 1;
  180354. //jpegCompStruct.smoothing_factor = 10;
  180355. if (quality < 0.0f)
  180356. quality = 0.85f;
  180357. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180358. jpeg_start_compress (&jpegCompStruct, TRUE);
  180359. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180360. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180361. JPOOL_IMAGE, strideBytes, 1);
  180362. const Image::BitmapData srcData (image, Image::BitmapData::readOnly);
  180363. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180364. {
  180365. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180366. uint8* dst = *buffer;
  180367. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180368. {
  180369. *dst++ = ((const PixelRGB*) src)->getRed();
  180370. *dst++ = ((const PixelRGB*) src)->getGreen();
  180371. *dst++ = ((const PixelRGB*) src)->getBlue();
  180372. src += srcData.pixelStride;
  180373. }
  180374. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180375. }
  180376. jpeg_finish_compress (&jpegCompStruct);
  180377. jpeg_destroy_compress (&jpegCompStruct);
  180378. out.flush();
  180379. return true;
  180380. }
  180381. END_JUCE_NAMESPACE
  180382. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180383. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180384. #if JUCE_MSVC
  180385. #pragma warning (push)
  180386. #pragma warning (disable: 4390 4611)
  180387. #ifdef __INTEL_COMPILER
  180388. #pragma warning (disable: 2544 2545)
  180389. #endif
  180390. #endif
  180391. namespace zlibNamespace
  180392. {
  180393. #if JUCE_INCLUDE_ZLIB_CODE
  180394. #undef OS_CODE
  180395. #undef fdopen
  180396. #undef OS_CODE
  180397. #else
  180398. #include <zlib.h>
  180399. #endif
  180400. }
  180401. namespace pnglibNamespace
  180402. {
  180403. using namespace zlibNamespace;
  180404. #if JUCE_INCLUDE_PNGLIB_CODE
  180405. #if _MSC_VER != 1310
  180406. using ::calloc; // (causes conflict in VS.NET 2003)
  180407. using ::malloc;
  180408. using ::free;
  180409. #endif
  180410. using ::abs;
  180411. #define PNG_INTERNAL
  180412. #define NO_DUMMY_DECL
  180413. #define PNG_SETJMP_NOT_SUPPORTED
  180414. /*** Start of inlined file: png.h ***/
  180415. /* png.h - header file for PNG reference library
  180416. *
  180417. * libpng version 1.2.21 - October 4, 2007
  180418. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180419. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180420. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180421. *
  180422. * Authors and maintainers:
  180423. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180424. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180425. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180426. * See also "Contributing Authors", below.
  180427. *
  180428. * Note about libpng version numbers:
  180429. *
  180430. * Due to various miscommunications, unforeseen code incompatibilities
  180431. * and occasional factors outside the authors' control, version numbering
  180432. * on the library has not always been consistent and straightforward.
  180433. * The following table summarizes matters since version 0.89c, which was
  180434. * the first widely used release:
  180435. *
  180436. * source png.h png.h shared-lib
  180437. * version string int version
  180438. * ------- ------ ----- ----------
  180439. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180440. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180441. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180442. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180443. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180444. * 0.97c 0.97 97 2.0.97
  180445. * 0.98 0.98 98 2.0.98
  180446. * 0.99 0.99 98 2.0.99
  180447. * 0.99a-m 0.99 99 2.0.99
  180448. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180449. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180450. * 1.0.1 png.h string is 10001 2.1.0
  180451. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180452. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180453. * 1.0.2a-b 10003 version, except as noted.
  180454. * 1.0.3 10003
  180455. * 1.0.3a-d 10004
  180456. * 1.0.4 10004
  180457. * 1.0.4a-f 10005
  180458. * 1.0.5 (+ 2 patches) 10005
  180459. * 1.0.5a-d 10006
  180460. * 1.0.5e-r 10100 (not source compatible)
  180461. * 1.0.5s-v 10006 (not binary compatible)
  180462. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180463. * 1.0.6d-f 10007 (still binary incompatible)
  180464. * 1.0.6g 10007
  180465. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180466. * 1.0.6i 10007 10.6i
  180467. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180468. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180469. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180470. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180471. * 1.0.7 1 10007 (still compatible)
  180472. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180473. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180474. * 1.0.8 1 10008 2.1.0.8
  180475. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180476. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180477. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180478. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180479. * 1.0.9 1 10009 2.1.0.9
  180480. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180481. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180482. * 1.0.10 1 10010 2.1.0.10
  180483. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180484. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180485. * 1.0.11 1 10011 2.1.0.11
  180486. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180487. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180488. * 1.0.12 2 10012 2.1.0.12
  180489. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180490. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180491. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180492. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180493. * 1.2.0 3 10200 3.1.2.0
  180494. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180495. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180496. * 1.2.1 3 10201 3.1.2.1
  180497. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180498. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180499. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180500. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180501. * 1.0.13 10 10013 10.so.0.1.0.13
  180502. * 1.2.2 12 10202 12.so.0.1.2.2
  180503. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180504. * 1.2.3 12 10203 12.so.0.1.2.3
  180505. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180506. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180507. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180508. * 1.0.14 10 10014 10.so.0.1.0.14
  180509. * 1.2.4 13 10204 12.so.0.1.2.4
  180510. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180511. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180512. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180513. * 1.0.15 10 10015 10.so.0.1.0.15
  180514. * 1.2.5 13 10205 12.so.0.1.2.5
  180515. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180516. * 1.0.16 10 10016 10.so.0.1.0.16
  180517. * 1.2.6 13 10206 12.so.0.1.2.6
  180518. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180519. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180520. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180521. * 1.0.17 10 10017 10.so.0.1.0.17
  180522. * 1.2.7 13 10207 12.so.0.1.2.7
  180523. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180524. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180525. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180526. * 1.0.18 10 10018 10.so.0.1.0.18
  180527. * 1.2.8 13 10208 12.so.0.1.2.8
  180528. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180529. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180530. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180531. * 1.2.9 13 10209 12.so.0.9[.0]
  180532. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180533. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180534. * 1.2.10 13 10210 12.so.0.10[.0]
  180535. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180536. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180537. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180538. * 1.0.19 10 10019 10.so.0.19[.0]
  180539. * 1.2.11 13 10211 12.so.0.11[.0]
  180540. * 1.0.20 10 10020 10.so.0.20[.0]
  180541. * 1.2.12 13 10212 12.so.0.12[.0]
  180542. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180543. * 1.0.21 10 10021 10.so.0.21[.0]
  180544. * 1.2.13 13 10213 12.so.0.13[.0]
  180545. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180546. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180547. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180548. * 1.0.22 10 10022 10.so.0.22[.0]
  180549. * 1.2.14 13 10214 12.so.0.14[.0]
  180550. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180551. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180552. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180553. * 1.0.23 10 10023 10.so.0.23[.0]
  180554. * 1.2.15 13 10215 12.so.0.15[.0]
  180555. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180556. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180557. * 1.0.24 10 10024 10.so.0.24[.0]
  180558. * 1.2.16 13 10216 12.so.0.16[.0]
  180559. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180560. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180561. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180562. * 1.0.25 10 10025 10.so.0.25[.0]
  180563. * 1.2.17 13 10217 12.so.0.17[.0]
  180564. * 1.0.26 10 10026 10.so.0.26[.0]
  180565. * 1.2.18 13 10218 12.so.0.18[.0]
  180566. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180567. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180568. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180569. * 1.0.27 10 10027 10.so.0.27[.0]
  180570. * 1.2.19 13 10219 12.so.0.19[.0]
  180571. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180572. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180573. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180574. * 1.0.28 10 10028 10.so.0.28[.0]
  180575. * 1.2.20 13 10220 12.so.0.20[.0]
  180576. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180577. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180578. * 1.0.29 10 10029 10.so.0.29[.0]
  180579. * 1.2.21 13 10221 12.so.0.21[.0]
  180580. *
  180581. * Henceforth the source version will match the shared-library major
  180582. * and minor numbers; the shared-library major version number will be
  180583. * used for changes in backward compatibility, as it is intended. The
  180584. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180585. * for applications, is an unsigned integer of the form xyyzz corresponding
  180586. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180587. * were given the previous public release number plus a letter, until
  180588. * version 1.0.6j; from then on they were given the upcoming public
  180589. * release number plus "betaNN" or "rcN".
  180590. *
  180591. * Binary incompatibility exists only when applications make direct access
  180592. * to the info_ptr or png_ptr members through png.h, and the compiled
  180593. * application is loaded with a different version of the library.
  180594. *
  180595. * DLLNUM will change each time there are forward or backward changes
  180596. * in binary compatibility (e.g., when a new feature is added).
  180597. *
  180598. * See libpng.txt or libpng.3 for more information. The PNG specification
  180599. * is available as a W3C Recommendation and as an ISO Specification,
  180600. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180601. */
  180602. /*
  180603. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180604. *
  180605. * If you modify libpng you may insert additional notices immediately following
  180606. * this sentence.
  180607. *
  180608. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180609. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180610. * distributed according to the same disclaimer and license as libpng-1.2.5
  180611. * with the following individual added to the list of Contributing Authors:
  180612. *
  180613. * Cosmin Truta
  180614. *
  180615. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180616. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180617. * distributed according to the same disclaimer and license as libpng-1.0.6
  180618. * with the following individuals added to the list of Contributing Authors:
  180619. *
  180620. * Simon-Pierre Cadieux
  180621. * Eric S. Raymond
  180622. * Gilles Vollant
  180623. *
  180624. * and with the following additions to the disclaimer:
  180625. *
  180626. * There is no warranty against interference with your enjoyment of the
  180627. * library or against infringement. There is no warranty that our
  180628. * efforts or the library will fulfill any of your particular purposes
  180629. * or needs. This library is provided with all faults, and the entire
  180630. * risk of satisfactory quality, performance, accuracy, and effort is with
  180631. * the user.
  180632. *
  180633. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180634. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180635. * distributed according to the same disclaimer and license as libpng-0.96,
  180636. * with the following individuals added to the list of Contributing Authors:
  180637. *
  180638. * Tom Lane
  180639. * Glenn Randers-Pehrson
  180640. * Willem van Schaik
  180641. *
  180642. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180643. * Copyright (c) 1996, 1997 Andreas Dilger
  180644. * Distributed according to the same disclaimer and license as libpng-0.88,
  180645. * with the following individuals added to the list of Contributing Authors:
  180646. *
  180647. * John Bowler
  180648. * Kevin Bracey
  180649. * Sam Bushell
  180650. * Magnus Holmgren
  180651. * Greg Roelofs
  180652. * Tom Tanner
  180653. *
  180654. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180655. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180656. *
  180657. * For the purposes of this copyright and license, "Contributing Authors"
  180658. * is defined as the following set of individuals:
  180659. *
  180660. * Andreas Dilger
  180661. * Dave Martindale
  180662. * Guy Eric Schalnat
  180663. * Paul Schmidt
  180664. * Tim Wegner
  180665. *
  180666. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180667. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180668. * including, without limitation, the warranties of merchantability and of
  180669. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180670. * assume no liability for direct, indirect, incidental, special, exemplary,
  180671. * or consequential damages, which may result from the use of the PNG
  180672. * Reference Library, even if advised of the possibility of such damage.
  180673. *
  180674. * Permission is hereby granted to use, copy, modify, and distribute this
  180675. * source code, or portions hereof, for any purpose, without fee, subject
  180676. * to the following restrictions:
  180677. *
  180678. * 1. The origin of this source code must not be misrepresented.
  180679. *
  180680. * 2. Altered versions must be plainly marked as such and
  180681. * must not be misrepresented as being the original source.
  180682. *
  180683. * 3. This Copyright notice may not be removed or altered from
  180684. * any source or altered source distribution.
  180685. *
  180686. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180687. * fee, and encourage the use of this source code as a component to
  180688. * supporting the PNG file format in commercial products. If you use this
  180689. * source code in a product, acknowledgment is not required but would be
  180690. * appreciated.
  180691. */
  180692. /*
  180693. * A "png_get_copyright" function is available, for convenient use in "about"
  180694. * boxes and the like:
  180695. *
  180696. * printf("%s",png_get_copyright(NULL));
  180697. *
  180698. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180699. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180700. */
  180701. /*
  180702. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180703. * certification mark of the Open Source Initiative.
  180704. */
  180705. /*
  180706. * The contributing authors would like to thank all those who helped
  180707. * with testing, bug fixes, and patience. This wouldn't have been
  180708. * possible without all of you.
  180709. *
  180710. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180711. */
  180712. /*
  180713. * Y2K compliance in libpng:
  180714. * =========================
  180715. *
  180716. * October 4, 2007
  180717. *
  180718. * Since the PNG Development group is an ad-hoc body, we can't make
  180719. * an official declaration.
  180720. *
  180721. * This is your unofficial assurance that libpng from version 0.71 and
  180722. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180723. * versions were also Y2K compliant.
  180724. *
  180725. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180726. * that will hold years up to 65535. The other two hold the date in text
  180727. * format, and will hold years up to 9999.
  180728. *
  180729. * The integer is
  180730. * "png_uint_16 year" in png_time_struct.
  180731. *
  180732. * The strings are
  180733. * "png_charp time_buffer" in png_struct and
  180734. * "near_time_buffer", which is a local character string in png.c.
  180735. *
  180736. * There are seven time-related functions:
  180737. * png.c: png_convert_to_rfc_1123() in png.c
  180738. * (formerly png_convert_to_rfc_1152() in error)
  180739. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180740. * png_convert_from_time_t() in pngwrite.c
  180741. * png_get_tIME() in pngget.c
  180742. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180743. * png_set_tIME() in pngset.c
  180744. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180745. *
  180746. * All handle dates properly in a Y2K environment. The
  180747. * png_convert_from_time_t() function calls gmtime() to convert from system
  180748. * clock time, which returns (year - 1900), which we properly convert to
  180749. * the full 4-digit year. There is a possibility that applications using
  180750. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180751. * function, or that they are incorrectly passing only a 2-digit year
  180752. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180753. * but this is not under our control. The libpng documentation has always
  180754. * stated that it works with 4-digit years, and the APIs have been
  180755. * documented as such.
  180756. *
  180757. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180758. * integer to hold the year, and can hold years as large as 65535.
  180759. *
  180760. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180761. * no date-related code.
  180762. *
  180763. * Glenn Randers-Pehrson
  180764. * libpng maintainer
  180765. * PNG Development Group
  180766. */
  180767. #ifndef PNG_H
  180768. #define PNG_H
  180769. /* This is not the place to learn how to use libpng. The file libpng.txt
  180770. * describes how to use libpng, and the file example.c summarizes it
  180771. * with some code on which to build. This file is useful for looking
  180772. * at the actual function definitions and structure components.
  180773. */
  180774. /* Version information for png.h - this should match the version in png.c */
  180775. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180776. #define PNG_HEADER_VERSION_STRING \
  180777. " libpng version 1.2.21 - October 4, 2007\n"
  180778. #define PNG_LIBPNG_VER_SONUM 0
  180779. #define PNG_LIBPNG_VER_DLLNUM 13
  180780. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180781. #define PNG_LIBPNG_VER_MAJOR 1
  180782. #define PNG_LIBPNG_VER_MINOR 2
  180783. #define PNG_LIBPNG_VER_RELEASE 21
  180784. /* This should match the numeric part of the final component of
  180785. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180786. #define PNG_LIBPNG_VER_BUILD 0
  180787. /* Release Status */
  180788. #define PNG_LIBPNG_BUILD_ALPHA 1
  180789. #define PNG_LIBPNG_BUILD_BETA 2
  180790. #define PNG_LIBPNG_BUILD_RC 3
  180791. #define PNG_LIBPNG_BUILD_STABLE 4
  180792. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180793. /* Release-Specific Flags */
  180794. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180795. PNG_LIBPNG_BUILD_STABLE only */
  180796. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180797. PNG_LIBPNG_BUILD_SPECIAL */
  180798. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180799. PNG_LIBPNG_BUILD_PRIVATE */
  180800. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180801. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180802. * We must not include leading zeros.
  180803. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180804. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180805. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180806. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180807. #ifndef PNG_VERSION_INFO_ONLY
  180808. /* include the compression library's header */
  180809. #endif
  180810. /* include all user configurable info, including optional assembler routines */
  180811. /*** Start of inlined file: pngconf.h ***/
  180812. /* pngconf.h - machine configurable file for libpng
  180813. *
  180814. * libpng version 1.2.21 - October 4, 2007
  180815. * For conditions of distribution and use, see copyright notice in png.h
  180816. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180817. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180818. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180819. */
  180820. /* Any machine specific code is near the front of this file, so if you
  180821. * are configuring libpng for a machine, you may want to read the section
  180822. * starting here down to where it starts to typedef png_color, png_text,
  180823. * and png_info.
  180824. */
  180825. #ifndef PNGCONF_H
  180826. #define PNGCONF_H
  180827. #define PNG_1_2_X
  180828. // These are some Juce config settings that should remove any unnecessary code bloat..
  180829. #define PNG_NO_STDIO 1
  180830. #define PNG_DEBUG 0
  180831. #define PNG_NO_WARNINGS 1
  180832. #define PNG_NO_ERROR_TEXT 1
  180833. #define PNG_NO_ERROR_NUMBERS 1
  180834. #define PNG_NO_USER_MEM 1
  180835. #define PNG_NO_READ_iCCP 1
  180836. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180837. #define PNG_NO_READ_USER_CHUNKS 1
  180838. #define PNG_NO_READ_iTXt 1
  180839. #define PNG_NO_READ_sCAL 1
  180840. #define PNG_NO_READ_sPLT 1
  180841. #define png_error(a, b) png_err(a)
  180842. #define png_warning(a, b)
  180843. #define png_chunk_error(a, b) png_err(a)
  180844. #define png_chunk_warning(a, b)
  180845. /*
  180846. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180847. * includes the resource compiler for Windows DLL configurations.
  180848. */
  180849. #ifdef PNG_USER_CONFIG
  180850. # ifndef PNG_USER_PRIVATEBUILD
  180851. # define PNG_USER_PRIVATEBUILD
  180852. # endif
  180853. #include "pngusr.h"
  180854. #endif
  180855. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180856. #ifdef PNG_CONFIGURE_LIBPNG
  180857. #ifdef HAVE_CONFIG_H
  180858. #include "config.h"
  180859. #endif
  180860. #endif
  180861. /*
  180862. * Added at libpng-1.2.8
  180863. *
  180864. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180865. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180866. * the DLL was built>
  180867. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180868. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180869. * distinguish your DLL from those of the official release. These
  180870. * correspond to the trailing letters that come after the version
  180871. * number and must match your private DLL name>
  180872. * e.g. // private DLL "libpng13gx.dll"
  180873. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180874. *
  180875. * The following macros are also at your disposal if you want to complete the
  180876. * DLL VERSIONINFO structure.
  180877. * - PNG_USER_VERSIONINFO_COMMENTS
  180878. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180879. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180880. */
  180881. #ifdef __STDC__
  180882. #ifdef SPECIALBUILD
  180883. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180884. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180885. #endif
  180886. #ifdef PRIVATEBUILD
  180887. # pragma message("PRIVATEBUILD is deprecated.\
  180888. Use PNG_USER_PRIVATEBUILD instead.")
  180889. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180890. #endif
  180891. #endif /* __STDC__ */
  180892. #ifndef PNG_VERSION_INFO_ONLY
  180893. /* End of material added to libpng-1.2.8 */
  180894. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180895. Restored at libpng-1.2.21 */
  180896. # define PNG_WARN_UNINITIALIZED_ROW 1
  180897. /* End of material added at libpng-1.2.19/1.2.21 */
  180898. /* This is the size of the compression buffer, and thus the size of
  180899. * an IDAT chunk. Make this whatever size you feel is best for your
  180900. * machine. One of these will be allocated per png_struct. When this
  180901. * is full, it writes the data to the disk, and does some other
  180902. * calculations. Making this an extremely small size will slow
  180903. * the library down, but you may want to experiment to determine
  180904. * where it becomes significant, if you are concerned with memory
  180905. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180906. * this describes the size of the buffer available to read the data in.
  180907. * Unless this gets smaller than the size of a row (compressed),
  180908. * it should not make much difference how big this is.
  180909. */
  180910. #ifndef PNG_ZBUF_SIZE
  180911. # define PNG_ZBUF_SIZE 8192
  180912. #endif
  180913. /* Enable if you want a write-only libpng */
  180914. #ifndef PNG_NO_READ_SUPPORTED
  180915. # define PNG_READ_SUPPORTED
  180916. #endif
  180917. /* Enable if you want a read-only libpng */
  180918. #ifndef PNG_NO_WRITE_SUPPORTED
  180919. # define PNG_WRITE_SUPPORTED
  180920. #endif
  180921. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180922. support PNGs that are embedded in MNG datastreams */
  180923. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180924. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180925. # define PNG_MNG_FEATURES_SUPPORTED
  180926. # endif
  180927. #endif
  180928. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180929. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180930. # define PNG_FLOATING_POINT_SUPPORTED
  180931. # endif
  180932. #endif
  180933. /* If you are running on a machine where you cannot allocate more
  180934. * than 64K of memory at once, uncomment this. While libpng will not
  180935. * normally need that much memory in a chunk (unless you load up a very
  180936. * large file), zlib needs to know how big of a chunk it can use, and
  180937. * libpng thus makes sure to check any memory allocation to verify it
  180938. * will fit into memory.
  180939. #define PNG_MAX_MALLOC_64K
  180940. */
  180941. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180942. # define PNG_MAX_MALLOC_64K
  180943. #endif
  180944. /* Special munging to support doing things the 'cygwin' way:
  180945. * 'Normal' png-on-win32 defines/defaults:
  180946. * PNG_BUILD_DLL -- building dll
  180947. * PNG_USE_DLL -- building an application, linking to dll
  180948. * (no define) -- building static library, or building an
  180949. * application and linking to the static lib
  180950. * 'Cygwin' defines/defaults:
  180951. * PNG_BUILD_DLL -- (ignored) building the dll
  180952. * (no define) -- (ignored) building an application, linking to the dll
  180953. * PNG_STATIC -- (ignored) building the static lib, or building an
  180954. * application that links to the static lib.
  180955. * ALL_STATIC -- (ignored) building various static libs, or building an
  180956. * application that links to the static libs.
  180957. * Thus,
  180958. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180959. * this bit of #ifdefs will define the 'correct' config variables based on
  180960. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180961. * unnecessary.
  180962. *
  180963. * Also, the precedence order is:
  180964. * ALL_STATIC (since we can't #undef something outside our namespace)
  180965. * PNG_BUILD_DLL
  180966. * PNG_STATIC
  180967. * (nothing) == PNG_USE_DLL
  180968. *
  180969. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180970. * of auto-import in binutils, we no longer need to worry about
  180971. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180972. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180973. * to __declspec() stuff. However, we DO need to worry about
  180974. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180975. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180976. */
  180977. #if defined(__CYGWIN__)
  180978. # if defined(ALL_STATIC)
  180979. # if defined(PNG_BUILD_DLL)
  180980. # undef PNG_BUILD_DLL
  180981. # endif
  180982. # if defined(PNG_USE_DLL)
  180983. # undef PNG_USE_DLL
  180984. # endif
  180985. # if defined(PNG_DLL)
  180986. # undef PNG_DLL
  180987. # endif
  180988. # if !defined(PNG_STATIC)
  180989. # define PNG_STATIC
  180990. # endif
  180991. # else
  180992. # if defined (PNG_BUILD_DLL)
  180993. # if defined(PNG_STATIC)
  180994. # undef PNG_STATIC
  180995. # endif
  180996. # if defined(PNG_USE_DLL)
  180997. # undef PNG_USE_DLL
  180998. # endif
  180999. # if !defined(PNG_DLL)
  181000. # define PNG_DLL
  181001. # endif
  181002. # else
  181003. # if defined(PNG_STATIC)
  181004. # if defined(PNG_USE_DLL)
  181005. # undef PNG_USE_DLL
  181006. # endif
  181007. # if defined(PNG_DLL)
  181008. # undef PNG_DLL
  181009. # endif
  181010. # else
  181011. # if !defined(PNG_USE_DLL)
  181012. # define PNG_USE_DLL
  181013. # endif
  181014. # if !defined(PNG_DLL)
  181015. # define PNG_DLL
  181016. # endif
  181017. # endif
  181018. # endif
  181019. # endif
  181020. #endif
  181021. /* This protects us against compilers that run on a windowing system
  181022. * and thus don't have or would rather us not use the stdio types:
  181023. * stdin, stdout, and stderr. The only one currently used is stderr
  181024. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  181025. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  181026. * will also prevent these, plus will prevent the entire set of stdio
  181027. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  181028. * unless (PNG_DEBUG > 0) has been #defined.
  181029. *
  181030. * #define PNG_NO_CONSOLE_IO
  181031. * #define PNG_NO_STDIO
  181032. */
  181033. #if defined(_WIN32_WCE)
  181034. # include <windows.h>
  181035. /* Console I/O functions are not supported on WindowsCE */
  181036. # define PNG_NO_CONSOLE_IO
  181037. # ifdef PNG_DEBUG
  181038. # undef PNG_DEBUG
  181039. # endif
  181040. #endif
  181041. #ifdef PNG_BUILD_DLL
  181042. # ifndef PNG_CONSOLE_IO_SUPPORTED
  181043. # ifndef PNG_NO_CONSOLE_IO
  181044. # define PNG_NO_CONSOLE_IO
  181045. # endif
  181046. # endif
  181047. #endif
  181048. # ifdef PNG_NO_STDIO
  181049. # ifndef PNG_NO_CONSOLE_IO
  181050. # define PNG_NO_CONSOLE_IO
  181051. # endif
  181052. # ifdef PNG_DEBUG
  181053. # if (PNG_DEBUG > 0)
  181054. # include <stdio.h>
  181055. # endif
  181056. # endif
  181057. # else
  181058. # if !defined(_WIN32_WCE)
  181059. /* "stdio.h" functions are not supported on WindowsCE */
  181060. # include <stdio.h>
  181061. # endif
  181062. # endif
  181063. /* This macro protects us against machines that don't have function
  181064. * prototypes (ie K&R style headers). If your compiler does not handle
  181065. * function prototypes, define this macro and use the included ansi2knr.
  181066. * I've always been able to use _NO_PROTO as the indicator, but you may
  181067. * need to drag the empty declaration out in front of here, or change the
  181068. * ifdef to suit your own needs.
  181069. */
  181070. #ifndef PNGARG
  181071. #ifdef OF /* zlib prototype munger */
  181072. # define PNGARG(arglist) OF(arglist)
  181073. #else
  181074. #ifdef _NO_PROTO
  181075. # define PNGARG(arglist) ()
  181076. # ifndef PNG_TYPECAST_NULL
  181077. # define PNG_TYPECAST_NULL
  181078. # endif
  181079. #else
  181080. # define PNGARG(arglist) arglist
  181081. #endif /* _NO_PROTO */
  181082. #endif /* OF */
  181083. #endif /* PNGARG */
  181084. /* Try to determine if we are compiling on a Mac. Note that testing for
  181085. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  181086. * on non-Mac platforms.
  181087. */
  181088. #ifndef MACOS
  181089. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  181090. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  181091. # define MACOS
  181092. # endif
  181093. #endif
  181094. /* enough people need this for various reasons to include it here */
  181095. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  181096. # include <sys/types.h>
  181097. #endif
  181098. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  181099. # define PNG_SETJMP_SUPPORTED
  181100. #endif
  181101. #ifdef PNG_SETJMP_SUPPORTED
  181102. /* This is an attempt to force a single setjmp behaviour on Linux. If
  181103. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  181104. */
  181105. # ifdef __linux__
  181106. # ifdef _BSD_SOURCE
  181107. # define PNG_SAVE_BSD_SOURCE
  181108. # undef _BSD_SOURCE
  181109. # endif
  181110. # ifdef _SETJMP_H
  181111. /* If you encounter a compiler error here, see the explanation
  181112. * near the end of INSTALL.
  181113. */
  181114. __png.h__ already includes setjmp.h;
  181115. __dont__ include it again.;
  181116. # endif
  181117. # endif /* __linux__ */
  181118. /* include setjmp.h for error handling */
  181119. # include <setjmp.h>
  181120. # ifdef __linux__
  181121. # ifdef PNG_SAVE_BSD_SOURCE
  181122. # define _BSD_SOURCE
  181123. # undef PNG_SAVE_BSD_SOURCE
  181124. # endif
  181125. # endif /* __linux__ */
  181126. #endif /* PNG_SETJMP_SUPPORTED */
  181127. #ifdef BSD
  181128. #if ! JUCE_MAC
  181129. # include <strings.h>
  181130. #endif
  181131. #else
  181132. # include <string.h>
  181133. #endif
  181134. /* Other defines for things like memory and the like can go here. */
  181135. #ifdef PNG_INTERNAL
  181136. #include <stdlib.h>
  181137. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  181138. * aren't usually used outside the library (as far as I know), so it is
  181139. * debatable if they should be exported at all. In the future, when it is
  181140. * possible to have run-time registry of chunk-handling functions, some of
  181141. * these will be made available again.
  181142. #define PNG_EXTERN extern
  181143. */
  181144. #define PNG_EXTERN
  181145. /* Other defines specific to compilers can go here. Try to keep
  181146. * them inside an appropriate ifdef/endif pair for portability.
  181147. */
  181148. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181149. # if defined(MACOS)
  181150. /* We need to check that <math.h> hasn't already been included earlier
  181151. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181152. * <fp.h> if possible.
  181153. */
  181154. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181155. # include <fp.h>
  181156. # endif
  181157. # else
  181158. # include <math.h>
  181159. # endif
  181160. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181161. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181162. * MATH=68881
  181163. */
  181164. # include <m68881.h>
  181165. # endif
  181166. #endif
  181167. /* Codewarrior on NT has linking problems without this. */
  181168. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181169. # define PNG_ALWAYS_EXTERN
  181170. #endif
  181171. /* This provides the non-ANSI (far) memory allocation routines. */
  181172. #if defined(__TURBOC__) && defined(__MSDOS__)
  181173. # include <mem.h>
  181174. # include <alloc.h>
  181175. #endif
  181176. /* I have no idea why is this necessary... */
  181177. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181178. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181179. # include <malloc.h>
  181180. #endif
  181181. /* This controls how fine the dithering gets. As this allocates
  181182. * a largish chunk of memory (32K), those who are not as concerned
  181183. * with dithering quality can decrease some or all of these.
  181184. */
  181185. #ifndef PNG_DITHER_RED_BITS
  181186. # define PNG_DITHER_RED_BITS 5
  181187. #endif
  181188. #ifndef PNG_DITHER_GREEN_BITS
  181189. # define PNG_DITHER_GREEN_BITS 5
  181190. #endif
  181191. #ifndef PNG_DITHER_BLUE_BITS
  181192. # define PNG_DITHER_BLUE_BITS 5
  181193. #endif
  181194. /* This controls how fine the gamma correction becomes when you
  181195. * are only interested in 8 bits anyway. Increasing this value
  181196. * results in more memory being used, and more pow() functions
  181197. * being called to fill in the gamma tables. Don't set this value
  181198. * less then 8, and even that may not work (I haven't tested it).
  181199. */
  181200. #ifndef PNG_MAX_GAMMA_8
  181201. # define PNG_MAX_GAMMA_8 11
  181202. #endif
  181203. /* This controls how much a difference in gamma we can tolerate before
  181204. * we actually start doing gamma conversion.
  181205. */
  181206. #ifndef PNG_GAMMA_THRESHOLD
  181207. # define PNG_GAMMA_THRESHOLD 0.05
  181208. #endif
  181209. #endif /* PNG_INTERNAL */
  181210. /* The following uses const char * instead of char * for error
  181211. * and warning message functions, so some compilers won't complain.
  181212. * If you do not want to use const, define PNG_NO_CONST here.
  181213. */
  181214. #ifndef PNG_NO_CONST
  181215. # define PNG_CONST const
  181216. #else
  181217. # define PNG_CONST
  181218. #endif
  181219. /* The following defines give you the ability to remove code from the
  181220. * library that you will not be using. I wish I could figure out how to
  181221. * automate this, but I can't do that without making it seriously hard
  181222. * on the users. So if you are not using an ability, change the #define
  181223. * to and #undef, and that part of the library will not be compiled. If
  181224. * your linker can't find a function, you may want to make sure the
  181225. * ability is defined here. Some of these depend upon some others being
  181226. * defined. I haven't figured out all the interactions here, so you may
  181227. * have to experiment awhile to get everything to compile. If you are
  181228. * creating or using a shared library, you probably shouldn't touch this,
  181229. * as it will affect the size of the structures, and this will cause bad
  181230. * things to happen if the library and/or application ever change.
  181231. */
  181232. /* Any features you will not be using can be undef'ed here */
  181233. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181234. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181235. * on the compile line, then pick and choose which ones to define without
  181236. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181237. * if you only want to have a png-compliant reader/writer but don't need
  181238. * any of the extra transformations. This saves about 80 kbytes in a
  181239. * typical installation of the library. (PNG_NO_* form added in version
  181240. * 1.0.1c, for consistency)
  181241. */
  181242. /* The size of the png_text structure changed in libpng-1.0.6 when
  181243. * iTXt support was added. iTXt support was turned off by default through
  181244. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181245. * instead of calling png_set_text() and letting libpng malloc it. It
  181246. * was turned on by default in libpng-1.3.0.
  181247. */
  181248. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181249. # ifndef PNG_NO_iTXt_SUPPORTED
  181250. # define PNG_NO_iTXt_SUPPORTED
  181251. # endif
  181252. # ifndef PNG_NO_READ_iTXt
  181253. # define PNG_NO_READ_iTXt
  181254. # endif
  181255. # ifndef PNG_NO_WRITE_iTXt
  181256. # define PNG_NO_WRITE_iTXt
  181257. # endif
  181258. #endif
  181259. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181260. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181261. # define PNG_READ_iTXt
  181262. # endif
  181263. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181264. # define PNG_WRITE_iTXt
  181265. # endif
  181266. #endif
  181267. /* The following support, added after version 1.0.0, can be turned off here en
  181268. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181269. * with old applications that require the length of png_struct and png_info
  181270. * to remain unchanged.
  181271. */
  181272. #ifdef PNG_LEGACY_SUPPORTED
  181273. # define PNG_NO_FREE_ME
  181274. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181275. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181276. # define PNG_NO_READ_USER_CHUNKS
  181277. # define PNG_NO_READ_iCCP
  181278. # define PNG_NO_WRITE_iCCP
  181279. # define PNG_NO_READ_iTXt
  181280. # define PNG_NO_WRITE_iTXt
  181281. # define PNG_NO_READ_sCAL
  181282. # define PNG_NO_WRITE_sCAL
  181283. # define PNG_NO_READ_sPLT
  181284. # define PNG_NO_WRITE_sPLT
  181285. # define PNG_NO_INFO_IMAGE
  181286. # define PNG_NO_READ_RGB_TO_GRAY
  181287. # define PNG_NO_READ_USER_TRANSFORM
  181288. # define PNG_NO_WRITE_USER_TRANSFORM
  181289. # define PNG_NO_USER_MEM
  181290. # define PNG_NO_READ_EMPTY_PLTE
  181291. # define PNG_NO_MNG_FEATURES
  181292. # define PNG_NO_FIXED_POINT_SUPPORTED
  181293. #endif
  181294. /* Ignore attempt to turn off both floating and fixed point support */
  181295. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181296. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181297. # define PNG_FIXED_POINT_SUPPORTED
  181298. #endif
  181299. #ifndef PNG_NO_FREE_ME
  181300. # define PNG_FREE_ME_SUPPORTED
  181301. #endif
  181302. #if defined(PNG_READ_SUPPORTED)
  181303. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181304. !defined(PNG_NO_READ_TRANSFORMS)
  181305. # define PNG_READ_TRANSFORMS_SUPPORTED
  181306. #endif
  181307. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181308. # ifndef PNG_NO_READ_EXPAND
  181309. # define PNG_READ_EXPAND_SUPPORTED
  181310. # endif
  181311. # ifndef PNG_NO_READ_SHIFT
  181312. # define PNG_READ_SHIFT_SUPPORTED
  181313. # endif
  181314. # ifndef PNG_NO_READ_PACK
  181315. # define PNG_READ_PACK_SUPPORTED
  181316. # endif
  181317. # ifndef PNG_NO_READ_BGR
  181318. # define PNG_READ_BGR_SUPPORTED
  181319. # endif
  181320. # ifndef PNG_NO_READ_SWAP
  181321. # define PNG_READ_SWAP_SUPPORTED
  181322. # endif
  181323. # ifndef PNG_NO_READ_PACKSWAP
  181324. # define PNG_READ_PACKSWAP_SUPPORTED
  181325. # endif
  181326. # ifndef PNG_NO_READ_INVERT
  181327. # define PNG_READ_INVERT_SUPPORTED
  181328. # endif
  181329. # ifndef PNG_NO_READ_DITHER
  181330. # define PNG_READ_DITHER_SUPPORTED
  181331. # endif
  181332. # ifndef PNG_NO_READ_BACKGROUND
  181333. # define PNG_READ_BACKGROUND_SUPPORTED
  181334. # endif
  181335. # ifndef PNG_NO_READ_16_TO_8
  181336. # define PNG_READ_16_TO_8_SUPPORTED
  181337. # endif
  181338. # ifndef PNG_NO_READ_FILLER
  181339. # define PNG_READ_FILLER_SUPPORTED
  181340. # endif
  181341. # ifndef PNG_NO_READ_GAMMA
  181342. # define PNG_READ_GAMMA_SUPPORTED
  181343. # endif
  181344. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181345. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181346. # endif
  181347. # ifndef PNG_NO_READ_SWAP_ALPHA
  181348. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181349. # endif
  181350. # ifndef PNG_NO_READ_INVERT_ALPHA
  181351. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181352. # endif
  181353. # ifndef PNG_NO_READ_STRIP_ALPHA
  181354. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181355. # endif
  181356. # ifndef PNG_NO_READ_USER_TRANSFORM
  181357. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181358. # endif
  181359. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181360. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181361. # endif
  181362. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181363. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181364. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181365. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181366. #endif /* about interlacing capability! You'll */
  181367. /* still have interlacing unless you change the following line: */
  181368. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181369. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181370. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181371. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181372. # endif
  181373. #endif
  181374. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181375. /* Deprecated, will be removed from version 2.0.0.
  181376. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181377. #ifndef PNG_NO_READ_EMPTY_PLTE
  181378. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181379. #endif
  181380. #endif
  181381. #endif /* PNG_READ_SUPPORTED */
  181382. #if defined(PNG_WRITE_SUPPORTED)
  181383. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181384. !defined(PNG_NO_WRITE_TRANSFORMS)
  181385. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181386. #endif
  181387. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181388. # ifndef PNG_NO_WRITE_SHIFT
  181389. # define PNG_WRITE_SHIFT_SUPPORTED
  181390. # endif
  181391. # ifndef PNG_NO_WRITE_PACK
  181392. # define PNG_WRITE_PACK_SUPPORTED
  181393. # endif
  181394. # ifndef PNG_NO_WRITE_BGR
  181395. # define PNG_WRITE_BGR_SUPPORTED
  181396. # endif
  181397. # ifndef PNG_NO_WRITE_SWAP
  181398. # define PNG_WRITE_SWAP_SUPPORTED
  181399. # endif
  181400. # ifndef PNG_NO_WRITE_PACKSWAP
  181401. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181402. # endif
  181403. # ifndef PNG_NO_WRITE_INVERT
  181404. # define PNG_WRITE_INVERT_SUPPORTED
  181405. # endif
  181406. # ifndef PNG_NO_WRITE_FILLER
  181407. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181408. # endif
  181409. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181410. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181411. # endif
  181412. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181413. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181414. # endif
  181415. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181416. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181417. # endif
  181418. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181419. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181420. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181421. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181422. encoders, but can cause trouble
  181423. if left undefined */
  181424. #endif
  181425. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181426. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181427. defined(PNG_FLOATING_POINT_SUPPORTED)
  181428. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181429. #endif
  181430. #ifndef PNG_NO_WRITE_FLUSH
  181431. # define PNG_WRITE_FLUSH_SUPPORTED
  181432. #endif
  181433. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181434. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181435. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181436. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181437. #endif
  181438. #endif
  181439. #endif /* PNG_WRITE_SUPPORTED */
  181440. #ifndef PNG_1_0_X
  181441. # ifndef PNG_NO_ERROR_NUMBERS
  181442. # define PNG_ERROR_NUMBERS_SUPPORTED
  181443. # endif
  181444. #endif /* PNG_1_0_X */
  181445. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181446. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181447. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181448. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181449. # endif
  181450. #endif
  181451. #ifndef PNG_NO_STDIO
  181452. # define PNG_TIME_RFC1123_SUPPORTED
  181453. #endif
  181454. /* This adds extra functions in pngget.c for accessing data from the
  181455. * info pointer (added in version 0.99)
  181456. * png_get_image_width()
  181457. * png_get_image_height()
  181458. * png_get_bit_depth()
  181459. * png_get_color_type()
  181460. * png_get_compression_type()
  181461. * png_get_filter_type()
  181462. * png_get_interlace_type()
  181463. * png_get_pixel_aspect_ratio()
  181464. * png_get_pixels_per_meter()
  181465. * png_get_x_offset_pixels()
  181466. * png_get_y_offset_pixels()
  181467. * png_get_x_offset_microns()
  181468. * png_get_y_offset_microns()
  181469. */
  181470. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181471. # define PNG_EASY_ACCESS_SUPPORTED
  181472. #endif
  181473. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181474. * and removed from version 1.2.20. The following will be removed
  181475. * from libpng-1.4.0
  181476. */
  181477. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181478. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181479. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181480. # endif
  181481. #endif
  181482. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181483. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181484. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181485. # endif
  181486. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181487. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181488. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181489. # define PNG_NO_MMX_CODE
  181490. # endif
  181491. # endif
  181492. # if defined(__APPLE__)
  181493. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181494. # define PNG_NO_MMX_CODE
  181495. # endif
  181496. # endif
  181497. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181498. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181499. # define PNG_NO_MMX_CODE
  181500. # endif
  181501. # endif
  181502. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181503. # define PNG_MMX_CODE_SUPPORTED
  181504. # endif
  181505. #endif
  181506. /* end of obsolete code to be removed from libpng-1.4.0 */
  181507. #if !defined(PNG_1_0_X)
  181508. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181509. # define PNG_USER_MEM_SUPPORTED
  181510. #endif
  181511. #endif /* PNG_1_0_X */
  181512. /* Added at libpng-1.2.6 */
  181513. #if !defined(PNG_1_0_X)
  181514. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181515. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181516. # define PNG_SET_USER_LIMITS_SUPPORTED
  181517. #endif
  181518. #endif
  181519. #endif /* PNG_1_0_X */
  181520. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181521. * how large, set these limits to 0x7fffffffL
  181522. */
  181523. #ifndef PNG_USER_WIDTH_MAX
  181524. # define PNG_USER_WIDTH_MAX 1000000L
  181525. #endif
  181526. #ifndef PNG_USER_HEIGHT_MAX
  181527. # define PNG_USER_HEIGHT_MAX 1000000L
  181528. #endif
  181529. /* These are currently experimental features, define them if you want */
  181530. /* very little testing */
  181531. /*
  181532. #ifdef PNG_READ_SUPPORTED
  181533. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181534. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181535. # endif
  181536. #endif
  181537. */
  181538. /* This is only for PowerPC big-endian and 680x0 systems */
  181539. /* some testing */
  181540. /*
  181541. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181542. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181543. #endif
  181544. */
  181545. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181546. /*
  181547. #define PNG_NO_POINTER_INDEXING
  181548. */
  181549. /* These functions are turned off by default, as they will be phased out. */
  181550. /*
  181551. #define PNG_USELESS_TESTS_SUPPORTED
  181552. #define PNG_CORRECT_PALETTE_SUPPORTED
  181553. */
  181554. /* Any chunks you are not interested in, you can undef here. The
  181555. * ones that allocate memory may be expecially important (hIST,
  181556. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181557. * a bit smaller.
  181558. */
  181559. #if defined(PNG_READ_SUPPORTED) && \
  181560. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181561. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181562. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181563. #endif
  181564. #if defined(PNG_WRITE_SUPPORTED) && \
  181565. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181566. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181567. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181568. #endif
  181569. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181570. #ifdef PNG_NO_READ_TEXT
  181571. # define PNG_NO_READ_iTXt
  181572. # define PNG_NO_READ_tEXt
  181573. # define PNG_NO_READ_zTXt
  181574. #endif
  181575. #ifndef PNG_NO_READ_bKGD
  181576. # define PNG_READ_bKGD_SUPPORTED
  181577. # define PNG_bKGD_SUPPORTED
  181578. #endif
  181579. #ifndef PNG_NO_READ_cHRM
  181580. # define PNG_READ_cHRM_SUPPORTED
  181581. # define PNG_cHRM_SUPPORTED
  181582. #endif
  181583. #ifndef PNG_NO_READ_gAMA
  181584. # define PNG_READ_gAMA_SUPPORTED
  181585. # define PNG_gAMA_SUPPORTED
  181586. #endif
  181587. #ifndef PNG_NO_READ_hIST
  181588. # define PNG_READ_hIST_SUPPORTED
  181589. # define PNG_hIST_SUPPORTED
  181590. #endif
  181591. #ifndef PNG_NO_READ_iCCP
  181592. # define PNG_READ_iCCP_SUPPORTED
  181593. # define PNG_iCCP_SUPPORTED
  181594. #endif
  181595. #ifndef PNG_NO_READ_iTXt
  181596. # ifndef PNG_READ_iTXt_SUPPORTED
  181597. # define PNG_READ_iTXt_SUPPORTED
  181598. # endif
  181599. # ifndef PNG_iTXt_SUPPORTED
  181600. # define PNG_iTXt_SUPPORTED
  181601. # endif
  181602. #endif
  181603. #ifndef PNG_NO_READ_oFFs
  181604. # define PNG_READ_oFFs_SUPPORTED
  181605. # define PNG_oFFs_SUPPORTED
  181606. #endif
  181607. #ifndef PNG_NO_READ_pCAL
  181608. # define PNG_READ_pCAL_SUPPORTED
  181609. # define PNG_pCAL_SUPPORTED
  181610. #endif
  181611. #ifndef PNG_NO_READ_sCAL
  181612. # define PNG_READ_sCAL_SUPPORTED
  181613. # define PNG_sCAL_SUPPORTED
  181614. #endif
  181615. #ifndef PNG_NO_READ_pHYs
  181616. # define PNG_READ_pHYs_SUPPORTED
  181617. # define PNG_pHYs_SUPPORTED
  181618. #endif
  181619. #ifndef PNG_NO_READ_sBIT
  181620. # define PNG_READ_sBIT_SUPPORTED
  181621. # define PNG_sBIT_SUPPORTED
  181622. #endif
  181623. #ifndef PNG_NO_READ_sPLT
  181624. # define PNG_READ_sPLT_SUPPORTED
  181625. # define PNG_sPLT_SUPPORTED
  181626. #endif
  181627. #ifndef PNG_NO_READ_sRGB
  181628. # define PNG_READ_sRGB_SUPPORTED
  181629. # define PNG_sRGB_SUPPORTED
  181630. #endif
  181631. #ifndef PNG_NO_READ_tEXt
  181632. # define PNG_READ_tEXt_SUPPORTED
  181633. # define PNG_tEXt_SUPPORTED
  181634. #endif
  181635. #ifndef PNG_NO_READ_tIME
  181636. # define PNG_READ_tIME_SUPPORTED
  181637. # define PNG_tIME_SUPPORTED
  181638. #endif
  181639. #ifndef PNG_NO_READ_tRNS
  181640. # define PNG_READ_tRNS_SUPPORTED
  181641. # define PNG_tRNS_SUPPORTED
  181642. #endif
  181643. #ifndef PNG_NO_READ_zTXt
  181644. # define PNG_READ_zTXt_SUPPORTED
  181645. # define PNG_zTXt_SUPPORTED
  181646. #endif
  181647. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181648. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181649. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181650. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181651. # endif
  181652. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181653. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181654. # endif
  181655. #endif
  181656. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181657. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181658. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181659. # define PNG_USER_CHUNKS_SUPPORTED
  181660. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181661. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181662. # endif
  181663. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181664. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181665. # endif
  181666. #endif
  181667. #ifndef PNG_NO_READ_OPT_PLTE
  181668. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181669. #endif /* optional PLTE chunk in RGB and RGBA images */
  181670. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181671. defined(PNG_READ_zTXt_SUPPORTED)
  181672. # define PNG_READ_TEXT_SUPPORTED
  181673. # define PNG_TEXT_SUPPORTED
  181674. #endif
  181675. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181676. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181677. #ifdef PNG_NO_WRITE_TEXT
  181678. # define PNG_NO_WRITE_iTXt
  181679. # define PNG_NO_WRITE_tEXt
  181680. # define PNG_NO_WRITE_zTXt
  181681. #endif
  181682. #ifndef PNG_NO_WRITE_bKGD
  181683. # define PNG_WRITE_bKGD_SUPPORTED
  181684. # ifndef PNG_bKGD_SUPPORTED
  181685. # define PNG_bKGD_SUPPORTED
  181686. # endif
  181687. #endif
  181688. #ifndef PNG_NO_WRITE_cHRM
  181689. # define PNG_WRITE_cHRM_SUPPORTED
  181690. # ifndef PNG_cHRM_SUPPORTED
  181691. # define PNG_cHRM_SUPPORTED
  181692. # endif
  181693. #endif
  181694. #ifndef PNG_NO_WRITE_gAMA
  181695. # define PNG_WRITE_gAMA_SUPPORTED
  181696. # ifndef PNG_gAMA_SUPPORTED
  181697. # define PNG_gAMA_SUPPORTED
  181698. # endif
  181699. #endif
  181700. #ifndef PNG_NO_WRITE_hIST
  181701. # define PNG_WRITE_hIST_SUPPORTED
  181702. # ifndef PNG_hIST_SUPPORTED
  181703. # define PNG_hIST_SUPPORTED
  181704. # endif
  181705. #endif
  181706. #ifndef PNG_NO_WRITE_iCCP
  181707. # define PNG_WRITE_iCCP_SUPPORTED
  181708. # ifndef PNG_iCCP_SUPPORTED
  181709. # define PNG_iCCP_SUPPORTED
  181710. # endif
  181711. #endif
  181712. #ifndef PNG_NO_WRITE_iTXt
  181713. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181714. # define PNG_WRITE_iTXt_SUPPORTED
  181715. # endif
  181716. # ifndef PNG_iTXt_SUPPORTED
  181717. # define PNG_iTXt_SUPPORTED
  181718. # endif
  181719. #endif
  181720. #ifndef PNG_NO_WRITE_oFFs
  181721. # define PNG_WRITE_oFFs_SUPPORTED
  181722. # ifndef PNG_oFFs_SUPPORTED
  181723. # define PNG_oFFs_SUPPORTED
  181724. # endif
  181725. #endif
  181726. #ifndef PNG_NO_WRITE_pCAL
  181727. # define PNG_WRITE_pCAL_SUPPORTED
  181728. # ifndef PNG_pCAL_SUPPORTED
  181729. # define PNG_pCAL_SUPPORTED
  181730. # endif
  181731. #endif
  181732. #ifndef PNG_NO_WRITE_sCAL
  181733. # define PNG_WRITE_sCAL_SUPPORTED
  181734. # ifndef PNG_sCAL_SUPPORTED
  181735. # define PNG_sCAL_SUPPORTED
  181736. # endif
  181737. #endif
  181738. #ifndef PNG_NO_WRITE_pHYs
  181739. # define PNG_WRITE_pHYs_SUPPORTED
  181740. # ifndef PNG_pHYs_SUPPORTED
  181741. # define PNG_pHYs_SUPPORTED
  181742. # endif
  181743. #endif
  181744. #ifndef PNG_NO_WRITE_sBIT
  181745. # define PNG_WRITE_sBIT_SUPPORTED
  181746. # ifndef PNG_sBIT_SUPPORTED
  181747. # define PNG_sBIT_SUPPORTED
  181748. # endif
  181749. #endif
  181750. #ifndef PNG_NO_WRITE_sPLT
  181751. # define PNG_WRITE_sPLT_SUPPORTED
  181752. # ifndef PNG_sPLT_SUPPORTED
  181753. # define PNG_sPLT_SUPPORTED
  181754. # endif
  181755. #endif
  181756. #ifndef PNG_NO_WRITE_sRGB
  181757. # define PNG_WRITE_sRGB_SUPPORTED
  181758. # ifndef PNG_sRGB_SUPPORTED
  181759. # define PNG_sRGB_SUPPORTED
  181760. # endif
  181761. #endif
  181762. #ifndef PNG_NO_WRITE_tEXt
  181763. # define PNG_WRITE_tEXt_SUPPORTED
  181764. # ifndef PNG_tEXt_SUPPORTED
  181765. # define PNG_tEXt_SUPPORTED
  181766. # endif
  181767. #endif
  181768. #ifndef PNG_NO_WRITE_tIME
  181769. # define PNG_WRITE_tIME_SUPPORTED
  181770. # ifndef PNG_tIME_SUPPORTED
  181771. # define PNG_tIME_SUPPORTED
  181772. # endif
  181773. #endif
  181774. #ifndef PNG_NO_WRITE_tRNS
  181775. # define PNG_WRITE_tRNS_SUPPORTED
  181776. # ifndef PNG_tRNS_SUPPORTED
  181777. # define PNG_tRNS_SUPPORTED
  181778. # endif
  181779. #endif
  181780. #ifndef PNG_NO_WRITE_zTXt
  181781. # define PNG_WRITE_zTXt_SUPPORTED
  181782. # ifndef PNG_zTXt_SUPPORTED
  181783. # define PNG_zTXt_SUPPORTED
  181784. # endif
  181785. #endif
  181786. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181787. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181788. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181789. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181790. # endif
  181791. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181792. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181793. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181794. # endif
  181795. # endif
  181796. #endif
  181797. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181798. defined(PNG_WRITE_zTXt_SUPPORTED)
  181799. # define PNG_WRITE_TEXT_SUPPORTED
  181800. # ifndef PNG_TEXT_SUPPORTED
  181801. # define PNG_TEXT_SUPPORTED
  181802. # endif
  181803. #endif
  181804. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181805. /* Turn this off to disable png_read_png() and
  181806. * png_write_png() and leave the row_pointers member
  181807. * out of the info structure.
  181808. */
  181809. #ifndef PNG_NO_INFO_IMAGE
  181810. # define PNG_INFO_IMAGE_SUPPORTED
  181811. #endif
  181812. /* need the time information for reading tIME chunks */
  181813. #if defined(PNG_tIME_SUPPORTED)
  181814. # if !defined(_WIN32_WCE)
  181815. /* "time.h" functions are not supported on WindowsCE */
  181816. # include <time.h>
  181817. # endif
  181818. #endif
  181819. /* Some typedefs to get us started. These should be safe on most of the
  181820. * common platforms. The typedefs should be at least as large as the
  181821. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181822. * don't have to be exactly that size. Some compilers dislike passing
  181823. * unsigned shorts as function parameters, so you may be better off using
  181824. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181825. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181826. */
  181827. typedef unsigned long png_uint_32;
  181828. typedef long png_int_32;
  181829. typedef unsigned short png_uint_16;
  181830. typedef short png_int_16;
  181831. typedef unsigned char png_byte;
  181832. /* This is usually size_t. It is typedef'ed just in case you need it to
  181833. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181834. #ifdef PNG_SIZE_T
  181835. typedef PNG_SIZE_T png_size_t;
  181836. # define png_sizeof(x) png_convert_size(sizeof (x))
  181837. #else
  181838. typedef size_t png_size_t;
  181839. # define png_sizeof(x) sizeof (x)
  181840. #endif
  181841. /* The following is needed for medium model support. It cannot be in the
  181842. * PNG_INTERNAL section. Needs modification for other compilers besides
  181843. * MSC. Model independent support declares all arrays and pointers to be
  181844. * large using the far keyword. The zlib version used must also support
  181845. * model independent data. As of version zlib 1.0.4, the necessary changes
  181846. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181847. * changes that are needed. (Tim Wegner)
  181848. */
  181849. /* Separate compiler dependencies (problem here is that zlib.h always
  181850. defines FAR. (SJT) */
  181851. #ifdef __BORLANDC__
  181852. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181853. # define LDATA 1
  181854. # else
  181855. # define LDATA 0
  181856. # endif
  181857. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181858. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181859. # define PNG_MAX_MALLOC_64K
  181860. # if (LDATA != 1)
  181861. # ifndef FAR
  181862. # define FAR __far
  181863. # endif
  181864. # define USE_FAR_KEYWORD
  181865. # endif /* LDATA != 1 */
  181866. /* Possibly useful for moving data out of default segment.
  181867. * Uncomment it if you want. Could also define FARDATA as
  181868. * const if your compiler supports it. (SJT)
  181869. # define FARDATA FAR
  181870. */
  181871. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181872. #endif /* __BORLANDC__ */
  181873. /* Suggest testing for specific compiler first before testing for
  181874. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181875. * making reliance oncertain keywords suspect. (SJT)
  181876. */
  181877. /* MSC Medium model */
  181878. #if defined(FAR)
  181879. # if defined(M_I86MM)
  181880. # define USE_FAR_KEYWORD
  181881. # define FARDATA FAR
  181882. # include <dos.h>
  181883. # endif
  181884. #endif
  181885. /* SJT: default case */
  181886. #ifndef FAR
  181887. # define FAR
  181888. #endif
  181889. /* At this point FAR is always defined */
  181890. #ifndef FARDATA
  181891. # define FARDATA
  181892. #endif
  181893. /* Typedef for floating-point numbers that are converted
  181894. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181895. typedef png_int_32 png_fixed_point;
  181896. /* Add typedefs for pointers */
  181897. typedef void FAR * png_voidp;
  181898. typedef png_byte FAR * png_bytep;
  181899. typedef png_uint_32 FAR * png_uint_32p;
  181900. typedef png_int_32 FAR * png_int_32p;
  181901. typedef png_uint_16 FAR * png_uint_16p;
  181902. typedef png_int_16 FAR * png_int_16p;
  181903. typedef PNG_CONST char FAR * png_const_charp;
  181904. typedef char FAR * png_charp;
  181905. typedef png_fixed_point FAR * png_fixed_point_p;
  181906. #ifndef PNG_NO_STDIO
  181907. #if defined(_WIN32_WCE)
  181908. typedef HANDLE png_FILE_p;
  181909. #else
  181910. typedef FILE * png_FILE_p;
  181911. #endif
  181912. #endif
  181913. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181914. typedef double FAR * png_doublep;
  181915. #endif
  181916. /* Pointers to pointers; i.e. arrays */
  181917. typedef png_byte FAR * FAR * png_bytepp;
  181918. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181919. typedef png_int_32 FAR * FAR * png_int_32pp;
  181920. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181921. typedef png_int_16 FAR * FAR * png_int_16pp;
  181922. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181923. typedef char FAR * FAR * png_charpp;
  181924. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181925. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181926. typedef double FAR * FAR * png_doublepp;
  181927. #endif
  181928. /* Pointers to pointers to pointers; i.e., pointer to array */
  181929. typedef char FAR * FAR * FAR * png_charppp;
  181930. #if 0
  181931. /* SPC - Is this stuff deprecated? */
  181932. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181933. /* libpng typedefs for types in zlib. If zlib changes
  181934. * or another compression library is used, then change these.
  181935. * Eliminates need to change all the source files.
  181936. */
  181937. typedef charf * png_zcharp;
  181938. typedef charf * FAR * png_zcharpp;
  181939. typedef z_stream FAR * png_zstreamp;
  181940. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181941. /*
  181942. * Define PNG_BUILD_DLL if the module being built is a Windows
  181943. * LIBPNG DLL.
  181944. *
  181945. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181946. * It is equivalent to Microsoft predefined macro _DLL that is
  181947. * automatically defined when you compile using the share
  181948. * version of the CRT (C Run-Time library)
  181949. *
  181950. * The cygwin mods make this behavior a little different:
  181951. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181952. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181953. * -or- if you are building an application that you want to link to the
  181954. * static library.
  181955. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181956. * the other flags is defined.
  181957. */
  181958. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181959. # define PNG_DLL
  181960. #endif
  181961. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181962. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181963. * command-line override
  181964. */
  181965. #if defined(__CYGWIN__)
  181966. # if !defined(PNG_STATIC)
  181967. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181968. # undef PNG_USE_GLOBAL_ARRAYS
  181969. # endif
  181970. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181971. # define PNG_USE_LOCAL_ARRAYS
  181972. # endif
  181973. # else
  181974. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181975. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181976. # undef PNG_USE_GLOBAL_ARRAYS
  181977. # endif
  181978. # endif
  181979. # endif
  181980. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181981. # define PNG_USE_LOCAL_ARRAYS
  181982. # endif
  181983. #endif
  181984. /* Do not use global arrays (helps with building DLL's)
  181985. * They are no longer used in libpng itself, since version 1.0.5c,
  181986. * but might be required for some pre-1.0.5c applications.
  181987. */
  181988. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181989. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181990. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181991. # define PNG_USE_LOCAL_ARRAYS
  181992. # else
  181993. # define PNG_USE_GLOBAL_ARRAYS
  181994. # endif
  181995. #endif
  181996. #if defined(__CYGWIN__)
  181997. # undef PNGAPI
  181998. # define PNGAPI __cdecl
  181999. # undef PNG_IMPEXP
  182000. # define PNG_IMPEXP
  182001. #endif
  182002. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  182003. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  182004. * Don't ignore those warnings; you must also reset the default calling
  182005. * convention in your compiler to match your PNGAPI, and you must build
  182006. * zlib and your applications the same way you build libpng.
  182007. */
  182008. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  182009. # ifndef PNG_NO_MODULEDEF
  182010. # define PNG_NO_MODULEDEF
  182011. # endif
  182012. #endif
  182013. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  182014. # define PNG_IMPEXP
  182015. #endif
  182016. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  182017. (( defined(_Windows) || defined(_WINDOWS) || \
  182018. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  182019. # ifndef PNGAPI
  182020. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  182021. # define PNGAPI __cdecl
  182022. # else
  182023. # define PNGAPI _cdecl
  182024. # endif
  182025. # endif
  182026. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  182027. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  182028. # define PNG_IMPEXP
  182029. # endif
  182030. # if !defined(PNG_IMPEXP)
  182031. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182032. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  182033. /* Borland/Microsoft */
  182034. # if defined(_MSC_VER) || defined(__BORLANDC__)
  182035. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  182036. # define PNG_EXPORT PNG_EXPORT_TYPE1
  182037. # else
  182038. # define PNG_EXPORT PNG_EXPORT_TYPE2
  182039. # if defined(PNG_BUILD_DLL)
  182040. # define PNG_IMPEXP __export
  182041. # else
  182042. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  182043. VC++ */
  182044. # endif /* Exists in Borland C++ for
  182045. C++ classes (== huge) */
  182046. # endif
  182047. # endif
  182048. # if !defined(PNG_IMPEXP)
  182049. # if defined(PNG_BUILD_DLL)
  182050. # define PNG_IMPEXP __declspec(dllexport)
  182051. # else
  182052. # define PNG_IMPEXP __declspec(dllimport)
  182053. # endif
  182054. # endif
  182055. # endif /* PNG_IMPEXP */
  182056. #else /* !(DLL || non-cygwin WINDOWS) */
  182057. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  182058. # ifndef PNGAPI
  182059. # define PNGAPI _System
  182060. # endif
  182061. # else
  182062. # if 0 /* ... other platforms, with other meanings */
  182063. # endif
  182064. # endif
  182065. #endif
  182066. #ifndef PNGAPI
  182067. # define PNGAPI
  182068. #endif
  182069. #ifndef PNG_IMPEXP
  182070. # define PNG_IMPEXP
  182071. #endif
  182072. #ifdef PNG_BUILDSYMS
  182073. # ifndef PNG_EXPORT
  182074. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  182075. # endif
  182076. # ifdef PNG_USE_GLOBAL_ARRAYS
  182077. # ifndef PNG_EXPORT_VAR
  182078. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  182079. # endif
  182080. # endif
  182081. #endif
  182082. #ifndef PNG_EXPORT
  182083. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182084. #endif
  182085. #ifdef PNG_USE_GLOBAL_ARRAYS
  182086. # ifndef PNG_EXPORT_VAR
  182087. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  182088. # endif
  182089. #endif
  182090. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  182091. * functions that are passed far data must be model independent.
  182092. */
  182093. #ifndef PNG_ABORT
  182094. # define PNG_ABORT() abort()
  182095. #endif
  182096. #ifdef PNG_SETJMP_SUPPORTED
  182097. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  182098. #else
  182099. # define png_jmpbuf(png_ptr) \
  182100. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  182101. #endif
  182102. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  182103. /* use this to make far-to-near assignments */
  182104. # define CHECK 1
  182105. # define NOCHECK 0
  182106. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  182107. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  182108. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  182109. # define png_strcpy _fstrcpy
  182110. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  182111. # define png_strlen _fstrlen
  182112. # define png_memcmp _fmemcmp /* SJT: added */
  182113. # define png_memcpy _fmemcpy
  182114. # define png_memset _fmemset
  182115. #else /* use the usual functions */
  182116. # define CVT_PTR(ptr) (ptr)
  182117. # define CVT_PTR_NOCHECK(ptr) (ptr)
  182118. # ifndef PNG_NO_SNPRINTF
  182119. # ifdef _MSC_VER
  182120. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  182121. # define png_snprintf2 _snprintf
  182122. # define png_snprintf6 _snprintf
  182123. # else
  182124. # define png_snprintf snprintf /* Added to v 1.2.19 */
  182125. # define png_snprintf2 snprintf
  182126. # define png_snprintf6 snprintf
  182127. # endif
  182128. # else
  182129. /* You don't have or don't want to use snprintf(). Caution: Using
  182130. * sprintf instead of snprintf exposes your application to accidental
  182131. * or malevolent buffer overflows. If you don't have snprintf()
  182132. * as a general rule you should provide one (you can get one from
  182133. * Portable OpenSSH). */
  182134. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  182135. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  182136. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  182137. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  182138. # endif
  182139. # define png_strcpy strcpy
  182140. # define png_strncpy strncpy /* Added to v 1.2.6 */
  182141. # define png_strlen strlen
  182142. # define png_memcmp memcmp /* SJT: added */
  182143. # define png_memcpy memcpy
  182144. # define png_memset memset
  182145. #endif
  182146. /* End of memory model independent support */
  182147. /* Just a little check that someone hasn't tried to define something
  182148. * contradictory.
  182149. */
  182150. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182151. # undef PNG_ZBUF_SIZE
  182152. # define PNG_ZBUF_SIZE 65536L
  182153. #endif
  182154. /* Added at libpng-1.2.8 */
  182155. #endif /* PNG_VERSION_INFO_ONLY */
  182156. #endif /* PNGCONF_H */
  182157. /*** End of inlined file: pngconf.h ***/
  182158. #ifdef _MSC_VER
  182159. #pragma warning (disable: 4996 4100)
  182160. #endif
  182161. /*
  182162. * Added at libpng-1.2.8 */
  182163. /* Ref MSDN: Private as priority over Special
  182164. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182165. * procedures. If this value is given, the StringFileInfo block must
  182166. * contain a PrivateBuild string.
  182167. *
  182168. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182169. * standard release procedures but is a variation of the standard
  182170. * file of the same version number. If this value is given, the
  182171. * StringFileInfo block must contain a SpecialBuild string.
  182172. */
  182173. #if defined(PNG_USER_PRIVATEBUILD)
  182174. # define PNG_LIBPNG_BUILD_TYPE \
  182175. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182176. #else
  182177. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182178. # define PNG_LIBPNG_BUILD_TYPE \
  182179. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182180. # else
  182181. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182182. # endif
  182183. #endif
  182184. #ifndef PNG_VERSION_INFO_ONLY
  182185. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182186. #ifdef __cplusplus
  182187. //extern "C" {
  182188. #endif /* __cplusplus */
  182189. /* This file is arranged in several sections. The first section contains
  182190. * structure and type definitions. The second section contains the external
  182191. * library functions, while the third has the internal library functions,
  182192. * which applications aren't expected to use directly.
  182193. */
  182194. #ifndef PNG_NO_TYPECAST_NULL
  182195. #define int_p_NULL (int *)NULL
  182196. #define png_bytep_NULL (png_bytep)NULL
  182197. #define png_bytepp_NULL (png_bytepp)NULL
  182198. #define png_doublep_NULL (png_doublep)NULL
  182199. #define png_error_ptr_NULL (png_error_ptr)NULL
  182200. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182201. #define png_free_ptr_NULL (png_free_ptr)NULL
  182202. #define png_infopp_NULL (png_infopp)NULL
  182203. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182204. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182205. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182206. #define png_structp_NULL (png_structp)NULL
  182207. #define png_uint_16p_NULL (png_uint_16p)NULL
  182208. #define png_voidp_NULL (png_voidp)NULL
  182209. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182210. #else
  182211. #define int_p_NULL NULL
  182212. #define png_bytep_NULL NULL
  182213. #define png_bytepp_NULL NULL
  182214. #define png_doublep_NULL NULL
  182215. #define png_error_ptr_NULL NULL
  182216. #define png_flush_ptr_NULL NULL
  182217. #define png_free_ptr_NULL NULL
  182218. #define png_infopp_NULL NULL
  182219. #define png_malloc_ptr_NULL NULL
  182220. #define png_read_status_ptr_NULL NULL
  182221. #define png_rw_ptr_NULL NULL
  182222. #define png_structp_NULL NULL
  182223. #define png_uint_16p_NULL NULL
  182224. #define png_voidp_NULL NULL
  182225. #define png_write_status_ptr_NULL NULL
  182226. #endif
  182227. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182228. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182229. /* Version information for C files, stored in png.c. This had better match
  182230. * the version above.
  182231. */
  182232. #ifdef PNG_USE_GLOBAL_ARRAYS
  182233. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182234. /* need room for 99.99.99beta99z */
  182235. #else
  182236. #define png_libpng_ver png_get_header_ver(NULL)
  182237. #endif
  182238. #ifdef PNG_USE_GLOBAL_ARRAYS
  182239. /* This was removed in version 1.0.5c */
  182240. /* Structures to facilitate easy interlacing. See png.c for more details */
  182241. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182242. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182243. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182244. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182245. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182246. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182247. /* This isn't currently used. If you need it, see png.c for more details.
  182248. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182249. */
  182250. #endif
  182251. #endif /* PNG_NO_EXTERN */
  182252. /* Three color definitions. The order of the red, green, and blue, (and the
  182253. * exact size) is not important, although the size of the fields need to
  182254. * be png_byte or png_uint_16 (as defined below).
  182255. */
  182256. typedef struct png_color_struct
  182257. {
  182258. png_byte red;
  182259. png_byte green;
  182260. png_byte blue;
  182261. } png_color;
  182262. typedef png_color FAR * png_colorp;
  182263. typedef png_color FAR * FAR * png_colorpp;
  182264. typedef struct png_color_16_struct
  182265. {
  182266. png_byte index; /* used for palette files */
  182267. png_uint_16 red; /* for use in red green blue files */
  182268. png_uint_16 green;
  182269. png_uint_16 blue;
  182270. png_uint_16 gray; /* for use in grayscale files */
  182271. } png_color_16;
  182272. typedef png_color_16 FAR * png_color_16p;
  182273. typedef png_color_16 FAR * FAR * png_color_16pp;
  182274. typedef struct png_color_8_struct
  182275. {
  182276. png_byte red; /* for use in red green blue files */
  182277. png_byte green;
  182278. png_byte blue;
  182279. png_byte gray; /* for use in grayscale files */
  182280. png_byte alpha; /* for alpha channel files */
  182281. } png_color_8;
  182282. typedef png_color_8 FAR * png_color_8p;
  182283. typedef png_color_8 FAR * FAR * png_color_8pp;
  182284. /*
  182285. * The following two structures are used for the in-core representation
  182286. * of sPLT chunks.
  182287. */
  182288. typedef struct png_sPLT_entry_struct
  182289. {
  182290. png_uint_16 red;
  182291. png_uint_16 green;
  182292. png_uint_16 blue;
  182293. png_uint_16 alpha;
  182294. png_uint_16 frequency;
  182295. } png_sPLT_entry;
  182296. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182297. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182298. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182299. * occupy the LSB of their respective members, and the MSB of each member
  182300. * is zero-filled. The frequency member always occupies the full 16 bits.
  182301. */
  182302. typedef struct png_sPLT_struct
  182303. {
  182304. png_charp name; /* palette name */
  182305. png_byte depth; /* depth of palette samples */
  182306. png_sPLT_entryp entries; /* palette entries */
  182307. png_int_32 nentries; /* number of palette entries */
  182308. } png_sPLT_t;
  182309. typedef png_sPLT_t FAR * png_sPLT_tp;
  182310. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182311. #ifdef PNG_TEXT_SUPPORTED
  182312. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182313. * and whether that contents is compressed or not. The "key" field
  182314. * points to a regular zero-terminated C string. The "text", "lang", and
  182315. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182316. * However, the * structure returned by png_get_text() will always contain
  182317. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182318. * so they can be safely used in printf() and other string-handling functions.
  182319. */
  182320. typedef struct png_text_struct
  182321. {
  182322. int compression; /* compression value:
  182323. -1: tEXt, none
  182324. 0: zTXt, deflate
  182325. 1: iTXt, none
  182326. 2: iTXt, deflate */
  182327. png_charp key; /* keyword, 1-79 character description of "text" */
  182328. png_charp text; /* comment, may be an empty string (ie "")
  182329. or a NULL pointer */
  182330. png_size_t text_length; /* length of the text string */
  182331. #ifdef PNG_iTXt_SUPPORTED
  182332. png_size_t itxt_length; /* length of the itxt string */
  182333. png_charp lang; /* language code, 0-79 characters
  182334. or a NULL pointer */
  182335. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182336. chars or a NULL pointer */
  182337. #endif
  182338. } png_text;
  182339. typedef png_text FAR * png_textp;
  182340. typedef png_text FAR * FAR * png_textpp;
  182341. #endif
  182342. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182343. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182344. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182345. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182346. #define PNG_TEXT_COMPRESSION_NONE -1
  182347. #define PNG_TEXT_COMPRESSION_zTXt 0
  182348. #define PNG_ITXT_COMPRESSION_NONE 1
  182349. #define PNG_ITXT_COMPRESSION_zTXt 2
  182350. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182351. /* png_time is a way to hold the time in an machine independent way.
  182352. * Two conversions are provided, both from time_t and struct tm. There
  182353. * is no portable way to convert to either of these structures, as far
  182354. * as I know. If you know of a portable way, send it to me. As a side
  182355. * note - PNG has always been Year 2000 compliant!
  182356. */
  182357. typedef struct png_time_struct
  182358. {
  182359. png_uint_16 year; /* full year, as in, 1995 */
  182360. png_byte month; /* month of year, 1 - 12 */
  182361. png_byte day; /* day of month, 1 - 31 */
  182362. png_byte hour; /* hour of day, 0 - 23 */
  182363. png_byte minute; /* minute of hour, 0 - 59 */
  182364. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182365. } png_time;
  182366. typedef png_time FAR * png_timep;
  182367. typedef png_time FAR * FAR * png_timepp;
  182368. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182369. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182370. * no specific support. The idea is that we can use this to queue
  182371. * up private chunks for output even though the library doesn't actually
  182372. * know about their semantics.
  182373. */
  182374. typedef struct png_unknown_chunk_t
  182375. {
  182376. png_byte name[5];
  182377. png_byte *data;
  182378. png_size_t size;
  182379. /* libpng-using applications should NOT directly modify this byte. */
  182380. png_byte location; /* mode of operation at read time */
  182381. }
  182382. png_unknown_chunk;
  182383. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182384. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182385. #endif
  182386. /* png_info is a structure that holds the information in a PNG file so
  182387. * that the application can find out the characteristics of the image.
  182388. * If you are reading the file, this structure will tell you what is
  182389. * in the PNG file. If you are writing the file, fill in the information
  182390. * you want to put into the PNG file, then call png_write_info().
  182391. * The names chosen should be very close to the PNG specification, so
  182392. * consult that document for information about the meaning of each field.
  182393. *
  182394. * With libpng < 0.95, it was only possible to directly set and read the
  182395. * the values in the png_info_struct, which meant that the contents and
  182396. * order of the values had to remain fixed. With libpng 0.95 and later,
  182397. * however, there are now functions that abstract the contents of
  182398. * png_info_struct from the application, so this makes it easier to use
  182399. * libpng with dynamic libraries, and even makes it possible to use
  182400. * libraries that don't have all of the libpng ancillary chunk-handing
  182401. * functionality.
  182402. *
  182403. * In any case, the order of the parameters in png_info_struct should NOT
  182404. * be changed for as long as possible to keep compatibility with applications
  182405. * that use the old direct-access method with png_info_struct.
  182406. *
  182407. * The following members may have allocated storage attached that should be
  182408. * cleaned up before the structure is discarded: palette, trans, text,
  182409. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182410. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182411. * are automatically freed when the info structure is deallocated, if they were
  182412. * allocated internally by libpng. This behavior can be changed by means
  182413. * of the png_data_freer() function.
  182414. *
  182415. * More allocation details: all the chunk-reading functions that
  182416. * change these members go through the corresponding png_set_*
  182417. * functions. A function to clear these members is available: see
  182418. * png_free_data(). The png_set_* functions do not depend on being
  182419. * able to point info structure members to any of the storage they are
  182420. * passed (they make their own copies), EXCEPT that the png_set_text
  182421. * functions use the same storage passed to them in the text_ptr or
  182422. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182423. * functions do not make their own copies.
  182424. */
  182425. typedef struct png_info_struct
  182426. {
  182427. /* the following are necessary for every PNG file */
  182428. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182429. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182430. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182431. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182432. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182433. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182434. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182435. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182436. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182437. /* The following three should have been named *_method not *_type */
  182438. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182439. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182440. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182441. /* The following is informational only on read, and not used on writes. */
  182442. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182443. png_byte pixel_depth; /* number of bits per pixel */
  182444. png_byte spare_byte; /* to align the data, and for future use */
  182445. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182446. /* The rest of the data is optional. If you are reading, check the
  182447. * valid field to see if the information in these are valid. If you
  182448. * are writing, set the valid field to those chunks you want written,
  182449. * and initialize the appropriate fields below.
  182450. */
  182451. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182452. /* The gAMA chunk describes the gamma characteristics of the system
  182453. * on which the image was created, normally in the range [1.0, 2.5].
  182454. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182455. */
  182456. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182457. #endif
  182458. #if defined(PNG_sRGB_SUPPORTED)
  182459. /* GR-P, 0.96a */
  182460. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182461. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182462. #endif
  182463. #if defined(PNG_TEXT_SUPPORTED)
  182464. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182465. * uncompressed, compressed, and optionally compressed forms, respectively.
  182466. * The data in "text" is an array of pointers to uncompressed,
  182467. * null-terminated C strings. Each chunk has a keyword that describes the
  182468. * textual data contained in that chunk. Keywords are not required to be
  182469. * unique, and the text string may be empty. Any number of text chunks may
  182470. * be in an image.
  182471. */
  182472. int num_text; /* number of comments read/to write */
  182473. int max_text; /* current size of text array */
  182474. png_textp text; /* array of comments read/to write */
  182475. #endif /* PNG_TEXT_SUPPORTED */
  182476. #if defined(PNG_tIME_SUPPORTED)
  182477. /* The tIME chunk holds the last time the displayed image data was
  182478. * modified. See the png_time struct for the contents of this struct.
  182479. */
  182480. png_time mod_time;
  182481. #endif
  182482. #if defined(PNG_sBIT_SUPPORTED)
  182483. /* The sBIT chunk specifies the number of significant high-order bits
  182484. * in the pixel data. Values are in the range [1, bit_depth], and are
  182485. * only specified for the channels in the pixel data. The contents of
  182486. * the low-order bits is not specified. Data is valid if
  182487. * (valid & PNG_INFO_sBIT) is non-zero.
  182488. */
  182489. png_color_8 sig_bit; /* significant bits in color channels */
  182490. #endif
  182491. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182492. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182493. /* The tRNS chunk supplies transparency data for paletted images and
  182494. * other image types that don't need a full alpha channel. There are
  182495. * "num_trans" transparency values for a paletted image, stored in the
  182496. * same order as the palette colors, starting from index 0. Values
  182497. * for the data are in the range [0, 255], ranging from fully transparent
  182498. * to fully opaque, respectively. For non-paletted images, there is a
  182499. * single color specified that should be treated as fully transparent.
  182500. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182501. */
  182502. png_bytep trans; /* transparent values for paletted image */
  182503. png_color_16 trans_values; /* transparent color for non-palette image */
  182504. #endif
  182505. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182506. /* The bKGD chunk gives the suggested image background color if the
  182507. * display program does not have its own background color and the image
  182508. * is needs to composited onto a background before display. The colors
  182509. * in "background" are normally in the same color space/depth as the
  182510. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182511. */
  182512. png_color_16 background;
  182513. #endif
  182514. #if defined(PNG_oFFs_SUPPORTED)
  182515. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182516. * and downwards from the top-left corner of the display, page, or other
  182517. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182518. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182519. */
  182520. png_int_32 x_offset; /* x offset on page */
  182521. png_int_32 y_offset; /* y offset on page */
  182522. png_byte offset_unit_type; /* offset units type */
  182523. #endif
  182524. #if defined(PNG_pHYs_SUPPORTED)
  182525. /* The pHYs chunk gives the physical pixel density of the image for
  182526. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182527. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182528. */
  182529. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182530. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182531. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182532. #endif
  182533. #if defined(PNG_hIST_SUPPORTED)
  182534. /* The hIST chunk contains the relative frequency or importance of the
  182535. * various palette entries, so that a viewer can intelligently select a
  182536. * reduced-color palette, if required. Data is an array of "num_palette"
  182537. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182538. * is non-zero.
  182539. */
  182540. png_uint_16p hist;
  182541. #endif
  182542. #ifdef PNG_cHRM_SUPPORTED
  182543. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182544. * on which the PNG was created. This data allows the viewer to do gamut
  182545. * mapping of the input image to ensure that the viewer sees the same
  182546. * colors in the image as the creator. Values are in the range
  182547. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182548. */
  182549. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182550. float x_white;
  182551. float y_white;
  182552. float x_red;
  182553. float y_red;
  182554. float x_green;
  182555. float y_green;
  182556. float x_blue;
  182557. float y_blue;
  182558. #endif
  182559. #endif
  182560. #if defined(PNG_pCAL_SUPPORTED)
  182561. /* The pCAL chunk describes a transformation between the stored pixel
  182562. * values and original physical data values used to create the image.
  182563. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182564. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182565. * (possibly non-linear) transformation function given by "pcal_type"
  182566. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182567. * defines below, and the PNG-Group's PNG extensions document for a
  182568. * complete description of the transformations and how they should be
  182569. * implemented, and for a description of the ASCII parameter strings.
  182570. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182571. */
  182572. png_charp pcal_purpose; /* pCAL chunk description string */
  182573. png_int_32 pcal_X0; /* minimum value */
  182574. png_int_32 pcal_X1; /* maximum value */
  182575. png_charp pcal_units; /* Latin-1 string giving physical units */
  182576. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182577. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182578. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182579. #endif
  182580. /* New members added in libpng-1.0.6 */
  182581. #ifdef PNG_FREE_ME_SUPPORTED
  182582. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182583. #endif
  182584. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182585. /* storage for unknown chunks that the library doesn't recognize. */
  182586. png_unknown_chunkp unknown_chunks;
  182587. png_size_t unknown_chunks_num;
  182588. #endif
  182589. #if defined(PNG_iCCP_SUPPORTED)
  182590. /* iCCP chunk data. */
  182591. png_charp iccp_name; /* profile name */
  182592. png_charp iccp_profile; /* International Color Consortium profile data */
  182593. /* Note to maintainer: should be png_bytep */
  182594. png_uint_32 iccp_proflen; /* ICC profile data length */
  182595. png_byte iccp_compression; /* Always zero */
  182596. #endif
  182597. #if defined(PNG_sPLT_SUPPORTED)
  182598. /* data on sPLT chunks (there may be more than one). */
  182599. png_sPLT_tp splt_palettes;
  182600. png_uint_32 splt_palettes_num;
  182601. #endif
  182602. #if defined(PNG_sCAL_SUPPORTED)
  182603. /* The sCAL chunk describes the actual physical dimensions of the
  182604. * subject matter of the graphic. The chunk contains a unit specification
  182605. * a byte value, and two ASCII strings representing floating-point
  182606. * values. The values are width and height corresponsing to one pixel
  182607. * in the image. This external representation is converted to double
  182608. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182609. */
  182610. png_byte scal_unit; /* unit of physical scale */
  182611. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182612. double scal_pixel_width; /* width of one pixel */
  182613. double scal_pixel_height; /* height of one pixel */
  182614. #endif
  182615. #ifdef PNG_FIXED_POINT_SUPPORTED
  182616. png_charp scal_s_width; /* string containing height */
  182617. png_charp scal_s_height; /* string containing width */
  182618. #endif
  182619. #endif
  182620. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182621. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182622. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182623. png_bytepp row_pointers; /* the image bits */
  182624. #endif
  182625. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182626. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182627. #endif
  182628. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182629. png_fixed_point int_x_white;
  182630. png_fixed_point int_y_white;
  182631. png_fixed_point int_x_red;
  182632. png_fixed_point int_y_red;
  182633. png_fixed_point int_x_green;
  182634. png_fixed_point int_y_green;
  182635. png_fixed_point int_x_blue;
  182636. png_fixed_point int_y_blue;
  182637. #endif
  182638. } png_info;
  182639. typedef png_info FAR * png_infop;
  182640. typedef png_info FAR * FAR * png_infopp;
  182641. /* Maximum positive integer used in PNG is (2^31)-1 */
  182642. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182643. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182644. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182645. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182646. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182647. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182648. #endif
  182649. /* These describe the color_type field in png_info. */
  182650. /* color type masks */
  182651. #define PNG_COLOR_MASK_PALETTE 1
  182652. #define PNG_COLOR_MASK_COLOR 2
  182653. #define PNG_COLOR_MASK_ALPHA 4
  182654. /* color types. Note that not all combinations are legal */
  182655. #define PNG_COLOR_TYPE_GRAY 0
  182656. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182657. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182658. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182659. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182660. /* aliases */
  182661. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182662. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182663. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182664. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182665. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182666. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182667. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182668. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182669. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182670. /* These are for the interlacing type. These values should NOT be changed. */
  182671. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182672. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182673. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182674. /* These are for the oFFs chunk. These values should NOT be changed. */
  182675. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182676. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182677. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182678. /* These are for the pCAL chunk. These values should NOT be changed. */
  182679. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182680. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182681. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182682. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182683. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182684. /* These are for the sCAL chunk. These values should NOT be changed. */
  182685. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182686. #define PNG_SCALE_METER 1 /* meters per pixel */
  182687. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182688. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182689. /* These are for the pHYs chunk. These values should NOT be changed. */
  182690. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182691. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182692. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182693. /* These are for the sRGB chunk. These values should NOT be changed. */
  182694. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182695. #define PNG_sRGB_INTENT_RELATIVE 1
  182696. #define PNG_sRGB_INTENT_SATURATION 2
  182697. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182698. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182699. /* This is for text chunks */
  182700. #define PNG_KEYWORD_MAX_LENGTH 79
  182701. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182702. #define PNG_MAX_PALETTE_LENGTH 256
  182703. /* These determine if an ancillary chunk's data has been successfully read
  182704. * from the PNG header, or if the application has filled in the corresponding
  182705. * data in the info_struct to be written into the output file. The values
  182706. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182707. */
  182708. #define PNG_INFO_gAMA 0x0001
  182709. #define PNG_INFO_sBIT 0x0002
  182710. #define PNG_INFO_cHRM 0x0004
  182711. #define PNG_INFO_PLTE 0x0008
  182712. #define PNG_INFO_tRNS 0x0010
  182713. #define PNG_INFO_bKGD 0x0020
  182714. #define PNG_INFO_hIST 0x0040
  182715. #define PNG_INFO_pHYs 0x0080
  182716. #define PNG_INFO_oFFs 0x0100
  182717. #define PNG_INFO_tIME 0x0200
  182718. #define PNG_INFO_pCAL 0x0400
  182719. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182720. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182721. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182722. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182723. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182724. /* This is used for the transformation routines, as some of them
  182725. * change these values for the row. It also should enable using
  182726. * the routines for other purposes.
  182727. */
  182728. typedef struct png_row_info_struct
  182729. {
  182730. png_uint_32 width; /* width of row */
  182731. png_uint_32 rowbytes; /* number of bytes in row */
  182732. png_byte color_type; /* color type of row */
  182733. png_byte bit_depth; /* bit depth of row */
  182734. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182735. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182736. } png_row_info;
  182737. typedef png_row_info FAR * png_row_infop;
  182738. typedef png_row_info FAR * FAR * png_row_infopp;
  182739. /* These are the function types for the I/O functions and for the functions
  182740. * that allow the user to override the default I/O functions with his or her
  182741. * own. The png_error_ptr type should match that of user-supplied warning
  182742. * and error functions, while the png_rw_ptr type should match that of the
  182743. * user read/write data functions.
  182744. */
  182745. typedef struct png_struct_def png_struct;
  182746. typedef png_struct FAR * png_structp;
  182747. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182748. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182749. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182750. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182751. int));
  182752. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182753. int));
  182754. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182755. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182756. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182757. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182758. png_uint_32, int));
  182759. #endif
  182760. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182761. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182762. defined(PNG_LEGACY_SUPPORTED)
  182763. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182764. png_row_infop, png_bytep));
  182765. #endif
  182766. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182767. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182768. #endif
  182769. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182770. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182771. #endif
  182772. /* Transform masks for the high-level interface */
  182773. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182774. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182775. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182776. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182777. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182778. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182779. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182780. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182781. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182782. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182783. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182784. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182785. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182786. /* Flags for MNG supported features */
  182787. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182788. #define PNG_FLAG_MNG_FILTER_64 0x04
  182789. #define PNG_ALL_MNG_FEATURES 0x05
  182790. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182791. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182792. /* The structure that holds the information to read and write PNG files.
  182793. * The only people who need to care about what is inside of this are the
  182794. * people who will be modifying the library for their own special needs.
  182795. * It should NOT be accessed directly by an application, except to store
  182796. * the jmp_buf.
  182797. */
  182798. struct png_struct_def
  182799. {
  182800. #ifdef PNG_SETJMP_SUPPORTED
  182801. jmp_buf jmpbuf; /* used in png_error */
  182802. #endif
  182803. png_error_ptr error_fn; /* function for printing errors and aborting */
  182804. png_error_ptr warning_fn; /* function for printing warnings */
  182805. png_voidp error_ptr; /* user supplied struct for error functions */
  182806. png_rw_ptr write_data_fn; /* function for writing output data */
  182807. png_rw_ptr read_data_fn; /* function for reading input data */
  182808. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182809. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182810. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182811. #endif
  182812. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182813. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182814. #endif
  182815. /* These were added in libpng-1.0.2 */
  182816. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182817. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182818. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182819. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182820. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182821. png_byte user_transform_channels; /* channels in user transformed pixels */
  182822. #endif
  182823. #endif
  182824. png_uint_32 mode; /* tells us where we are in the PNG file */
  182825. png_uint_32 flags; /* flags indicating various things to libpng */
  182826. png_uint_32 transformations; /* which transformations to perform */
  182827. z_stream zstream; /* pointer to decompression structure (below) */
  182828. png_bytep zbuf; /* buffer for zlib */
  182829. png_size_t zbuf_size; /* size of zbuf */
  182830. int zlib_level; /* holds zlib compression level */
  182831. int zlib_method; /* holds zlib compression method */
  182832. int zlib_window_bits; /* holds zlib compression window bits */
  182833. int zlib_mem_level; /* holds zlib compression memory level */
  182834. int zlib_strategy; /* holds zlib compression strategy */
  182835. png_uint_32 width; /* width of image in pixels */
  182836. png_uint_32 height; /* height of image in pixels */
  182837. png_uint_32 num_rows; /* number of rows in current pass */
  182838. png_uint_32 usr_width; /* width of row at start of write */
  182839. png_uint_32 rowbytes; /* size of row in bytes */
  182840. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182841. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182842. png_uint_32 row_number; /* current row in interlace pass */
  182843. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182844. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182845. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182846. png_bytep up_row; /* buffer to save "up" row when filtering */
  182847. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182848. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182849. png_row_info row_info; /* used for transformation routines */
  182850. png_uint_32 idat_size; /* current IDAT size for read */
  182851. png_uint_32 crc; /* current chunk CRC value */
  182852. png_colorp palette; /* palette from the input file */
  182853. png_uint_16 num_palette; /* number of color entries in palette */
  182854. png_uint_16 num_trans; /* number of transparency values */
  182855. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182856. png_byte compression; /* file compression type (always 0) */
  182857. png_byte filter; /* file filter type (always 0) */
  182858. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182859. png_byte pass; /* current interlace pass (0 - 6) */
  182860. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182861. png_byte color_type; /* color type of file */
  182862. png_byte bit_depth; /* bit depth of file */
  182863. png_byte usr_bit_depth; /* bit depth of users row */
  182864. png_byte pixel_depth; /* number of bits per pixel */
  182865. png_byte channels; /* number of channels in file */
  182866. png_byte usr_channels; /* channels at start of write */
  182867. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182868. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182869. #ifdef PNG_LEGACY_SUPPORTED
  182870. png_byte filler; /* filler byte for pixel expansion */
  182871. #else
  182872. png_uint_16 filler; /* filler bytes for pixel expansion */
  182873. #endif
  182874. #endif
  182875. #if defined(PNG_bKGD_SUPPORTED)
  182876. png_byte background_gamma_type;
  182877. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182878. float background_gamma;
  182879. # endif
  182880. png_color_16 background; /* background color in screen gamma space */
  182881. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182882. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182883. #endif
  182884. #endif /* PNG_bKGD_SUPPORTED */
  182885. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182886. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182887. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182888. png_uint_32 flush_rows; /* number of rows written since last flush */
  182889. #endif
  182890. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182891. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182892. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182893. float gamma; /* file gamma value */
  182894. float screen_gamma; /* screen gamma value (display_exponent) */
  182895. #endif
  182896. #endif
  182897. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182898. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182899. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182900. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182901. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182902. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182903. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182904. #endif
  182905. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182906. png_color_8 sig_bit; /* significant bits in each available channel */
  182907. #endif
  182908. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182909. png_color_8 shift; /* shift for significant bit tranformation */
  182910. #endif
  182911. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182912. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182913. png_bytep trans; /* transparency values for paletted files */
  182914. png_color_16 trans_values; /* transparency values for non-paletted files */
  182915. #endif
  182916. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182917. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182918. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182919. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182920. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182921. png_progressive_end_ptr end_fn; /* called after image is complete */
  182922. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182923. png_bytep save_buffer; /* buffer for previously read data */
  182924. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182925. png_bytep current_buffer; /* buffer for recently used data */
  182926. png_uint_32 push_length; /* size of current input chunk */
  182927. png_uint_32 skip_length; /* bytes to skip in input data */
  182928. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182929. png_size_t save_buffer_max; /* total size of save_buffer */
  182930. png_size_t buffer_size; /* total amount of available input data */
  182931. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182932. int process_mode; /* what push library is currently doing */
  182933. int cur_palette; /* current push library palette index */
  182934. # if defined(PNG_TEXT_SUPPORTED)
  182935. png_size_t current_text_size; /* current size of text input data */
  182936. png_size_t current_text_left; /* how much text left to read in input */
  182937. png_charp current_text; /* current text chunk buffer */
  182938. png_charp current_text_ptr; /* current location in current_text */
  182939. # endif /* PNG_TEXT_SUPPORTED */
  182940. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182941. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182942. /* for the Borland special 64K segment handler */
  182943. png_bytepp offset_table_ptr;
  182944. png_bytep offset_table;
  182945. png_uint_16 offset_table_number;
  182946. png_uint_16 offset_table_count;
  182947. png_uint_16 offset_table_count_free;
  182948. #endif
  182949. #if defined(PNG_READ_DITHER_SUPPORTED)
  182950. png_bytep palette_lookup; /* lookup table for dithering */
  182951. png_bytep dither_index; /* index translation for palette files */
  182952. #endif
  182953. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182954. png_uint_16p hist; /* histogram */
  182955. #endif
  182956. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182957. png_byte heuristic_method; /* heuristic for row filter selection */
  182958. png_byte num_prev_filters; /* number of weights for previous rows */
  182959. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182960. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182961. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182962. png_uint_16p filter_costs; /* relative filter calculation cost */
  182963. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182964. #endif
  182965. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182966. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182967. #endif
  182968. /* New members added in libpng-1.0.6 */
  182969. #ifdef PNG_FREE_ME_SUPPORTED
  182970. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182971. #endif
  182972. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182973. png_voidp user_chunk_ptr;
  182974. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182975. #endif
  182976. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182977. int num_chunk_list;
  182978. png_bytep chunk_list;
  182979. #endif
  182980. /* New members added in libpng-1.0.3 */
  182981. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182982. png_byte rgb_to_gray_status;
  182983. /* These were changed from png_byte in libpng-1.0.6 */
  182984. png_uint_16 rgb_to_gray_red_coeff;
  182985. png_uint_16 rgb_to_gray_green_coeff;
  182986. png_uint_16 rgb_to_gray_blue_coeff;
  182987. #endif
  182988. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182989. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182990. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182991. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182992. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182993. #ifdef PNG_1_0_X
  182994. png_byte mng_features_permitted;
  182995. #else
  182996. png_uint_32 mng_features_permitted;
  182997. #endif /* PNG_1_0_X */
  182998. #endif
  182999. /* New member added in libpng-1.0.7 */
  183000. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183001. png_fixed_point int_gamma;
  183002. #endif
  183003. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  183004. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183005. png_byte filter_type;
  183006. #endif
  183007. #if defined(PNG_1_0_X)
  183008. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  183009. png_uint_32 row_buf_size;
  183010. #endif
  183011. /* New members added in libpng-1.2.0 */
  183012. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183013. # if !defined(PNG_1_0_X)
  183014. # if defined(PNG_MMX_CODE_SUPPORTED)
  183015. png_byte mmx_bitdepth_threshold;
  183016. png_uint_32 mmx_rowbytes_threshold;
  183017. # endif
  183018. png_uint_32 asm_flags;
  183019. # endif
  183020. #endif
  183021. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  183022. #ifdef PNG_USER_MEM_SUPPORTED
  183023. png_voidp mem_ptr; /* user supplied struct for mem functions */
  183024. png_malloc_ptr malloc_fn; /* function for allocating memory */
  183025. png_free_ptr free_fn; /* function for freeing memory */
  183026. #endif
  183027. /* New member added in libpng-1.0.13 and 1.2.0 */
  183028. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  183029. #if defined(PNG_READ_DITHER_SUPPORTED)
  183030. /* The following three members were added at version 1.0.14 and 1.2.4 */
  183031. png_bytep dither_sort; /* working sort array */
  183032. png_bytep index_to_palette; /* where the original index currently is */
  183033. /* in the palette */
  183034. png_bytep palette_to_index; /* which original index points to this */
  183035. /* palette color */
  183036. #endif
  183037. /* New members added in libpng-1.0.16 and 1.2.6 */
  183038. png_byte compression_type;
  183039. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183040. png_uint_32 user_width_max;
  183041. png_uint_32 user_height_max;
  183042. #endif
  183043. /* New member added in libpng-1.0.25 and 1.2.17 */
  183044. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183045. /* storage for unknown chunk that the library doesn't recognize. */
  183046. png_unknown_chunk unknown_chunk;
  183047. #endif
  183048. };
  183049. /* This triggers a compiler error in png.c, if png.c and png.h
  183050. * do not agree upon the version number.
  183051. */
  183052. typedef png_structp version_1_2_21;
  183053. typedef png_struct FAR * FAR * png_structpp;
  183054. /* Here are the function definitions most commonly used. This is not
  183055. * the place to find out how to use libpng. See libpng.txt for the
  183056. * full explanation, see example.c for the summary. This just provides
  183057. * a simple one line description of the use of each function.
  183058. */
  183059. /* Returns the version number of the library */
  183060. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  183061. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  183062. * Handling more than 8 bytes from the beginning of the file is an error.
  183063. */
  183064. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  183065. int num_bytes));
  183066. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  183067. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  183068. * signature, and non-zero otherwise. Having num_to_check == 0 or
  183069. * start > 7 will always fail (ie return non-zero).
  183070. */
  183071. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  183072. png_size_t num_to_check));
  183073. /* Simple signature checking function. This is the same as calling
  183074. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  183075. */
  183076. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  183077. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  183078. extern PNG_EXPORT(png_structp,png_create_read_struct)
  183079. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183080. png_error_ptr error_fn, png_error_ptr warn_fn));
  183081. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  183082. extern PNG_EXPORT(png_structp,png_create_write_struct)
  183083. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183084. png_error_ptr error_fn, png_error_ptr warn_fn));
  183085. #ifdef PNG_WRITE_SUPPORTED
  183086. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  183087. PNGARG((png_structp png_ptr));
  183088. #endif
  183089. #ifdef PNG_WRITE_SUPPORTED
  183090. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  183091. PNGARG((png_structp png_ptr, png_uint_32 size));
  183092. #endif
  183093. /* Reset the compression stream */
  183094. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  183095. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  183096. #ifdef PNG_USER_MEM_SUPPORTED
  183097. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  183098. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183099. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183100. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183101. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  183102. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183103. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183104. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183105. #endif
  183106. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  183107. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  183108. png_bytep chunk_name, png_bytep data, png_size_t length));
  183109. /* Write the start of a PNG chunk - length and chunk name. */
  183110. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  183111. png_bytep chunk_name, png_uint_32 length));
  183112. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  183113. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  183114. png_bytep data, png_size_t length));
  183115. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  183116. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  183117. /* Allocate and initialize the info structure */
  183118. extern PNG_EXPORT(png_infop,png_create_info_struct)
  183119. PNGARG((png_structp png_ptr));
  183120. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183121. /* Initialize the info structure (old interface - DEPRECATED) */
  183122. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  183123. #undef png_info_init
  183124. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  183125. png_sizeof(png_info));
  183126. #endif
  183127. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  183128. png_size_t png_info_struct_size));
  183129. /* Writes all the PNG information before the image. */
  183130. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  183131. png_infop info_ptr));
  183132. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  183133. png_infop info_ptr));
  183134. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183135. /* read the information before the actual image data. */
  183136. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  183137. png_infop info_ptr));
  183138. #endif
  183139. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183140. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  183141. PNGARG((png_structp png_ptr, png_timep ptime));
  183142. #endif
  183143. #if !defined(_WIN32_WCE)
  183144. /* "time.h" functions are not supported on WindowsCE */
  183145. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183146. /* convert from a struct tm to png_time */
  183147. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183148. struct tm FAR * ttime));
  183149. /* convert from time_t to png_time. Uses gmtime() */
  183150. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183151. time_t ttime));
  183152. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183153. #endif /* _WIN32_WCE */
  183154. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183155. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183156. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183157. #if !defined(PNG_1_0_X)
  183158. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183159. png_ptr));
  183160. #endif
  183161. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183162. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183163. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183164. /* Deprecated */
  183165. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183166. #endif
  183167. #endif
  183168. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183169. /* Use blue, green, red order for pixels. */
  183170. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183171. #endif
  183172. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183173. /* Expand the grayscale to 24-bit RGB if necessary. */
  183174. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183175. #endif
  183176. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183177. /* Reduce RGB to grayscale. */
  183178. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183179. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183180. int error_action, double red, double green ));
  183181. #endif
  183182. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183183. int error_action, png_fixed_point red, png_fixed_point green ));
  183184. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183185. png_ptr));
  183186. #endif
  183187. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183188. png_colorp palette));
  183189. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183190. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183191. #endif
  183192. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183193. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183194. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183195. #endif
  183196. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183197. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183198. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183199. #endif
  183200. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183201. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183202. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183203. png_uint_32 filler, int flags));
  183204. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183205. #define PNG_FILLER_BEFORE 0
  183206. #define PNG_FILLER_AFTER 1
  183207. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183208. #if !defined(PNG_1_0_X)
  183209. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183210. png_uint_32 filler, int flags));
  183211. #endif
  183212. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183213. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183214. /* Swap bytes in 16-bit depth files. */
  183215. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183216. #endif
  183217. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183218. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183219. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183220. #endif
  183221. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183222. /* Swap packing order of pixels in bytes. */
  183223. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183224. #endif
  183225. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183226. /* Converts files to legal bit depths. */
  183227. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183228. png_color_8p true_bits));
  183229. #endif
  183230. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183231. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183232. /* Have the code handle the interlacing. Returns the number of passes. */
  183233. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183234. #endif
  183235. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183236. /* Invert monochrome files */
  183237. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183238. #endif
  183239. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183240. /* Handle alpha and tRNS by replacing with a background color. */
  183241. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183242. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183243. png_color_16p background_color, int background_gamma_code,
  183244. int need_expand, double background_gamma));
  183245. #endif
  183246. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183247. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183248. #define PNG_BACKGROUND_GAMMA_FILE 2
  183249. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183250. #endif
  183251. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183252. /* strip the second byte of information from a 16-bit depth file. */
  183253. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183254. #endif
  183255. #if defined(PNG_READ_DITHER_SUPPORTED)
  183256. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183257. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183258. png_colorp palette, int num_palette, int maximum_colors,
  183259. png_uint_16p histogram, int full_dither));
  183260. #endif
  183261. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183262. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183263. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183264. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183265. double screen_gamma, double default_file_gamma));
  183266. #endif
  183267. #endif
  183268. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183269. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183270. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183271. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183272. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183273. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183274. int empty_plte_permitted));
  183275. #endif
  183276. #endif
  183277. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183278. /* Set how many lines between output flushes - 0 for no flushing */
  183279. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183280. /* Flush the current PNG output buffer */
  183281. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183282. #endif
  183283. /* optional update palette with requested transformations */
  183284. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183285. /* optional call to update the users info structure */
  183286. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183287. png_infop info_ptr));
  183288. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183289. /* read one or more rows of image data. */
  183290. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183291. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183292. #endif
  183293. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183294. /* read a row of data. */
  183295. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183296. png_bytep row,
  183297. png_bytep display_row));
  183298. #endif
  183299. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183300. /* read the whole image into memory at once. */
  183301. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183302. png_bytepp image));
  183303. #endif
  183304. /* write a row of image data */
  183305. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183306. png_bytep row));
  183307. /* write a few rows of image data */
  183308. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183309. png_bytepp row, png_uint_32 num_rows));
  183310. /* write the image data */
  183311. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183312. png_bytepp image));
  183313. /* writes the end of the PNG file. */
  183314. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183315. png_infop info_ptr));
  183316. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183317. /* read the end of the PNG file. */
  183318. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183319. png_infop info_ptr));
  183320. #endif
  183321. /* free any memory associated with the png_info_struct */
  183322. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183323. png_infopp info_ptr_ptr));
  183324. /* free any memory associated with the png_struct and the png_info_structs */
  183325. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183326. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183327. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183328. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183329. png_infop end_info_ptr));
  183330. /* free any memory associated with the png_struct and the png_info_structs */
  183331. extern PNG_EXPORT(void,png_destroy_write_struct)
  183332. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183333. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183334. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183335. /* set the libpng method of handling chunk CRC errors */
  183336. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183337. int crit_action, int ancil_action));
  183338. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183339. * ancillary and critical chunks, and whether to use the data contained
  183340. * therein. Note that it is impossible to "discard" data in a critical
  183341. * chunk. For versions prior to 0.90, the action was always error/quit,
  183342. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183343. * chunks is warn/discard. These values should NOT be changed.
  183344. *
  183345. * value action:critical action:ancillary
  183346. */
  183347. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183348. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183349. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183350. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183351. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183352. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183353. /* These functions give the user control over the scan-line filtering in
  183354. * libpng and the compression methods used by zlib. These functions are
  183355. * mainly useful for testing, as the defaults should work with most users.
  183356. * Those users who are tight on memory or want faster performance at the
  183357. * expense of compression can modify them. See the compression library
  183358. * header file (zlib.h) for an explination of the compression functions.
  183359. */
  183360. /* set the filtering method(s) used by libpng. Currently, the only valid
  183361. * value for "method" is 0.
  183362. */
  183363. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183364. int filters));
  183365. /* Flags for png_set_filter() to say which filters to use. The flags
  183366. * are chosen so that they don't conflict with real filter types
  183367. * below, in case they are supplied instead of the #defined constants.
  183368. * These values should NOT be changed.
  183369. */
  183370. #define PNG_NO_FILTERS 0x00
  183371. #define PNG_FILTER_NONE 0x08
  183372. #define PNG_FILTER_SUB 0x10
  183373. #define PNG_FILTER_UP 0x20
  183374. #define PNG_FILTER_AVG 0x40
  183375. #define PNG_FILTER_PAETH 0x80
  183376. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183377. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183378. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183379. * These defines should NOT be changed.
  183380. */
  183381. #define PNG_FILTER_VALUE_NONE 0
  183382. #define PNG_FILTER_VALUE_SUB 1
  183383. #define PNG_FILTER_VALUE_UP 2
  183384. #define PNG_FILTER_VALUE_AVG 3
  183385. #define PNG_FILTER_VALUE_PAETH 4
  183386. #define PNG_FILTER_VALUE_LAST 5
  183387. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183388. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183389. * defines, either the default (minimum-sum-of-absolute-differences), or
  183390. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183391. *
  183392. * Weights are factors >= 1.0, indicating how important it is to keep the
  183393. * filter type consistent between rows. Larger numbers mean the current
  183394. * filter is that many times as likely to be the same as the "num_weights"
  183395. * previous filters. This is cumulative for each previous row with a weight.
  183396. * There needs to be "num_weights" values in "filter_weights", or it can be
  183397. * NULL if the weights aren't being specified. Weights have no influence on
  183398. * the selection of the first row filter. Well chosen weights can (in theory)
  183399. * improve the compression for a given image.
  183400. *
  183401. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183402. * filter type. Higher costs indicate more decoding expense, and are
  183403. * therefore less likely to be selected over a filter with lower computational
  183404. * costs. There needs to be a value in "filter_costs" for each valid filter
  183405. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183406. * setting the costs. Costs try to improve the speed of decompression without
  183407. * unduly increasing the compressed image size.
  183408. *
  183409. * A negative weight or cost indicates the default value is to be used, and
  183410. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183411. * The default values for both weights and costs are currently 1.0, but may
  183412. * change if good general weighting/cost heuristics can be found. If both
  183413. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183414. * to the UNWEIGHTED method, but with added encoding time/computation.
  183415. */
  183416. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183417. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183418. int heuristic_method, int num_weights, png_doublep filter_weights,
  183419. png_doublep filter_costs));
  183420. #endif
  183421. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183422. /* Heuristic used for row filter selection. These defines should NOT be
  183423. * changed.
  183424. */
  183425. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183426. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183427. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183428. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183429. /* Set the library compression level. Currently, valid values range from
  183430. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183431. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183432. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183433. * for PNG images, and do considerably fewer caclulations. In the future,
  183434. * these values may not correspond directly to the zlib compression levels.
  183435. */
  183436. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183437. int level));
  183438. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183439. PNGARG((png_structp png_ptr, int mem_level));
  183440. extern PNG_EXPORT(void,png_set_compression_strategy)
  183441. PNGARG((png_structp png_ptr, int strategy));
  183442. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183443. PNGARG((png_structp png_ptr, int window_bits));
  183444. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183445. int method));
  183446. /* These next functions are called for input/output, memory, and error
  183447. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183448. * and call standard C I/O routines such as fread(), fwrite(), and
  183449. * fprintf(). These functions can be made to use other I/O routines
  183450. * at run time for those applications that need to handle I/O in a
  183451. * different manner by calling png_set_???_fn(). See libpng.txt for
  183452. * more information.
  183453. */
  183454. #if !defined(PNG_NO_STDIO)
  183455. /* Initialize the input/output for the PNG file to the default functions. */
  183456. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183457. #endif
  183458. /* Replace the (error and abort), and warning functions with user
  183459. * supplied functions. If no messages are to be printed you must still
  183460. * write and use replacement functions. The replacement error_fn should
  183461. * still do a longjmp to the last setjmp location if you are using this
  183462. * method of error handling. If error_fn or warning_fn is NULL, the
  183463. * default function will be used.
  183464. */
  183465. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183466. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183467. /* Return the user pointer associated with the error functions */
  183468. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183469. /* Replace the default data output functions with a user supplied one(s).
  183470. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183471. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183472. * output_flush_fn will be ignored (and thus can be NULL).
  183473. */
  183474. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183475. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183476. /* Replace the default data input function with a user supplied one. */
  183477. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183478. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183479. /* Return the user pointer associated with the I/O functions */
  183480. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183481. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183482. png_read_status_ptr read_row_fn));
  183483. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183484. png_write_status_ptr write_row_fn));
  183485. #ifdef PNG_USER_MEM_SUPPORTED
  183486. /* Replace the default memory allocation functions with user supplied one(s). */
  183487. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183488. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183489. /* Return the user pointer associated with the memory functions */
  183490. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183491. #endif
  183492. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183493. defined(PNG_LEGACY_SUPPORTED)
  183494. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183495. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183496. #endif
  183497. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183498. defined(PNG_LEGACY_SUPPORTED)
  183499. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183500. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183501. #endif
  183502. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183503. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183504. defined(PNG_LEGACY_SUPPORTED)
  183505. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183506. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183507. int user_transform_channels));
  183508. /* Return the user pointer associated with the user transform functions */
  183509. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183510. PNGARG((png_structp png_ptr));
  183511. #endif
  183512. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183513. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183514. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183515. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183516. png_ptr));
  183517. #endif
  183518. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183519. /* Sets the function callbacks for the push reader, and a pointer to a
  183520. * user-defined structure available to the callback functions.
  183521. */
  183522. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183523. png_voidp progressive_ptr,
  183524. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183525. png_progressive_end_ptr end_fn));
  183526. /* returns the user pointer associated with the push read functions */
  183527. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183528. PNGARG((png_structp png_ptr));
  183529. /* function to be called when data becomes available */
  183530. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183531. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183532. /* function that combines rows. Not very much different than the
  183533. * png_combine_row() call. Is this even used?????
  183534. */
  183535. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183536. png_bytep old_row, png_bytep new_row));
  183537. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183538. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183539. png_uint_32 size));
  183540. #if defined(PNG_1_0_X)
  183541. # define png_malloc_warn png_malloc
  183542. #else
  183543. /* Added at libpng version 1.2.4 */
  183544. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183545. png_uint_32 size));
  183546. #endif
  183547. /* frees a pointer allocated by png_malloc() */
  183548. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183549. #if defined(PNG_1_0_X)
  183550. /* Function to allocate memory for zlib. */
  183551. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183552. uInt size));
  183553. /* Function to free memory for zlib */
  183554. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183555. #endif
  183556. /* Free data that was allocated internally */
  183557. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183558. png_infop info_ptr, png_uint_32 free_me, int num));
  183559. #ifdef PNG_FREE_ME_SUPPORTED
  183560. /* Reassign responsibility for freeing existing data, whether allocated
  183561. * by libpng or by the application */
  183562. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183563. png_infop info_ptr, int freer, png_uint_32 mask));
  183564. #endif
  183565. /* assignments for png_data_freer */
  183566. #define PNG_DESTROY_WILL_FREE_DATA 1
  183567. #define PNG_SET_WILL_FREE_DATA 1
  183568. #define PNG_USER_WILL_FREE_DATA 2
  183569. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183570. #define PNG_FREE_HIST 0x0008
  183571. #define PNG_FREE_ICCP 0x0010
  183572. #define PNG_FREE_SPLT 0x0020
  183573. #define PNG_FREE_ROWS 0x0040
  183574. #define PNG_FREE_PCAL 0x0080
  183575. #define PNG_FREE_SCAL 0x0100
  183576. #define PNG_FREE_UNKN 0x0200
  183577. #define PNG_FREE_LIST 0x0400
  183578. #define PNG_FREE_PLTE 0x1000
  183579. #define PNG_FREE_TRNS 0x2000
  183580. #define PNG_FREE_TEXT 0x4000
  183581. #define PNG_FREE_ALL 0x7fff
  183582. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183583. #ifdef PNG_USER_MEM_SUPPORTED
  183584. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183585. png_uint_32 size));
  183586. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183587. png_voidp ptr));
  183588. #endif
  183589. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183590. png_voidp s1, png_voidp s2, png_uint_32 size));
  183591. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183592. png_voidp s1, int value, png_uint_32 size));
  183593. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183594. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183595. int check));
  183596. #endif /* USE_FAR_KEYWORD */
  183597. #ifndef PNG_NO_ERROR_TEXT
  183598. /* Fatal error in PNG image of libpng - can't continue */
  183599. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183600. png_const_charp error_message));
  183601. /* The same, but the chunk name is prepended to the error string. */
  183602. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183603. png_const_charp error_message));
  183604. #else
  183605. /* Fatal error in PNG image of libpng - can't continue */
  183606. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183607. #endif
  183608. #ifndef PNG_NO_WARNINGS
  183609. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183610. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183611. png_const_charp warning_message));
  183612. #ifdef PNG_READ_SUPPORTED
  183613. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183614. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183615. png_const_charp warning_message));
  183616. #endif /* PNG_READ_SUPPORTED */
  183617. #endif /* PNG_NO_WARNINGS */
  183618. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183619. * Similarly, the png_get_<chunk> calls are used to read values from the
  183620. * png_info_struct, either storing the parameters in the passed variables, or
  183621. * setting pointers into the png_info_struct where the data is stored. The
  183622. * png_get_<chunk> functions return a non-zero value if the data was available
  183623. * in info_ptr, or return zero and do not change any of the parameters if the
  183624. * data was not available.
  183625. *
  183626. * These functions should be used instead of directly accessing png_info
  183627. * to avoid problems with future changes in the size and internal layout of
  183628. * png_info_struct.
  183629. */
  183630. /* Returns "flag" if chunk data is valid in info_ptr. */
  183631. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183632. png_infop info_ptr, png_uint_32 flag));
  183633. /* Returns number of bytes needed to hold a transformed row. */
  183634. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183635. png_infop info_ptr));
  183636. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183637. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183638. returned from png_read_png(). */
  183639. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183640. png_infop info_ptr));
  183641. /* Set row_pointers, which is an array of pointers to scanlines for use
  183642. by png_write_png(). */
  183643. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183644. png_infop info_ptr, png_bytepp row_pointers));
  183645. #endif
  183646. /* Returns number of color channels in image. */
  183647. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183648. png_infop info_ptr));
  183649. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183650. /* Returns image width in pixels. */
  183651. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183652. png_ptr, png_infop info_ptr));
  183653. /* Returns image height in pixels. */
  183654. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183655. png_ptr, png_infop info_ptr));
  183656. /* Returns image bit_depth. */
  183657. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183658. png_ptr, png_infop info_ptr));
  183659. /* Returns image color_type. */
  183660. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183661. png_ptr, png_infop info_ptr));
  183662. /* Returns image filter_type. */
  183663. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183664. png_ptr, png_infop info_ptr));
  183665. /* Returns image interlace_type. */
  183666. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183667. png_ptr, png_infop info_ptr));
  183668. /* Returns image compression_type. */
  183669. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183670. png_ptr, png_infop info_ptr));
  183671. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183672. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183673. png_ptr, png_infop info_ptr));
  183674. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183675. png_ptr, png_infop info_ptr));
  183676. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183677. png_ptr, png_infop info_ptr));
  183678. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183679. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183680. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183681. png_ptr, png_infop info_ptr));
  183682. #endif
  183683. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183684. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183685. png_ptr, png_infop info_ptr));
  183686. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183687. png_ptr, png_infop info_ptr));
  183688. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183689. png_ptr, png_infop info_ptr));
  183690. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183691. png_ptr, png_infop info_ptr));
  183692. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183693. /* Returns pointer to signature string read from PNG header */
  183694. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183695. png_infop info_ptr));
  183696. #if defined(PNG_bKGD_SUPPORTED)
  183697. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183698. png_infop info_ptr, png_color_16p *background));
  183699. #endif
  183700. #if defined(PNG_bKGD_SUPPORTED)
  183701. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183702. png_infop info_ptr, png_color_16p background));
  183703. #endif
  183704. #if defined(PNG_cHRM_SUPPORTED)
  183705. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183706. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183707. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183708. double *red_y, double *green_x, double *green_y, double *blue_x,
  183709. double *blue_y));
  183710. #endif
  183711. #ifdef PNG_FIXED_POINT_SUPPORTED
  183712. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183713. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183714. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183715. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183716. *int_blue_x, png_fixed_point *int_blue_y));
  183717. #endif
  183718. #endif
  183719. #if defined(PNG_cHRM_SUPPORTED)
  183720. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183721. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183722. png_infop info_ptr, double white_x, double white_y, double red_x,
  183723. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183724. #endif
  183725. #ifdef PNG_FIXED_POINT_SUPPORTED
  183726. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183727. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183728. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183729. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183730. png_fixed_point int_blue_y));
  183731. #endif
  183732. #endif
  183733. #if defined(PNG_gAMA_SUPPORTED)
  183734. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183735. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183736. png_infop info_ptr, double *file_gamma));
  183737. #endif
  183738. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183739. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183740. #endif
  183741. #if defined(PNG_gAMA_SUPPORTED)
  183742. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183743. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183744. png_infop info_ptr, double file_gamma));
  183745. #endif
  183746. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183747. png_infop info_ptr, png_fixed_point int_file_gamma));
  183748. #endif
  183749. #if defined(PNG_hIST_SUPPORTED)
  183750. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183751. png_infop info_ptr, png_uint_16p *hist));
  183752. #endif
  183753. #if defined(PNG_hIST_SUPPORTED)
  183754. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183755. png_infop info_ptr, png_uint_16p hist));
  183756. #endif
  183757. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183758. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183759. int *bit_depth, int *color_type, int *interlace_method,
  183760. int *compression_method, int *filter_method));
  183761. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183762. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183763. int color_type, int interlace_method, int compression_method,
  183764. int filter_method));
  183765. #if defined(PNG_oFFs_SUPPORTED)
  183766. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183767. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183768. int *unit_type));
  183769. #endif
  183770. #if defined(PNG_oFFs_SUPPORTED)
  183771. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183772. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183773. int unit_type));
  183774. #endif
  183775. #if defined(PNG_pCAL_SUPPORTED)
  183776. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183777. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183778. int *type, int *nparams, png_charp *units, png_charpp *params));
  183779. #endif
  183780. #if defined(PNG_pCAL_SUPPORTED)
  183781. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183782. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183783. int type, int nparams, png_charp units, png_charpp params));
  183784. #endif
  183785. #if defined(PNG_pHYs_SUPPORTED)
  183786. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183787. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183788. #endif
  183789. #if defined(PNG_pHYs_SUPPORTED)
  183790. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183791. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183792. #endif
  183793. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183794. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183795. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183796. png_infop info_ptr, png_colorp palette, int num_palette));
  183797. #if defined(PNG_sBIT_SUPPORTED)
  183798. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183799. png_infop info_ptr, png_color_8p *sig_bit));
  183800. #endif
  183801. #if defined(PNG_sBIT_SUPPORTED)
  183802. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183803. png_infop info_ptr, png_color_8p sig_bit));
  183804. #endif
  183805. #if defined(PNG_sRGB_SUPPORTED)
  183806. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183807. png_infop info_ptr, int *intent));
  183808. #endif
  183809. #if defined(PNG_sRGB_SUPPORTED)
  183810. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183811. png_infop info_ptr, int intent));
  183812. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183813. png_infop info_ptr, int intent));
  183814. #endif
  183815. #if defined(PNG_iCCP_SUPPORTED)
  183816. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183817. png_infop info_ptr, png_charpp name, int *compression_type,
  183818. png_charpp profile, png_uint_32 *proflen));
  183819. /* Note to maintainer: profile should be png_bytepp */
  183820. #endif
  183821. #if defined(PNG_iCCP_SUPPORTED)
  183822. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183823. png_infop info_ptr, png_charp name, int compression_type,
  183824. png_charp profile, png_uint_32 proflen));
  183825. /* Note to maintainer: profile should be png_bytep */
  183826. #endif
  183827. #if defined(PNG_sPLT_SUPPORTED)
  183828. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183829. png_infop info_ptr, png_sPLT_tpp entries));
  183830. #endif
  183831. #if defined(PNG_sPLT_SUPPORTED)
  183832. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183833. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183834. #endif
  183835. #if defined(PNG_TEXT_SUPPORTED)
  183836. /* png_get_text also returns the number of text chunks in *num_text */
  183837. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183838. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183839. #endif
  183840. /*
  183841. * Note while png_set_text() will accept a structure whose text,
  183842. * language, and translated keywords are NULL pointers, the structure
  183843. * returned by png_get_text will always contain regular
  183844. * zero-terminated C strings. They might be empty strings but
  183845. * they will never be NULL pointers.
  183846. */
  183847. #if defined(PNG_TEXT_SUPPORTED)
  183848. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183849. png_infop info_ptr, png_textp text_ptr, int num_text));
  183850. #endif
  183851. #if defined(PNG_tIME_SUPPORTED)
  183852. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183853. png_infop info_ptr, png_timep *mod_time));
  183854. #endif
  183855. #if defined(PNG_tIME_SUPPORTED)
  183856. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183857. png_infop info_ptr, png_timep mod_time));
  183858. #endif
  183859. #if defined(PNG_tRNS_SUPPORTED)
  183860. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183861. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183862. png_color_16p *trans_values));
  183863. #endif
  183864. #if defined(PNG_tRNS_SUPPORTED)
  183865. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183866. png_infop info_ptr, png_bytep trans, int num_trans,
  183867. png_color_16p trans_values));
  183868. #endif
  183869. #if defined(PNG_tRNS_SUPPORTED)
  183870. #endif
  183871. #if defined(PNG_sCAL_SUPPORTED)
  183872. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183873. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183874. png_infop info_ptr, int *unit, double *width, double *height));
  183875. #else
  183876. #ifdef PNG_FIXED_POINT_SUPPORTED
  183877. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183878. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183879. #endif
  183880. #endif
  183881. #endif /* PNG_sCAL_SUPPORTED */
  183882. #if defined(PNG_sCAL_SUPPORTED)
  183883. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183884. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183885. png_infop info_ptr, int unit, double width, double height));
  183886. #else
  183887. #ifdef PNG_FIXED_POINT_SUPPORTED
  183888. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183889. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183890. #endif
  183891. #endif
  183892. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183893. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183894. /* provide a list of chunks and how they are to be handled, if the built-in
  183895. handling or default unknown chunk handling is not desired. Any chunks not
  183896. listed will be handled in the default manner. The IHDR and IEND chunks
  183897. must not be listed.
  183898. keep = 0: follow default behaviour
  183899. = 1: do not keep
  183900. = 2: keep only if safe-to-copy
  183901. = 3: keep even if unsafe-to-copy
  183902. */
  183903. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183904. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183905. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183906. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183907. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183908. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183909. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183910. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183911. #endif
  183912. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183913. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183914. chunk_name));
  183915. #endif
  183916. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183917. If you need to turn it off for a chunk that your application has freed,
  183918. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183919. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183920. png_infop info_ptr, int mask));
  183921. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183922. /* The "params" pointer is currently not used and is for future expansion. */
  183923. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183924. png_infop info_ptr,
  183925. int transforms,
  183926. png_voidp params));
  183927. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183928. png_infop info_ptr,
  183929. int transforms,
  183930. png_voidp params));
  183931. #endif
  183932. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183933. * numbers for PNG_DEBUG mean more debugging information. This has
  183934. * only been added since version 0.95 so it is not implemented throughout
  183935. * libpng yet, but more support will be added as needed.
  183936. */
  183937. #ifdef PNG_DEBUG
  183938. #if (PNG_DEBUG > 0)
  183939. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183940. #include <crtdbg.h>
  183941. #if (PNG_DEBUG > 1)
  183942. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183943. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183944. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183945. #endif
  183946. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183947. #ifndef PNG_DEBUG_FILE
  183948. #define PNG_DEBUG_FILE stderr
  183949. #endif /* PNG_DEBUG_FILE */
  183950. #if (PNG_DEBUG > 1)
  183951. #define png_debug(l,m) \
  183952. { \
  183953. int num_tabs=l; \
  183954. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183955. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183956. }
  183957. #define png_debug1(l,m,p1) \
  183958. { \
  183959. int num_tabs=l; \
  183960. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183961. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183962. }
  183963. #define png_debug2(l,m,p1,p2) \
  183964. { \
  183965. int num_tabs=l; \
  183966. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183967. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183968. }
  183969. #endif /* (PNG_DEBUG > 1) */
  183970. #endif /* _MSC_VER */
  183971. #endif /* (PNG_DEBUG > 0) */
  183972. #endif /* PNG_DEBUG */
  183973. #ifndef png_debug
  183974. #define png_debug(l, m)
  183975. #endif
  183976. #ifndef png_debug1
  183977. #define png_debug1(l, m, p1)
  183978. #endif
  183979. #ifndef png_debug2
  183980. #define png_debug2(l, m, p1, p2)
  183981. #endif
  183982. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183983. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183984. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183985. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183986. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183987. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183988. png_ptr, png_uint_32 mng_features_permitted));
  183989. #endif
  183990. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183991. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183992. #define PNG_HANDLE_CHUNK_NEVER 1
  183993. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183994. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183995. /* Added to version 1.2.0 */
  183996. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183997. #if defined(PNG_MMX_CODE_SUPPORTED)
  183998. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183999. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  184000. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  184001. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  184002. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  184003. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  184004. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  184005. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  184006. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  184007. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  184008. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  184009. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  184010. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  184011. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  184012. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  184013. #define PNG_MMX_WRITE_FLAGS ( 0 )
  184014. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  184015. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  184016. | PNG_MMX_READ_FLAGS \
  184017. | PNG_MMX_WRITE_FLAGS )
  184018. #define PNG_SELECT_READ 1
  184019. #define PNG_SELECT_WRITE 2
  184020. #endif /* PNG_MMX_CODE_SUPPORTED */
  184021. #if !defined(PNG_1_0_X)
  184022. /* pngget.c */
  184023. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  184024. PNGARG((int flag_select, int *compilerID));
  184025. /* pngget.c */
  184026. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  184027. PNGARG((int flag_select));
  184028. /* pngget.c */
  184029. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  184030. PNGARG((png_structp png_ptr));
  184031. /* pngget.c */
  184032. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  184033. PNGARG((png_structp png_ptr));
  184034. /* pngget.c */
  184035. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  184036. PNGARG((png_structp png_ptr));
  184037. /* pngset.c */
  184038. extern PNG_EXPORT(void,png_set_asm_flags)
  184039. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  184040. /* pngset.c */
  184041. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  184042. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  184043. png_uint_32 mmx_rowbytes_threshold));
  184044. #endif /* PNG_1_0_X */
  184045. #if !defined(PNG_1_0_X)
  184046. /* png.c, pnggccrd.c, or pngvcrd.c */
  184047. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  184048. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  184049. /* Strip the prepended error numbers ("#nnn ") from error and warning
  184050. * messages before passing them to the error or warning handler. */
  184051. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184052. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  184053. png_ptr, png_uint_32 strip_mode));
  184054. #endif
  184055. #endif /* PNG_1_0_X */
  184056. /* Added at libpng-1.2.6 */
  184057. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184058. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  184059. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  184060. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  184061. png_ptr));
  184062. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  184063. png_ptr));
  184064. #endif
  184065. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  184066. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  184067. /* With these routines we avoid an integer divide, which will be slower on
  184068. * most machines. However, it does take more operations than the corresponding
  184069. * divide method, so it may be slower on a few RISC systems. There are two
  184070. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  184071. *
  184072. * Note that the rounding factors are NOT supposed to be the same! 128 and
  184073. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  184074. * standard method.
  184075. *
  184076. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  184077. */
  184078. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  184079. # define png_composite(composite, fg, alpha, bg) \
  184080. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  184081. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  184082. (png_uint_16)(alpha)) + (png_uint_16)128); \
  184083. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  184084. # define png_composite_16(composite, fg, alpha, bg) \
  184085. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  184086. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  184087. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  184088. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  184089. #else /* standard method using integer division */
  184090. # define png_composite(composite, fg, alpha, bg) \
  184091. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  184092. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  184093. (png_uint_16)127) / 255)
  184094. # define png_composite_16(composite, fg, alpha, bg) \
  184095. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  184096. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  184097. (png_uint_32)32767) / (png_uint_32)65535L)
  184098. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  184099. /* Inline macros to do direct reads of bytes from the input buffer. These
  184100. * require that you are using an architecture that uses PNG byte ordering
  184101. * (MSB first) and supports unaligned data storage. I think that PowerPC
  184102. * in big-endian mode and 680x0 are the only ones that will support this.
  184103. * The x86 line of processors definitely do not. The png_get_int_32()
  184104. * routine also assumes we are using two's complement format for negative
  184105. * values, which is almost certainly true.
  184106. */
  184107. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  184108. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  184109. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  184110. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  184111. #else
  184112. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  184113. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  184114. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  184115. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  184116. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  184117. PNGARG((png_structp png_ptr, png_bytep buf));
  184118. /* No png_get_int_16 -- may be added if there's a real need for it. */
  184119. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  184120. */
  184121. extern PNG_EXPORT(void,png_save_uint_32)
  184122. PNGARG((png_bytep buf, png_uint_32 i));
  184123. extern PNG_EXPORT(void,png_save_int_32)
  184124. PNGARG((png_bytep buf, png_int_32 i));
  184125. /* Place a 16-bit number into a buffer in PNG byte order.
  184126. * The parameter is declared unsigned int, not png_uint_16,
  184127. * just to avoid potential problems on pre-ANSI C compilers.
  184128. */
  184129. extern PNG_EXPORT(void,png_save_uint_16)
  184130. PNGARG((png_bytep buf, unsigned int i));
  184131. /* No png_save_int_16 -- may be added if there's a real need for it. */
  184132. /* ************************************************************************* */
  184133. /* These next functions are used internally in the code. They generally
  184134. * shouldn't be used unless you are writing code to add or replace some
  184135. * functionality in libpng. More information about most functions can
  184136. * be found in the files where the functions are located.
  184137. */
  184138. /* Various modes of operation, that are visible to applications because
  184139. * they are used for unknown chunk location.
  184140. */
  184141. #define PNG_HAVE_IHDR 0x01
  184142. #define PNG_HAVE_PLTE 0x02
  184143. #define PNG_HAVE_IDAT 0x04
  184144. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  184145. #define PNG_HAVE_IEND 0x10
  184146. #if defined(PNG_INTERNAL)
  184147. /* More modes of operation. Note that after an init, mode is set to
  184148. * zero automatically when the structure is created.
  184149. */
  184150. #define PNG_HAVE_gAMA 0x20
  184151. #define PNG_HAVE_cHRM 0x40
  184152. #define PNG_HAVE_sRGB 0x80
  184153. #define PNG_HAVE_CHUNK_HEADER 0x100
  184154. #define PNG_WROTE_tIME 0x200
  184155. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184156. #define PNG_BACKGROUND_IS_GRAY 0x800
  184157. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184158. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184159. /* flags for the transformations the PNG library does on the image data */
  184160. #define PNG_BGR 0x0001
  184161. #define PNG_INTERLACE 0x0002
  184162. #define PNG_PACK 0x0004
  184163. #define PNG_SHIFT 0x0008
  184164. #define PNG_SWAP_BYTES 0x0010
  184165. #define PNG_INVERT_MONO 0x0020
  184166. #define PNG_DITHER 0x0040
  184167. #define PNG_BACKGROUND 0x0080
  184168. #define PNG_BACKGROUND_EXPAND 0x0100
  184169. /* 0x0200 unused */
  184170. #define PNG_16_TO_8 0x0400
  184171. #define PNG_RGBA 0x0800
  184172. #define PNG_EXPAND 0x1000
  184173. #define PNG_GAMMA 0x2000
  184174. #define PNG_GRAY_TO_RGB 0x4000
  184175. #define PNG_FILLER 0x8000L
  184176. #define PNG_PACKSWAP 0x10000L
  184177. #define PNG_SWAP_ALPHA 0x20000L
  184178. #define PNG_STRIP_ALPHA 0x40000L
  184179. #define PNG_INVERT_ALPHA 0x80000L
  184180. #define PNG_USER_TRANSFORM 0x100000L
  184181. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184182. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184183. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184184. /* 0x800000L Unused */
  184185. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184186. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184187. /* 0x4000000L unused */
  184188. /* 0x8000000L unused */
  184189. /* 0x10000000L unused */
  184190. /* 0x20000000L unused */
  184191. /* 0x40000000L unused */
  184192. /* flags for png_create_struct */
  184193. #define PNG_STRUCT_PNG 0x0001
  184194. #define PNG_STRUCT_INFO 0x0002
  184195. /* Scaling factor for filter heuristic weighting calculations */
  184196. #define PNG_WEIGHT_SHIFT 8
  184197. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184198. #define PNG_COST_SHIFT 3
  184199. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184200. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184201. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184202. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184203. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184204. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184205. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184206. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184207. #define PNG_FLAG_ROW_INIT 0x0040
  184208. #define PNG_FLAG_FILLER_AFTER 0x0080
  184209. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184210. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184211. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184212. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184213. #define PNG_FLAG_FREE_PLTE 0x1000
  184214. #define PNG_FLAG_FREE_TRNS 0x2000
  184215. #define PNG_FLAG_FREE_HIST 0x4000
  184216. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184217. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184218. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184219. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184220. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184221. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184222. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184223. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184224. /* 0x800000L unused */
  184225. /* 0x1000000L unused */
  184226. /* 0x2000000L unused */
  184227. /* 0x4000000L unused */
  184228. /* 0x8000000L unused */
  184229. /* 0x10000000L unused */
  184230. /* 0x20000000L unused */
  184231. /* 0x40000000L unused */
  184232. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184233. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184234. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184235. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184236. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184237. PNG_FLAG_CRC_CRITICAL_MASK)
  184238. /* save typing and make code easier to understand */
  184239. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184240. abs((int)((c1).green) - (int)((c2).green)) + \
  184241. abs((int)((c1).blue) - (int)((c2).blue)))
  184242. /* Added to libpng-1.2.6 JB */
  184243. #define PNG_ROWBYTES(pixel_bits, width) \
  184244. ((pixel_bits) >= 8 ? \
  184245. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184246. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184247. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184248. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184249. "ideal" and "delta" should be constants, normally simple
  184250. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184251. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184252. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184253. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184254. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184255. /* place to hold the signature string for a PNG file. */
  184256. #ifdef PNG_USE_GLOBAL_ARRAYS
  184257. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184258. #else
  184259. #endif
  184260. #endif /* PNG_NO_EXTERN */
  184261. /* Constant strings for known chunk types. If you need to add a chunk,
  184262. * define the name here, and add an invocation of the macro in png.c and
  184263. * wherever it's needed.
  184264. */
  184265. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184266. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184267. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184268. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184269. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184270. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184271. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184272. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184273. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184274. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184275. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184276. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184277. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184278. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184279. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184280. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184281. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184282. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184283. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184284. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184285. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184286. #ifdef PNG_USE_GLOBAL_ARRAYS
  184287. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184288. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184289. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184290. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184291. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184292. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184293. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184294. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184295. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184296. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184297. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184298. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184299. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184300. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184301. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184302. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184303. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184304. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184305. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184306. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184307. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184308. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184309. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184310. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184311. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184312. */
  184313. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184314. #undef png_read_init
  184315. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184316. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184317. #endif
  184318. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184319. png_const_charp user_png_ver, png_size_t png_struct_size));
  184320. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184321. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184322. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184323. png_info_size));
  184324. #endif
  184325. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184326. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184327. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184328. */
  184329. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184330. #undef png_write_init
  184331. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184332. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184333. #endif
  184334. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184335. png_const_charp user_png_ver, png_size_t png_struct_size));
  184336. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184337. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184338. png_info_size));
  184339. /* Allocate memory for an internal libpng struct */
  184340. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184341. /* Free memory from internal libpng struct */
  184342. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184343. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184344. malloc_fn, png_voidp mem_ptr));
  184345. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184346. png_free_ptr free_fn, png_voidp mem_ptr));
  184347. /* Free any memory that info_ptr points to and reset struct. */
  184348. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184349. png_infop info_ptr));
  184350. #ifndef PNG_1_0_X
  184351. /* Function to allocate memory for zlib. */
  184352. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184353. /* Function to free memory for zlib */
  184354. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184355. #ifdef PNG_SIZE_T
  184356. /* Function to convert a sizeof an item to png_sizeof item */
  184357. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184358. #endif
  184359. /* Next four functions are used internally as callbacks. PNGAPI is required
  184360. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184361. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184362. png_bytep data, png_size_t length));
  184363. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184364. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184365. png_bytep buffer, png_size_t length));
  184366. #endif
  184367. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184368. png_bytep data, png_size_t length));
  184369. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184370. #if !defined(PNG_NO_STDIO)
  184371. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184372. #endif
  184373. #endif
  184374. #else /* PNG_1_0_X */
  184375. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184376. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184377. png_bytep buffer, png_size_t length));
  184378. #endif
  184379. #endif /* PNG_1_0_X */
  184380. /* Reset the CRC variable */
  184381. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184382. /* Write the "data" buffer to whatever output you are using. */
  184383. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184384. png_size_t length));
  184385. /* Read data from whatever input you are using into the "data" buffer */
  184386. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184387. png_size_t length));
  184388. /* Read bytes into buf, and update png_ptr->crc */
  184389. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184390. png_size_t length));
  184391. /* Decompress data in a chunk that uses compression */
  184392. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184393. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184394. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184395. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184396. png_size_t prefix_length, png_size_t *data_length));
  184397. #endif
  184398. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184399. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184400. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184401. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184402. /* Calculate the CRC over a section of data. Note that we are only
  184403. * passing a maximum of 64K on systems that have this as a memory limit,
  184404. * since this is the maximum buffer size we can specify.
  184405. */
  184406. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184407. png_size_t length));
  184408. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184409. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184410. #endif
  184411. /* simple function to write the signature */
  184412. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184413. /* write various chunks */
  184414. /* Write the IHDR chunk, and update the png_struct with the necessary
  184415. * information.
  184416. */
  184417. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184418. png_uint_32 height,
  184419. int bit_depth, int color_type, int compression_method, int filter_method,
  184420. int interlace_method));
  184421. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184422. png_uint_32 num_pal));
  184423. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184424. png_size_t length));
  184425. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184426. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184427. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184428. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184429. #endif
  184430. #ifdef PNG_FIXED_POINT_SUPPORTED
  184431. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184432. file_gamma));
  184433. #endif
  184434. #endif
  184435. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184436. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184437. int color_type));
  184438. #endif
  184439. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184440. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184441. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184442. double white_x, double white_y,
  184443. double red_x, double red_y, double green_x, double green_y,
  184444. double blue_x, double blue_y));
  184445. #endif
  184446. #ifdef PNG_FIXED_POINT_SUPPORTED
  184447. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184448. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184449. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184450. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184451. png_fixed_point int_blue_y));
  184452. #endif
  184453. #endif
  184454. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184455. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184456. int intent));
  184457. #endif
  184458. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184459. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184460. png_charp name, int compression_type,
  184461. png_charp profile, int proflen));
  184462. /* Note to maintainer: profile should be png_bytep */
  184463. #endif
  184464. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184465. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184466. png_sPLT_tp palette));
  184467. #endif
  184468. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184469. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184470. png_color_16p values, int number, int color_type));
  184471. #endif
  184472. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184473. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184474. png_color_16p values, int color_type));
  184475. #endif
  184476. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184477. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184478. int num_hist));
  184479. #endif
  184480. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184481. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184482. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184483. png_charp key, png_charpp new_key));
  184484. #endif
  184485. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184486. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184487. png_charp text, png_size_t text_len));
  184488. #endif
  184489. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184490. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184491. png_charp text, png_size_t text_len, int compression));
  184492. #endif
  184493. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184494. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184495. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184496. png_charp text));
  184497. #endif
  184498. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184499. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184500. png_infop info_ptr, png_textp text_ptr, int num_text));
  184501. #endif
  184502. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184503. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184504. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184505. #endif
  184506. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184507. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184508. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184509. png_charp units, png_charpp params));
  184510. #endif
  184511. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184512. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184513. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184514. int unit_type));
  184515. #endif
  184516. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184517. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184518. png_timep mod_time));
  184519. #endif
  184520. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184521. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184522. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184523. int unit, double width, double height));
  184524. #else
  184525. #ifdef PNG_FIXED_POINT_SUPPORTED
  184526. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184527. int unit, png_charp width, png_charp height));
  184528. #endif
  184529. #endif
  184530. #endif
  184531. /* Called when finished processing a row of data */
  184532. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184533. /* Internal use only. Called before first row of data */
  184534. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184535. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184536. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184537. #endif
  184538. /* combine a row of data, dealing with alpha, etc. if requested */
  184539. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184540. int mask));
  184541. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184542. /* expand an interlaced row */
  184543. /* OLD pre-1.0.9 interface:
  184544. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184545. png_bytep row, int pass, png_uint_32 transformations));
  184546. */
  184547. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184548. #endif
  184549. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184550. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184551. /* grab pixels out of a row for an interlaced pass */
  184552. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184553. png_bytep row, int pass));
  184554. #endif
  184555. /* unfilter a row */
  184556. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184557. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184558. /* Choose the best filter to use and filter the row data */
  184559. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184560. png_row_infop row_info));
  184561. /* Write out the filtered row. */
  184562. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184563. png_bytep filtered_row));
  184564. /* finish a row while reading, dealing with interlacing passes, etc. */
  184565. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184566. /* initialize the row buffers, etc. */
  184567. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184568. /* optional call to update the users info structure */
  184569. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184570. png_infop info_ptr));
  184571. /* these are the functions that do the transformations */
  184572. #if defined(PNG_READ_FILLER_SUPPORTED)
  184573. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184574. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184575. #endif
  184576. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184577. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184578. png_bytep row));
  184579. #endif
  184580. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184581. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184582. png_bytep row));
  184583. #endif
  184584. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184585. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184586. png_bytep row));
  184587. #endif
  184588. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184589. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184590. png_bytep row));
  184591. #endif
  184592. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184593. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184594. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184595. png_bytep row, png_uint_32 flags));
  184596. #endif
  184597. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184598. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184599. #endif
  184600. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184601. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184602. #endif
  184603. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184604. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184605. row_info, png_bytep row));
  184606. #endif
  184607. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184608. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184609. png_bytep row));
  184610. #endif
  184611. #if defined(PNG_READ_PACK_SUPPORTED)
  184612. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184613. #endif
  184614. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184615. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184616. png_color_8p sig_bits));
  184617. #endif
  184618. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184619. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184620. #endif
  184621. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184622. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184623. #endif
  184624. #if defined(PNG_READ_DITHER_SUPPORTED)
  184625. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184626. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184627. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184628. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184629. png_colorp palette, int num_palette));
  184630. # endif
  184631. #endif
  184632. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184633. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184634. #endif
  184635. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184636. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184637. png_bytep row, png_uint_32 bit_depth));
  184638. #endif
  184639. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184640. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184641. png_color_8p bit_depth));
  184642. #endif
  184643. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184644. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184645. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184646. png_color_16p trans_values, png_color_16p background,
  184647. png_color_16p background_1,
  184648. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184649. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184650. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184651. #else
  184652. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184653. png_color_16p trans_values, png_color_16p background));
  184654. #endif
  184655. #endif
  184656. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184657. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184658. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184659. int gamma_shift));
  184660. #endif
  184661. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184662. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184663. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184664. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184665. png_bytep row, png_color_16p trans_value));
  184666. #endif
  184667. /* The following decodes the appropriate chunks, and does error correction,
  184668. * then calls the appropriate callback for the chunk if it is valid.
  184669. */
  184670. /* decode the IHDR chunk */
  184671. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184672. png_uint_32 length));
  184673. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184674. png_uint_32 length));
  184675. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184676. png_uint_32 length));
  184677. #if defined(PNG_READ_bKGD_SUPPORTED)
  184678. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184679. png_uint_32 length));
  184680. #endif
  184681. #if defined(PNG_READ_cHRM_SUPPORTED)
  184682. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184683. png_uint_32 length));
  184684. #endif
  184685. #if defined(PNG_READ_gAMA_SUPPORTED)
  184686. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184687. png_uint_32 length));
  184688. #endif
  184689. #if defined(PNG_READ_hIST_SUPPORTED)
  184690. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184691. png_uint_32 length));
  184692. #endif
  184693. #if defined(PNG_READ_iCCP_SUPPORTED)
  184694. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184695. png_uint_32 length));
  184696. #endif /* PNG_READ_iCCP_SUPPORTED */
  184697. #if defined(PNG_READ_iTXt_SUPPORTED)
  184698. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184699. png_uint_32 length));
  184700. #endif
  184701. #if defined(PNG_READ_oFFs_SUPPORTED)
  184702. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184703. png_uint_32 length));
  184704. #endif
  184705. #if defined(PNG_READ_pCAL_SUPPORTED)
  184706. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184707. png_uint_32 length));
  184708. #endif
  184709. #if defined(PNG_READ_pHYs_SUPPORTED)
  184710. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184711. png_uint_32 length));
  184712. #endif
  184713. #if defined(PNG_READ_sBIT_SUPPORTED)
  184714. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184715. png_uint_32 length));
  184716. #endif
  184717. #if defined(PNG_READ_sCAL_SUPPORTED)
  184718. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184719. png_uint_32 length));
  184720. #endif
  184721. #if defined(PNG_READ_sPLT_SUPPORTED)
  184722. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184723. png_uint_32 length));
  184724. #endif /* PNG_READ_sPLT_SUPPORTED */
  184725. #if defined(PNG_READ_sRGB_SUPPORTED)
  184726. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184727. png_uint_32 length));
  184728. #endif
  184729. #if defined(PNG_READ_tEXt_SUPPORTED)
  184730. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184731. png_uint_32 length));
  184732. #endif
  184733. #if defined(PNG_READ_tIME_SUPPORTED)
  184734. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184735. png_uint_32 length));
  184736. #endif
  184737. #if defined(PNG_READ_tRNS_SUPPORTED)
  184738. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184739. png_uint_32 length));
  184740. #endif
  184741. #if defined(PNG_READ_zTXt_SUPPORTED)
  184742. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184743. png_uint_32 length));
  184744. #endif
  184745. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184746. png_infop info_ptr, png_uint_32 length));
  184747. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184748. png_bytep chunk_name));
  184749. /* handle the transformations for reading and writing */
  184750. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184751. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184752. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184753. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184754. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184755. png_infop info_ptr));
  184756. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184757. png_infop info_ptr));
  184758. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184759. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184760. png_uint_32 length));
  184761. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184762. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184763. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184764. png_bytep buffer, png_size_t buffer_length));
  184765. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184766. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184767. png_bytep buffer, png_size_t buffer_length));
  184768. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184769. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184770. png_infop info_ptr, png_uint_32 length));
  184771. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184772. png_infop info_ptr));
  184773. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184774. png_infop info_ptr));
  184775. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184776. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184777. png_infop info_ptr));
  184778. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184779. png_infop info_ptr));
  184780. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184781. #if defined(PNG_READ_tEXt_SUPPORTED)
  184782. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184783. png_infop info_ptr, png_uint_32 length));
  184784. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184785. png_infop info_ptr));
  184786. #endif
  184787. #if defined(PNG_READ_zTXt_SUPPORTED)
  184788. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184789. png_infop info_ptr, png_uint_32 length));
  184790. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184791. png_infop info_ptr));
  184792. #endif
  184793. #if defined(PNG_READ_iTXt_SUPPORTED)
  184794. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184795. png_infop info_ptr, png_uint_32 length));
  184796. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184797. png_infop info_ptr));
  184798. #endif
  184799. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184800. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184801. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184802. png_bytep row));
  184803. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184804. png_bytep row));
  184805. #endif
  184806. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184807. #if defined(PNG_MMX_CODE_SUPPORTED)
  184808. /* png.c */ /* PRIVATE */
  184809. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184810. #endif
  184811. #endif
  184812. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184813. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184814. png_infop info_ptr));
  184815. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184816. png_infop info_ptr));
  184817. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184818. png_infop info_ptr));
  184819. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184820. png_infop info_ptr));
  184821. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184822. png_infop info_ptr));
  184823. #if defined(PNG_pHYs_SUPPORTED)
  184824. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184825. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184826. #endif /* PNG_pHYs_SUPPORTED */
  184827. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184828. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184829. #endif /* PNG_INTERNAL */
  184830. #ifdef __cplusplus
  184831. //}
  184832. #endif
  184833. #endif /* PNG_VERSION_INFO_ONLY */
  184834. /* do not put anything past this line */
  184835. #endif /* PNG_H */
  184836. /*** End of inlined file: png.h ***/
  184837. #define PNG_NO_EXTERN
  184838. /*** Start of inlined file: png.c ***/
  184839. /* png.c - location for general purpose libpng functions
  184840. *
  184841. * Last changed in libpng 1.2.21 [October 4, 2007]
  184842. * For conditions of distribution and use, see copyright notice in png.h
  184843. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184844. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184845. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184846. */
  184847. #define PNG_INTERNAL
  184848. #define PNG_NO_EXTERN
  184849. /* Generate a compiler error if there is an old png.h in the search path. */
  184850. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184851. /* Version information for C files. This had better match the version
  184852. * string defined in png.h. */
  184853. #ifdef PNG_USE_GLOBAL_ARRAYS
  184854. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184855. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184856. #ifdef PNG_READ_SUPPORTED
  184857. /* png_sig was changed to a function in version 1.0.5c */
  184858. /* Place to hold the signature string for a PNG file. */
  184859. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184860. #endif /* PNG_READ_SUPPORTED */
  184861. /* Invoke global declarations for constant strings for known chunk types */
  184862. PNG_IHDR;
  184863. PNG_IDAT;
  184864. PNG_IEND;
  184865. PNG_PLTE;
  184866. PNG_bKGD;
  184867. PNG_cHRM;
  184868. PNG_gAMA;
  184869. PNG_hIST;
  184870. PNG_iCCP;
  184871. PNG_iTXt;
  184872. PNG_oFFs;
  184873. PNG_pCAL;
  184874. PNG_sCAL;
  184875. PNG_pHYs;
  184876. PNG_sBIT;
  184877. PNG_sPLT;
  184878. PNG_sRGB;
  184879. PNG_tEXt;
  184880. PNG_tIME;
  184881. PNG_tRNS;
  184882. PNG_zTXt;
  184883. #ifdef PNG_READ_SUPPORTED
  184884. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184885. /* start of interlace block */
  184886. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184887. /* offset to next interlace block */
  184888. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184889. /* start of interlace block in the y direction */
  184890. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184891. /* offset to next interlace block in the y direction */
  184892. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184893. /* Height of interlace block. This is not currently used - if you need
  184894. * it, uncomment it here and in png.h
  184895. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184896. */
  184897. /* Mask to determine which pixels are valid in a pass */
  184898. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184899. /* Mask to determine which pixels to overwrite while displaying */
  184900. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184901. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184902. #endif /* PNG_READ_SUPPORTED */
  184903. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184904. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184905. * of the PNG file signature. If the PNG data is embedded into another
  184906. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184907. * or write any of the magic bytes before it starts on the IHDR.
  184908. */
  184909. #ifdef PNG_READ_SUPPORTED
  184910. void PNGAPI
  184911. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184912. {
  184913. if(png_ptr == NULL) return;
  184914. png_debug(1, "in png_set_sig_bytes\n");
  184915. if (num_bytes > 8)
  184916. png_error(png_ptr, "Too many bytes for PNG signature.");
  184917. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184918. }
  184919. /* Checks whether the supplied bytes match the PNG signature. We allow
  184920. * checking less than the full 8-byte signature so that those apps that
  184921. * already read the first few bytes of a file to determine the file type
  184922. * can simply check the remaining bytes for extra assurance. Returns
  184923. * an integer less than, equal to, or greater than zero if sig is found,
  184924. * respectively, to be less than, to match, or be greater than the correct
  184925. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184926. */
  184927. int PNGAPI
  184928. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184929. {
  184930. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184931. if (num_to_check > 8)
  184932. num_to_check = 8;
  184933. else if (num_to_check < 1)
  184934. return (-1);
  184935. if (start > 7)
  184936. return (-1);
  184937. if (start + num_to_check > 8)
  184938. num_to_check = 8 - start;
  184939. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184940. }
  184941. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184942. /* (Obsolete) function to check signature bytes. It does not allow one
  184943. * to check a partial signature. This function might be removed in the
  184944. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184945. */
  184946. int PNGAPI
  184947. png_check_sig(png_bytep sig, int num)
  184948. {
  184949. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184950. }
  184951. #endif
  184952. #endif /* PNG_READ_SUPPORTED */
  184953. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184954. /* Function to allocate memory for zlib and clear it to 0. */
  184955. #ifdef PNG_1_0_X
  184956. voidpf PNGAPI
  184957. #else
  184958. voidpf /* private */
  184959. #endif
  184960. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184961. {
  184962. png_voidp ptr;
  184963. png_structp p=(png_structp)png_ptr;
  184964. png_uint_32 save_flags=p->flags;
  184965. png_uint_32 num_bytes;
  184966. if(png_ptr == NULL) return (NULL);
  184967. if (items > PNG_UINT_32_MAX/size)
  184968. {
  184969. png_warning (p, "Potential overflow in png_zalloc()");
  184970. return (NULL);
  184971. }
  184972. num_bytes = (png_uint_32)items * size;
  184973. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184974. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184975. p->flags=save_flags;
  184976. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184977. if (ptr == NULL)
  184978. return ((voidpf)ptr);
  184979. if (num_bytes > (png_uint_32)0x8000L)
  184980. {
  184981. png_memset(ptr, 0, (png_size_t)0x8000L);
  184982. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184983. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184984. }
  184985. else
  184986. {
  184987. png_memset(ptr, 0, (png_size_t)num_bytes);
  184988. }
  184989. #endif
  184990. return ((voidpf)ptr);
  184991. }
  184992. /* function to free memory for zlib */
  184993. #ifdef PNG_1_0_X
  184994. void PNGAPI
  184995. #else
  184996. void /* private */
  184997. #endif
  184998. png_zfree(voidpf png_ptr, voidpf ptr)
  184999. {
  185000. png_free((png_structp)png_ptr, (png_voidp)ptr);
  185001. }
  185002. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  185003. * in case CRC is > 32 bits to leave the top bits 0.
  185004. */
  185005. void /* PRIVATE */
  185006. png_reset_crc(png_structp png_ptr)
  185007. {
  185008. png_ptr->crc = crc32(0, Z_NULL, 0);
  185009. }
  185010. /* Calculate the CRC over a section of data. We can only pass as
  185011. * much data to this routine as the largest single buffer size. We
  185012. * also check that this data will actually be used before going to the
  185013. * trouble of calculating it.
  185014. */
  185015. void /* PRIVATE */
  185016. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  185017. {
  185018. int need_crc = 1;
  185019. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  185020. {
  185021. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  185022. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  185023. need_crc = 0;
  185024. }
  185025. else /* critical */
  185026. {
  185027. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  185028. need_crc = 0;
  185029. }
  185030. if (need_crc)
  185031. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  185032. }
  185033. /* Allocate the memory for an info_struct for the application. We don't
  185034. * really need the png_ptr, but it could potentially be useful in the
  185035. * future. This should be used in favour of malloc(png_sizeof(png_info))
  185036. * and png_info_init() so that applications that want to use a shared
  185037. * libpng don't have to be recompiled if png_info changes size.
  185038. */
  185039. png_infop PNGAPI
  185040. png_create_info_struct(png_structp png_ptr)
  185041. {
  185042. png_infop info_ptr;
  185043. png_debug(1, "in png_create_info_struct\n");
  185044. if(png_ptr == NULL) return (NULL);
  185045. #ifdef PNG_USER_MEM_SUPPORTED
  185046. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  185047. png_ptr->malloc_fn, png_ptr->mem_ptr);
  185048. #else
  185049. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185050. #endif
  185051. if (info_ptr != NULL)
  185052. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185053. return (info_ptr);
  185054. }
  185055. /* This function frees the memory associated with a single info struct.
  185056. * Normally, one would use either png_destroy_read_struct() or
  185057. * png_destroy_write_struct() to free an info struct, but this may be
  185058. * useful for some applications.
  185059. */
  185060. void PNGAPI
  185061. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  185062. {
  185063. png_infop info_ptr = NULL;
  185064. if(png_ptr == NULL) return;
  185065. png_debug(1, "in png_destroy_info_struct\n");
  185066. if (info_ptr_ptr != NULL)
  185067. info_ptr = *info_ptr_ptr;
  185068. if (info_ptr != NULL)
  185069. {
  185070. png_info_destroy(png_ptr, info_ptr);
  185071. #ifdef PNG_USER_MEM_SUPPORTED
  185072. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  185073. png_ptr->mem_ptr);
  185074. #else
  185075. png_destroy_struct((png_voidp)info_ptr);
  185076. #endif
  185077. *info_ptr_ptr = NULL;
  185078. }
  185079. }
  185080. /* Initialize the info structure. This is now an internal function (0.89)
  185081. * and applications using it are urged to use png_create_info_struct()
  185082. * instead.
  185083. */
  185084. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185085. #undef png_info_init
  185086. void PNGAPI
  185087. png_info_init(png_infop info_ptr)
  185088. {
  185089. /* We only come here via pre-1.0.12-compiled applications */
  185090. png_info_init_3(&info_ptr, 0);
  185091. }
  185092. #endif
  185093. void PNGAPI
  185094. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  185095. {
  185096. png_infop info_ptr = *ptr_ptr;
  185097. if(info_ptr == NULL) return;
  185098. png_debug(1, "in png_info_init_3\n");
  185099. if(png_sizeof(png_info) > png_info_struct_size)
  185100. {
  185101. png_destroy_struct(info_ptr);
  185102. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185103. *ptr_ptr = info_ptr;
  185104. }
  185105. /* set everything to 0 */
  185106. png_memset(info_ptr, 0, png_sizeof (png_info));
  185107. }
  185108. #ifdef PNG_FREE_ME_SUPPORTED
  185109. void PNGAPI
  185110. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  185111. int freer, png_uint_32 mask)
  185112. {
  185113. png_debug(1, "in png_data_freer\n");
  185114. if (png_ptr == NULL || info_ptr == NULL)
  185115. return;
  185116. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  185117. info_ptr->free_me |= mask;
  185118. else if(freer == PNG_USER_WILL_FREE_DATA)
  185119. info_ptr->free_me &= ~mask;
  185120. else
  185121. png_warning(png_ptr,
  185122. "Unknown freer parameter in png_data_freer.");
  185123. }
  185124. #endif
  185125. void PNGAPI
  185126. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  185127. int num)
  185128. {
  185129. png_debug(1, "in png_free_data\n");
  185130. if (png_ptr == NULL || info_ptr == NULL)
  185131. return;
  185132. #if defined(PNG_TEXT_SUPPORTED)
  185133. /* free text item num or (if num == -1) all text items */
  185134. #ifdef PNG_FREE_ME_SUPPORTED
  185135. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  185136. #else
  185137. if (mask & PNG_FREE_TEXT)
  185138. #endif
  185139. {
  185140. if (num != -1)
  185141. {
  185142. if (info_ptr->text && info_ptr->text[num].key)
  185143. {
  185144. png_free(png_ptr, info_ptr->text[num].key);
  185145. info_ptr->text[num].key = NULL;
  185146. }
  185147. }
  185148. else
  185149. {
  185150. int i;
  185151. for (i = 0; i < info_ptr->num_text; i++)
  185152. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185153. png_free(png_ptr, info_ptr->text);
  185154. info_ptr->text = NULL;
  185155. info_ptr->num_text=0;
  185156. }
  185157. }
  185158. #endif
  185159. #if defined(PNG_tRNS_SUPPORTED)
  185160. /* free any tRNS entry */
  185161. #ifdef PNG_FREE_ME_SUPPORTED
  185162. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185163. #else
  185164. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185165. #endif
  185166. {
  185167. png_free(png_ptr, info_ptr->trans);
  185168. info_ptr->valid &= ~PNG_INFO_tRNS;
  185169. #ifndef PNG_FREE_ME_SUPPORTED
  185170. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185171. #endif
  185172. info_ptr->trans = NULL;
  185173. }
  185174. #endif
  185175. #if defined(PNG_sCAL_SUPPORTED)
  185176. /* free any sCAL entry */
  185177. #ifdef PNG_FREE_ME_SUPPORTED
  185178. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185179. #else
  185180. if (mask & PNG_FREE_SCAL)
  185181. #endif
  185182. {
  185183. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185184. png_free(png_ptr, info_ptr->scal_s_width);
  185185. png_free(png_ptr, info_ptr->scal_s_height);
  185186. info_ptr->scal_s_width = NULL;
  185187. info_ptr->scal_s_height = NULL;
  185188. #endif
  185189. info_ptr->valid &= ~PNG_INFO_sCAL;
  185190. }
  185191. #endif
  185192. #if defined(PNG_pCAL_SUPPORTED)
  185193. /* free any pCAL entry */
  185194. #ifdef PNG_FREE_ME_SUPPORTED
  185195. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185196. #else
  185197. if (mask & PNG_FREE_PCAL)
  185198. #endif
  185199. {
  185200. png_free(png_ptr, info_ptr->pcal_purpose);
  185201. png_free(png_ptr, info_ptr->pcal_units);
  185202. info_ptr->pcal_purpose = NULL;
  185203. info_ptr->pcal_units = NULL;
  185204. if (info_ptr->pcal_params != NULL)
  185205. {
  185206. int i;
  185207. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185208. {
  185209. png_free(png_ptr, info_ptr->pcal_params[i]);
  185210. info_ptr->pcal_params[i]=NULL;
  185211. }
  185212. png_free(png_ptr, info_ptr->pcal_params);
  185213. info_ptr->pcal_params = NULL;
  185214. }
  185215. info_ptr->valid &= ~PNG_INFO_pCAL;
  185216. }
  185217. #endif
  185218. #if defined(PNG_iCCP_SUPPORTED)
  185219. /* free any iCCP entry */
  185220. #ifdef PNG_FREE_ME_SUPPORTED
  185221. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185222. #else
  185223. if (mask & PNG_FREE_ICCP)
  185224. #endif
  185225. {
  185226. png_free(png_ptr, info_ptr->iccp_name);
  185227. png_free(png_ptr, info_ptr->iccp_profile);
  185228. info_ptr->iccp_name = NULL;
  185229. info_ptr->iccp_profile = NULL;
  185230. info_ptr->valid &= ~PNG_INFO_iCCP;
  185231. }
  185232. #endif
  185233. #if defined(PNG_sPLT_SUPPORTED)
  185234. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185235. #ifdef PNG_FREE_ME_SUPPORTED
  185236. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185237. #else
  185238. if (mask & PNG_FREE_SPLT)
  185239. #endif
  185240. {
  185241. if (num != -1)
  185242. {
  185243. if(info_ptr->splt_palettes)
  185244. {
  185245. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185246. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185247. info_ptr->splt_palettes[num].name = NULL;
  185248. info_ptr->splt_palettes[num].entries = NULL;
  185249. }
  185250. }
  185251. else
  185252. {
  185253. if(info_ptr->splt_palettes_num)
  185254. {
  185255. int i;
  185256. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185257. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185258. png_free(png_ptr, info_ptr->splt_palettes);
  185259. info_ptr->splt_palettes = NULL;
  185260. info_ptr->splt_palettes_num = 0;
  185261. }
  185262. info_ptr->valid &= ~PNG_INFO_sPLT;
  185263. }
  185264. }
  185265. #endif
  185266. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185267. if(png_ptr->unknown_chunk.data)
  185268. {
  185269. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185270. png_ptr->unknown_chunk.data = NULL;
  185271. }
  185272. #ifdef PNG_FREE_ME_SUPPORTED
  185273. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185274. #else
  185275. if (mask & PNG_FREE_UNKN)
  185276. #endif
  185277. {
  185278. if (num != -1)
  185279. {
  185280. if(info_ptr->unknown_chunks)
  185281. {
  185282. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185283. info_ptr->unknown_chunks[num].data = NULL;
  185284. }
  185285. }
  185286. else
  185287. {
  185288. int i;
  185289. if(info_ptr->unknown_chunks_num)
  185290. {
  185291. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185292. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185293. png_free(png_ptr, info_ptr->unknown_chunks);
  185294. info_ptr->unknown_chunks = NULL;
  185295. info_ptr->unknown_chunks_num = 0;
  185296. }
  185297. }
  185298. }
  185299. #endif
  185300. #if defined(PNG_hIST_SUPPORTED)
  185301. /* free any hIST entry */
  185302. #ifdef PNG_FREE_ME_SUPPORTED
  185303. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185304. #else
  185305. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185306. #endif
  185307. {
  185308. png_free(png_ptr, info_ptr->hist);
  185309. info_ptr->hist = NULL;
  185310. info_ptr->valid &= ~PNG_INFO_hIST;
  185311. #ifndef PNG_FREE_ME_SUPPORTED
  185312. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185313. #endif
  185314. }
  185315. #endif
  185316. /* free any PLTE entry that was internally allocated */
  185317. #ifdef PNG_FREE_ME_SUPPORTED
  185318. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185319. #else
  185320. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185321. #endif
  185322. {
  185323. png_zfree(png_ptr, info_ptr->palette);
  185324. info_ptr->palette = NULL;
  185325. info_ptr->valid &= ~PNG_INFO_PLTE;
  185326. #ifndef PNG_FREE_ME_SUPPORTED
  185327. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185328. #endif
  185329. info_ptr->num_palette = 0;
  185330. }
  185331. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185332. /* free any image bits attached to the info structure */
  185333. #ifdef PNG_FREE_ME_SUPPORTED
  185334. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185335. #else
  185336. if (mask & PNG_FREE_ROWS)
  185337. #endif
  185338. {
  185339. if(info_ptr->row_pointers)
  185340. {
  185341. int row;
  185342. for (row = 0; row < (int)info_ptr->height; row++)
  185343. {
  185344. png_free(png_ptr, info_ptr->row_pointers[row]);
  185345. info_ptr->row_pointers[row]=NULL;
  185346. }
  185347. png_free(png_ptr, info_ptr->row_pointers);
  185348. info_ptr->row_pointers=NULL;
  185349. }
  185350. info_ptr->valid &= ~PNG_INFO_IDAT;
  185351. }
  185352. #endif
  185353. #ifdef PNG_FREE_ME_SUPPORTED
  185354. if(num == -1)
  185355. info_ptr->free_me &= ~mask;
  185356. else
  185357. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185358. #endif
  185359. }
  185360. /* This is an internal routine to free any memory that the info struct is
  185361. * pointing to before re-using it or freeing the struct itself. Recall
  185362. * that png_free() checks for NULL pointers for us.
  185363. */
  185364. void /* PRIVATE */
  185365. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185366. {
  185367. png_debug(1, "in png_info_destroy\n");
  185368. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185369. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185370. if (png_ptr->num_chunk_list)
  185371. {
  185372. png_free(png_ptr, png_ptr->chunk_list);
  185373. png_ptr->chunk_list=NULL;
  185374. png_ptr->num_chunk_list=0;
  185375. }
  185376. #endif
  185377. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185378. }
  185379. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185380. /* This function returns a pointer to the io_ptr associated with the user
  185381. * functions. The application should free any memory associated with this
  185382. * pointer before png_write_destroy() or png_read_destroy() are called.
  185383. */
  185384. png_voidp PNGAPI
  185385. png_get_io_ptr(png_structp png_ptr)
  185386. {
  185387. if(png_ptr == NULL) return (NULL);
  185388. return (png_ptr->io_ptr);
  185389. }
  185390. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185391. #if !defined(PNG_NO_STDIO)
  185392. /* Initialize the default input/output functions for the PNG file. If you
  185393. * use your own read or write routines, you can call either png_set_read_fn()
  185394. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185395. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185396. * necessarily available.
  185397. */
  185398. void PNGAPI
  185399. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185400. {
  185401. png_debug(1, "in png_init_io\n");
  185402. if(png_ptr == NULL) return;
  185403. png_ptr->io_ptr = (png_voidp)fp;
  185404. }
  185405. #endif
  185406. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185407. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185408. * a "Creation Time" or other text-based time string.
  185409. */
  185410. png_charp PNGAPI
  185411. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185412. {
  185413. static PNG_CONST char short_months[12][4] =
  185414. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185415. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185416. if(png_ptr == NULL) return (NULL);
  185417. if (png_ptr->time_buffer == NULL)
  185418. {
  185419. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185420. png_sizeof(char)));
  185421. }
  185422. #if defined(_WIN32_WCE)
  185423. {
  185424. wchar_t time_buf[29];
  185425. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185426. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185427. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185428. ptime->second % 61);
  185429. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185430. NULL, NULL);
  185431. }
  185432. #else
  185433. #ifdef USE_FAR_KEYWORD
  185434. {
  185435. char near_time_buf[29];
  185436. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185437. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185438. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185439. ptime->second % 61);
  185440. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185441. 29*png_sizeof(char));
  185442. }
  185443. #else
  185444. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185445. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185446. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185447. ptime->second % 61);
  185448. #endif
  185449. #endif /* _WIN32_WCE */
  185450. return ((png_charp)png_ptr->time_buffer);
  185451. }
  185452. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185453. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185454. png_charp PNGAPI
  185455. png_get_copyright(png_structp png_ptr)
  185456. {
  185457. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185458. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185459. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185460. Copyright (c) 1996-1997 Andreas Dilger\n\
  185461. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185462. }
  185463. /* The following return the library version as a short string in the
  185464. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185465. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185466. * is defined in png.h.
  185467. * Note: now there is no difference between png_get_libpng_ver() and
  185468. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185469. * it is guaranteed that png.c uses the correct version of png.h.
  185470. */
  185471. png_charp PNGAPI
  185472. png_get_libpng_ver(png_structp png_ptr)
  185473. {
  185474. /* Version of *.c files used when building libpng */
  185475. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185476. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185477. }
  185478. png_charp PNGAPI
  185479. png_get_header_ver(png_structp png_ptr)
  185480. {
  185481. /* Version of *.h files used when building libpng */
  185482. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185483. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185484. }
  185485. png_charp PNGAPI
  185486. png_get_header_version(png_structp png_ptr)
  185487. {
  185488. /* Returns longer string containing both version and date */
  185489. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185490. return ((png_charp) PNG_HEADER_VERSION_STRING
  185491. #ifndef PNG_READ_SUPPORTED
  185492. " (NO READ SUPPORT)"
  185493. #endif
  185494. "\n");
  185495. }
  185496. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185497. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185498. int PNGAPI
  185499. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185500. {
  185501. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185502. int i;
  185503. png_bytep p;
  185504. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185505. return 0;
  185506. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185507. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185508. if (!png_memcmp(chunk_name, p, 4))
  185509. return ((int)*(p+4));
  185510. return 0;
  185511. }
  185512. #endif
  185513. /* This function, added to libpng-1.0.6g, is untested. */
  185514. int PNGAPI
  185515. png_reset_zstream(png_structp png_ptr)
  185516. {
  185517. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185518. return (inflateReset(&png_ptr->zstream));
  185519. }
  185520. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185521. /* This function was added to libpng-1.0.7 */
  185522. png_uint_32 PNGAPI
  185523. png_access_version_number(void)
  185524. {
  185525. /* Version of *.c files used when building libpng */
  185526. return((png_uint_32) PNG_LIBPNG_VER);
  185527. }
  185528. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185529. #if !defined(PNG_1_0_X)
  185530. /* this function was added to libpng 1.2.0 */
  185531. int PNGAPI
  185532. png_mmx_support(void)
  185533. {
  185534. /* obsolete, to be removed from libpng-1.4.0 */
  185535. return -1;
  185536. }
  185537. #endif /* PNG_1_0_X */
  185538. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185539. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185540. #ifdef PNG_SIZE_T
  185541. /* Added at libpng version 1.2.6 */
  185542. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185543. png_size_t PNGAPI
  185544. png_convert_size(size_t size)
  185545. {
  185546. if (size > (png_size_t)-1)
  185547. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185548. return ((png_size_t)size);
  185549. }
  185550. #endif /* PNG_SIZE_T */
  185551. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185552. /*** End of inlined file: png.c ***/
  185553. /*** Start of inlined file: pngerror.c ***/
  185554. /* pngerror.c - stub functions for i/o and memory allocation
  185555. *
  185556. * Last changed in libpng 1.2.20 October 4, 2007
  185557. * For conditions of distribution and use, see copyright notice in png.h
  185558. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185559. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185560. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185561. *
  185562. * This file provides a location for all error handling. Users who
  185563. * need special error handling are expected to write replacement functions
  185564. * and use png_set_error_fn() to use those functions. See the instructions
  185565. * at each function.
  185566. */
  185567. #define PNG_INTERNAL
  185568. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185569. static void /* PRIVATE */
  185570. png_default_error PNGARG((png_structp png_ptr,
  185571. png_const_charp error_message));
  185572. #ifndef PNG_NO_WARNINGS
  185573. static void /* PRIVATE */
  185574. png_default_warning PNGARG((png_structp png_ptr,
  185575. png_const_charp warning_message));
  185576. #endif /* PNG_NO_WARNINGS */
  185577. /* This function is called whenever there is a fatal error. This function
  185578. * should not be changed. If there is a need to handle errors differently,
  185579. * you should supply a replacement error function and use png_set_error_fn()
  185580. * to replace the error function at run-time.
  185581. */
  185582. #ifndef PNG_NO_ERROR_TEXT
  185583. void PNGAPI
  185584. png_error(png_structp png_ptr, png_const_charp error_message)
  185585. {
  185586. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185587. char msg[16];
  185588. if (png_ptr != NULL)
  185589. {
  185590. if (png_ptr->flags&
  185591. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185592. {
  185593. if (*error_message == '#')
  185594. {
  185595. int offset;
  185596. for (offset=1; offset<15; offset++)
  185597. if (*(error_message+offset) == ' ')
  185598. break;
  185599. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185600. {
  185601. int i;
  185602. for (i=0; i<offset-1; i++)
  185603. msg[i]=error_message[i+1];
  185604. msg[i]='\0';
  185605. error_message=msg;
  185606. }
  185607. else
  185608. error_message+=offset;
  185609. }
  185610. else
  185611. {
  185612. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185613. {
  185614. msg[0]='0';
  185615. msg[1]='\0';
  185616. error_message=msg;
  185617. }
  185618. }
  185619. }
  185620. }
  185621. #endif
  185622. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185623. (*(png_ptr->error_fn))(png_ptr, error_message);
  185624. /* If the custom handler doesn't exist, or if it returns,
  185625. use the default handler, which will not return. */
  185626. png_default_error(png_ptr, error_message);
  185627. }
  185628. #else
  185629. void PNGAPI
  185630. png_err(png_structp png_ptr)
  185631. {
  185632. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185633. (*(png_ptr->error_fn))(png_ptr, '\0');
  185634. /* If the custom handler doesn't exist, or if it returns,
  185635. use the default handler, which will not return. */
  185636. png_default_error(png_ptr, '\0');
  185637. }
  185638. #endif /* PNG_NO_ERROR_TEXT */
  185639. #ifndef PNG_NO_WARNINGS
  185640. /* This function is called whenever there is a non-fatal error. This function
  185641. * should not be changed. If there is a need to handle warnings differently,
  185642. * you should supply a replacement warning function and use
  185643. * png_set_error_fn() to replace the warning function at run-time.
  185644. */
  185645. void PNGAPI
  185646. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185647. {
  185648. int offset = 0;
  185649. if (png_ptr != NULL)
  185650. {
  185651. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185652. if (png_ptr->flags&
  185653. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185654. #endif
  185655. {
  185656. if (*warning_message == '#')
  185657. {
  185658. for (offset=1; offset<15; offset++)
  185659. if (*(warning_message+offset) == ' ')
  185660. break;
  185661. }
  185662. }
  185663. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185664. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185665. }
  185666. else
  185667. png_default_warning(png_ptr, warning_message+offset);
  185668. }
  185669. #endif /* PNG_NO_WARNINGS */
  185670. /* These utilities are used internally to build an error message that relates
  185671. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185672. * this is used to prefix the message. The message is limited in length
  185673. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185674. * if the character is invalid.
  185675. */
  185676. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185677. /*static PNG_CONST char png_digit[16] = {
  185678. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185679. 'A', 'B', 'C', 'D', 'E', 'F'
  185680. };*/
  185681. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185682. static void /* PRIVATE */
  185683. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185684. error_message)
  185685. {
  185686. int iout = 0, iin = 0;
  185687. while (iin < 4)
  185688. {
  185689. int c = png_ptr->chunk_name[iin++];
  185690. if (isnonalpha(c))
  185691. {
  185692. buffer[iout++] = '[';
  185693. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185694. buffer[iout++] = png_digit[c & 0x0f];
  185695. buffer[iout++] = ']';
  185696. }
  185697. else
  185698. {
  185699. buffer[iout++] = (png_byte)c;
  185700. }
  185701. }
  185702. if (error_message == NULL)
  185703. buffer[iout] = 0;
  185704. else
  185705. {
  185706. buffer[iout++] = ':';
  185707. buffer[iout++] = ' ';
  185708. png_strncpy(buffer+iout, error_message, 63);
  185709. buffer[iout+63] = 0;
  185710. }
  185711. }
  185712. #ifdef PNG_READ_SUPPORTED
  185713. void PNGAPI
  185714. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185715. {
  185716. char msg[18+64];
  185717. if (png_ptr == NULL)
  185718. png_error(png_ptr, error_message);
  185719. else
  185720. {
  185721. png_format_buffer(png_ptr, msg, error_message);
  185722. png_error(png_ptr, msg);
  185723. }
  185724. }
  185725. #endif /* PNG_READ_SUPPORTED */
  185726. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185727. #ifndef PNG_NO_WARNINGS
  185728. void PNGAPI
  185729. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185730. {
  185731. char msg[18+64];
  185732. if (png_ptr == NULL)
  185733. png_warning(png_ptr, warning_message);
  185734. else
  185735. {
  185736. png_format_buffer(png_ptr, msg, warning_message);
  185737. png_warning(png_ptr, msg);
  185738. }
  185739. }
  185740. #endif /* PNG_NO_WARNINGS */
  185741. /* This is the default error handling function. Note that replacements for
  185742. * this function MUST NOT RETURN, or the program will likely crash. This
  185743. * function is used by default, or if the program supplies NULL for the
  185744. * error function pointer in png_set_error_fn().
  185745. */
  185746. static void /* PRIVATE */
  185747. png_default_error(png_structp, png_const_charp error_message)
  185748. {
  185749. #ifndef PNG_NO_CONSOLE_IO
  185750. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185751. if (*error_message == '#')
  185752. {
  185753. int offset;
  185754. char error_number[16];
  185755. for (offset=0; offset<15; offset++)
  185756. {
  185757. error_number[offset] = *(error_message+offset+1);
  185758. if (*(error_message+offset) == ' ')
  185759. break;
  185760. }
  185761. if((offset > 1) && (offset < 15))
  185762. {
  185763. error_number[offset-1]='\0';
  185764. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185765. error_message+offset);
  185766. }
  185767. else
  185768. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185769. }
  185770. else
  185771. #endif
  185772. fprintf(stderr, "libpng error: %s\n", error_message);
  185773. #endif
  185774. #ifdef PNG_SETJMP_SUPPORTED
  185775. if (png_ptr)
  185776. {
  185777. # ifdef USE_FAR_KEYWORD
  185778. {
  185779. jmp_buf jmpbuf;
  185780. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185781. longjmp(jmpbuf, 1);
  185782. }
  185783. # else
  185784. longjmp(png_ptr->jmpbuf, 1);
  185785. # endif
  185786. }
  185787. #else
  185788. PNG_ABORT();
  185789. #endif
  185790. #ifdef PNG_NO_CONSOLE_IO
  185791. error_message = error_message; /* make compiler happy */
  185792. #endif
  185793. }
  185794. #ifndef PNG_NO_WARNINGS
  185795. /* This function is called when there is a warning, but the library thinks
  185796. * it can continue anyway. Replacement functions don't have to do anything
  185797. * here if you don't want them to. In the default configuration, png_ptr is
  185798. * not used, but it is passed in case it may be useful.
  185799. */
  185800. static void /* PRIVATE */
  185801. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185802. {
  185803. #ifndef PNG_NO_CONSOLE_IO
  185804. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185805. if (*warning_message == '#')
  185806. {
  185807. int offset;
  185808. char warning_number[16];
  185809. for (offset=0; offset<15; offset++)
  185810. {
  185811. warning_number[offset]=*(warning_message+offset+1);
  185812. if (*(warning_message+offset) == ' ')
  185813. break;
  185814. }
  185815. if((offset > 1) && (offset < 15))
  185816. {
  185817. warning_number[offset-1]='\0';
  185818. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185819. warning_message+offset);
  185820. }
  185821. else
  185822. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185823. }
  185824. else
  185825. # endif
  185826. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185827. #else
  185828. warning_message = warning_message; /* make compiler happy */
  185829. #endif
  185830. png_ptr = png_ptr; /* make compiler happy */
  185831. }
  185832. #endif /* PNG_NO_WARNINGS */
  185833. /* This function is called when the application wants to use another method
  185834. * of handling errors and warnings. Note that the error function MUST NOT
  185835. * return to the calling routine or serious problems will occur. The return
  185836. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185837. */
  185838. void PNGAPI
  185839. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185840. png_error_ptr error_fn, png_error_ptr warning_fn)
  185841. {
  185842. if (png_ptr == NULL)
  185843. return;
  185844. png_ptr->error_ptr = error_ptr;
  185845. png_ptr->error_fn = error_fn;
  185846. png_ptr->warning_fn = warning_fn;
  185847. }
  185848. /* This function returns a pointer to the error_ptr associated with the user
  185849. * functions. The application should free any memory associated with this
  185850. * pointer before png_write_destroy and png_read_destroy are called.
  185851. */
  185852. png_voidp PNGAPI
  185853. png_get_error_ptr(png_structp png_ptr)
  185854. {
  185855. if (png_ptr == NULL)
  185856. return NULL;
  185857. return ((png_voidp)png_ptr->error_ptr);
  185858. }
  185859. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185860. void PNGAPI
  185861. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185862. {
  185863. if(png_ptr != NULL)
  185864. {
  185865. png_ptr->flags &=
  185866. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185867. }
  185868. }
  185869. #endif
  185870. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185871. /*** End of inlined file: pngerror.c ***/
  185872. /*** Start of inlined file: pngget.c ***/
  185873. /* pngget.c - retrieval of values from info struct
  185874. *
  185875. * Last changed in libpng 1.2.15 January 5, 2007
  185876. * For conditions of distribution and use, see copyright notice in png.h
  185877. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185878. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185879. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185880. */
  185881. #define PNG_INTERNAL
  185882. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185883. png_uint_32 PNGAPI
  185884. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185885. {
  185886. if (png_ptr != NULL && info_ptr != NULL)
  185887. return(info_ptr->valid & flag);
  185888. else
  185889. return(0);
  185890. }
  185891. png_uint_32 PNGAPI
  185892. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185893. {
  185894. if (png_ptr != NULL && info_ptr != NULL)
  185895. return(info_ptr->rowbytes);
  185896. else
  185897. return(0);
  185898. }
  185899. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185900. png_bytepp PNGAPI
  185901. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185902. {
  185903. if (png_ptr != NULL && info_ptr != NULL)
  185904. return(info_ptr->row_pointers);
  185905. else
  185906. return(0);
  185907. }
  185908. #endif
  185909. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185910. /* easy access to info, added in libpng-0.99 */
  185911. png_uint_32 PNGAPI
  185912. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185913. {
  185914. if (png_ptr != NULL && info_ptr != NULL)
  185915. {
  185916. return info_ptr->width;
  185917. }
  185918. return (0);
  185919. }
  185920. png_uint_32 PNGAPI
  185921. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185922. {
  185923. if (png_ptr != NULL && info_ptr != NULL)
  185924. {
  185925. return info_ptr->height;
  185926. }
  185927. return (0);
  185928. }
  185929. png_byte PNGAPI
  185930. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185931. {
  185932. if (png_ptr != NULL && info_ptr != NULL)
  185933. {
  185934. return info_ptr->bit_depth;
  185935. }
  185936. return (0);
  185937. }
  185938. png_byte PNGAPI
  185939. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185940. {
  185941. if (png_ptr != NULL && info_ptr != NULL)
  185942. {
  185943. return info_ptr->color_type;
  185944. }
  185945. return (0);
  185946. }
  185947. png_byte PNGAPI
  185948. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185949. {
  185950. if (png_ptr != NULL && info_ptr != NULL)
  185951. {
  185952. return info_ptr->filter_type;
  185953. }
  185954. return (0);
  185955. }
  185956. png_byte PNGAPI
  185957. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185958. {
  185959. if (png_ptr != NULL && info_ptr != NULL)
  185960. {
  185961. return info_ptr->interlace_type;
  185962. }
  185963. return (0);
  185964. }
  185965. png_byte PNGAPI
  185966. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185967. {
  185968. if (png_ptr != NULL && info_ptr != NULL)
  185969. {
  185970. return info_ptr->compression_type;
  185971. }
  185972. return (0);
  185973. }
  185974. png_uint_32 PNGAPI
  185975. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185976. {
  185977. if (png_ptr != NULL && info_ptr != NULL)
  185978. #if defined(PNG_pHYs_SUPPORTED)
  185979. if (info_ptr->valid & PNG_INFO_pHYs)
  185980. {
  185981. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185982. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185983. return (0);
  185984. else return (info_ptr->x_pixels_per_unit);
  185985. }
  185986. #else
  185987. return (0);
  185988. #endif
  185989. return (0);
  185990. }
  185991. png_uint_32 PNGAPI
  185992. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185993. {
  185994. if (png_ptr != NULL && info_ptr != NULL)
  185995. #if defined(PNG_pHYs_SUPPORTED)
  185996. if (info_ptr->valid & PNG_INFO_pHYs)
  185997. {
  185998. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185999. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186000. return (0);
  186001. else return (info_ptr->y_pixels_per_unit);
  186002. }
  186003. #else
  186004. return (0);
  186005. #endif
  186006. return (0);
  186007. }
  186008. png_uint_32 PNGAPI
  186009. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186010. {
  186011. if (png_ptr != NULL && info_ptr != NULL)
  186012. #if defined(PNG_pHYs_SUPPORTED)
  186013. if (info_ptr->valid & PNG_INFO_pHYs)
  186014. {
  186015. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  186016. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  186017. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  186018. return (0);
  186019. else return (info_ptr->x_pixels_per_unit);
  186020. }
  186021. #else
  186022. return (0);
  186023. #endif
  186024. return (0);
  186025. }
  186026. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186027. float PNGAPI
  186028. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  186029. {
  186030. if (png_ptr != NULL && info_ptr != NULL)
  186031. #if defined(PNG_pHYs_SUPPORTED)
  186032. if (info_ptr->valid & PNG_INFO_pHYs)
  186033. {
  186034. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  186035. if (info_ptr->x_pixels_per_unit == 0)
  186036. return ((float)0.0);
  186037. else
  186038. return ((float)((float)info_ptr->y_pixels_per_unit
  186039. /(float)info_ptr->x_pixels_per_unit));
  186040. }
  186041. #else
  186042. return (0.0);
  186043. #endif
  186044. return ((float)0.0);
  186045. }
  186046. #endif
  186047. png_int_32 PNGAPI
  186048. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186049. {
  186050. if (png_ptr != NULL && info_ptr != NULL)
  186051. #if defined(PNG_oFFs_SUPPORTED)
  186052. if (info_ptr->valid & PNG_INFO_oFFs)
  186053. {
  186054. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186055. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186056. return (0);
  186057. else return (info_ptr->x_offset);
  186058. }
  186059. #else
  186060. return (0);
  186061. #endif
  186062. return (0);
  186063. }
  186064. png_int_32 PNGAPI
  186065. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186066. {
  186067. if (png_ptr != NULL && info_ptr != NULL)
  186068. #if defined(PNG_oFFs_SUPPORTED)
  186069. if (info_ptr->valid & PNG_INFO_oFFs)
  186070. {
  186071. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186072. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186073. return (0);
  186074. else return (info_ptr->y_offset);
  186075. }
  186076. #else
  186077. return (0);
  186078. #endif
  186079. return (0);
  186080. }
  186081. png_int_32 PNGAPI
  186082. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186083. {
  186084. if (png_ptr != NULL && info_ptr != NULL)
  186085. #if defined(PNG_oFFs_SUPPORTED)
  186086. if (info_ptr->valid & PNG_INFO_oFFs)
  186087. {
  186088. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186089. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186090. return (0);
  186091. else return (info_ptr->x_offset);
  186092. }
  186093. #else
  186094. return (0);
  186095. #endif
  186096. return (0);
  186097. }
  186098. png_int_32 PNGAPI
  186099. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186100. {
  186101. if (png_ptr != NULL && info_ptr != NULL)
  186102. #if defined(PNG_oFFs_SUPPORTED)
  186103. if (info_ptr->valid & PNG_INFO_oFFs)
  186104. {
  186105. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186106. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186107. return (0);
  186108. else return (info_ptr->y_offset);
  186109. }
  186110. #else
  186111. return (0);
  186112. #endif
  186113. return (0);
  186114. }
  186115. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186116. png_uint_32 PNGAPI
  186117. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186118. {
  186119. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  186120. *.0254 +.5));
  186121. }
  186122. png_uint_32 PNGAPI
  186123. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186124. {
  186125. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  186126. *.0254 +.5));
  186127. }
  186128. png_uint_32 PNGAPI
  186129. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186130. {
  186131. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  186132. *.0254 +.5));
  186133. }
  186134. float PNGAPI
  186135. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186136. {
  186137. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  186138. *.00003937);
  186139. }
  186140. float PNGAPI
  186141. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186142. {
  186143. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  186144. *.00003937);
  186145. }
  186146. #if defined(PNG_pHYs_SUPPORTED)
  186147. png_uint_32 PNGAPI
  186148. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186149. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186150. {
  186151. png_uint_32 retval = 0;
  186152. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186153. {
  186154. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186155. if (res_x != NULL)
  186156. {
  186157. *res_x = info_ptr->x_pixels_per_unit;
  186158. retval |= PNG_INFO_pHYs;
  186159. }
  186160. if (res_y != NULL)
  186161. {
  186162. *res_y = info_ptr->y_pixels_per_unit;
  186163. retval |= PNG_INFO_pHYs;
  186164. }
  186165. if (unit_type != NULL)
  186166. {
  186167. *unit_type = (int)info_ptr->phys_unit_type;
  186168. retval |= PNG_INFO_pHYs;
  186169. if(*unit_type == 1)
  186170. {
  186171. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186172. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186173. }
  186174. }
  186175. }
  186176. return (retval);
  186177. }
  186178. #endif /* PNG_pHYs_SUPPORTED */
  186179. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186180. /* png_get_channels really belongs in here, too, but it's been around longer */
  186181. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186182. png_byte PNGAPI
  186183. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186184. {
  186185. if (png_ptr != NULL && info_ptr != NULL)
  186186. return(info_ptr->channels);
  186187. else
  186188. return (0);
  186189. }
  186190. png_bytep PNGAPI
  186191. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186192. {
  186193. if (png_ptr != NULL && info_ptr != NULL)
  186194. return(info_ptr->signature);
  186195. else
  186196. return (NULL);
  186197. }
  186198. #if defined(PNG_bKGD_SUPPORTED)
  186199. png_uint_32 PNGAPI
  186200. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186201. png_color_16p *background)
  186202. {
  186203. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186204. && background != NULL)
  186205. {
  186206. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186207. *background = &(info_ptr->background);
  186208. return (PNG_INFO_bKGD);
  186209. }
  186210. return (0);
  186211. }
  186212. #endif
  186213. #if defined(PNG_cHRM_SUPPORTED)
  186214. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186215. png_uint_32 PNGAPI
  186216. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186217. double *white_x, double *white_y, double *red_x, double *red_y,
  186218. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186219. {
  186220. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186221. {
  186222. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186223. if (white_x != NULL)
  186224. *white_x = (double)info_ptr->x_white;
  186225. if (white_y != NULL)
  186226. *white_y = (double)info_ptr->y_white;
  186227. if (red_x != NULL)
  186228. *red_x = (double)info_ptr->x_red;
  186229. if (red_y != NULL)
  186230. *red_y = (double)info_ptr->y_red;
  186231. if (green_x != NULL)
  186232. *green_x = (double)info_ptr->x_green;
  186233. if (green_y != NULL)
  186234. *green_y = (double)info_ptr->y_green;
  186235. if (blue_x != NULL)
  186236. *blue_x = (double)info_ptr->x_blue;
  186237. if (blue_y != NULL)
  186238. *blue_y = (double)info_ptr->y_blue;
  186239. return (PNG_INFO_cHRM);
  186240. }
  186241. return (0);
  186242. }
  186243. #endif
  186244. #ifdef PNG_FIXED_POINT_SUPPORTED
  186245. png_uint_32 PNGAPI
  186246. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186247. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186248. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186249. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186250. {
  186251. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186252. {
  186253. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186254. if (white_x != NULL)
  186255. *white_x = info_ptr->int_x_white;
  186256. if (white_y != NULL)
  186257. *white_y = info_ptr->int_y_white;
  186258. if (red_x != NULL)
  186259. *red_x = info_ptr->int_x_red;
  186260. if (red_y != NULL)
  186261. *red_y = info_ptr->int_y_red;
  186262. if (green_x != NULL)
  186263. *green_x = info_ptr->int_x_green;
  186264. if (green_y != NULL)
  186265. *green_y = info_ptr->int_y_green;
  186266. if (blue_x != NULL)
  186267. *blue_x = info_ptr->int_x_blue;
  186268. if (blue_y != NULL)
  186269. *blue_y = info_ptr->int_y_blue;
  186270. return (PNG_INFO_cHRM);
  186271. }
  186272. return (0);
  186273. }
  186274. #endif
  186275. #endif
  186276. #if defined(PNG_gAMA_SUPPORTED)
  186277. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186278. png_uint_32 PNGAPI
  186279. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186280. {
  186281. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186282. && file_gamma != NULL)
  186283. {
  186284. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186285. *file_gamma = (double)info_ptr->gamma;
  186286. return (PNG_INFO_gAMA);
  186287. }
  186288. return (0);
  186289. }
  186290. #endif
  186291. #ifdef PNG_FIXED_POINT_SUPPORTED
  186292. png_uint_32 PNGAPI
  186293. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186294. png_fixed_point *int_file_gamma)
  186295. {
  186296. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186297. && int_file_gamma != NULL)
  186298. {
  186299. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186300. *int_file_gamma = info_ptr->int_gamma;
  186301. return (PNG_INFO_gAMA);
  186302. }
  186303. return (0);
  186304. }
  186305. #endif
  186306. #endif
  186307. #if defined(PNG_sRGB_SUPPORTED)
  186308. png_uint_32 PNGAPI
  186309. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186310. {
  186311. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186312. && file_srgb_intent != NULL)
  186313. {
  186314. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186315. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186316. return (PNG_INFO_sRGB);
  186317. }
  186318. return (0);
  186319. }
  186320. #endif
  186321. #if defined(PNG_iCCP_SUPPORTED)
  186322. png_uint_32 PNGAPI
  186323. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186324. png_charpp name, int *compression_type,
  186325. png_charpp profile, png_uint_32 *proflen)
  186326. {
  186327. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186328. && name != NULL && profile != NULL && proflen != NULL)
  186329. {
  186330. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186331. *name = info_ptr->iccp_name;
  186332. *profile = info_ptr->iccp_profile;
  186333. /* compression_type is a dummy so the API won't have to change
  186334. if we introduce multiple compression types later. */
  186335. *proflen = (int)info_ptr->iccp_proflen;
  186336. *compression_type = (int)info_ptr->iccp_compression;
  186337. return (PNG_INFO_iCCP);
  186338. }
  186339. return (0);
  186340. }
  186341. #endif
  186342. #if defined(PNG_sPLT_SUPPORTED)
  186343. png_uint_32 PNGAPI
  186344. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186345. png_sPLT_tpp spalettes)
  186346. {
  186347. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186348. {
  186349. *spalettes = info_ptr->splt_palettes;
  186350. return ((png_uint_32)info_ptr->splt_palettes_num);
  186351. }
  186352. return (0);
  186353. }
  186354. #endif
  186355. #if defined(PNG_hIST_SUPPORTED)
  186356. png_uint_32 PNGAPI
  186357. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186358. {
  186359. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186360. && hist != NULL)
  186361. {
  186362. png_debug1(1, "in %s retrieval function\n", "hIST");
  186363. *hist = info_ptr->hist;
  186364. return (PNG_INFO_hIST);
  186365. }
  186366. return (0);
  186367. }
  186368. #endif
  186369. png_uint_32 PNGAPI
  186370. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186371. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186372. int *color_type, int *interlace_type, int *compression_type,
  186373. int *filter_type)
  186374. {
  186375. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186376. bit_depth != NULL && color_type != NULL)
  186377. {
  186378. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186379. *width = info_ptr->width;
  186380. *height = info_ptr->height;
  186381. *bit_depth = info_ptr->bit_depth;
  186382. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186383. png_error(png_ptr, "Invalid bit depth");
  186384. *color_type = info_ptr->color_type;
  186385. if (info_ptr->color_type > 6)
  186386. png_error(png_ptr, "Invalid color type");
  186387. if (compression_type != NULL)
  186388. *compression_type = info_ptr->compression_type;
  186389. if (filter_type != NULL)
  186390. *filter_type = info_ptr->filter_type;
  186391. if (interlace_type != NULL)
  186392. *interlace_type = info_ptr->interlace_type;
  186393. /* check for potential overflow of rowbytes */
  186394. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186395. png_error(png_ptr, "Invalid image width");
  186396. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186397. png_error(png_ptr, "Invalid image height");
  186398. if (info_ptr->width > (PNG_UINT_32_MAX
  186399. >> 3) /* 8-byte RGBA pixels */
  186400. - 64 /* bigrowbuf hack */
  186401. - 1 /* filter byte */
  186402. - 7*8 /* rounding of width to multiple of 8 pixels */
  186403. - 8) /* extra max_pixel_depth pad */
  186404. {
  186405. png_warning(png_ptr,
  186406. "Width too large for libpng to process image data.");
  186407. }
  186408. return (1);
  186409. }
  186410. return (0);
  186411. }
  186412. #if defined(PNG_oFFs_SUPPORTED)
  186413. png_uint_32 PNGAPI
  186414. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186415. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186416. {
  186417. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186418. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186419. {
  186420. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186421. *offset_x = info_ptr->x_offset;
  186422. *offset_y = info_ptr->y_offset;
  186423. *unit_type = (int)info_ptr->offset_unit_type;
  186424. return (PNG_INFO_oFFs);
  186425. }
  186426. return (0);
  186427. }
  186428. #endif
  186429. #if defined(PNG_pCAL_SUPPORTED)
  186430. png_uint_32 PNGAPI
  186431. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186432. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186433. png_charp *units, png_charpp *params)
  186434. {
  186435. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186436. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186437. nparams != NULL && units != NULL && params != NULL)
  186438. {
  186439. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186440. *purpose = info_ptr->pcal_purpose;
  186441. *X0 = info_ptr->pcal_X0;
  186442. *X1 = info_ptr->pcal_X1;
  186443. *type = (int)info_ptr->pcal_type;
  186444. *nparams = (int)info_ptr->pcal_nparams;
  186445. *units = info_ptr->pcal_units;
  186446. *params = info_ptr->pcal_params;
  186447. return (PNG_INFO_pCAL);
  186448. }
  186449. return (0);
  186450. }
  186451. #endif
  186452. #if defined(PNG_sCAL_SUPPORTED)
  186453. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186454. png_uint_32 PNGAPI
  186455. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186456. int *unit, double *width, double *height)
  186457. {
  186458. if (png_ptr != NULL && info_ptr != NULL &&
  186459. (info_ptr->valid & PNG_INFO_sCAL))
  186460. {
  186461. *unit = info_ptr->scal_unit;
  186462. *width = info_ptr->scal_pixel_width;
  186463. *height = info_ptr->scal_pixel_height;
  186464. return (PNG_INFO_sCAL);
  186465. }
  186466. return(0);
  186467. }
  186468. #else
  186469. #ifdef PNG_FIXED_POINT_SUPPORTED
  186470. png_uint_32 PNGAPI
  186471. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186472. int *unit, png_charpp width, png_charpp height)
  186473. {
  186474. if (png_ptr != NULL && info_ptr != NULL &&
  186475. (info_ptr->valid & PNG_INFO_sCAL))
  186476. {
  186477. *unit = info_ptr->scal_unit;
  186478. *width = info_ptr->scal_s_width;
  186479. *height = info_ptr->scal_s_height;
  186480. return (PNG_INFO_sCAL);
  186481. }
  186482. return(0);
  186483. }
  186484. #endif
  186485. #endif
  186486. #endif
  186487. #if defined(PNG_pHYs_SUPPORTED)
  186488. png_uint_32 PNGAPI
  186489. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186490. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186491. {
  186492. png_uint_32 retval = 0;
  186493. if (png_ptr != NULL && info_ptr != NULL &&
  186494. (info_ptr->valid & PNG_INFO_pHYs))
  186495. {
  186496. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186497. if (res_x != NULL)
  186498. {
  186499. *res_x = info_ptr->x_pixels_per_unit;
  186500. retval |= PNG_INFO_pHYs;
  186501. }
  186502. if (res_y != NULL)
  186503. {
  186504. *res_y = info_ptr->y_pixels_per_unit;
  186505. retval |= PNG_INFO_pHYs;
  186506. }
  186507. if (unit_type != NULL)
  186508. {
  186509. *unit_type = (int)info_ptr->phys_unit_type;
  186510. retval |= PNG_INFO_pHYs;
  186511. }
  186512. }
  186513. return (retval);
  186514. }
  186515. #endif
  186516. png_uint_32 PNGAPI
  186517. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186518. int *num_palette)
  186519. {
  186520. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186521. && palette != NULL)
  186522. {
  186523. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186524. *palette = info_ptr->palette;
  186525. *num_palette = info_ptr->num_palette;
  186526. png_debug1(3, "num_palette = %d\n", *num_palette);
  186527. return (PNG_INFO_PLTE);
  186528. }
  186529. return (0);
  186530. }
  186531. #if defined(PNG_sBIT_SUPPORTED)
  186532. png_uint_32 PNGAPI
  186533. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186534. {
  186535. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186536. && sig_bit != NULL)
  186537. {
  186538. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186539. *sig_bit = &(info_ptr->sig_bit);
  186540. return (PNG_INFO_sBIT);
  186541. }
  186542. return (0);
  186543. }
  186544. #endif
  186545. #if defined(PNG_TEXT_SUPPORTED)
  186546. png_uint_32 PNGAPI
  186547. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186548. int *num_text)
  186549. {
  186550. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186551. {
  186552. png_debug1(1, "in %s retrieval function\n",
  186553. (png_ptr->chunk_name[0] == '\0' ? "text"
  186554. : (png_const_charp)png_ptr->chunk_name));
  186555. if (text_ptr != NULL)
  186556. *text_ptr = info_ptr->text;
  186557. if (num_text != NULL)
  186558. *num_text = info_ptr->num_text;
  186559. return ((png_uint_32)info_ptr->num_text);
  186560. }
  186561. if (num_text != NULL)
  186562. *num_text = 0;
  186563. return(0);
  186564. }
  186565. #endif
  186566. #if defined(PNG_tIME_SUPPORTED)
  186567. png_uint_32 PNGAPI
  186568. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186569. {
  186570. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186571. && mod_time != NULL)
  186572. {
  186573. png_debug1(1, "in %s retrieval function\n", "tIME");
  186574. *mod_time = &(info_ptr->mod_time);
  186575. return (PNG_INFO_tIME);
  186576. }
  186577. return (0);
  186578. }
  186579. #endif
  186580. #if defined(PNG_tRNS_SUPPORTED)
  186581. png_uint_32 PNGAPI
  186582. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186583. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186584. {
  186585. png_uint_32 retval = 0;
  186586. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186587. {
  186588. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186589. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186590. {
  186591. if (trans != NULL)
  186592. {
  186593. *trans = info_ptr->trans;
  186594. retval |= PNG_INFO_tRNS;
  186595. }
  186596. if (trans_values != NULL)
  186597. *trans_values = &(info_ptr->trans_values);
  186598. }
  186599. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186600. {
  186601. if (trans_values != NULL)
  186602. {
  186603. *trans_values = &(info_ptr->trans_values);
  186604. retval |= PNG_INFO_tRNS;
  186605. }
  186606. if(trans != NULL)
  186607. *trans = NULL;
  186608. }
  186609. if(num_trans != NULL)
  186610. {
  186611. *num_trans = info_ptr->num_trans;
  186612. retval |= PNG_INFO_tRNS;
  186613. }
  186614. }
  186615. return (retval);
  186616. }
  186617. #endif
  186618. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186619. png_uint_32 PNGAPI
  186620. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186621. png_unknown_chunkpp unknowns)
  186622. {
  186623. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186624. {
  186625. *unknowns = info_ptr->unknown_chunks;
  186626. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186627. }
  186628. return (0);
  186629. }
  186630. #endif
  186631. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186632. png_byte PNGAPI
  186633. png_get_rgb_to_gray_status (png_structp png_ptr)
  186634. {
  186635. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186636. }
  186637. #endif
  186638. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186639. png_voidp PNGAPI
  186640. png_get_user_chunk_ptr(png_structp png_ptr)
  186641. {
  186642. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186643. }
  186644. #endif
  186645. #ifdef PNG_WRITE_SUPPORTED
  186646. png_uint_32 PNGAPI
  186647. png_get_compression_buffer_size(png_structp png_ptr)
  186648. {
  186649. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186650. }
  186651. #endif
  186652. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186653. #ifndef PNG_1_0_X
  186654. /* this function was added to libpng 1.2.0 and should exist by default */
  186655. png_uint_32 PNGAPI
  186656. png_get_asm_flags (png_structp png_ptr)
  186657. {
  186658. /* obsolete, to be removed from libpng-1.4.0 */
  186659. return (png_ptr? 0L: 0L);
  186660. }
  186661. /* this function was added to libpng 1.2.0 and should exist by default */
  186662. png_uint_32 PNGAPI
  186663. png_get_asm_flagmask (int flag_select)
  186664. {
  186665. /* obsolete, to be removed from libpng-1.4.0 */
  186666. flag_select=flag_select;
  186667. return 0L;
  186668. }
  186669. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186670. /* this function was added to libpng 1.2.0 */
  186671. png_uint_32 PNGAPI
  186672. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186673. {
  186674. /* obsolete, to be removed from libpng-1.4.0 */
  186675. flag_select=flag_select;
  186676. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186677. return 0L;
  186678. }
  186679. /* this function was added to libpng 1.2.0 */
  186680. png_byte PNGAPI
  186681. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186682. {
  186683. /* obsolete, to be removed from libpng-1.4.0 */
  186684. return (png_ptr? 0: 0);
  186685. }
  186686. /* this function was added to libpng 1.2.0 */
  186687. png_uint_32 PNGAPI
  186688. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186689. {
  186690. /* obsolete, to be removed from libpng-1.4.0 */
  186691. return (png_ptr? 0L: 0L);
  186692. }
  186693. #endif /* ?PNG_1_0_X */
  186694. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186695. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186696. /* these functions were added to libpng 1.2.6 */
  186697. png_uint_32 PNGAPI
  186698. png_get_user_width_max (png_structp png_ptr)
  186699. {
  186700. return (png_ptr? png_ptr->user_width_max : 0);
  186701. }
  186702. png_uint_32 PNGAPI
  186703. png_get_user_height_max (png_structp png_ptr)
  186704. {
  186705. return (png_ptr? png_ptr->user_height_max : 0);
  186706. }
  186707. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186708. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186709. /*** End of inlined file: pngget.c ***/
  186710. /*** Start of inlined file: pngmem.c ***/
  186711. /* pngmem.c - stub functions for memory allocation
  186712. *
  186713. * Last changed in libpng 1.2.13 November 13, 2006
  186714. * For conditions of distribution and use, see copyright notice in png.h
  186715. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186716. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186717. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186718. *
  186719. * This file provides a location for all memory allocation. Users who
  186720. * need special memory handling are expected to supply replacement
  186721. * functions for png_malloc() and png_free(), and to use
  186722. * png_create_read_struct_2() and png_create_write_struct_2() to
  186723. * identify the replacement functions.
  186724. */
  186725. #define PNG_INTERNAL
  186726. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186727. /* Borland DOS special memory handler */
  186728. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186729. /* if you change this, be sure to change the one in png.h also */
  186730. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186731. by a single call to calloc() if this is thought to improve performance. */
  186732. png_voidp /* PRIVATE */
  186733. png_create_struct(int type)
  186734. {
  186735. #ifdef PNG_USER_MEM_SUPPORTED
  186736. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186737. }
  186738. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186739. png_voidp /* PRIVATE */
  186740. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186741. {
  186742. #endif /* PNG_USER_MEM_SUPPORTED */
  186743. png_size_t size;
  186744. png_voidp struct_ptr;
  186745. if (type == PNG_STRUCT_INFO)
  186746. size = png_sizeof(png_info);
  186747. else if (type == PNG_STRUCT_PNG)
  186748. size = png_sizeof(png_struct);
  186749. else
  186750. return (png_get_copyright(NULL));
  186751. #ifdef PNG_USER_MEM_SUPPORTED
  186752. if(malloc_fn != NULL)
  186753. {
  186754. png_struct dummy_struct;
  186755. png_structp png_ptr = &dummy_struct;
  186756. png_ptr->mem_ptr=mem_ptr;
  186757. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186758. }
  186759. else
  186760. #endif /* PNG_USER_MEM_SUPPORTED */
  186761. struct_ptr = (png_voidp)farmalloc(size);
  186762. if (struct_ptr != NULL)
  186763. png_memset(struct_ptr, 0, size);
  186764. return (struct_ptr);
  186765. }
  186766. /* Free memory allocated by a png_create_struct() call */
  186767. void /* PRIVATE */
  186768. png_destroy_struct(png_voidp struct_ptr)
  186769. {
  186770. #ifdef PNG_USER_MEM_SUPPORTED
  186771. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186772. }
  186773. /* Free memory allocated by a png_create_struct() call */
  186774. void /* PRIVATE */
  186775. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186776. png_voidp mem_ptr)
  186777. {
  186778. #endif
  186779. if (struct_ptr != NULL)
  186780. {
  186781. #ifdef PNG_USER_MEM_SUPPORTED
  186782. if(free_fn != NULL)
  186783. {
  186784. png_struct dummy_struct;
  186785. png_structp png_ptr = &dummy_struct;
  186786. png_ptr->mem_ptr=mem_ptr;
  186787. (*(free_fn))(png_ptr, struct_ptr);
  186788. return;
  186789. }
  186790. #endif /* PNG_USER_MEM_SUPPORTED */
  186791. farfree (struct_ptr);
  186792. }
  186793. }
  186794. /* Allocate memory. For reasonable files, size should never exceed
  186795. * 64K. However, zlib may allocate more then 64K if you don't tell
  186796. * it not to. See zconf.h and png.h for more information. zlib does
  186797. * need to allocate exactly 64K, so whatever you call here must
  186798. * have the ability to do that.
  186799. *
  186800. * Borland seems to have a problem in DOS mode for exactly 64K.
  186801. * It gives you a segment with an offset of 8 (perhaps to store its
  186802. * memory stuff). zlib doesn't like this at all, so we have to
  186803. * detect and deal with it. This code should not be needed in
  186804. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186805. * been updated by Alexander Lehmann for version 0.89 to waste less
  186806. * memory.
  186807. *
  186808. * Note that we can't use png_size_t for the "size" declaration,
  186809. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186810. * result, we would be truncating potentially larger memory requests
  186811. * (which should cause a fatal error) and introducing major problems.
  186812. */
  186813. png_voidp PNGAPI
  186814. png_malloc(png_structp png_ptr, png_uint_32 size)
  186815. {
  186816. png_voidp ret;
  186817. if (png_ptr == NULL || size == 0)
  186818. return (NULL);
  186819. #ifdef PNG_USER_MEM_SUPPORTED
  186820. if(png_ptr->malloc_fn != NULL)
  186821. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186822. else
  186823. ret = (png_malloc_default(png_ptr, size));
  186824. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186825. png_error(png_ptr, "Out of memory!");
  186826. return (ret);
  186827. }
  186828. png_voidp PNGAPI
  186829. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186830. {
  186831. png_voidp ret;
  186832. #endif /* PNG_USER_MEM_SUPPORTED */
  186833. if (png_ptr == NULL || size == 0)
  186834. return (NULL);
  186835. #ifdef PNG_MAX_MALLOC_64K
  186836. if (size > (png_uint_32)65536L)
  186837. {
  186838. png_warning(png_ptr, "Cannot Allocate > 64K");
  186839. ret = NULL;
  186840. }
  186841. else
  186842. #endif
  186843. if (size != (size_t)size)
  186844. ret = NULL;
  186845. else if (size == (png_uint_32)65536L)
  186846. {
  186847. if (png_ptr->offset_table == NULL)
  186848. {
  186849. /* try to see if we need to do any of this fancy stuff */
  186850. ret = farmalloc(size);
  186851. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186852. {
  186853. int num_blocks;
  186854. png_uint_32 total_size;
  186855. png_bytep table;
  186856. int i;
  186857. png_byte huge * hptr;
  186858. if (ret != NULL)
  186859. {
  186860. farfree(ret);
  186861. ret = NULL;
  186862. }
  186863. if(png_ptr->zlib_window_bits > 14)
  186864. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186865. else
  186866. num_blocks = 1;
  186867. if (png_ptr->zlib_mem_level >= 7)
  186868. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186869. else
  186870. num_blocks++;
  186871. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186872. table = farmalloc(total_size);
  186873. if (table == NULL)
  186874. {
  186875. #ifndef PNG_USER_MEM_SUPPORTED
  186876. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186877. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186878. else
  186879. png_warning(png_ptr, "Out Of Memory.");
  186880. #endif
  186881. return (NULL);
  186882. }
  186883. if ((png_size_t)table & 0xfff0)
  186884. {
  186885. #ifndef PNG_USER_MEM_SUPPORTED
  186886. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186887. png_error(png_ptr,
  186888. "Farmalloc didn't return normalized pointer");
  186889. else
  186890. png_warning(png_ptr,
  186891. "Farmalloc didn't return normalized pointer");
  186892. #endif
  186893. return (NULL);
  186894. }
  186895. png_ptr->offset_table = table;
  186896. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186897. png_sizeof (png_bytep));
  186898. if (png_ptr->offset_table_ptr == NULL)
  186899. {
  186900. #ifndef PNG_USER_MEM_SUPPORTED
  186901. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186902. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186903. else
  186904. png_warning(png_ptr, "Out Of memory.");
  186905. #endif
  186906. return (NULL);
  186907. }
  186908. hptr = (png_byte huge *)table;
  186909. if ((png_size_t)hptr & 0xf)
  186910. {
  186911. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186912. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186913. }
  186914. for (i = 0; i < num_blocks; i++)
  186915. {
  186916. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186917. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186918. }
  186919. png_ptr->offset_table_number = num_blocks;
  186920. png_ptr->offset_table_count = 0;
  186921. png_ptr->offset_table_count_free = 0;
  186922. }
  186923. }
  186924. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186925. {
  186926. #ifndef PNG_USER_MEM_SUPPORTED
  186927. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186928. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186929. else
  186930. png_warning(png_ptr, "Out of Memory.");
  186931. #endif
  186932. return (NULL);
  186933. }
  186934. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186935. }
  186936. else
  186937. ret = farmalloc(size);
  186938. #ifndef PNG_USER_MEM_SUPPORTED
  186939. if (ret == NULL)
  186940. {
  186941. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186942. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186943. else
  186944. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186945. }
  186946. #endif
  186947. return (ret);
  186948. }
  186949. /* free a pointer allocated by png_malloc(). In the default
  186950. configuration, png_ptr is not used, but is passed in case it
  186951. is needed. If ptr is NULL, return without taking any action. */
  186952. void PNGAPI
  186953. png_free(png_structp png_ptr, png_voidp ptr)
  186954. {
  186955. if (png_ptr == NULL || ptr == NULL)
  186956. return;
  186957. #ifdef PNG_USER_MEM_SUPPORTED
  186958. if (png_ptr->free_fn != NULL)
  186959. {
  186960. (*(png_ptr->free_fn))(png_ptr, ptr);
  186961. return;
  186962. }
  186963. else png_free_default(png_ptr, ptr);
  186964. }
  186965. void PNGAPI
  186966. png_free_default(png_structp png_ptr, png_voidp ptr)
  186967. {
  186968. #endif /* PNG_USER_MEM_SUPPORTED */
  186969. if(png_ptr == NULL) return;
  186970. if (png_ptr->offset_table != NULL)
  186971. {
  186972. int i;
  186973. for (i = 0; i < png_ptr->offset_table_count; i++)
  186974. {
  186975. if (ptr == png_ptr->offset_table_ptr[i])
  186976. {
  186977. ptr = NULL;
  186978. png_ptr->offset_table_count_free++;
  186979. break;
  186980. }
  186981. }
  186982. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186983. {
  186984. farfree(png_ptr->offset_table);
  186985. farfree(png_ptr->offset_table_ptr);
  186986. png_ptr->offset_table = NULL;
  186987. png_ptr->offset_table_ptr = NULL;
  186988. }
  186989. }
  186990. if (ptr != NULL)
  186991. {
  186992. farfree(ptr);
  186993. }
  186994. }
  186995. #else /* Not the Borland DOS special memory handler */
  186996. /* Allocate memory for a png_struct or a png_info. The malloc and
  186997. memset can be replaced by a single call to calloc() if this is thought
  186998. to improve performance noticably. */
  186999. png_voidp /* PRIVATE */
  187000. png_create_struct(int type)
  187001. {
  187002. #ifdef PNG_USER_MEM_SUPPORTED
  187003. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  187004. }
  187005. /* Allocate memory for a png_struct or a png_info. The malloc and
  187006. memset can be replaced by a single call to calloc() if this is thought
  187007. to improve performance noticably. */
  187008. png_voidp /* PRIVATE */
  187009. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  187010. {
  187011. #endif /* PNG_USER_MEM_SUPPORTED */
  187012. png_size_t size;
  187013. png_voidp struct_ptr;
  187014. if (type == PNG_STRUCT_INFO)
  187015. size = png_sizeof(png_info);
  187016. else if (type == PNG_STRUCT_PNG)
  187017. size = png_sizeof(png_struct);
  187018. else
  187019. return (NULL);
  187020. #ifdef PNG_USER_MEM_SUPPORTED
  187021. if(malloc_fn != NULL)
  187022. {
  187023. png_struct dummy_struct;
  187024. png_structp png_ptr = &dummy_struct;
  187025. png_ptr->mem_ptr=mem_ptr;
  187026. struct_ptr = (*(malloc_fn))(png_ptr, size);
  187027. if (struct_ptr != NULL)
  187028. png_memset(struct_ptr, 0, size);
  187029. return (struct_ptr);
  187030. }
  187031. #endif /* PNG_USER_MEM_SUPPORTED */
  187032. #if defined(__TURBOC__) && !defined(__FLAT__)
  187033. struct_ptr = (png_voidp)farmalloc(size);
  187034. #else
  187035. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187036. struct_ptr = (png_voidp)halloc(size,1);
  187037. # else
  187038. struct_ptr = (png_voidp)malloc(size);
  187039. # endif
  187040. #endif
  187041. if (struct_ptr != NULL)
  187042. png_memset(struct_ptr, 0, size);
  187043. return (struct_ptr);
  187044. }
  187045. /* Free memory allocated by a png_create_struct() call */
  187046. void /* PRIVATE */
  187047. png_destroy_struct(png_voidp struct_ptr)
  187048. {
  187049. #ifdef PNG_USER_MEM_SUPPORTED
  187050. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  187051. }
  187052. /* Free memory allocated by a png_create_struct() call */
  187053. void /* PRIVATE */
  187054. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  187055. png_voidp mem_ptr)
  187056. {
  187057. #endif /* PNG_USER_MEM_SUPPORTED */
  187058. if (struct_ptr != NULL)
  187059. {
  187060. #ifdef PNG_USER_MEM_SUPPORTED
  187061. if(free_fn != NULL)
  187062. {
  187063. png_struct dummy_struct;
  187064. png_structp png_ptr = &dummy_struct;
  187065. png_ptr->mem_ptr=mem_ptr;
  187066. (*(free_fn))(png_ptr, struct_ptr);
  187067. return;
  187068. }
  187069. #endif /* PNG_USER_MEM_SUPPORTED */
  187070. #if defined(__TURBOC__) && !defined(__FLAT__)
  187071. farfree(struct_ptr);
  187072. #else
  187073. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187074. hfree(struct_ptr);
  187075. # else
  187076. free(struct_ptr);
  187077. # endif
  187078. #endif
  187079. }
  187080. }
  187081. /* Allocate memory. For reasonable files, size should never exceed
  187082. 64K. However, zlib may allocate more then 64K if you don't tell
  187083. it not to. See zconf.h and png.h for more information. zlib does
  187084. need to allocate exactly 64K, so whatever you call here must
  187085. have the ability to do that. */
  187086. png_voidp PNGAPI
  187087. png_malloc(png_structp png_ptr, png_uint_32 size)
  187088. {
  187089. png_voidp ret;
  187090. #ifdef PNG_USER_MEM_SUPPORTED
  187091. if (png_ptr == NULL || size == 0)
  187092. return (NULL);
  187093. if(png_ptr->malloc_fn != NULL)
  187094. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  187095. else
  187096. ret = (png_malloc_default(png_ptr, size));
  187097. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187098. png_error(png_ptr, "Out of Memory!");
  187099. return (ret);
  187100. }
  187101. png_voidp PNGAPI
  187102. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  187103. {
  187104. png_voidp ret;
  187105. #endif /* PNG_USER_MEM_SUPPORTED */
  187106. if (png_ptr == NULL || size == 0)
  187107. return (NULL);
  187108. #ifdef PNG_MAX_MALLOC_64K
  187109. if (size > (png_uint_32)65536L)
  187110. {
  187111. #ifndef PNG_USER_MEM_SUPPORTED
  187112. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187113. png_error(png_ptr, "Cannot Allocate > 64K");
  187114. else
  187115. #endif
  187116. return NULL;
  187117. }
  187118. #endif
  187119. /* Check for overflow */
  187120. #if defined(__TURBOC__) && !defined(__FLAT__)
  187121. if (size != (unsigned long)size)
  187122. ret = NULL;
  187123. else
  187124. ret = farmalloc(size);
  187125. #else
  187126. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187127. if (size != (unsigned long)size)
  187128. ret = NULL;
  187129. else
  187130. ret = halloc(size, 1);
  187131. # else
  187132. if (size != (size_t)size)
  187133. ret = NULL;
  187134. else
  187135. ret = malloc((size_t)size);
  187136. # endif
  187137. #endif
  187138. #ifndef PNG_USER_MEM_SUPPORTED
  187139. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187140. png_error(png_ptr, "Out of Memory");
  187141. #endif
  187142. return (ret);
  187143. }
  187144. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  187145. without taking any action. */
  187146. void PNGAPI
  187147. png_free(png_structp png_ptr, png_voidp ptr)
  187148. {
  187149. if (png_ptr == NULL || ptr == NULL)
  187150. return;
  187151. #ifdef PNG_USER_MEM_SUPPORTED
  187152. if (png_ptr->free_fn != NULL)
  187153. {
  187154. (*(png_ptr->free_fn))(png_ptr, ptr);
  187155. return;
  187156. }
  187157. else png_free_default(png_ptr, ptr);
  187158. }
  187159. void PNGAPI
  187160. png_free_default(png_structp png_ptr, png_voidp ptr)
  187161. {
  187162. if (png_ptr == NULL || ptr == NULL)
  187163. return;
  187164. #endif /* PNG_USER_MEM_SUPPORTED */
  187165. #if defined(__TURBOC__) && !defined(__FLAT__)
  187166. farfree(ptr);
  187167. #else
  187168. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187169. hfree(ptr);
  187170. # else
  187171. free(ptr);
  187172. # endif
  187173. #endif
  187174. }
  187175. #endif /* Not Borland DOS special memory handler */
  187176. #if defined(PNG_1_0_X)
  187177. # define png_malloc_warn png_malloc
  187178. #else
  187179. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187180. * function will set up png_malloc() to issue a png_warning and return NULL
  187181. * instead of issuing a png_error, if it fails to allocate the requested
  187182. * memory.
  187183. */
  187184. png_voidp PNGAPI
  187185. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187186. {
  187187. png_voidp ptr;
  187188. png_uint_32 save_flags;
  187189. if(png_ptr == NULL) return (NULL);
  187190. save_flags=png_ptr->flags;
  187191. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187192. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187193. png_ptr->flags=save_flags;
  187194. return(ptr);
  187195. }
  187196. #endif
  187197. png_voidp PNGAPI
  187198. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187199. png_uint_32 length)
  187200. {
  187201. png_size_t size;
  187202. size = (png_size_t)length;
  187203. if ((png_uint_32)size != length)
  187204. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187205. return(png_memcpy (s1, s2, size));
  187206. }
  187207. png_voidp PNGAPI
  187208. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187209. png_uint_32 length)
  187210. {
  187211. png_size_t size;
  187212. size = (png_size_t)length;
  187213. if ((png_uint_32)size != length)
  187214. png_error(png_ptr,"Overflow in png_memset_check.");
  187215. return (png_memset (s1, value, size));
  187216. }
  187217. #ifdef PNG_USER_MEM_SUPPORTED
  187218. /* This function is called when the application wants to use another method
  187219. * of allocating and freeing memory.
  187220. */
  187221. void PNGAPI
  187222. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187223. malloc_fn, png_free_ptr free_fn)
  187224. {
  187225. if(png_ptr != NULL) {
  187226. png_ptr->mem_ptr = mem_ptr;
  187227. png_ptr->malloc_fn = malloc_fn;
  187228. png_ptr->free_fn = free_fn;
  187229. }
  187230. }
  187231. /* This function returns a pointer to the mem_ptr associated with the user
  187232. * functions. The application should free any memory associated with this
  187233. * pointer before png_write_destroy and png_read_destroy are called.
  187234. */
  187235. png_voidp PNGAPI
  187236. png_get_mem_ptr(png_structp png_ptr)
  187237. {
  187238. if(png_ptr == NULL) return (NULL);
  187239. return ((png_voidp)png_ptr->mem_ptr);
  187240. }
  187241. #endif /* PNG_USER_MEM_SUPPORTED */
  187242. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187243. /*** End of inlined file: pngmem.c ***/
  187244. /*** Start of inlined file: pngread.c ***/
  187245. /* pngread.c - read a PNG file
  187246. *
  187247. * Last changed in libpng 1.2.20 September 7, 2007
  187248. * For conditions of distribution and use, see copyright notice in png.h
  187249. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187250. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187251. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187252. *
  187253. * This file contains routines that an application calls directly to
  187254. * read a PNG file or stream.
  187255. */
  187256. #define PNG_INTERNAL
  187257. #if defined(PNG_READ_SUPPORTED)
  187258. /* Create a PNG structure for reading, and allocate any memory needed. */
  187259. png_structp PNGAPI
  187260. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187261. png_error_ptr error_fn, png_error_ptr warn_fn)
  187262. {
  187263. #ifdef PNG_USER_MEM_SUPPORTED
  187264. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187265. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187266. }
  187267. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187268. png_structp PNGAPI
  187269. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187270. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187271. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187272. {
  187273. #endif /* PNG_USER_MEM_SUPPORTED */
  187274. png_structp png_ptr;
  187275. #ifdef PNG_SETJMP_SUPPORTED
  187276. #ifdef USE_FAR_KEYWORD
  187277. jmp_buf jmpbuf;
  187278. #endif
  187279. #endif
  187280. int i;
  187281. png_debug(1, "in png_create_read_struct\n");
  187282. #ifdef PNG_USER_MEM_SUPPORTED
  187283. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187284. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187285. #else
  187286. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187287. #endif
  187288. if (png_ptr == NULL)
  187289. return (NULL);
  187290. /* added at libpng-1.2.6 */
  187291. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187292. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187293. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187294. #endif
  187295. #ifdef PNG_SETJMP_SUPPORTED
  187296. #ifdef USE_FAR_KEYWORD
  187297. if (setjmp(jmpbuf))
  187298. #else
  187299. if (setjmp(png_ptr->jmpbuf))
  187300. #endif
  187301. {
  187302. png_free(png_ptr, png_ptr->zbuf);
  187303. png_ptr->zbuf=NULL;
  187304. #ifdef PNG_USER_MEM_SUPPORTED
  187305. png_destroy_struct_2((png_voidp)png_ptr,
  187306. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187307. #else
  187308. png_destroy_struct((png_voidp)png_ptr);
  187309. #endif
  187310. return (NULL);
  187311. }
  187312. #ifdef USE_FAR_KEYWORD
  187313. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187314. #endif
  187315. #endif
  187316. #ifdef PNG_USER_MEM_SUPPORTED
  187317. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187318. #endif
  187319. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187320. i=0;
  187321. do
  187322. {
  187323. if(user_png_ver[i] != png_libpng_ver[i])
  187324. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187325. } while (png_libpng_ver[i++]);
  187326. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187327. {
  187328. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187329. * we must recompile any applications that use any older library version.
  187330. * For versions after libpng 1.0, we will be compatible, so we need
  187331. * only check the first digit.
  187332. */
  187333. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187334. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187335. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187336. {
  187337. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187338. char msg[80];
  187339. if (user_png_ver)
  187340. {
  187341. png_snprintf(msg, 80,
  187342. "Application was compiled with png.h from libpng-%.20s",
  187343. user_png_ver);
  187344. png_warning(png_ptr, msg);
  187345. }
  187346. png_snprintf(msg, 80,
  187347. "Application is running with png.c from libpng-%.20s",
  187348. png_libpng_ver);
  187349. png_warning(png_ptr, msg);
  187350. #endif
  187351. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187352. png_ptr->flags=0;
  187353. #endif
  187354. png_error(png_ptr,
  187355. "Incompatible libpng version in application and library");
  187356. }
  187357. }
  187358. /* initialize zbuf - compression buffer */
  187359. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187360. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187361. (png_uint_32)png_ptr->zbuf_size);
  187362. png_ptr->zstream.zalloc = png_zalloc;
  187363. png_ptr->zstream.zfree = png_zfree;
  187364. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187365. switch (inflateInit(&png_ptr->zstream))
  187366. {
  187367. case Z_OK: /* Do nothing */ break;
  187368. case Z_MEM_ERROR:
  187369. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187370. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187371. default: png_error(png_ptr, "Unknown zlib error");
  187372. }
  187373. png_ptr->zstream.next_out = png_ptr->zbuf;
  187374. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187375. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187376. #ifdef PNG_SETJMP_SUPPORTED
  187377. /* Applications that neglect to set up their own setjmp() and then encounter
  187378. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187379. abort instead of returning. */
  187380. #ifdef USE_FAR_KEYWORD
  187381. if (setjmp(jmpbuf))
  187382. PNG_ABORT();
  187383. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187384. #else
  187385. if (setjmp(png_ptr->jmpbuf))
  187386. PNG_ABORT();
  187387. #endif
  187388. #endif
  187389. return (png_ptr);
  187390. }
  187391. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187392. /* Initialize PNG structure for reading, and allocate any memory needed.
  187393. This interface is deprecated in favour of the png_create_read_struct(),
  187394. and it will disappear as of libpng-1.3.0. */
  187395. #undef png_read_init
  187396. void PNGAPI
  187397. png_read_init(png_structp png_ptr)
  187398. {
  187399. /* We only come here via pre-1.0.7-compiled applications */
  187400. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187401. }
  187402. void PNGAPI
  187403. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187404. png_size_t png_struct_size, png_size_t png_info_size)
  187405. {
  187406. /* We only come here via pre-1.0.12-compiled applications */
  187407. if(png_ptr == NULL) return;
  187408. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187409. if(png_sizeof(png_struct) > png_struct_size ||
  187410. png_sizeof(png_info) > png_info_size)
  187411. {
  187412. char msg[80];
  187413. png_ptr->warning_fn=NULL;
  187414. if (user_png_ver)
  187415. {
  187416. png_snprintf(msg, 80,
  187417. "Application was compiled with png.h from libpng-%.20s",
  187418. user_png_ver);
  187419. png_warning(png_ptr, msg);
  187420. }
  187421. png_snprintf(msg, 80,
  187422. "Application is running with png.c from libpng-%.20s",
  187423. png_libpng_ver);
  187424. png_warning(png_ptr, msg);
  187425. }
  187426. #endif
  187427. if(png_sizeof(png_struct) > png_struct_size)
  187428. {
  187429. png_ptr->error_fn=NULL;
  187430. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187431. png_ptr->flags=0;
  187432. #endif
  187433. png_error(png_ptr,
  187434. "The png struct allocated by the application for reading is too small.");
  187435. }
  187436. if(png_sizeof(png_info) > png_info_size)
  187437. {
  187438. png_ptr->error_fn=NULL;
  187439. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187440. png_ptr->flags=0;
  187441. #endif
  187442. png_error(png_ptr,
  187443. "The info struct allocated by application for reading is too small.");
  187444. }
  187445. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187446. }
  187447. #endif /* PNG_1_0_X || PNG_1_2_X */
  187448. void PNGAPI
  187449. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187450. png_size_t png_struct_size)
  187451. {
  187452. #ifdef PNG_SETJMP_SUPPORTED
  187453. jmp_buf tmp_jmp; /* to save current jump buffer */
  187454. #endif
  187455. int i=0;
  187456. png_structp png_ptr=*ptr_ptr;
  187457. if(png_ptr == NULL) return;
  187458. do
  187459. {
  187460. if(user_png_ver[i] != png_libpng_ver[i])
  187461. {
  187462. #ifdef PNG_LEGACY_SUPPORTED
  187463. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187464. #else
  187465. png_ptr->warning_fn=NULL;
  187466. png_warning(png_ptr,
  187467. "Application uses deprecated png_read_init() and should be recompiled.");
  187468. break;
  187469. #endif
  187470. }
  187471. } while (png_libpng_ver[i++]);
  187472. png_debug(1, "in png_read_init_3\n");
  187473. #ifdef PNG_SETJMP_SUPPORTED
  187474. /* save jump buffer and error functions */
  187475. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187476. #endif
  187477. if(png_sizeof(png_struct) > png_struct_size)
  187478. {
  187479. png_destroy_struct(png_ptr);
  187480. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187481. png_ptr = *ptr_ptr;
  187482. }
  187483. /* reset all variables to 0 */
  187484. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187485. #ifdef PNG_SETJMP_SUPPORTED
  187486. /* restore jump buffer */
  187487. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187488. #endif
  187489. /* added at libpng-1.2.6 */
  187490. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187491. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187492. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187493. #endif
  187494. /* initialize zbuf - compression buffer */
  187495. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187496. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187497. (png_uint_32)png_ptr->zbuf_size);
  187498. png_ptr->zstream.zalloc = png_zalloc;
  187499. png_ptr->zstream.zfree = png_zfree;
  187500. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187501. switch (inflateInit(&png_ptr->zstream))
  187502. {
  187503. case Z_OK: /* Do nothing */ break;
  187504. case Z_MEM_ERROR:
  187505. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187506. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187507. default: png_error(png_ptr, "Unknown zlib error");
  187508. }
  187509. png_ptr->zstream.next_out = png_ptr->zbuf;
  187510. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187511. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187512. }
  187513. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187514. /* Read the information before the actual image data. This has been
  187515. * changed in v0.90 to allow reading a file that already has the magic
  187516. * bytes read from the stream. You can tell libpng how many bytes have
  187517. * been read from the beginning of the stream (up to the maximum of 8)
  187518. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187519. * here. The application can then have access to the signature bytes we
  187520. * read if it is determined that this isn't a valid PNG file.
  187521. */
  187522. void PNGAPI
  187523. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187524. {
  187525. if(png_ptr == NULL) return;
  187526. png_debug(1, "in png_read_info\n");
  187527. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187528. if (png_ptr->sig_bytes < 8)
  187529. {
  187530. png_size_t num_checked = png_ptr->sig_bytes,
  187531. num_to_check = 8 - num_checked;
  187532. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187533. png_ptr->sig_bytes = 8;
  187534. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187535. {
  187536. if (num_checked < 4 &&
  187537. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187538. png_error(png_ptr, "Not a PNG file");
  187539. else
  187540. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187541. }
  187542. if (num_checked < 3)
  187543. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187544. }
  187545. for(;;)
  187546. {
  187547. #ifdef PNG_USE_LOCAL_ARRAYS
  187548. PNG_CONST PNG_IHDR;
  187549. PNG_CONST PNG_IDAT;
  187550. PNG_CONST PNG_IEND;
  187551. PNG_CONST PNG_PLTE;
  187552. #if defined(PNG_READ_bKGD_SUPPORTED)
  187553. PNG_CONST PNG_bKGD;
  187554. #endif
  187555. #if defined(PNG_READ_cHRM_SUPPORTED)
  187556. PNG_CONST PNG_cHRM;
  187557. #endif
  187558. #if defined(PNG_READ_gAMA_SUPPORTED)
  187559. PNG_CONST PNG_gAMA;
  187560. #endif
  187561. #if defined(PNG_READ_hIST_SUPPORTED)
  187562. PNG_CONST PNG_hIST;
  187563. #endif
  187564. #if defined(PNG_READ_iCCP_SUPPORTED)
  187565. PNG_CONST PNG_iCCP;
  187566. #endif
  187567. #if defined(PNG_READ_iTXt_SUPPORTED)
  187568. PNG_CONST PNG_iTXt;
  187569. #endif
  187570. #if defined(PNG_READ_oFFs_SUPPORTED)
  187571. PNG_CONST PNG_oFFs;
  187572. #endif
  187573. #if defined(PNG_READ_pCAL_SUPPORTED)
  187574. PNG_CONST PNG_pCAL;
  187575. #endif
  187576. #if defined(PNG_READ_pHYs_SUPPORTED)
  187577. PNG_CONST PNG_pHYs;
  187578. #endif
  187579. #if defined(PNG_READ_sBIT_SUPPORTED)
  187580. PNG_CONST PNG_sBIT;
  187581. #endif
  187582. #if defined(PNG_READ_sCAL_SUPPORTED)
  187583. PNG_CONST PNG_sCAL;
  187584. #endif
  187585. #if defined(PNG_READ_sPLT_SUPPORTED)
  187586. PNG_CONST PNG_sPLT;
  187587. #endif
  187588. #if defined(PNG_READ_sRGB_SUPPORTED)
  187589. PNG_CONST PNG_sRGB;
  187590. #endif
  187591. #if defined(PNG_READ_tEXt_SUPPORTED)
  187592. PNG_CONST PNG_tEXt;
  187593. #endif
  187594. #if defined(PNG_READ_tIME_SUPPORTED)
  187595. PNG_CONST PNG_tIME;
  187596. #endif
  187597. #if defined(PNG_READ_tRNS_SUPPORTED)
  187598. PNG_CONST PNG_tRNS;
  187599. #endif
  187600. #if defined(PNG_READ_zTXt_SUPPORTED)
  187601. PNG_CONST PNG_zTXt;
  187602. #endif
  187603. #endif /* PNG_USE_LOCAL_ARRAYS */
  187604. png_byte chunk_length[4];
  187605. png_uint_32 length;
  187606. png_read_data(png_ptr, chunk_length, 4);
  187607. length = png_get_uint_31(png_ptr,chunk_length);
  187608. png_reset_crc(png_ptr);
  187609. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187610. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187611. length);
  187612. /* This should be a binary subdivision search or a hash for
  187613. * matching the chunk name rather than a linear search.
  187614. */
  187615. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187616. if(png_ptr->mode & PNG_AFTER_IDAT)
  187617. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187618. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187619. png_handle_IHDR(png_ptr, info_ptr, length);
  187620. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187621. png_handle_IEND(png_ptr, info_ptr, length);
  187622. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187623. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187624. {
  187625. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187626. png_ptr->mode |= PNG_HAVE_IDAT;
  187627. png_handle_unknown(png_ptr, info_ptr, length);
  187628. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187629. png_ptr->mode |= PNG_HAVE_PLTE;
  187630. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187631. {
  187632. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187633. png_error(png_ptr, "Missing IHDR before IDAT");
  187634. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187635. !(png_ptr->mode & PNG_HAVE_PLTE))
  187636. png_error(png_ptr, "Missing PLTE before IDAT");
  187637. break;
  187638. }
  187639. }
  187640. #endif
  187641. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187642. png_handle_PLTE(png_ptr, info_ptr, length);
  187643. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187644. {
  187645. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187646. png_error(png_ptr, "Missing IHDR before IDAT");
  187647. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187648. !(png_ptr->mode & PNG_HAVE_PLTE))
  187649. png_error(png_ptr, "Missing PLTE before IDAT");
  187650. png_ptr->idat_size = length;
  187651. png_ptr->mode |= PNG_HAVE_IDAT;
  187652. break;
  187653. }
  187654. #if defined(PNG_READ_bKGD_SUPPORTED)
  187655. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187656. png_handle_bKGD(png_ptr, info_ptr, length);
  187657. #endif
  187658. #if defined(PNG_READ_cHRM_SUPPORTED)
  187659. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187660. png_handle_cHRM(png_ptr, info_ptr, length);
  187661. #endif
  187662. #if defined(PNG_READ_gAMA_SUPPORTED)
  187663. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187664. png_handle_gAMA(png_ptr, info_ptr, length);
  187665. #endif
  187666. #if defined(PNG_READ_hIST_SUPPORTED)
  187667. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187668. png_handle_hIST(png_ptr, info_ptr, length);
  187669. #endif
  187670. #if defined(PNG_READ_oFFs_SUPPORTED)
  187671. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187672. png_handle_oFFs(png_ptr, info_ptr, length);
  187673. #endif
  187674. #if defined(PNG_READ_pCAL_SUPPORTED)
  187675. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187676. png_handle_pCAL(png_ptr, info_ptr, length);
  187677. #endif
  187678. #if defined(PNG_READ_sCAL_SUPPORTED)
  187679. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187680. png_handle_sCAL(png_ptr, info_ptr, length);
  187681. #endif
  187682. #if defined(PNG_READ_pHYs_SUPPORTED)
  187683. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187684. png_handle_pHYs(png_ptr, info_ptr, length);
  187685. #endif
  187686. #if defined(PNG_READ_sBIT_SUPPORTED)
  187687. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187688. png_handle_sBIT(png_ptr, info_ptr, length);
  187689. #endif
  187690. #if defined(PNG_READ_sRGB_SUPPORTED)
  187691. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187692. png_handle_sRGB(png_ptr, info_ptr, length);
  187693. #endif
  187694. #if defined(PNG_READ_iCCP_SUPPORTED)
  187695. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187696. png_handle_iCCP(png_ptr, info_ptr, length);
  187697. #endif
  187698. #if defined(PNG_READ_sPLT_SUPPORTED)
  187699. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187700. png_handle_sPLT(png_ptr, info_ptr, length);
  187701. #endif
  187702. #if defined(PNG_READ_tEXt_SUPPORTED)
  187703. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187704. png_handle_tEXt(png_ptr, info_ptr, length);
  187705. #endif
  187706. #if defined(PNG_READ_tIME_SUPPORTED)
  187707. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187708. png_handle_tIME(png_ptr, info_ptr, length);
  187709. #endif
  187710. #if defined(PNG_READ_tRNS_SUPPORTED)
  187711. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187712. png_handle_tRNS(png_ptr, info_ptr, length);
  187713. #endif
  187714. #if defined(PNG_READ_zTXt_SUPPORTED)
  187715. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187716. png_handle_zTXt(png_ptr, info_ptr, length);
  187717. #endif
  187718. #if defined(PNG_READ_iTXt_SUPPORTED)
  187719. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187720. png_handle_iTXt(png_ptr, info_ptr, length);
  187721. #endif
  187722. else
  187723. png_handle_unknown(png_ptr, info_ptr, length);
  187724. }
  187725. }
  187726. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187727. /* optional call to update the users info_ptr structure */
  187728. void PNGAPI
  187729. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187730. {
  187731. png_debug(1, "in png_read_update_info\n");
  187732. if(png_ptr == NULL) return;
  187733. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187734. png_read_start_row(png_ptr);
  187735. else
  187736. png_warning(png_ptr,
  187737. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187738. png_read_transform_info(png_ptr, info_ptr);
  187739. }
  187740. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187741. /* Initialize palette, background, etc, after transformations
  187742. * are set, but before any reading takes place. This allows
  187743. * the user to obtain a gamma-corrected palette, for example.
  187744. * If the user doesn't call this, we will do it ourselves.
  187745. */
  187746. void PNGAPI
  187747. png_start_read_image(png_structp png_ptr)
  187748. {
  187749. png_debug(1, "in png_start_read_image\n");
  187750. if(png_ptr == NULL) return;
  187751. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187752. png_read_start_row(png_ptr);
  187753. }
  187754. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187755. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187756. void PNGAPI
  187757. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187758. {
  187759. #ifdef PNG_USE_LOCAL_ARRAYS
  187760. PNG_CONST PNG_IDAT;
  187761. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187762. 0xff};
  187763. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187764. #endif
  187765. int ret;
  187766. if(png_ptr == NULL) return;
  187767. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187768. png_ptr->row_number, png_ptr->pass);
  187769. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187770. png_read_start_row(png_ptr);
  187771. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187772. {
  187773. /* check for transforms that have been set but were defined out */
  187774. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187775. if (png_ptr->transformations & PNG_INVERT_MONO)
  187776. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187777. #endif
  187778. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187779. if (png_ptr->transformations & PNG_FILLER)
  187780. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187781. #endif
  187782. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187783. if (png_ptr->transformations & PNG_PACKSWAP)
  187784. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187785. #endif
  187786. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187787. if (png_ptr->transformations & PNG_PACK)
  187788. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187789. #endif
  187790. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187791. if (png_ptr->transformations & PNG_SHIFT)
  187792. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187793. #endif
  187794. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187795. if (png_ptr->transformations & PNG_BGR)
  187796. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187797. #endif
  187798. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187799. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187800. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187801. #endif
  187802. }
  187803. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187804. /* if interlaced and we do not need a new row, combine row and return */
  187805. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187806. {
  187807. switch (png_ptr->pass)
  187808. {
  187809. case 0:
  187810. if (png_ptr->row_number & 0x07)
  187811. {
  187812. if (dsp_row != NULL)
  187813. png_combine_row(png_ptr, dsp_row,
  187814. png_pass_dsp_mask[png_ptr->pass]);
  187815. png_read_finish_row(png_ptr);
  187816. return;
  187817. }
  187818. break;
  187819. case 1:
  187820. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187821. {
  187822. if (dsp_row != NULL)
  187823. png_combine_row(png_ptr, dsp_row,
  187824. png_pass_dsp_mask[png_ptr->pass]);
  187825. png_read_finish_row(png_ptr);
  187826. return;
  187827. }
  187828. break;
  187829. case 2:
  187830. if ((png_ptr->row_number & 0x07) != 4)
  187831. {
  187832. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187833. png_combine_row(png_ptr, dsp_row,
  187834. png_pass_dsp_mask[png_ptr->pass]);
  187835. png_read_finish_row(png_ptr);
  187836. return;
  187837. }
  187838. break;
  187839. case 3:
  187840. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187841. {
  187842. if (dsp_row != NULL)
  187843. png_combine_row(png_ptr, dsp_row,
  187844. png_pass_dsp_mask[png_ptr->pass]);
  187845. png_read_finish_row(png_ptr);
  187846. return;
  187847. }
  187848. break;
  187849. case 4:
  187850. if ((png_ptr->row_number & 3) != 2)
  187851. {
  187852. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187853. png_combine_row(png_ptr, dsp_row,
  187854. png_pass_dsp_mask[png_ptr->pass]);
  187855. png_read_finish_row(png_ptr);
  187856. return;
  187857. }
  187858. break;
  187859. case 5:
  187860. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187861. {
  187862. if (dsp_row != NULL)
  187863. png_combine_row(png_ptr, dsp_row,
  187864. png_pass_dsp_mask[png_ptr->pass]);
  187865. png_read_finish_row(png_ptr);
  187866. return;
  187867. }
  187868. break;
  187869. case 6:
  187870. if (!(png_ptr->row_number & 1))
  187871. {
  187872. png_read_finish_row(png_ptr);
  187873. return;
  187874. }
  187875. break;
  187876. }
  187877. }
  187878. #endif
  187879. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187880. png_error(png_ptr, "Invalid attempt to read row data");
  187881. png_ptr->zstream.next_out = png_ptr->row_buf;
  187882. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187883. do
  187884. {
  187885. if (!(png_ptr->zstream.avail_in))
  187886. {
  187887. while (!png_ptr->idat_size)
  187888. {
  187889. png_byte chunk_length[4];
  187890. png_crc_finish(png_ptr, 0);
  187891. png_read_data(png_ptr, chunk_length, 4);
  187892. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187893. png_reset_crc(png_ptr);
  187894. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187895. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187896. png_error(png_ptr, "Not enough image data");
  187897. }
  187898. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187899. png_ptr->zstream.next_in = png_ptr->zbuf;
  187900. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187901. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187902. png_crc_read(png_ptr, png_ptr->zbuf,
  187903. (png_size_t)png_ptr->zstream.avail_in);
  187904. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187905. }
  187906. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187907. if (ret == Z_STREAM_END)
  187908. {
  187909. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187910. png_ptr->idat_size)
  187911. png_error(png_ptr, "Extra compressed data");
  187912. png_ptr->mode |= PNG_AFTER_IDAT;
  187913. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187914. break;
  187915. }
  187916. if (ret != Z_OK)
  187917. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187918. "Decompression error");
  187919. } while (png_ptr->zstream.avail_out);
  187920. png_ptr->row_info.color_type = png_ptr->color_type;
  187921. png_ptr->row_info.width = png_ptr->iwidth;
  187922. png_ptr->row_info.channels = png_ptr->channels;
  187923. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187924. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187925. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187926. png_ptr->row_info.width);
  187927. if(png_ptr->row_buf[0])
  187928. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187929. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187930. (int)(png_ptr->row_buf[0]));
  187931. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187932. png_ptr->rowbytes + 1);
  187933. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187934. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187935. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187936. {
  187937. /* Intrapixel differencing */
  187938. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187939. }
  187940. #endif
  187941. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187942. png_do_read_transformations(png_ptr);
  187943. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187944. /* blow up interlaced rows to full size */
  187945. if (png_ptr->interlaced &&
  187946. (png_ptr->transformations & PNG_INTERLACE))
  187947. {
  187948. if (png_ptr->pass < 6)
  187949. /* old interface (pre-1.0.9):
  187950. png_do_read_interlace(&(png_ptr->row_info),
  187951. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187952. */
  187953. png_do_read_interlace(png_ptr);
  187954. if (dsp_row != NULL)
  187955. png_combine_row(png_ptr, dsp_row,
  187956. png_pass_dsp_mask[png_ptr->pass]);
  187957. if (row != NULL)
  187958. png_combine_row(png_ptr, row,
  187959. png_pass_mask[png_ptr->pass]);
  187960. }
  187961. else
  187962. #endif
  187963. {
  187964. if (row != NULL)
  187965. png_combine_row(png_ptr, row, 0xff);
  187966. if (dsp_row != NULL)
  187967. png_combine_row(png_ptr, dsp_row, 0xff);
  187968. }
  187969. png_read_finish_row(png_ptr);
  187970. if (png_ptr->read_row_fn != NULL)
  187971. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187972. }
  187973. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187974. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187975. /* Read one or more rows of image data. If the image is interlaced,
  187976. * and png_set_interlace_handling() has been called, the rows need to
  187977. * contain the contents of the rows from the previous pass. If the
  187978. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187979. * called, the rows contents must be initialized to the contents of the
  187980. * screen.
  187981. *
  187982. * "row" holds the actual image, and pixels are placed in it
  187983. * as they arrive. If the image is displayed after each pass, it will
  187984. * appear to "sparkle" in. "display_row" can be used to display a
  187985. * "chunky" progressive image, with finer detail added as it becomes
  187986. * available. If you do not want this "chunky" display, you may pass
  187987. * NULL for display_row. If you do not want the sparkle display, and
  187988. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187989. * If you have called png_handle_alpha(), and the image has either an
  187990. * alpha channel or a transparency chunk, you must provide a buffer for
  187991. * rows. In this case, you do not have to provide a display_row buffer
  187992. * also, but you may. If the image is not interlaced, or if you have
  187993. * not called png_set_interlace_handling(), the display_row buffer will
  187994. * be ignored, so pass NULL to it.
  187995. *
  187996. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187997. */
  187998. void PNGAPI
  187999. png_read_rows(png_structp png_ptr, png_bytepp row,
  188000. png_bytepp display_row, png_uint_32 num_rows)
  188001. {
  188002. png_uint_32 i;
  188003. png_bytepp rp;
  188004. png_bytepp dp;
  188005. png_debug(1, "in png_read_rows\n");
  188006. if(png_ptr == NULL) return;
  188007. rp = row;
  188008. dp = display_row;
  188009. if (rp != NULL && dp != NULL)
  188010. for (i = 0; i < num_rows; i++)
  188011. {
  188012. png_bytep rptr = *rp++;
  188013. png_bytep dptr = *dp++;
  188014. png_read_row(png_ptr, rptr, dptr);
  188015. }
  188016. else if(rp != NULL)
  188017. for (i = 0; i < num_rows; i++)
  188018. {
  188019. png_bytep rptr = *rp;
  188020. png_read_row(png_ptr, rptr, png_bytep_NULL);
  188021. rp++;
  188022. }
  188023. else if(dp != NULL)
  188024. for (i = 0; i < num_rows; i++)
  188025. {
  188026. png_bytep dptr = *dp;
  188027. png_read_row(png_ptr, png_bytep_NULL, dptr);
  188028. dp++;
  188029. }
  188030. }
  188031. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188032. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188033. /* Read the entire image. If the image has an alpha channel or a tRNS
  188034. * chunk, and you have called png_handle_alpha()[*], you will need to
  188035. * initialize the image to the current image that PNG will be overlaying.
  188036. * We set the num_rows again here, in case it was incorrectly set in
  188037. * png_read_start_row() by a call to png_read_update_info() or
  188038. * png_start_read_image() if png_set_interlace_handling() wasn't called
  188039. * prior to either of these functions like it should have been. You can
  188040. * only call this function once. If you desire to have an image for
  188041. * each pass of a interlaced image, use png_read_rows() instead.
  188042. *
  188043. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188044. */
  188045. void PNGAPI
  188046. png_read_image(png_structp png_ptr, png_bytepp image)
  188047. {
  188048. png_uint_32 i,image_height;
  188049. int pass, j;
  188050. png_bytepp rp;
  188051. png_debug(1, "in png_read_image\n");
  188052. if(png_ptr == NULL) return;
  188053. #ifdef PNG_READ_INTERLACING_SUPPORTED
  188054. pass = png_set_interlace_handling(png_ptr);
  188055. #else
  188056. if (png_ptr->interlaced)
  188057. png_error(png_ptr,
  188058. "Cannot read interlaced image -- interlace handler disabled.");
  188059. pass = 1;
  188060. #endif
  188061. image_height=png_ptr->height;
  188062. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  188063. for (j = 0; j < pass; j++)
  188064. {
  188065. rp = image;
  188066. for (i = 0; i < image_height; i++)
  188067. {
  188068. png_read_row(png_ptr, *rp, png_bytep_NULL);
  188069. rp++;
  188070. }
  188071. }
  188072. }
  188073. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188074. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188075. /* Read the end of the PNG file. Will not read past the end of the
  188076. * file, will verify the end is accurate, and will read any comments
  188077. * or time information at the end of the file, if info is not NULL.
  188078. */
  188079. void PNGAPI
  188080. png_read_end(png_structp png_ptr, png_infop info_ptr)
  188081. {
  188082. png_byte chunk_length[4];
  188083. png_uint_32 length;
  188084. png_debug(1, "in png_read_end\n");
  188085. if(png_ptr == NULL) return;
  188086. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  188087. do
  188088. {
  188089. #ifdef PNG_USE_LOCAL_ARRAYS
  188090. PNG_CONST PNG_IHDR;
  188091. PNG_CONST PNG_IDAT;
  188092. PNG_CONST PNG_IEND;
  188093. PNG_CONST PNG_PLTE;
  188094. #if defined(PNG_READ_bKGD_SUPPORTED)
  188095. PNG_CONST PNG_bKGD;
  188096. #endif
  188097. #if defined(PNG_READ_cHRM_SUPPORTED)
  188098. PNG_CONST PNG_cHRM;
  188099. #endif
  188100. #if defined(PNG_READ_gAMA_SUPPORTED)
  188101. PNG_CONST PNG_gAMA;
  188102. #endif
  188103. #if defined(PNG_READ_hIST_SUPPORTED)
  188104. PNG_CONST PNG_hIST;
  188105. #endif
  188106. #if defined(PNG_READ_iCCP_SUPPORTED)
  188107. PNG_CONST PNG_iCCP;
  188108. #endif
  188109. #if defined(PNG_READ_iTXt_SUPPORTED)
  188110. PNG_CONST PNG_iTXt;
  188111. #endif
  188112. #if defined(PNG_READ_oFFs_SUPPORTED)
  188113. PNG_CONST PNG_oFFs;
  188114. #endif
  188115. #if defined(PNG_READ_pCAL_SUPPORTED)
  188116. PNG_CONST PNG_pCAL;
  188117. #endif
  188118. #if defined(PNG_READ_pHYs_SUPPORTED)
  188119. PNG_CONST PNG_pHYs;
  188120. #endif
  188121. #if defined(PNG_READ_sBIT_SUPPORTED)
  188122. PNG_CONST PNG_sBIT;
  188123. #endif
  188124. #if defined(PNG_READ_sCAL_SUPPORTED)
  188125. PNG_CONST PNG_sCAL;
  188126. #endif
  188127. #if defined(PNG_READ_sPLT_SUPPORTED)
  188128. PNG_CONST PNG_sPLT;
  188129. #endif
  188130. #if defined(PNG_READ_sRGB_SUPPORTED)
  188131. PNG_CONST PNG_sRGB;
  188132. #endif
  188133. #if defined(PNG_READ_tEXt_SUPPORTED)
  188134. PNG_CONST PNG_tEXt;
  188135. #endif
  188136. #if defined(PNG_READ_tIME_SUPPORTED)
  188137. PNG_CONST PNG_tIME;
  188138. #endif
  188139. #if defined(PNG_READ_tRNS_SUPPORTED)
  188140. PNG_CONST PNG_tRNS;
  188141. #endif
  188142. #if defined(PNG_READ_zTXt_SUPPORTED)
  188143. PNG_CONST PNG_zTXt;
  188144. #endif
  188145. #endif /* PNG_USE_LOCAL_ARRAYS */
  188146. png_read_data(png_ptr, chunk_length, 4);
  188147. length = png_get_uint_31(png_ptr,chunk_length);
  188148. png_reset_crc(png_ptr);
  188149. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188150. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188151. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188152. png_handle_IHDR(png_ptr, info_ptr, length);
  188153. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188154. png_handle_IEND(png_ptr, info_ptr, length);
  188155. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188156. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188157. {
  188158. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188159. {
  188160. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188161. png_error(png_ptr, "Too many IDAT's found");
  188162. }
  188163. png_handle_unknown(png_ptr, info_ptr, length);
  188164. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188165. png_ptr->mode |= PNG_HAVE_PLTE;
  188166. }
  188167. #endif
  188168. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188169. {
  188170. /* Zero length IDATs are legal after the last IDAT has been
  188171. * read, but not after other chunks have been read.
  188172. */
  188173. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188174. png_error(png_ptr, "Too many IDAT's found");
  188175. png_crc_finish(png_ptr, length);
  188176. }
  188177. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188178. png_handle_PLTE(png_ptr, info_ptr, length);
  188179. #if defined(PNG_READ_bKGD_SUPPORTED)
  188180. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188181. png_handle_bKGD(png_ptr, info_ptr, length);
  188182. #endif
  188183. #if defined(PNG_READ_cHRM_SUPPORTED)
  188184. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188185. png_handle_cHRM(png_ptr, info_ptr, length);
  188186. #endif
  188187. #if defined(PNG_READ_gAMA_SUPPORTED)
  188188. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188189. png_handle_gAMA(png_ptr, info_ptr, length);
  188190. #endif
  188191. #if defined(PNG_READ_hIST_SUPPORTED)
  188192. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188193. png_handle_hIST(png_ptr, info_ptr, length);
  188194. #endif
  188195. #if defined(PNG_READ_oFFs_SUPPORTED)
  188196. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188197. png_handle_oFFs(png_ptr, info_ptr, length);
  188198. #endif
  188199. #if defined(PNG_READ_pCAL_SUPPORTED)
  188200. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188201. png_handle_pCAL(png_ptr, info_ptr, length);
  188202. #endif
  188203. #if defined(PNG_READ_sCAL_SUPPORTED)
  188204. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188205. png_handle_sCAL(png_ptr, info_ptr, length);
  188206. #endif
  188207. #if defined(PNG_READ_pHYs_SUPPORTED)
  188208. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188209. png_handle_pHYs(png_ptr, info_ptr, length);
  188210. #endif
  188211. #if defined(PNG_READ_sBIT_SUPPORTED)
  188212. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188213. png_handle_sBIT(png_ptr, info_ptr, length);
  188214. #endif
  188215. #if defined(PNG_READ_sRGB_SUPPORTED)
  188216. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188217. png_handle_sRGB(png_ptr, info_ptr, length);
  188218. #endif
  188219. #if defined(PNG_READ_iCCP_SUPPORTED)
  188220. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188221. png_handle_iCCP(png_ptr, info_ptr, length);
  188222. #endif
  188223. #if defined(PNG_READ_sPLT_SUPPORTED)
  188224. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188225. png_handle_sPLT(png_ptr, info_ptr, length);
  188226. #endif
  188227. #if defined(PNG_READ_tEXt_SUPPORTED)
  188228. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188229. png_handle_tEXt(png_ptr, info_ptr, length);
  188230. #endif
  188231. #if defined(PNG_READ_tIME_SUPPORTED)
  188232. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188233. png_handle_tIME(png_ptr, info_ptr, length);
  188234. #endif
  188235. #if defined(PNG_READ_tRNS_SUPPORTED)
  188236. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188237. png_handle_tRNS(png_ptr, info_ptr, length);
  188238. #endif
  188239. #if defined(PNG_READ_zTXt_SUPPORTED)
  188240. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188241. png_handle_zTXt(png_ptr, info_ptr, length);
  188242. #endif
  188243. #if defined(PNG_READ_iTXt_SUPPORTED)
  188244. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188245. png_handle_iTXt(png_ptr, info_ptr, length);
  188246. #endif
  188247. else
  188248. png_handle_unknown(png_ptr, info_ptr, length);
  188249. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188250. }
  188251. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188252. /* free all memory used by the read */
  188253. void PNGAPI
  188254. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188255. png_infopp end_info_ptr_ptr)
  188256. {
  188257. png_structp png_ptr = NULL;
  188258. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188259. #ifdef PNG_USER_MEM_SUPPORTED
  188260. png_free_ptr free_fn;
  188261. png_voidp mem_ptr;
  188262. #endif
  188263. png_debug(1, "in png_destroy_read_struct\n");
  188264. if (png_ptr_ptr != NULL)
  188265. png_ptr = *png_ptr_ptr;
  188266. if (info_ptr_ptr != NULL)
  188267. info_ptr = *info_ptr_ptr;
  188268. if (end_info_ptr_ptr != NULL)
  188269. end_info_ptr = *end_info_ptr_ptr;
  188270. #ifdef PNG_USER_MEM_SUPPORTED
  188271. free_fn = png_ptr->free_fn;
  188272. mem_ptr = png_ptr->mem_ptr;
  188273. #endif
  188274. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188275. if (info_ptr != NULL)
  188276. {
  188277. #if defined(PNG_TEXT_SUPPORTED)
  188278. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188279. #endif
  188280. #ifdef PNG_USER_MEM_SUPPORTED
  188281. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188282. (png_voidp)mem_ptr);
  188283. #else
  188284. png_destroy_struct((png_voidp)info_ptr);
  188285. #endif
  188286. *info_ptr_ptr = NULL;
  188287. }
  188288. if (end_info_ptr != NULL)
  188289. {
  188290. #if defined(PNG_READ_TEXT_SUPPORTED)
  188291. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188292. #endif
  188293. #ifdef PNG_USER_MEM_SUPPORTED
  188294. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188295. (png_voidp)mem_ptr);
  188296. #else
  188297. png_destroy_struct((png_voidp)end_info_ptr);
  188298. #endif
  188299. *end_info_ptr_ptr = NULL;
  188300. }
  188301. if (png_ptr != NULL)
  188302. {
  188303. #ifdef PNG_USER_MEM_SUPPORTED
  188304. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188305. (png_voidp)mem_ptr);
  188306. #else
  188307. png_destroy_struct((png_voidp)png_ptr);
  188308. #endif
  188309. *png_ptr_ptr = NULL;
  188310. }
  188311. }
  188312. /* free all memory used by the read (old method) */
  188313. void /* PRIVATE */
  188314. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188315. {
  188316. #ifdef PNG_SETJMP_SUPPORTED
  188317. jmp_buf tmp_jmp;
  188318. #endif
  188319. png_error_ptr error_fn;
  188320. png_error_ptr warning_fn;
  188321. png_voidp error_ptr;
  188322. #ifdef PNG_USER_MEM_SUPPORTED
  188323. png_free_ptr free_fn;
  188324. #endif
  188325. png_debug(1, "in png_read_destroy\n");
  188326. if (info_ptr != NULL)
  188327. png_info_destroy(png_ptr, info_ptr);
  188328. if (end_info_ptr != NULL)
  188329. png_info_destroy(png_ptr, end_info_ptr);
  188330. png_free(png_ptr, png_ptr->zbuf);
  188331. png_free(png_ptr, png_ptr->big_row_buf);
  188332. png_free(png_ptr, png_ptr->prev_row);
  188333. #if defined(PNG_READ_DITHER_SUPPORTED)
  188334. png_free(png_ptr, png_ptr->palette_lookup);
  188335. png_free(png_ptr, png_ptr->dither_index);
  188336. #endif
  188337. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188338. png_free(png_ptr, png_ptr->gamma_table);
  188339. #endif
  188340. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188341. png_free(png_ptr, png_ptr->gamma_from_1);
  188342. png_free(png_ptr, png_ptr->gamma_to_1);
  188343. #endif
  188344. #ifdef PNG_FREE_ME_SUPPORTED
  188345. if (png_ptr->free_me & PNG_FREE_PLTE)
  188346. png_zfree(png_ptr, png_ptr->palette);
  188347. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188348. #else
  188349. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188350. png_zfree(png_ptr, png_ptr->palette);
  188351. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188352. #endif
  188353. #if defined(PNG_tRNS_SUPPORTED) || \
  188354. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188355. #ifdef PNG_FREE_ME_SUPPORTED
  188356. if (png_ptr->free_me & PNG_FREE_TRNS)
  188357. png_free(png_ptr, png_ptr->trans);
  188358. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188359. #else
  188360. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188361. png_free(png_ptr, png_ptr->trans);
  188362. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188363. #endif
  188364. #endif
  188365. #if defined(PNG_READ_hIST_SUPPORTED)
  188366. #ifdef PNG_FREE_ME_SUPPORTED
  188367. if (png_ptr->free_me & PNG_FREE_HIST)
  188368. png_free(png_ptr, png_ptr->hist);
  188369. png_ptr->free_me &= ~PNG_FREE_HIST;
  188370. #else
  188371. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188372. png_free(png_ptr, png_ptr->hist);
  188373. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188374. #endif
  188375. #endif
  188376. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188377. if (png_ptr->gamma_16_table != NULL)
  188378. {
  188379. int i;
  188380. int istop = (1 << (8 - png_ptr->gamma_shift));
  188381. for (i = 0; i < istop; i++)
  188382. {
  188383. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188384. }
  188385. png_free(png_ptr, png_ptr->gamma_16_table);
  188386. }
  188387. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188388. if (png_ptr->gamma_16_from_1 != NULL)
  188389. {
  188390. int i;
  188391. int istop = (1 << (8 - png_ptr->gamma_shift));
  188392. for (i = 0; i < istop; i++)
  188393. {
  188394. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188395. }
  188396. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188397. }
  188398. if (png_ptr->gamma_16_to_1 != NULL)
  188399. {
  188400. int i;
  188401. int istop = (1 << (8 - png_ptr->gamma_shift));
  188402. for (i = 0; i < istop; i++)
  188403. {
  188404. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188405. }
  188406. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188407. }
  188408. #endif
  188409. #endif
  188410. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188411. png_free(png_ptr, png_ptr->time_buffer);
  188412. #endif
  188413. inflateEnd(&png_ptr->zstream);
  188414. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188415. png_free(png_ptr, png_ptr->save_buffer);
  188416. #endif
  188417. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188418. #ifdef PNG_TEXT_SUPPORTED
  188419. png_free(png_ptr, png_ptr->current_text);
  188420. #endif /* PNG_TEXT_SUPPORTED */
  188421. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188422. /* Save the important info out of the png_struct, in case it is
  188423. * being used again.
  188424. */
  188425. #ifdef PNG_SETJMP_SUPPORTED
  188426. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188427. #endif
  188428. error_fn = png_ptr->error_fn;
  188429. warning_fn = png_ptr->warning_fn;
  188430. error_ptr = png_ptr->error_ptr;
  188431. #ifdef PNG_USER_MEM_SUPPORTED
  188432. free_fn = png_ptr->free_fn;
  188433. #endif
  188434. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188435. png_ptr->error_fn = error_fn;
  188436. png_ptr->warning_fn = warning_fn;
  188437. png_ptr->error_ptr = error_ptr;
  188438. #ifdef PNG_USER_MEM_SUPPORTED
  188439. png_ptr->free_fn = free_fn;
  188440. #endif
  188441. #ifdef PNG_SETJMP_SUPPORTED
  188442. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188443. #endif
  188444. }
  188445. void PNGAPI
  188446. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188447. {
  188448. if(png_ptr == NULL) return;
  188449. png_ptr->read_row_fn = read_row_fn;
  188450. }
  188451. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188452. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188453. void PNGAPI
  188454. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188455. int transforms,
  188456. voidp params)
  188457. {
  188458. int row;
  188459. if(png_ptr == NULL) return;
  188460. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188461. /* invert the alpha channel from opacity to transparency
  188462. */
  188463. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188464. png_set_invert_alpha(png_ptr);
  188465. #endif
  188466. /* png_read_info() gives us all of the information from the
  188467. * PNG file before the first IDAT (image data chunk).
  188468. */
  188469. png_read_info(png_ptr, info_ptr);
  188470. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188471. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188472. /* -------------- image transformations start here ------------------- */
  188473. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188474. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188475. */
  188476. if (transforms & PNG_TRANSFORM_STRIP_16)
  188477. png_set_strip_16(png_ptr);
  188478. #endif
  188479. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188480. /* Strip alpha bytes from the input data without combining with
  188481. * the background (not recommended).
  188482. */
  188483. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188484. png_set_strip_alpha(png_ptr);
  188485. #endif
  188486. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188487. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188488. * byte into separate bytes (useful for paletted and grayscale images).
  188489. */
  188490. if (transforms & PNG_TRANSFORM_PACKING)
  188491. png_set_packing(png_ptr);
  188492. #endif
  188493. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188494. /* Change the order of packed pixels to least significant bit first
  188495. * (not useful if you are using png_set_packing).
  188496. */
  188497. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188498. png_set_packswap(png_ptr);
  188499. #endif
  188500. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188501. /* Expand paletted colors into true RGB triplets
  188502. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188503. * Expand paletted or RGB images with transparency to full alpha
  188504. * channels so the data will be available as RGBA quartets.
  188505. */
  188506. if (transforms & PNG_TRANSFORM_EXPAND)
  188507. if ((png_ptr->bit_depth < 8) ||
  188508. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188509. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188510. png_set_expand(png_ptr);
  188511. #endif
  188512. /* We don't handle background color or gamma transformation or dithering.
  188513. */
  188514. #if defined(PNG_READ_INVERT_SUPPORTED)
  188515. /* invert monochrome files to have 0 as white and 1 as black
  188516. */
  188517. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188518. png_set_invert_mono(png_ptr);
  188519. #endif
  188520. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188521. /* If you want to shift the pixel values from the range [0,255] or
  188522. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188523. * colors were originally in:
  188524. */
  188525. if ((transforms & PNG_TRANSFORM_SHIFT)
  188526. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188527. {
  188528. png_color_8p sig_bit;
  188529. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188530. png_set_shift(png_ptr, sig_bit);
  188531. }
  188532. #endif
  188533. #if defined(PNG_READ_BGR_SUPPORTED)
  188534. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188535. */
  188536. if (transforms & PNG_TRANSFORM_BGR)
  188537. png_set_bgr(png_ptr);
  188538. #endif
  188539. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188540. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188541. */
  188542. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188543. png_set_swap_alpha(png_ptr);
  188544. #endif
  188545. #if defined(PNG_READ_SWAP_SUPPORTED)
  188546. /* swap bytes of 16 bit files to least significant byte first
  188547. */
  188548. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188549. png_set_swap(png_ptr);
  188550. #endif
  188551. /* We don't handle adding filler bytes */
  188552. /* Optional call to gamma correct and add the background to the palette
  188553. * and update info structure. REQUIRED if you are expecting libpng to
  188554. * update the palette for you (i.e., you selected such a transform above).
  188555. */
  188556. png_read_update_info(png_ptr, info_ptr);
  188557. /* -------------- image transformations end here ------------------- */
  188558. #ifdef PNG_FREE_ME_SUPPORTED
  188559. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188560. #endif
  188561. if(info_ptr->row_pointers == NULL)
  188562. {
  188563. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188564. info_ptr->height * png_sizeof(png_bytep));
  188565. #ifdef PNG_FREE_ME_SUPPORTED
  188566. info_ptr->free_me |= PNG_FREE_ROWS;
  188567. #endif
  188568. for (row = 0; row < (int)info_ptr->height; row++)
  188569. {
  188570. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188571. png_get_rowbytes(png_ptr, info_ptr));
  188572. }
  188573. }
  188574. png_read_image(png_ptr, info_ptr->row_pointers);
  188575. info_ptr->valid |= PNG_INFO_IDAT;
  188576. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188577. png_read_end(png_ptr, info_ptr);
  188578. transforms = transforms; /* quiet compiler warnings */
  188579. params = params;
  188580. }
  188581. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188582. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188583. #endif /* PNG_READ_SUPPORTED */
  188584. /*** End of inlined file: pngread.c ***/
  188585. /*** Start of inlined file: pngpread.c ***/
  188586. /* pngpread.c - read a png file in push mode
  188587. *
  188588. * Last changed in libpng 1.2.21 October 4, 2007
  188589. * For conditions of distribution and use, see copyright notice in png.h
  188590. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188591. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188592. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188593. */
  188594. #define PNG_INTERNAL
  188595. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188596. /* push model modes */
  188597. #define PNG_READ_SIG_MODE 0
  188598. #define PNG_READ_CHUNK_MODE 1
  188599. #define PNG_READ_IDAT_MODE 2
  188600. #define PNG_SKIP_MODE 3
  188601. #define PNG_READ_tEXt_MODE 4
  188602. #define PNG_READ_zTXt_MODE 5
  188603. #define PNG_READ_DONE_MODE 6
  188604. #define PNG_READ_iTXt_MODE 7
  188605. #define PNG_ERROR_MODE 8
  188606. void PNGAPI
  188607. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188608. png_bytep buffer, png_size_t buffer_size)
  188609. {
  188610. if(png_ptr == NULL) return;
  188611. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188612. while (png_ptr->buffer_size)
  188613. {
  188614. png_process_some_data(png_ptr, info_ptr);
  188615. }
  188616. }
  188617. /* What we do with the incoming data depends on what we were previously
  188618. * doing before we ran out of data...
  188619. */
  188620. void /* PRIVATE */
  188621. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188622. {
  188623. if(png_ptr == NULL) return;
  188624. switch (png_ptr->process_mode)
  188625. {
  188626. case PNG_READ_SIG_MODE:
  188627. {
  188628. png_push_read_sig(png_ptr, info_ptr);
  188629. break;
  188630. }
  188631. case PNG_READ_CHUNK_MODE:
  188632. {
  188633. png_push_read_chunk(png_ptr, info_ptr);
  188634. break;
  188635. }
  188636. case PNG_READ_IDAT_MODE:
  188637. {
  188638. png_push_read_IDAT(png_ptr);
  188639. break;
  188640. }
  188641. #if defined(PNG_READ_tEXt_SUPPORTED)
  188642. case PNG_READ_tEXt_MODE:
  188643. {
  188644. png_push_read_tEXt(png_ptr, info_ptr);
  188645. break;
  188646. }
  188647. #endif
  188648. #if defined(PNG_READ_zTXt_SUPPORTED)
  188649. case PNG_READ_zTXt_MODE:
  188650. {
  188651. png_push_read_zTXt(png_ptr, info_ptr);
  188652. break;
  188653. }
  188654. #endif
  188655. #if defined(PNG_READ_iTXt_SUPPORTED)
  188656. case PNG_READ_iTXt_MODE:
  188657. {
  188658. png_push_read_iTXt(png_ptr, info_ptr);
  188659. break;
  188660. }
  188661. #endif
  188662. case PNG_SKIP_MODE:
  188663. {
  188664. png_push_crc_finish(png_ptr);
  188665. break;
  188666. }
  188667. default:
  188668. {
  188669. png_ptr->buffer_size = 0;
  188670. break;
  188671. }
  188672. }
  188673. }
  188674. /* Read any remaining signature bytes from the stream and compare them with
  188675. * the correct PNG signature. It is possible that this routine is called
  188676. * with bytes already read from the signature, either because they have been
  188677. * checked by the calling application, or because of multiple calls to this
  188678. * routine.
  188679. */
  188680. void /* PRIVATE */
  188681. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188682. {
  188683. png_size_t num_checked = png_ptr->sig_bytes,
  188684. num_to_check = 8 - num_checked;
  188685. if (png_ptr->buffer_size < num_to_check)
  188686. {
  188687. num_to_check = png_ptr->buffer_size;
  188688. }
  188689. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188690. num_to_check);
  188691. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188692. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188693. {
  188694. if (num_checked < 4 &&
  188695. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188696. png_error(png_ptr, "Not a PNG file");
  188697. else
  188698. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188699. }
  188700. else
  188701. {
  188702. if (png_ptr->sig_bytes >= 8)
  188703. {
  188704. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188705. }
  188706. }
  188707. }
  188708. void /* PRIVATE */
  188709. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188710. {
  188711. #ifdef PNG_USE_LOCAL_ARRAYS
  188712. PNG_CONST PNG_IHDR;
  188713. PNG_CONST PNG_IDAT;
  188714. PNG_CONST PNG_IEND;
  188715. PNG_CONST PNG_PLTE;
  188716. #if defined(PNG_READ_bKGD_SUPPORTED)
  188717. PNG_CONST PNG_bKGD;
  188718. #endif
  188719. #if defined(PNG_READ_cHRM_SUPPORTED)
  188720. PNG_CONST PNG_cHRM;
  188721. #endif
  188722. #if defined(PNG_READ_gAMA_SUPPORTED)
  188723. PNG_CONST PNG_gAMA;
  188724. #endif
  188725. #if defined(PNG_READ_hIST_SUPPORTED)
  188726. PNG_CONST PNG_hIST;
  188727. #endif
  188728. #if defined(PNG_READ_iCCP_SUPPORTED)
  188729. PNG_CONST PNG_iCCP;
  188730. #endif
  188731. #if defined(PNG_READ_iTXt_SUPPORTED)
  188732. PNG_CONST PNG_iTXt;
  188733. #endif
  188734. #if defined(PNG_READ_oFFs_SUPPORTED)
  188735. PNG_CONST PNG_oFFs;
  188736. #endif
  188737. #if defined(PNG_READ_pCAL_SUPPORTED)
  188738. PNG_CONST PNG_pCAL;
  188739. #endif
  188740. #if defined(PNG_READ_pHYs_SUPPORTED)
  188741. PNG_CONST PNG_pHYs;
  188742. #endif
  188743. #if defined(PNG_READ_sBIT_SUPPORTED)
  188744. PNG_CONST PNG_sBIT;
  188745. #endif
  188746. #if defined(PNG_READ_sCAL_SUPPORTED)
  188747. PNG_CONST PNG_sCAL;
  188748. #endif
  188749. #if defined(PNG_READ_sRGB_SUPPORTED)
  188750. PNG_CONST PNG_sRGB;
  188751. #endif
  188752. #if defined(PNG_READ_sPLT_SUPPORTED)
  188753. PNG_CONST PNG_sPLT;
  188754. #endif
  188755. #if defined(PNG_READ_tEXt_SUPPORTED)
  188756. PNG_CONST PNG_tEXt;
  188757. #endif
  188758. #if defined(PNG_READ_tIME_SUPPORTED)
  188759. PNG_CONST PNG_tIME;
  188760. #endif
  188761. #if defined(PNG_READ_tRNS_SUPPORTED)
  188762. PNG_CONST PNG_tRNS;
  188763. #endif
  188764. #if defined(PNG_READ_zTXt_SUPPORTED)
  188765. PNG_CONST PNG_zTXt;
  188766. #endif
  188767. #endif /* PNG_USE_LOCAL_ARRAYS */
  188768. /* First we make sure we have enough data for the 4 byte chunk name
  188769. * and the 4 byte chunk length before proceeding with decoding the
  188770. * chunk data. To fully decode each of these chunks, we also make
  188771. * sure we have enough data in the buffer for the 4 byte CRC at the
  188772. * end of every chunk (except IDAT, which is handled separately).
  188773. */
  188774. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188775. {
  188776. png_byte chunk_length[4];
  188777. if (png_ptr->buffer_size < 8)
  188778. {
  188779. png_push_save_buffer(png_ptr);
  188780. return;
  188781. }
  188782. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188783. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188784. png_reset_crc(png_ptr);
  188785. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188786. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188787. }
  188788. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188789. if(png_ptr->mode & PNG_AFTER_IDAT)
  188790. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188791. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188792. {
  188793. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188794. {
  188795. png_push_save_buffer(png_ptr);
  188796. return;
  188797. }
  188798. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188799. }
  188800. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188801. {
  188802. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188803. {
  188804. png_push_save_buffer(png_ptr);
  188805. return;
  188806. }
  188807. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188808. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188809. png_push_have_end(png_ptr, info_ptr);
  188810. }
  188811. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188812. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188813. {
  188814. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188815. {
  188816. png_push_save_buffer(png_ptr);
  188817. return;
  188818. }
  188819. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188820. png_ptr->mode |= PNG_HAVE_IDAT;
  188821. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188822. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188823. png_ptr->mode |= PNG_HAVE_PLTE;
  188824. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188825. {
  188826. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188827. png_error(png_ptr, "Missing IHDR before IDAT");
  188828. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188829. !(png_ptr->mode & PNG_HAVE_PLTE))
  188830. png_error(png_ptr, "Missing PLTE before IDAT");
  188831. }
  188832. }
  188833. #endif
  188834. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188835. {
  188836. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188837. {
  188838. png_push_save_buffer(png_ptr);
  188839. return;
  188840. }
  188841. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188842. }
  188843. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188844. {
  188845. /* If we reach an IDAT chunk, this means we have read all of the
  188846. * header chunks, and we can start reading the image (or if this
  188847. * is called after the image has been read - we have an error).
  188848. */
  188849. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188850. png_error(png_ptr, "Missing IHDR before IDAT");
  188851. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188852. !(png_ptr->mode & PNG_HAVE_PLTE))
  188853. png_error(png_ptr, "Missing PLTE before IDAT");
  188854. if (png_ptr->mode & PNG_HAVE_IDAT)
  188855. {
  188856. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188857. if (png_ptr->push_length == 0)
  188858. return;
  188859. if (png_ptr->mode & PNG_AFTER_IDAT)
  188860. png_error(png_ptr, "Too many IDAT's found");
  188861. }
  188862. png_ptr->idat_size = png_ptr->push_length;
  188863. png_ptr->mode |= PNG_HAVE_IDAT;
  188864. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188865. png_push_have_info(png_ptr, info_ptr);
  188866. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188867. png_ptr->zstream.next_out = png_ptr->row_buf;
  188868. return;
  188869. }
  188870. #if defined(PNG_READ_gAMA_SUPPORTED)
  188871. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188872. {
  188873. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188874. {
  188875. png_push_save_buffer(png_ptr);
  188876. return;
  188877. }
  188878. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188879. }
  188880. #endif
  188881. #if defined(PNG_READ_sBIT_SUPPORTED)
  188882. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188883. {
  188884. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188885. {
  188886. png_push_save_buffer(png_ptr);
  188887. return;
  188888. }
  188889. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188890. }
  188891. #endif
  188892. #if defined(PNG_READ_cHRM_SUPPORTED)
  188893. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188894. {
  188895. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188896. {
  188897. png_push_save_buffer(png_ptr);
  188898. return;
  188899. }
  188900. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188901. }
  188902. #endif
  188903. #if defined(PNG_READ_sRGB_SUPPORTED)
  188904. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188905. {
  188906. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188907. {
  188908. png_push_save_buffer(png_ptr);
  188909. return;
  188910. }
  188911. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188912. }
  188913. #endif
  188914. #if defined(PNG_READ_iCCP_SUPPORTED)
  188915. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188916. {
  188917. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188918. {
  188919. png_push_save_buffer(png_ptr);
  188920. return;
  188921. }
  188922. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188923. }
  188924. #endif
  188925. #if defined(PNG_READ_sPLT_SUPPORTED)
  188926. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188927. {
  188928. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188929. {
  188930. png_push_save_buffer(png_ptr);
  188931. return;
  188932. }
  188933. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188934. }
  188935. #endif
  188936. #if defined(PNG_READ_tRNS_SUPPORTED)
  188937. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188938. {
  188939. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188940. {
  188941. png_push_save_buffer(png_ptr);
  188942. return;
  188943. }
  188944. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188945. }
  188946. #endif
  188947. #if defined(PNG_READ_bKGD_SUPPORTED)
  188948. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188949. {
  188950. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188951. {
  188952. png_push_save_buffer(png_ptr);
  188953. return;
  188954. }
  188955. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188956. }
  188957. #endif
  188958. #if defined(PNG_READ_hIST_SUPPORTED)
  188959. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188960. {
  188961. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188962. {
  188963. png_push_save_buffer(png_ptr);
  188964. return;
  188965. }
  188966. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188967. }
  188968. #endif
  188969. #if defined(PNG_READ_pHYs_SUPPORTED)
  188970. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188971. {
  188972. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188973. {
  188974. png_push_save_buffer(png_ptr);
  188975. return;
  188976. }
  188977. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188978. }
  188979. #endif
  188980. #if defined(PNG_READ_oFFs_SUPPORTED)
  188981. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188982. {
  188983. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188984. {
  188985. png_push_save_buffer(png_ptr);
  188986. return;
  188987. }
  188988. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188989. }
  188990. #endif
  188991. #if defined(PNG_READ_pCAL_SUPPORTED)
  188992. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188993. {
  188994. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188995. {
  188996. png_push_save_buffer(png_ptr);
  188997. return;
  188998. }
  188999. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  189000. }
  189001. #endif
  189002. #if defined(PNG_READ_sCAL_SUPPORTED)
  189003. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  189004. {
  189005. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189006. {
  189007. png_push_save_buffer(png_ptr);
  189008. return;
  189009. }
  189010. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  189011. }
  189012. #endif
  189013. #if defined(PNG_READ_tIME_SUPPORTED)
  189014. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  189015. {
  189016. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189017. {
  189018. png_push_save_buffer(png_ptr);
  189019. return;
  189020. }
  189021. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  189022. }
  189023. #endif
  189024. #if defined(PNG_READ_tEXt_SUPPORTED)
  189025. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  189026. {
  189027. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189028. {
  189029. png_push_save_buffer(png_ptr);
  189030. return;
  189031. }
  189032. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  189033. }
  189034. #endif
  189035. #if defined(PNG_READ_zTXt_SUPPORTED)
  189036. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  189037. {
  189038. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189039. {
  189040. png_push_save_buffer(png_ptr);
  189041. return;
  189042. }
  189043. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  189044. }
  189045. #endif
  189046. #if defined(PNG_READ_iTXt_SUPPORTED)
  189047. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  189048. {
  189049. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189050. {
  189051. png_push_save_buffer(png_ptr);
  189052. return;
  189053. }
  189054. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  189055. }
  189056. #endif
  189057. else
  189058. {
  189059. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189060. {
  189061. png_push_save_buffer(png_ptr);
  189062. return;
  189063. }
  189064. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  189065. }
  189066. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189067. }
  189068. void /* PRIVATE */
  189069. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  189070. {
  189071. png_ptr->process_mode = PNG_SKIP_MODE;
  189072. png_ptr->skip_length = skip;
  189073. }
  189074. void /* PRIVATE */
  189075. png_push_crc_finish(png_structp png_ptr)
  189076. {
  189077. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  189078. {
  189079. png_size_t save_size;
  189080. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  189081. save_size = (png_size_t)png_ptr->skip_length;
  189082. else
  189083. save_size = png_ptr->save_buffer_size;
  189084. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189085. png_ptr->skip_length -= save_size;
  189086. png_ptr->buffer_size -= save_size;
  189087. png_ptr->save_buffer_size -= save_size;
  189088. png_ptr->save_buffer_ptr += save_size;
  189089. }
  189090. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  189091. {
  189092. png_size_t save_size;
  189093. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  189094. save_size = (png_size_t)png_ptr->skip_length;
  189095. else
  189096. save_size = png_ptr->current_buffer_size;
  189097. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189098. png_ptr->skip_length -= save_size;
  189099. png_ptr->buffer_size -= save_size;
  189100. png_ptr->current_buffer_size -= save_size;
  189101. png_ptr->current_buffer_ptr += save_size;
  189102. }
  189103. if (!png_ptr->skip_length)
  189104. {
  189105. if (png_ptr->buffer_size < 4)
  189106. {
  189107. png_push_save_buffer(png_ptr);
  189108. return;
  189109. }
  189110. png_crc_finish(png_ptr, 0);
  189111. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189112. }
  189113. }
  189114. void PNGAPI
  189115. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  189116. {
  189117. png_bytep ptr;
  189118. if(png_ptr == NULL) return;
  189119. ptr = buffer;
  189120. if (png_ptr->save_buffer_size)
  189121. {
  189122. png_size_t save_size;
  189123. if (length < png_ptr->save_buffer_size)
  189124. save_size = length;
  189125. else
  189126. save_size = png_ptr->save_buffer_size;
  189127. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  189128. length -= save_size;
  189129. ptr += save_size;
  189130. png_ptr->buffer_size -= save_size;
  189131. png_ptr->save_buffer_size -= save_size;
  189132. png_ptr->save_buffer_ptr += save_size;
  189133. }
  189134. if (length && png_ptr->current_buffer_size)
  189135. {
  189136. png_size_t save_size;
  189137. if (length < png_ptr->current_buffer_size)
  189138. save_size = length;
  189139. else
  189140. save_size = png_ptr->current_buffer_size;
  189141. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  189142. png_ptr->buffer_size -= save_size;
  189143. png_ptr->current_buffer_size -= save_size;
  189144. png_ptr->current_buffer_ptr += save_size;
  189145. }
  189146. }
  189147. void /* PRIVATE */
  189148. png_push_save_buffer(png_structp png_ptr)
  189149. {
  189150. if (png_ptr->save_buffer_size)
  189151. {
  189152. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189153. {
  189154. png_size_t i,istop;
  189155. png_bytep sp;
  189156. png_bytep dp;
  189157. istop = png_ptr->save_buffer_size;
  189158. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189159. i < istop; i++, sp++, dp++)
  189160. {
  189161. *dp = *sp;
  189162. }
  189163. }
  189164. }
  189165. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189166. png_ptr->save_buffer_max)
  189167. {
  189168. png_size_t new_max;
  189169. png_bytep old_buffer;
  189170. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189171. (png_ptr->current_buffer_size + 256))
  189172. {
  189173. png_error(png_ptr, "Potential overflow of save_buffer");
  189174. }
  189175. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189176. old_buffer = png_ptr->save_buffer;
  189177. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189178. (png_uint_32)new_max);
  189179. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189180. png_free(png_ptr, old_buffer);
  189181. png_ptr->save_buffer_max = new_max;
  189182. }
  189183. if (png_ptr->current_buffer_size)
  189184. {
  189185. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189186. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189187. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189188. png_ptr->current_buffer_size = 0;
  189189. }
  189190. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189191. png_ptr->buffer_size = 0;
  189192. }
  189193. void /* PRIVATE */
  189194. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189195. png_size_t buffer_length)
  189196. {
  189197. png_ptr->current_buffer = buffer;
  189198. png_ptr->current_buffer_size = buffer_length;
  189199. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189200. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189201. }
  189202. void /* PRIVATE */
  189203. png_push_read_IDAT(png_structp png_ptr)
  189204. {
  189205. #ifdef PNG_USE_LOCAL_ARRAYS
  189206. PNG_CONST PNG_IDAT;
  189207. #endif
  189208. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189209. {
  189210. png_byte chunk_length[4];
  189211. if (png_ptr->buffer_size < 8)
  189212. {
  189213. png_push_save_buffer(png_ptr);
  189214. return;
  189215. }
  189216. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189217. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189218. png_reset_crc(png_ptr);
  189219. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189220. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189221. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189222. {
  189223. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189224. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189225. png_error(png_ptr, "Not enough compressed data");
  189226. return;
  189227. }
  189228. png_ptr->idat_size = png_ptr->push_length;
  189229. }
  189230. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189231. {
  189232. png_size_t save_size;
  189233. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189234. {
  189235. save_size = (png_size_t)png_ptr->idat_size;
  189236. /* check for overflow */
  189237. if((png_uint_32)save_size != png_ptr->idat_size)
  189238. png_error(png_ptr, "save_size overflowed in pngpread");
  189239. }
  189240. else
  189241. save_size = png_ptr->save_buffer_size;
  189242. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189243. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189244. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189245. png_ptr->idat_size -= save_size;
  189246. png_ptr->buffer_size -= save_size;
  189247. png_ptr->save_buffer_size -= save_size;
  189248. png_ptr->save_buffer_ptr += save_size;
  189249. }
  189250. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189251. {
  189252. png_size_t save_size;
  189253. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189254. {
  189255. save_size = (png_size_t)png_ptr->idat_size;
  189256. /* check for overflow */
  189257. if((png_uint_32)save_size != png_ptr->idat_size)
  189258. png_error(png_ptr, "save_size overflowed in pngpread");
  189259. }
  189260. else
  189261. save_size = png_ptr->current_buffer_size;
  189262. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189263. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189264. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189265. png_ptr->idat_size -= save_size;
  189266. png_ptr->buffer_size -= save_size;
  189267. png_ptr->current_buffer_size -= save_size;
  189268. png_ptr->current_buffer_ptr += save_size;
  189269. }
  189270. if (!png_ptr->idat_size)
  189271. {
  189272. if (png_ptr->buffer_size < 4)
  189273. {
  189274. png_push_save_buffer(png_ptr);
  189275. return;
  189276. }
  189277. png_crc_finish(png_ptr, 0);
  189278. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189279. png_ptr->mode |= PNG_AFTER_IDAT;
  189280. }
  189281. }
  189282. void /* PRIVATE */
  189283. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189284. png_size_t buffer_length)
  189285. {
  189286. int ret;
  189287. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189288. png_error(png_ptr, "Extra compression data");
  189289. png_ptr->zstream.next_in = buffer;
  189290. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189291. for(;;)
  189292. {
  189293. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189294. if (ret != Z_OK)
  189295. {
  189296. if (ret == Z_STREAM_END)
  189297. {
  189298. if (png_ptr->zstream.avail_in)
  189299. png_error(png_ptr, "Extra compressed data");
  189300. if (!(png_ptr->zstream.avail_out))
  189301. {
  189302. png_push_process_row(png_ptr);
  189303. }
  189304. png_ptr->mode |= PNG_AFTER_IDAT;
  189305. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189306. break;
  189307. }
  189308. else if (ret == Z_BUF_ERROR)
  189309. break;
  189310. else
  189311. png_error(png_ptr, "Decompression Error");
  189312. }
  189313. if (!(png_ptr->zstream.avail_out))
  189314. {
  189315. if ((
  189316. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189317. png_ptr->interlaced && png_ptr->pass > 6) ||
  189318. (!png_ptr->interlaced &&
  189319. #endif
  189320. png_ptr->row_number == png_ptr->num_rows))
  189321. {
  189322. if (png_ptr->zstream.avail_in)
  189323. {
  189324. png_warning(png_ptr, "Too much data in IDAT chunks");
  189325. }
  189326. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189327. break;
  189328. }
  189329. png_push_process_row(png_ptr);
  189330. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189331. png_ptr->zstream.next_out = png_ptr->row_buf;
  189332. }
  189333. else
  189334. break;
  189335. }
  189336. }
  189337. void /* PRIVATE */
  189338. png_push_process_row(png_structp png_ptr)
  189339. {
  189340. png_ptr->row_info.color_type = png_ptr->color_type;
  189341. png_ptr->row_info.width = png_ptr->iwidth;
  189342. png_ptr->row_info.channels = png_ptr->channels;
  189343. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189344. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189345. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189346. png_ptr->row_info.width);
  189347. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189348. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189349. (int)(png_ptr->row_buf[0]));
  189350. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189351. png_ptr->rowbytes + 1);
  189352. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189353. png_do_read_transformations(png_ptr);
  189354. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189355. /* blow up interlaced rows to full size */
  189356. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189357. {
  189358. if (png_ptr->pass < 6)
  189359. /* old interface (pre-1.0.9):
  189360. png_do_read_interlace(&(png_ptr->row_info),
  189361. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189362. */
  189363. png_do_read_interlace(png_ptr);
  189364. switch (png_ptr->pass)
  189365. {
  189366. case 0:
  189367. {
  189368. int i;
  189369. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189370. {
  189371. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189372. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189373. }
  189374. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189375. {
  189376. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189377. {
  189378. png_push_have_row(png_ptr, png_bytep_NULL);
  189379. png_read_push_finish_row(png_ptr);
  189380. }
  189381. }
  189382. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189383. {
  189384. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189385. {
  189386. png_push_have_row(png_ptr, png_bytep_NULL);
  189387. png_read_push_finish_row(png_ptr);
  189388. }
  189389. }
  189390. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189391. {
  189392. png_push_have_row(png_ptr, png_bytep_NULL);
  189393. png_read_push_finish_row(png_ptr);
  189394. }
  189395. break;
  189396. }
  189397. case 1:
  189398. {
  189399. int i;
  189400. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189401. {
  189402. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189403. png_read_push_finish_row(png_ptr);
  189404. }
  189405. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189406. {
  189407. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189408. {
  189409. png_push_have_row(png_ptr, png_bytep_NULL);
  189410. png_read_push_finish_row(png_ptr);
  189411. }
  189412. }
  189413. break;
  189414. }
  189415. case 2:
  189416. {
  189417. int i;
  189418. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189419. {
  189420. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189421. png_read_push_finish_row(png_ptr);
  189422. }
  189423. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189424. {
  189425. png_push_have_row(png_ptr, png_bytep_NULL);
  189426. png_read_push_finish_row(png_ptr);
  189427. }
  189428. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189429. {
  189430. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189431. {
  189432. png_push_have_row(png_ptr, png_bytep_NULL);
  189433. png_read_push_finish_row(png_ptr);
  189434. }
  189435. }
  189436. break;
  189437. }
  189438. case 3:
  189439. {
  189440. int i;
  189441. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189442. {
  189443. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189444. png_read_push_finish_row(png_ptr);
  189445. }
  189446. if (png_ptr->pass == 4) /* skip top two generated rows */
  189447. {
  189448. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189449. {
  189450. png_push_have_row(png_ptr, png_bytep_NULL);
  189451. png_read_push_finish_row(png_ptr);
  189452. }
  189453. }
  189454. break;
  189455. }
  189456. case 4:
  189457. {
  189458. int i;
  189459. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189460. {
  189461. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189462. png_read_push_finish_row(png_ptr);
  189463. }
  189464. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189465. {
  189466. png_push_have_row(png_ptr, png_bytep_NULL);
  189467. png_read_push_finish_row(png_ptr);
  189468. }
  189469. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189470. {
  189471. png_push_have_row(png_ptr, png_bytep_NULL);
  189472. png_read_push_finish_row(png_ptr);
  189473. }
  189474. break;
  189475. }
  189476. case 5:
  189477. {
  189478. int i;
  189479. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189480. {
  189481. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189482. png_read_push_finish_row(png_ptr);
  189483. }
  189484. if (png_ptr->pass == 6) /* skip top generated row */
  189485. {
  189486. png_push_have_row(png_ptr, png_bytep_NULL);
  189487. png_read_push_finish_row(png_ptr);
  189488. }
  189489. break;
  189490. }
  189491. case 6:
  189492. {
  189493. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189494. png_read_push_finish_row(png_ptr);
  189495. if (png_ptr->pass != 6)
  189496. break;
  189497. png_push_have_row(png_ptr, png_bytep_NULL);
  189498. png_read_push_finish_row(png_ptr);
  189499. }
  189500. }
  189501. }
  189502. else
  189503. #endif
  189504. {
  189505. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189506. png_read_push_finish_row(png_ptr);
  189507. }
  189508. }
  189509. void /* PRIVATE */
  189510. png_read_push_finish_row(png_structp png_ptr)
  189511. {
  189512. #ifdef PNG_USE_LOCAL_ARRAYS
  189513. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189514. /* start of interlace block */
  189515. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189516. /* offset to next interlace block */
  189517. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189518. /* start of interlace block in the y direction */
  189519. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189520. /* offset to next interlace block in the y direction */
  189521. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189522. /* Height of interlace block. This is not currently used - if you need
  189523. * it, uncomment it here and in png.h
  189524. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189525. */
  189526. #endif
  189527. png_ptr->row_number++;
  189528. if (png_ptr->row_number < png_ptr->num_rows)
  189529. return;
  189530. if (png_ptr->interlaced)
  189531. {
  189532. png_ptr->row_number = 0;
  189533. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189534. png_ptr->rowbytes + 1);
  189535. do
  189536. {
  189537. png_ptr->pass++;
  189538. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189539. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189540. (png_ptr->pass == 5 && png_ptr->width < 2))
  189541. png_ptr->pass++;
  189542. if (png_ptr->pass > 7)
  189543. png_ptr->pass--;
  189544. if (png_ptr->pass >= 7)
  189545. break;
  189546. png_ptr->iwidth = (png_ptr->width +
  189547. png_pass_inc[png_ptr->pass] - 1 -
  189548. png_pass_start[png_ptr->pass]) /
  189549. png_pass_inc[png_ptr->pass];
  189550. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189551. png_ptr->iwidth) + 1;
  189552. if (png_ptr->transformations & PNG_INTERLACE)
  189553. break;
  189554. png_ptr->num_rows = (png_ptr->height +
  189555. png_pass_yinc[png_ptr->pass] - 1 -
  189556. png_pass_ystart[png_ptr->pass]) /
  189557. png_pass_yinc[png_ptr->pass];
  189558. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189559. }
  189560. }
  189561. #if defined(PNG_READ_tEXt_SUPPORTED)
  189562. void /* PRIVATE */
  189563. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189564. length)
  189565. {
  189566. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189567. {
  189568. png_error(png_ptr, "Out of place tEXt");
  189569. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189570. }
  189571. #ifdef PNG_MAX_MALLOC_64K
  189572. png_ptr->skip_length = 0; /* This may not be necessary */
  189573. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189574. {
  189575. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189576. png_ptr->skip_length = length - (png_uint_32)65535L;
  189577. length = (png_uint_32)65535L;
  189578. }
  189579. #endif
  189580. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189581. (png_uint_32)(length+1));
  189582. png_ptr->current_text[length] = '\0';
  189583. png_ptr->current_text_ptr = png_ptr->current_text;
  189584. png_ptr->current_text_size = (png_size_t)length;
  189585. png_ptr->current_text_left = (png_size_t)length;
  189586. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189587. }
  189588. void /* PRIVATE */
  189589. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189590. {
  189591. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189592. {
  189593. png_size_t text_size;
  189594. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189595. text_size = png_ptr->buffer_size;
  189596. else
  189597. text_size = png_ptr->current_text_left;
  189598. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189599. png_ptr->current_text_left -= text_size;
  189600. png_ptr->current_text_ptr += text_size;
  189601. }
  189602. if (!(png_ptr->current_text_left))
  189603. {
  189604. png_textp text_ptr;
  189605. png_charp text;
  189606. png_charp key;
  189607. int ret;
  189608. if (png_ptr->buffer_size < 4)
  189609. {
  189610. png_push_save_buffer(png_ptr);
  189611. return;
  189612. }
  189613. png_push_crc_finish(png_ptr);
  189614. #if defined(PNG_MAX_MALLOC_64K)
  189615. if (png_ptr->skip_length)
  189616. return;
  189617. #endif
  189618. key = png_ptr->current_text;
  189619. for (text = key; *text; text++)
  189620. /* empty loop */ ;
  189621. if (text < key + png_ptr->current_text_size)
  189622. text++;
  189623. text_ptr = (png_textp)png_malloc(png_ptr,
  189624. (png_uint_32)png_sizeof(png_text));
  189625. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189626. text_ptr->key = key;
  189627. #ifdef PNG_iTXt_SUPPORTED
  189628. text_ptr->lang = NULL;
  189629. text_ptr->lang_key = NULL;
  189630. #endif
  189631. text_ptr->text = text;
  189632. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189633. png_free(png_ptr, key);
  189634. png_free(png_ptr, text_ptr);
  189635. png_ptr->current_text = NULL;
  189636. if (ret)
  189637. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189638. }
  189639. }
  189640. #endif
  189641. #if defined(PNG_READ_zTXt_SUPPORTED)
  189642. void /* PRIVATE */
  189643. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189644. length)
  189645. {
  189646. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189647. {
  189648. png_error(png_ptr, "Out of place zTXt");
  189649. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189650. }
  189651. #ifdef PNG_MAX_MALLOC_64K
  189652. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189653. * to be able to store the uncompressed data. Actually, the threshold
  189654. * is probably around 32K, but it isn't as definite as 64K is.
  189655. */
  189656. if (length > (png_uint_32)65535L)
  189657. {
  189658. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189659. png_push_crc_skip(png_ptr, length);
  189660. return;
  189661. }
  189662. #endif
  189663. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189664. (png_uint_32)(length+1));
  189665. png_ptr->current_text[length] = '\0';
  189666. png_ptr->current_text_ptr = png_ptr->current_text;
  189667. png_ptr->current_text_size = (png_size_t)length;
  189668. png_ptr->current_text_left = (png_size_t)length;
  189669. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189670. }
  189671. void /* PRIVATE */
  189672. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189673. {
  189674. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189675. {
  189676. png_size_t text_size;
  189677. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189678. text_size = png_ptr->buffer_size;
  189679. else
  189680. text_size = png_ptr->current_text_left;
  189681. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189682. png_ptr->current_text_left -= text_size;
  189683. png_ptr->current_text_ptr += text_size;
  189684. }
  189685. if (!(png_ptr->current_text_left))
  189686. {
  189687. png_textp text_ptr;
  189688. png_charp text;
  189689. png_charp key;
  189690. int ret;
  189691. png_size_t text_size, key_size;
  189692. if (png_ptr->buffer_size < 4)
  189693. {
  189694. png_push_save_buffer(png_ptr);
  189695. return;
  189696. }
  189697. png_push_crc_finish(png_ptr);
  189698. key = png_ptr->current_text;
  189699. for (text = key; *text; text++)
  189700. /* empty loop */ ;
  189701. /* zTXt can't have zero text */
  189702. if (text >= key + png_ptr->current_text_size)
  189703. {
  189704. png_ptr->current_text = NULL;
  189705. png_free(png_ptr, key);
  189706. return;
  189707. }
  189708. text++;
  189709. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189710. {
  189711. png_ptr->current_text = NULL;
  189712. png_free(png_ptr, key);
  189713. return;
  189714. }
  189715. text++;
  189716. png_ptr->zstream.next_in = (png_bytep )text;
  189717. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189718. (text - key));
  189719. png_ptr->zstream.next_out = png_ptr->zbuf;
  189720. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189721. key_size = text - key;
  189722. text_size = 0;
  189723. text = NULL;
  189724. ret = Z_STREAM_END;
  189725. while (png_ptr->zstream.avail_in)
  189726. {
  189727. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189728. if (ret != Z_OK && ret != Z_STREAM_END)
  189729. {
  189730. inflateReset(&png_ptr->zstream);
  189731. png_ptr->zstream.avail_in = 0;
  189732. png_ptr->current_text = NULL;
  189733. png_free(png_ptr, key);
  189734. png_free(png_ptr, text);
  189735. return;
  189736. }
  189737. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189738. {
  189739. if (text == NULL)
  189740. {
  189741. text = (png_charp)png_malloc(png_ptr,
  189742. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189743. + key_size + 1));
  189744. png_memcpy(text + key_size, png_ptr->zbuf,
  189745. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189746. png_memcpy(text, key, key_size);
  189747. text_size = key_size + png_ptr->zbuf_size -
  189748. png_ptr->zstream.avail_out;
  189749. *(text + text_size) = '\0';
  189750. }
  189751. else
  189752. {
  189753. png_charp tmp;
  189754. tmp = text;
  189755. text = (png_charp)png_malloc(png_ptr, text_size +
  189756. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189757. + 1));
  189758. png_memcpy(text, tmp, text_size);
  189759. png_free(png_ptr, tmp);
  189760. png_memcpy(text + text_size, png_ptr->zbuf,
  189761. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189762. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189763. *(text + text_size) = '\0';
  189764. }
  189765. if (ret != Z_STREAM_END)
  189766. {
  189767. png_ptr->zstream.next_out = png_ptr->zbuf;
  189768. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189769. }
  189770. }
  189771. else
  189772. {
  189773. break;
  189774. }
  189775. if (ret == Z_STREAM_END)
  189776. break;
  189777. }
  189778. inflateReset(&png_ptr->zstream);
  189779. png_ptr->zstream.avail_in = 0;
  189780. if (ret != Z_STREAM_END)
  189781. {
  189782. png_ptr->current_text = NULL;
  189783. png_free(png_ptr, key);
  189784. png_free(png_ptr, text);
  189785. return;
  189786. }
  189787. png_ptr->current_text = NULL;
  189788. png_free(png_ptr, key);
  189789. key = text;
  189790. text += key_size;
  189791. text_ptr = (png_textp)png_malloc(png_ptr,
  189792. (png_uint_32)png_sizeof(png_text));
  189793. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189794. text_ptr->key = key;
  189795. #ifdef PNG_iTXt_SUPPORTED
  189796. text_ptr->lang = NULL;
  189797. text_ptr->lang_key = NULL;
  189798. #endif
  189799. text_ptr->text = text;
  189800. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189801. png_free(png_ptr, key);
  189802. png_free(png_ptr, text_ptr);
  189803. if (ret)
  189804. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189805. }
  189806. }
  189807. #endif
  189808. #if defined(PNG_READ_iTXt_SUPPORTED)
  189809. void /* PRIVATE */
  189810. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189811. length)
  189812. {
  189813. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189814. {
  189815. png_error(png_ptr, "Out of place iTXt");
  189816. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189817. }
  189818. #ifdef PNG_MAX_MALLOC_64K
  189819. png_ptr->skip_length = 0; /* This may not be necessary */
  189820. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189821. {
  189822. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189823. png_ptr->skip_length = length - (png_uint_32)65535L;
  189824. length = (png_uint_32)65535L;
  189825. }
  189826. #endif
  189827. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189828. (png_uint_32)(length+1));
  189829. png_ptr->current_text[length] = '\0';
  189830. png_ptr->current_text_ptr = png_ptr->current_text;
  189831. png_ptr->current_text_size = (png_size_t)length;
  189832. png_ptr->current_text_left = (png_size_t)length;
  189833. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189834. }
  189835. void /* PRIVATE */
  189836. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189837. {
  189838. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189839. {
  189840. png_size_t text_size;
  189841. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189842. text_size = png_ptr->buffer_size;
  189843. else
  189844. text_size = png_ptr->current_text_left;
  189845. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189846. png_ptr->current_text_left -= text_size;
  189847. png_ptr->current_text_ptr += text_size;
  189848. }
  189849. if (!(png_ptr->current_text_left))
  189850. {
  189851. png_textp text_ptr;
  189852. png_charp key;
  189853. int comp_flag;
  189854. png_charp lang;
  189855. png_charp lang_key;
  189856. png_charp text;
  189857. int ret;
  189858. if (png_ptr->buffer_size < 4)
  189859. {
  189860. png_push_save_buffer(png_ptr);
  189861. return;
  189862. }
  189863. png_push_crc_finish(png_ptr);
  189864. #if defined(PNG_MAX_MALLOC_64K)
  189865. if (png_ptr->skip_length)
  189866. return;
  189867. #endif
  189868. key = png_ptr->current_text;
  189869. for (lang = key; *lang; lang++)
  189870. /* empty loop */ ;
  189871. if (lang < key + png_ptr->current_text_size - 3)
  189872. lang++;
  189873. comp_flag = *lang++;
  189874. lang++; /* skip comp_type, always zero */
  189875. for (lang_key = lang; *lang_key; lang_key++)
  189876. /* empty loop */ ;
  189877. lang_key++; /* skip NUL separator */
  189878. text=lang_key;
  189879. if (lang_key < key + png_ptr->current_text_size - 1)
  189880. {
  189881. for (; *text; text++)
  189882. /* empty loop */ ;
  189883. }
  189884. if (text < key + png_ptr->current_text_size)
  189885. text++;
  189886. text_ptr = (png_textp)png_malloc(png_ptr,
  189887. (png_uint_32)png_sizeof(png_text));
  189888. text_ptr->compression = comp_flag + 2;
  189889. text_ptr->key = key;
  189890. text_ptr->lang = lang;
  189891. text_ptr->lang_key = lang_key;
  189892. text_ptr->text = text;
  189893. text_ptr->text_length = 0;
  189894. text_ptr->itxt_length = png_strlen(text);
  189895. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189896. png_ptr->current_text = NULL;
  189897. png_free(png_ptr, text_ptr);
  189898. if (ret)
  189899. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189900. }
  189901. }
  189902. #endif
  189903. /* This function is called when we haven't found a handler for this
  189904. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189905. * name or a critical chunk), the chunk is (currently) silently ignored.
  189906. */
  189907. void /* PRIVATE */
  189908. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189909. length)
  189910. {
  189911. png_uint_32 skip=0;
  189912. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189913. if (!(png_ptr->chunk_name[0] & 0x20))
  189914. {
  189915. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189916. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189917. PNG_HANDLE_CHUNK_ALWAYS
  189918. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189919. && png_ptr->read_user_chunk_fn == NULL
  189920. #endif
  189921. )
  189922. #endif
  189923. png_chunk_error(png_ptr, "unknown critical chunk");
  189924. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189925. }
  189926. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189927. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189928. {
  189929. #ifdef PNG_MAX_MALLOC_64K
  189930. if (length > (png_uint_32)65535L)
  189931. {
  189932. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189933. skip = length - (png_uint_32)65535L;
  189934. length = (png_uint_32)65535L;
  189935. }
  189936. #endif
  189937. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189938. (png_charp)png_ptr->chunk_name, 5);
  189939. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189940. png_ptr->unknown_chunk.size = (png_size_t)length;
  189941. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189942. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189943. if(png_ptr->read_user_chunk_fn != NULL)
  189944. {
  189945. /* callback to user unknown chunk handler */
  189946. int ret;
  189947. ret = (*(png_ptr->read_user_chunk_fn))
  189948. (png_ptr, &png_ptr->unknown_chunk);
  189949. if (ret < 0)
  189950. png_chunk_error(png_ptr, "error in user chunk");
  189951. if (ret == 0)
  189952. {
  189953. if (!(png_ptr->chunk_name[0] & 0x20))
  189954. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189955. PNG_HANDLE_CHUNK_ALWAYS)
  189956. png_chunk_error(png_ptr, "unknown critical chunk");
  189957. png_set_unknown_chunks(png_ptr, info_ptr,
  189958. &png_ptr->unknown_chunk, 1);
  189959. }
  189960. }
  189961. #else
  189962. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189963. #endif
  189964. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189965. png_ptr->unknown_chunk.data = NULL;
  189966. }
  189967. else
  189968. #endif
  189969. skip=length;
  189970. png_push_crc_skip(png_ptr, skip);
  189971. }
  189972. void /* PRIVATE */
  189973. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189974. {
  189975. if (png_ptr->info_fn != NULL)
  189976. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189977. }
  189978. void /* PRIVATE */
  189979. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189980. {
  189981. if (png_ptr->end_fn != NULL)
  189982. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189983. }
  189984. void /* PRIVATE */
  189985. png_push_have_row(png_structp png_ptr, png_bytep row)
  189986. {
  189987. if (png_ptr->row_fn != NULL)
  189988. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189989. (int)png_ptr->pass);
  189990. }
  189991. void PNGAPI
  189992. png_progressive_combine_row (png_structp png_ptr,
  189993. png_bytep old_row, png_bytep new_row)
  189994. {
  189995. #ifdef PNG_USE_LOCAL_ARRAYS
  189996. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189997. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189998. #endif
  189999. if(png_ptr == NULL) return;
  190000. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  190001. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  190002. }
  190003. void PNGAPI
  190004. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  190005. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  190006. png_progressive_end_ptr end_fn)
  190007. {
  190008. if(png_ptr == NULL) return;
  190009. png_ptr->info_fn = info_fn;
  190010. png_ptr->row_fn = row_fn;
  190011. png_ptr->end_fn = end_fn;
  190012. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  190013. }
  190014. png_voidp PNGAPI
  190015. png_get_progressive_ptr(png_structp png_ptr)
  190016. {
  190017. if(png_ptr == NULL) return (NULL);
  190018. return png_ptr->io_ptr;
  190019. }
  190020. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  190021. /*** End of inlined file: pngpread.c ***/
  190022. /*** Start of inlined file: pngrio.c ***/
  190023. /* pngrio.c - functions for data input
  190024. *
  190025. * Last changed in libpng 1.2.13 November 13, 2006
  190026. * For conditions of distribution and use, see copyright notice in png.h
  190027. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  190028. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190029. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190030. *
  190031. * This file provides a location for all input. Users who need
  190032. * special handling are expected to write a function that has the same
  190033. * arguments as this and performs a similar function, but that possibly
  190034. * has a different input method. Note that you shouldn't change this
  190035. * function, but rather write a replacement function and then make
  190036. * libpng use it at run time with png_set_read_fn(...).
  190037. */
  190038. #define PNG_INTERNAL
  190039. #if defined(PNG_READ_SUPPORTED)
  190040. /* Read the data from whatever input you are using. The default routine
  190041. reads from a file pointer. Note that this routine sometimes gets called
  190042. with very small lengths, so you should implement some kind of simple
  190043. buffering if you are using unbuffered reads. This should never be asked
  190044. to read more then 64K on a 16 bit machine. */
  190045. void /* PRIVATE */
  190046. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190047. {
  190048. png_debug1(4,"reading %d bytes\n", (int)length);
  190049. if (png_ptr->read_data_fn != NULL)
  190050. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  190051. else
  190052. png_error(png_ptr, "Call to NULL read function");
  190053. }
  190054. #if !defined(PNG_NO_STDIO)
  190055. /* This is the function that does the actual reading of data. If you are
  190056. not reading from a standard C stream, you should create a replacement
  190057. read_data function and use it at run time with png_set_read_fn(), rather
  190058. than changing the library. */
  190059. #ifndef USE_FAR_KEYWORD
  190060. void PNGAPI
  190061. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190062. {
  190063. png_size_t check;
  190064. if(png_ptr == NULL) return;
  190065. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  190066. * instead of an int, which is what fread() actually returns.
  190067. */
  190068. #if defined(_WIN32_WCE)
  190069. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190070. check = 0;
  190071. #else
  190072. check = (png_size_t)fread(data, (png_size_t)1, length,
  190073. (png_FILE_p)png_ptr->io_ptr);
  190074. #endif
  190075. if (check != length)
  190076. png_error(png_ptr, "Read Error");
  190077. }
  190078. #else
  190079. /* this is the model-independent version. Since the standard I/O library
  190080. can't handle far buffers in the medium and small models, we have to copy
  190081. the data.
  190082. */
  190083. #define NEAR_BUF_SIZE 1024
  190084. #define MIN(a,b) (a <= b ? a : b)
  190085. static void PNGAPI
  190086. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190087. {
  190088. int check;
  190089. png_byte *n_data;
  190090. png_FILE_p io_ptr;
  190091. if(png_ptr == NULL) return;
  190092. /* Check if data really is near. If so, use usual code. */
  190093. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  190094. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  190095. if ((png_bytep)n_data == data)
  190096. {
  190097. #if defined(_WIN32_WCE)
  190098. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190099. check = 0;
  190100. #else
  190101. check = fread(n_data, 1, length, io_ptr);
  190102. #endif
  190103. }
  190104. else
  190105. {
  190106. png_byte buf[NEAR_BUF_SIZE];
  190107. png_size_t read, remaining, err;
  190108. check = 0;
  190109. remaining = length;
  190110. do
  190111. {
  190112. read = MIN(NEAR_BUF_SIZE, remaining);
  190113. #if defined(_WIN32_WCE)
  190114. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  190115. err = 0;
  190116. #else
  190117. err = fread(buf, (png_size_t)1, read, io_ptr);
  190118. #endif
  190119. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  190120. if(err != read)
  190121. break;
  190122. else
  190123. check += err;
  190124. data += read;
  190125. remaining -= read;
  190126. }
  190127. while (remaining != 0);
  190128. }
  190129. if ((png_uint_32)check != (png_uint_32)length)
  190130. png_error(png_ptr, "read Error");
  190131. }
  190132. #endif
  190133. #endif
  190134. /* This function allows the application to supply a new input function
  190135. for libpng if standard C streams aren't being used.
  190136. This function takes as its arguments:
  190137. png_ptr - pointer to a png input data structure
  190138. io_ptr - pointer to user supplied structure containing info about
  190139. the input functions. May be NULL.
  190140. read_data_fn - pointer to a new input function that takes as its
  190141. arguments a pointer to a png_struct, a pointer to
  190142. a location where input data can be stored, and a 32-bit
  190143. unsigned int that is the number of bytes to be read.
  190144. To exit and output any fatal error messages the new write
  190145. function should call png_error(png_ptr, "Error msg"). */
  190146. void PNGAPI
  190147. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190148. png_rw_ptr read_data_fn)
  190149. {
  190150. if(png_ptr == NULL) return;
  190151. png_ptr->io_ptr = io_ptr;
  190152. #if !defined(PNG_NO_STDIO)
  190153. if (read_data_fn != NULL)
  190154. png_ptr->read_data_fn = read_data_fn;
  190155. else
  190156. png_ptr->read_data_fn = png_default_read_data;
  190157. #else
  190158. png_ptr->read_data_fn = read_data_fn;
  190159. #endif
  190160. /* It is an error to write to a read device */
  190161. if (png_ptr->write_data_fn != NULL)
  190162. {
  190163. png_ptr->write_data_fn = NULL;
  190164. png_warning(png_ptr,
  190165. "It's an error to set both read_data_fn and write_data_fn in the ");
  190166. png_warning(png_ptr,
  190167. "same structure. Resetting write_data_fn to NULL.");
  190168. }
  190169. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190170. png_ptr->output_flush_fn = NULL;
  190171. #endif
  190172. }
  190173. #endif /* PNG_READ_SUPPORTED */
  190174. /*** End of inlined file: pngrio.c ***/
  190175. /*** Start of inlined file: pngrtran.c ***/
  190176. /* pngrtran.c - transforms the data in a row for PNG readers
  190177. *
  190178. * Last changed in libpng 1.2.21 [October 4, 2007]
  190179. * For conditions of distribution and use, see copyright notice in png.h
  190180. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190181. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190182. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190183. *
  190184. * This file contains functions optionally called by an application
  190185. * in order to tell libpng how to handle data when reading a PNG.
  190186. * Transformations that are used in both reading and writing are
  190187. * in pngtrans.c.
  190188. */
  190189. #define PNG_INTERNAL
  190190. #if defined(PNG_READ_SUPPORTED)
  190191. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190192. void PNGAPI
  190193. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190194. {
  190195. png_debug(1, "in png_set_crc_action\n");
  190196. /* Tell libpng how we react to CRC errors in critical chunks */
  190197. if(png_ptr == NULL) return;
  190198. switch (crit_action)
  190199. {
  190200. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190201. break;
  190202. case PNG_CRC_WARN_USE: /* warn/use data */
  190203. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190204. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190205. break;
  190206. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190207. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190208. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190209. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190210. break;
  190211. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190212. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190213. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190214. case PNG_CRC_DEFAULT:
  190215. default:
  190216. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190217. break;
  190218. }
  190219. switch (ancil_action)
  190220. {
  190221. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190222. break;
  190223. case PNG_CRC_WARN_USE: /* warn/use data */
  190224. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190225. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190226. break;
  190227. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190228. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190229. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190230. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190231. break;
  190232. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190233. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190234. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190235. break;
  190236. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190237. case PNG_CRC_DEFAULT:
  190238. default:
  190239. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190240. break;
  190241. }
  190242. }
  190243. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190244. defined(PNG_FLOATING_POINT_SUPPORTED)
  190245. /* handle alpha and tRNS via a background color */
  190246. void PNGAPI
  190247. png_set_background(png_structp png_ptr,
  190248. png_color_16p background_color, int background_gamma_code,
  190249. int need_expand, double background_gamma)
  190250. {
  190251. png_debug(1, "in png_set_background\n");
  190252. if(png_ptr == NULL) return;
  190253. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190254. {
  190255. png_warning(png_ptr, "Application must supply a known background gamma");
  190256. return;
  190257. }
  190258. png_ptr->transformations |= PNG_BACKGROUND;
  190259. png_memcpy(&(png_ptr->background), background_color,
  190260. png_sizeof(png_color_16));
  190261. png_ptr->background_gamma = (float)background_gamma;
  190262. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190263. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190264. }
  190265. #endif
  190266. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190267. /* strip 16 bit depth files to 8 bit depth */
  190268. void PNGAPI
  190269. png_set_strip_16(png_structp png_ptr)
  190270. {
  190271. png_debug(1, "in png_set_strip_16\n");
  190272. if(png_ptr == NULL) return;
  190273. png_ptr->transformations |= PNG_16_TO_8;
  190274. }
  190275. #endif
  190276. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190277. void PNGAPI
  190278. png_set_strip_alpha(png_structp png_ptr)
  190279. {
  190280. png_debug(1, "in png_set_strip_alpha\n");
  190281. if(png_ptr == NULL) return;
  190282. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190283. }
  190284. #endif
  190285. #if defined(PNG_READ_DITHER_SUPPORTED)
  190286. /* Dither file to 8 bit. Supply a palette, the current number
  190287. * of elements in the palette, the maximum number of elements
  190288. * allowed, and a histogram if possible. If the current number
  190289. * of colors is greater then the maximum number, the palette will be
  190290. * modified to fit in the maximum number. "full_dither" indicates
  190291. * whether we need a dithering cube set up for RGB images, or if we
  190292. * simply are reducing the number of colors in a paletted image.
  190293. */
  190294. typedef struct png_dsort_struct
  190295. {
  190296. struct png_dsort_struct FAR * next;
  190297. png_byte left;
  190298. png_byte right;
  190299. } png_dsort;
  190300. typedef png_dsort FAR * png_dsortp;
  190301. typedef png_dsort FAR * FAR * png_dsortpp;
  190302. void PNGAPI
  190303. png_set_dither(png_structp png_ptr, png_colorp palette,
  190304. int num_palette, int maximum_colors, png_uint_16p histogram,
  190305. int full_dither)
  190306. {
  190307. png_debug(1, "in png_set_dither\n");
  190308. if(png_ptr == NULL) return;
  190309. png_ptr->transformations |= PNG_DITHER;
  190310. if (!full_dither)
  190311. {
  190312. int i;
  190313. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190314. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190315. for (i = 0; i < num_palette; i++)
  190316. png_ptr->dither_index[i] = (png_byte)i;
  190317. }
  190318. if (num_palette > maximum_colors)
  190319. {
  190320. if (histogram != NULL)
  190321. {
  190322. /* This is easy enough, just throw out the least used colors.
  190323. Perhaps not the best solution, but good enough. */
  190324. int i;
  190325. /* initialize an array to sort colors */
  190326. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190327. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190328. /* initialize the dither_sort array */
  190329. for (i = 0; i < num_palette; i++)
  190330. png_ptr->dither_sort[i] = (png_byte)i;
  190331. /* Find the least used palette entries by starting a
  190332. bubble sort, and running it until we have sorted
  190333. out enough colors. Note that we don't care about
  190334. sorting all the colors, just finding which are
  190335. least used. */
  190336. for (i = num_palette - 1; i >= maximum_colors; i--)
  190337. {
  190338. int done; /* to stop early if the list is pre-sorted */
  190339. int j;
  190340. done = 1;
  190341. for (j = 0; j < i; j++)
  190342. {
  190343. if (histogram[png_ptr->dither_sort[j]]
  190344. < histogram[png_ptr->dither_sort[j + 1]])
  190345. {
  190346. png_byte t;
  190347. t = png_ptr->dither_sort[j];
  190348. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190349. png_ptr->dither_sort[j + 1] = t;
  190350. done = 0;
  190351. }
  190352. }
  190353. if (done)
  190354. break;
  190355. }
  190356. /* swap the palette around, and set up a table, if necessary */
  190357. if (full_dither)
  190358. {
  190359. int j = num_palette;
  190360. /* put all the useful colors within the max, but don't
  190361. move the others */
  190362. for (i = 0; i < maximum_colors; i++)
  190363. {
  190364. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190365. {
  190366. do
  190367. j--;
  190368. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190369. palette[i] = palette[j];
  190370. }
  190371. }
  190372. }
  190373. else
  190374. {
  190375. int j = num_palette;
  190376. /* move all the used colors inside the max limit, and
  190377. develop a translation table */
  190378. for (i = 0; i < maximum_colors; i++)
  190379. {
  190380. /* only move the colors we need to */
  190381. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190382. {
  190383. png_color tmp_color;
  190384. do
  190385. j--;
  190386. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190387. tmp_color = palette[j];
  190388. palette[j] = palette[i];
  190389. palette[i] = tmp_color;
  190390. /* indicate where the color went */
  190391. png_ptr->dither_index[j] = (png_byte)i;
  190392. png_ptr->dither_index[i] = (png_byte)j;
  190393. }
  190394. }
  190395. /* find closest color for those colors we are not using */
  190396. for (i = 0; i < num_palette; i++)
  190397. {
  190398. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190399. {
  190400. int min_d, k, min_k, d_index;
  190401. /* find the closest color to one we threw out */
  190402. d_index = png_ptr->dither_index[i];
  190403. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190404. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190405. {
  190406. int d;
  190407. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190408. if (d < min_d)
  190409. {
  190410. min_d = d;
  190411. min_k = k;
  190412. }
  190413. }
  190414. /* point to closest color */
  190415. png_ptr->dither_index[i] = (png_byte)min_k;
  190416. }
  190417. }
  190418. }
  190419. png_free(png_ptr, png_ptr->dither_sort);
  190420. png_ptr->dither_sort=NULL;
  190421. }
  190422. else
  190423. {
  190424. /* This is much harder to do simply (and quickly). Perhaps
  190425. we need to go through a median cut routine, but those
  190426. don't always behave themselves with only a few colors
  190427. as input. So we will just find the closest two colors,
  190428. and throw out one of them (chosen somewhat randomly).
  190429. [We don't understand this at all, so if someone wants to
  190430. work on improving it, be our guest - AED, GRP]
  190431. */
  190432. int i;
  190433. int max_d;
  190434. int num_new_palette;
  190435. png_dsortp t;
  190436. png_dsortpp hash;
  190437. t=NULL;
  190438. /* initialize palette index arrays */
  190439. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190440. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190441. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190442. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190443. /* initialize the sort array */
  190444. for (i = 0; i < num_palette; i++)
  190445. {
  190446. png_ptr->index_to_palette[i] = (png_byte)i;
  190447. png_ptr->palette_to_index[i] = (png_byte)i;
  190448. }
  190449. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190450. png_sizeof (png_dsortp)));
  190451. for (i = 0; i < 769; i++)
  190452. hash[i] = NULL;
  190453. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190454. num_new_palette = num_palette;
  190455. /* initial wild guess at how far apart the farthest pixel
  190456. pair we will be eliminating will be. Larger
  190457. numbers mean more areas will be allocated, Smaller
  190458. numbers run the risk of not saving enough data, and
  190459. having to do this all over again.
  190460. I have not done extensive checking on this number.
  190461. */
  190462. max_d = 96;
  190463. while (num_new_palette > maximum_colors)
  190464. {
  190465. for (i = 0; i < num_new_palette - 1; i++)
  190466. {
  190467. int j;
  190468. for (j = i + 1; j < num_new_palette; j++)
  190469. {
  190470. int d;
  190471. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190472. if (d <= max_d)
  190473. {
  190474. t = (png_dsortp)png_malloc_warn(png_ptr,
  190475. (png_uint_32)(png_sizeof(png_dsort)));
  190476. if (t == NULL)
  190477. break;
  190478. t->next = hash[d];
  190479. t->left = (png_byte)i;
  190480. t->right = (png_byte)j;
  190481. hash[d] = t;
  190482. }
  190483. }
  190484. if (t == NULL)
  190485. break;
  190486. }
  190487. if (t != NULL)
  190488. for (i = 0; i <= max_d; i++)
  190489. {
  190490. if (hash[i] != NULL)
  190491. {
  190492. png_dsortp p;
  190493. for (p = hash[i]; p; p = p->next)
  190494. {
  190495. if ((int)png_ptr->index_to_palette[p->left]
  190496. < num_new_palette &&
  190497. (int)png_ptr->index_to_palette[p->right]
  190498. < num_new_palette)
  190499. {
  190500. int j, next_j;
  190501. if (num_new_palette & 0x01)
  190502. {
  190503. j = p->left;
  190504. next_j = p->right;
  190505. }
  190506. else
  190507. {
  190508. j = p->right;
  190509. next_j = p->left;
  190510. }
  190511. num_new_palette--;
  190512. palette[png_ptr->index_to_palette[j]]
  190513. = palette[num_new_palette];
  190514. if (!full_dither)
  190515. {
  190516. int k;
  190517. for (k = 0; k < num_palette; k++)
  190518. {
  190519. if (png_ptr->dither_index[k] ==
  190520. png_ptr->index_to_palette[j])
  190521. png_ptr->dither_index[k] =
  190522. png_ptr->index_to_palette[next_j];
  190523. if ((int)png_ptr->dither_index[k] ==
  190524. num_new_palette)
  190525. png_ptr->dither_index[k] =
  190526. png_ptr->index_to_palette[j];
  190527. }
  190528. }
  190529. png_ptr->index_to_palette[png_ptr->palette_to_index
  190530. [num_new_palette]] = png_ptr->index_to_palette[j];
  190531. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190532. = png_ptr->palette_to_index[num_new_palette];
  190533. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190534. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190535. }
  190536. if (num_new_palette <= maximum_colors)
  190537. break;
  190538. }
  190539. if (num_new_palette <= maximum_colors)
  190540. break;
  190541. }
  190542. }
  190543. for (i = 0; i < 769; i++)
  190544. {
  190545. if (hash[i] != NULL)
  190546. {
  190547. png_dsortp p = hash[i];
  190548. while (p)
  190549. {
  190550. t = p->next;
  190551. png_free(png_ptr, p);
  190552. p = t;
  190553. }
  190554. }
  190555. hash[i] = 0;
  190556. }
  190557. max_d += 96;
  190558. }
  190559. png_free(png_ptr, hash);
  190560. png_free(png_ptr, png_ptr->palette_to_index);
  190561. png_free(png_ptr, png_ptr->index_to_palette);
  190562. png_ptr->palette_to_index=NULL;
  190563. png_ptr->index_to_palette=NULL;
  190564. }
  190565. num_palette = maximum_colors;
  190566. }
  190567. if (png_ptr->palette == NULL)
  190568. {
  190569. png_ptr->palette = palette;
  190570. }
  190571. png_ptr->num_palette = (png_uint_16)num_palette;
  190572. if (full_dither)
  190573. {
  190574. int i;
  190575. png_bytep distance;
  190576. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190577. PNG_DITHER_BLUE_BITS;
  190578. int num_red = (1 << PNG_DITHER_RED_BITS);
  190579. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190580. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190581. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190582. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190583. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190584. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190585. png_sizeof (png_byte));
  190586. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190587. png_sizeof(png_byte)));
  190588. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190589. for (i = 0; i < num_palette; i++)
  190590. {
  190591. int ir, ig, ib;
  190592. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190593. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190594. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190595. for (ir = 0; ir < num_red; ir++)
  190596. {
  190597. /* int dr = abs(ir - r); */
  190598. int dr = ((ir > r) ? ir - r : r - ir);
  190599. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190600. for (ig = 0; ig < num_green; ig++)
  190601. {
  190602. /* int dg = abs(ig - g); */
  190603. int dg = ((ig > g) ? ig - g : g - ig);
  190604. int dt = dr + dg;
  190605. int dm = ((dr > dg) ? dr : dg);
  190606. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190607. for (ib = 0; ib < num_blue; ib++)
  190608. {
  190609. int d_index = index_g | ib;
  190610. /* int db = abs(ib - b); */
  190611. int db = ((ib > b) ? ib - b : b - ib);
  190612. int dmax = ((dm > db) ? dm : db);
  190613. int d = dmax + dt + db;
  190614. if (d < (int)distance[d_index])
  190615. {
  190616. distance[d_index] = (png_byte)d;
  190617. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190618. }
  190619. }
  190620. }
  190621. }
  190622. }
  190623. png_free(png_ptr, distance);
  190624. }
  190625. }
  190626. #endif
  190627. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190628. /* Transform the image from the file_gamma to the screen_gamma. We
  190629. * only do transformations on images where the file_gamma and screen_gamma
  190630. * are not close reciprocals, otherwise it slows things down slightly, and
  190631. * also needlessly introduces small errors.
  190632. *
  190633. * We will turn off gamma transformation later if no semitransparent entries
  190634. * are present in the tRNS array for palette images. We can't do it here
  190635. * because we don't necessarily have the tRNS chunk yet.
  190636. */
  190637. void PNGAPI
  190638. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190639. {
  190640. png_debug(1, "in png_set_gamma\n");
  190641. if(png_ptr == NULL) return;
  190642. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190643. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190644. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190645. png_ptr->transformations |= PNG_GAMMA;
  190646. png_ptr->gamma = (float)file_gamma;
  190647. png_ptr->screen_gamma = (float)scrn_gamma;
  190648. }
  190649. #endif
  190650. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190651. /* Expand paletted images to RGB, expand grayscale images of
  190652. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190653. * to alpha channels.
  190654. */
  190655. void PNGAPI
  190656. png_set_expand(png_structp png_ptr)
  190657. {
  190658. png_debug(1, "in png_set_expand\n");
  190659. if(png_ptr == NULL) return;
  190660. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190661. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190662. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190663. #endif
  190664. }
  190665. /* GRR 19990627: the following three functions currently are identical
  190666. * to png_set_expand(). However, it is entirely reasonable that someone
  190667. * might wish to expand an indexed image to RGB but *not* expand a single,
  190668. * fully transparent palette entry to a full alpha channel--perhaps instead
  190669. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190670. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190671. * IOW, a future version of the library may make the transformations flag
  190672. * a bit more fine-grained, with separate bits for each of these three
  190673. * functions.
  190674. *
  190675. * More to the point, these functions make it obvious what libpng will be
  190676. * doing, whereas "expand" can (and does) mean any number of things.
  190677. *
  190678. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190679. * to expand only the sample depth but not to expand the tRNS to alpha.
  190680. */
  190681. /* Expand paletted images to RGB. */
  190682. void PNGAPI
  190683. png_set_palette_to_rgb(png_structp png_ptr)
  190684. {
  190685. png_debug(1, "in png_set_palette_to_rgb\n");
  190686. if(png_ptr == NULL) return;
  190687. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190688. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190689. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190690. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190691. #endif
  190692. }
  190693. #if !defined(PNG_1_0_X)
  190694. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190695. void PNGAPI
  190696. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190697. {
  190698. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190699. if(png_ptr == NULL) return;
  190700. png_ptr->transformations |= PNG_EXPAND;
  190701. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190702. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190703. #endif
  190704. }
  190705. #endif
  190706. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190707. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190708. /* Deprecated as of libpng-1.2.9 */
  190709. void PNGAPI
  190710. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190711. {
  190712. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190713. if(png_ptr == NULL) return;
  190714. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190715. }
  190716. #endif
  190717. /* Expand tRNS chunks to alpha channels. */
  190718. void PNGAPI
  190719. png_set_tRNS_to_alpha(png_structp png_ptr)
  190720. {
  190721. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190722. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190723. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190724. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190725. #endif
  190726. }
  190727. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190728. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190729. void PNGAPI
  190730. png_set_gray_to_rgb(png_structp png_ptr)
  190731. {
  190732. png_debug(1, "in png_set_gray_to_rgb\n");
  190733. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190734. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190735. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190736. #endif
  190737. }
  190738. #endif
  190739. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190740. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190741. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190742. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190743. */
  190744. void PNGAPI
  190745. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190746. double green)
  190747. {
  190748. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190749. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190750. if(png_ptr == NULL) return;
  190751. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190752. }
  190753. #endif
  190754. void PNGAPI
  190755. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190756. png_fixed_point red, png_fixed_point green)
  190757. {
  190758. png_debug(1, "in png_set_rgb_to_gray\n");
  190759. if(png_ptr == NULL) return;
  190760. switch(error_action)
  190761. {
  190762. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190763. break;
  190764. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190765. break;
  190766. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190767. }
  190768. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190769. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190770. png_ptr->transformations |= PNG_EXPAND;
  190771. #else
  190772. {
  190773. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190774. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190775. }
  190776. #endif
  190777. {
  190778. png_uint_16 red_int, green_int;
  190779. if(red < 0 || green < 0)
  190780. {
  190781. red_int = 6968; /* .212671 * 32768 + .5 */
  190782. green_int = 23434; /* .715160 * 32768 + .5 */
  190783. }
  190784. else if(red + green < 100000L)
  190785. {
  190786. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190787. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190788. }
  190789. else
  190790. {
  190791. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190792. red_int = 6968;
  190793. green_int = 23434;
  190794. }
  190795. png_ptr->rgb_to_gray_red_coeff = red_int;
  190796. png_ptr->rgb_to_gray_green_coeff = green_int;
  190797. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190798. }
  190799. }
  190800. #endif
  190801. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190802. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190803. defined(PNG_LEGACY_SUPPORTED)
  190804. void PNGAPI
  190805. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190806. read_user_transform_fn)
  190807. {
  190808. png_debug(1, "in png_set_read_user_transform_fn\n");
  190809. if(png_ptr == NULL) return;
  190810. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190811. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190812. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190813. #endif
  190814. #ifdef PNG_LEGACY_SUPPORTED
  190815. if(read_user_transform_fn)
  190816. png_warning(png_ptr,
  190817. "This version of libpng does not support user transforms");
  190818. #endif
  190819. }
  190820. #endif
  190821. /* Initialize everything needed for the read. This includes modifying
  190822. * the palette.
  190823. */
  190824. void /* PRIVATE */
  190825. png_init_read_transformations(png_structp png_ptr)
  190826. {
  190827. png_debug(1, "in png_init_read_transformations\n");
  190828. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190829. if(png_ptr != NULL)
  190830. #endif
  190831. {
  190832. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190833. || defined(PNG_READ_GAMMA_SUPPORTED)
  190834. int color_type = png_ptr->color_type;
  190835. #endif
  190836. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190837. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190838. /* Detect gray background and attempt to enable optimization
  190839. * for gray --> RGB case */
  190840. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190841. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190842. * background color might actually be gray yet not be flagged as such.
  190843. * This is not a problem for the current code, which uses
  190844. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190845. * png_do_gray_to_rgb() transformation.
  190846. */
  190847. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190848. !(color_type & PNG_COLOR_MASK_COLOR))
  190849. {
  190850. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190851. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190852. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190853. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190854. png_ptr->background.red == png_ptr->background.green &&
  190855. png_ptr->background.red == png_ptr->background.blue)
  190856. {
  190857. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190858. png_ptr->background.gray = png_ptr->background.red;
  190859. }
  190860. #endif
  190861. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190862. (png_ptr->transformations & PNG_EXPAND))
  190863. {
  190864. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190865. {
  190866. /* expand background and tRNS chunks */
  190867. switch (png_ptr->bit_depth)
  190868. {
  190869. case 1:
  190870. png_ptr->background.gray *= (png_uint_16)0xff;
  190871. png_ptr->background.red = png_ptr->background.green
  190872. = png_ptr->background.blue = png_ptr->background.gray;
  190873. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190874. {
  190875. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190876. png_ptr->trans_values.red = png_ptr->trans_values.green
  190877. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190878. }
  190879. break;
  190880. case 2:
  190881. png_ptr->background.gray *= (png_uint_16)0x55;
  190882. png_ptr->background.red = png_ptr->background.green
  190883. = png_ptr->background.blue = png_ptr->background.gray;
  190884. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190885. {
  190886. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190887. png_ptr->trans_values.red = png_ptr->trans_values.green
  190888. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190889. }
  190890. break;
  190891. case 4:
  190892. png_ptr->background.gray *= (png_uint_16)0x11;
  190893. png_ptr->background.red = png_ptr->background.green
  190894. = png_ptr->background.blue = png_ptr->background.gray;
  190895. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190896. {
  190897. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190898. png_ptr->trans_values.red = png_ptr->trans_values.green
  190899. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190900. }
  190901. break;
  190902. case 8:
  190903. case 16:
  190904. png_ptr->background.red = png_ptr->background.green
  190905. = png_ptr->background.blue = png_ptr->background.gray;
  190906. break;
  190907. }
  190908. }
  190909. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190910. {
  190911. png_ptr->background.red =
  190912. png_ptr->palette[png_ptr->background.index].red;
  190913. png_ptr->background.green =
  190914. png_ptr->palette[png_ptr->background.index].green;
  190915. png_ptr->background.blue =
  190916. png_ptr->palette[png_ptr->background.index].blue;
  190917. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190918. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190919. {
  190920. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190921. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190922. #endif
  190923. {
  190924. /* invert the alpha channel (in tRNS) unless the pixels are
  190925. going to be expanded, in which case leave it for later */
  190926. int i,istop;
  190927. istop=(int)png_ptr->num_trans;
  190928. for (i=0; i<istop; i++)
  190929. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190930. }
  190931. }
  190932. #endif
  190933. }
  190934. }
  190935. #endif
  190936. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190937. png_ptr->background_1 = png_ptr->background;
  190938. #endif
  190939. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190940. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190941. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190942. < PNG_GAMMA_THRESHOLD))
  190943. {
  190944. int i,k;
  190945. k=0;
  190946. for (i=0; i<png_ptr->num_trans; i++)
  190947. {
  190948. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190949. k=1; /* partial transparency is present */
  190950. }
  190951. if (k == 0)
  190952. png_ptr->transformations &= (~PNG_GAMMA);
  190953. }
  190954. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190955. png_ptr->gamma != 0.0)
  190956. {
  190957. png_build_gamma_table(png_ptr);
  190958. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190959. if (png_ptr->transformations & PNG_BACKGROUND)
  190960. {
  190961. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190962. {
  190963. /* could skip if no transparency and
  190964. */
  190965. png_color back, back_1;
  190966. png_colorp palette = png_ptr->palette;
  190967. int num_palette = png_ptr->num_palette;
  190968. int i;
  190969. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190970. {
  190971. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190972. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190973. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190974. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190975. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190976. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190977. }
  190978. else
  190979. {
  190980. double g, gs;
  190981. switch (png_ptr->background_gamma_type)
  190982. {
  190983. case PNG_BACKGROUND_GAMMA_SCREEN:
  190984. g = (png_ptr->screen_gamma);
  190985. gs = 1.0;
  190986. break;
  190987. case PNG_BACKGROUND_GAMMA_FILE:
  190988. g = 1.0 / (png_ptr->gamma);
  190989. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190990. break;
  190991. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190992. g = 1.0 / (png_ptr->background_gamma);
  190993. gs = 1.0 / (png_ptr->background_gamma *
  190994. png_ptr->screen_gamma);
  190995. break;
  190996. default:
  190997. g = 1.0; /* back_1 */
  190998. gs = 1.0; /* back */
  190999. }
  191000. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  191001. {
  191002. back.red = (png_byte)png_ptr->background.red;
  191003. back.green = (png_byte)png_ptr->background.green;
  191004. back.blue = (png_byte)png_ptr->background.blue;
  191005. }
  191006. else
  191007. {
  191008. back.red = (png_byte)(pow(
  191009. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  191010. back.green = (png_byte)(pow(
  191011. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  191012. back.blue = (png_byte)(pow(
  191013. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  191014. }
  191015. back_1.red = (png_byte)(pow(
  191016. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  191017. back_1.green = (png_byte)(pow(
  191018. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  191019. back_1.blue = (png_byte)(pow(
  191020. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  191021. }
  191022. for (i = 0; i < num_palette; i++)
  191023. {
  191024. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191025. {
  191026. if (png_ptr->trans[i] == 0)
  191027. {
  191028. palette[i] = back;
  191029. }
  191030. else /* if (png_ptr->trans[i] != 0xff) */
  191031. {
  191032. png_byte v, w;
  191033. v = png_ptr->gamma_to_1[palette[i].red];
  191034. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191035. palette[i].red = png_ptr->gamma_from_1[w];
  191036. v = png_ptr->gamma_to_1[palette[i].green];
  191037. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191038. palette[i].green = png_ptr->gamma_from_1[w];
  191039. v = png_ptr->gamma_to_1[palette[i].blue];
  191040. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191041. palette[i].blue = png_ptr->gamma_from_1[w];
  191042. }
  191043. }
  191044. else
  191045. {
  191046. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191047. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191048. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191049. }
  191050. }
  191051. }
  191052. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  191053. else
  191054. /* color_type != PNG_COLOR_TYPE_PALETTE */
  191055. {
  191056. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  191057. double g = 1.0;
  191058. double gs = 1.0;
  191059. switch (png_ptr->background_gamma_type)
  191060. {
  191061. case PNG_BACKGROUND_GAMMA_SCREEN:
  191062. g = (png_ptr->screen_gamma);
  191063. gs = 1.0;
  191064. break;
  191065. case PNG_BACKGROUND_GAMMA_FILE:
  191066. g = 1.0 / (png_ptr->gamma);
  191067. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191068. break;
  191069. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191070. g = 1.0 / (png_ptr->background_gamma);
  191071. gs = 1.0 / (png_ptr->background_gamma *
  191072. png_ptr->screen_gamma);
  191073. break;
  191074. }
  191075. png_ptr->background_1.gray = (png_uint_16)(pow(
  191076. (double)png_ptr->background.gray / m, g) * m + .5);
  191077. png_ptr->background.gray = (png_uint_16)(pow(
  191078. (double)png_ptr->background.gray / m, gs) * m + .5);
  191079. if ((png_ptr->background.red != png_ptr->background.green) ||
  191080. (png_ptr->background.red != png_ptr->background.blue) ||
  191081. (png_ptr->background.red != png_ptr->background.gray))
  191082. {
  191083. /* RGB or RGBA with color background */
  191084. png_ptr->background_1.red = (png_uint_16)(pow(
  191085. (double)png_ptr->background.red / m, g) * m + .5);
  191086. png_ptr->background_1.green = (png_uint_16)(pow(
  191087. (double)png_ptr->background.green / m, g) * m + .5);
  191088. png_ptr->background_1.blue = (png_uint_16)(pow(
  191089. (double)png_ptr->background.blue / m, g) * m + .5);
  191090. png_ptr->background.red = (png_uint_16)(pow(
  191091. (double)png_ptr->background.red / m, gs) * m + .5);
  191092. png_ptr->background.green = (png_uint_16)(pow(
  191093. (double)png_ptr->background.green / m, gs) * m + .5);
  191094. png_ptr->background.blue = (png_uint_16)(pow(
  191095. (double)png_ptr->background.blue / m, gs) * m + .5);
  191096. }
  191097. else
  191098. {
  191099. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  191100. png_ptr->background_1.red = png_ptr->background_1.green
  191101. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  191102. png_ptr->background.red = png_ptr->background.green
  191103. = png_ptr->background.blue = png_ptr->background.gray;
  191104. }
  191105. }
  191106. }
  191107. else
  191108. /* transformation does not include PNG_BACKGROUND */
  191109. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191110. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191111. {
  191112. png_colorp palette = png_ptr->palette;
  191113. int num_palette = png_ptr->num_palette;
  191114. int i;
  191115. for (i = 0; i < num_palette; i++)
  191116. {
  191117. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191118. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191119. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191120. }
  191121. }
  191122. }
  191123. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191124. else
  191125. #endif
  191126. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  191127. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191128. /* No GAMMA transformation */
  191129. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191130. (color_type == PNG_COLOR_TYPE_PALETTE))
  191131. {
  191132. int i;
  191133. int istop = (int)png_ptr->num_trans;
  191134. png_color back;
  191135. png_colorp palette = png_ptr->palette;
  191136. back.red = (png_byte)png_ptr->background.red;
  191137. back.green = (png_byte)png_ptr->background.green;
  191138. back.blue = (png_byte)png_ptr->background.blue;
  191139. for (i = 0; i < istop; i++)
  191140. {
  191141. if (png_ptr->trans[i] == 0)
  191142. {
  191143. palette[i] = back;
  191144. }
  191145. else if (png_ptr->trans[i] != 0xff)
  191146. {
  191147. /* The png_composite() macro is defined in png.h */
  191148. png_composite(palette[i].red, palette[i].red,
  191149. png_ptr->trans[i], back.red);
  191150. png_composite(palette[i].green, palette[i].green,
  191151. png_ptr->trans[i], back.green);
  191152. png_composite(palette[i].blue, palette[i].blue,
  191153. png_ptr->trans[i], back.blue);
  191154. }
  191155. }
  191156. }
  191157. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191158. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191159. if ((png_ptr->transformations & PNG_SHIFT) &&
  191160. (color_type == PNG_COLOR_TYPE_PALETTE))
  191161. {
  191162. png_uint_16 i;
  191163. png_uint_16 istop = png_ptr->num_palette;
  191164. int sr = 8 - png_ptr->sig_bit.red;
  191165. int sg = 8 - png_ptr->sig_bit.green;
  191166. int sb = 8 - png_ptr->sig_bit.blue;
  191167. if (sr < 0 || sr > 8)
  191168. sr = 0;
  191169. if (sg < 0 || sg > 8)
  191170. sg = 0;
  191171. if (sb < 0 || sb > 8)
  191172. sb = 0;
  191173. for (i = 0; i < istop; i++)
  191174. {
  191175. png_ptr->palette[i].red >>= sr;
  191176. png_ptr->palette[i].green >>= sg;
  191177. png_ptr->palette[i].blue >>= sb;
  191178. }
  191179. }
  191180. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191181. }
  191182. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191183. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191184. if(png_ptr)
  191185. return;
  191186. #endif
  191187. }
  191188. /* Modify the info structure to reflect the transformations. The
  191189. * info should be updated so a PNG file could be written with it,
  191190. * assuming the transformations result in valid PNG data.
  191191. */
  191192. void /* PRIVATE */
  191193. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191194. {
  191195. png_debug(1, "in png_read_transform_info\n");
  191196. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191197. if (png_ptr->transformations & PNG_EXPAND)
  191198. {
  191199. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191200. {
  191201. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191202. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191203. else
  191204. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191205. info_ptr->bit_depth = 8;
  191206. info_ptr->num_trans = 0;
  191207. }
  191208. else
  191209. {
  191210. if (png_ptr->num_trans)
  191211. {
  191212. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191213. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191214. else
  191215. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191216. }
  191217. if (info_ptr->bit_depth < 8)
  191218. info_ptr->bit_depth = 8;
  191219. info_ptr->num_trans = 0;
  191220. }
  191221. }
  191222. #endif
  191223. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191224. if (png_ptr->transformations & PNG_BACKGROUND)
  191225. {
  191226. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191227. info_ptr->num_trans = 0;
  191228. info_ptr->background = png_ptr->background;
  191229. }
  191230. #endif
  191231. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191232. if (png_ptr->transformations & PNG_GAMMA)
  191233. {
  191234. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191235. info_ptr->gamma = png_ptr->gamma;
  191236. #endif
  191237. #ifdef PNG_FIXED_POINT_SUPPORTED
  191238. info_ptr->int_gamma = png_ptr->int_gamma;
  191239. #endif
  191240. }
  191241. #endif
  191242. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191243. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191244. info_ptr->bit_depth = 8;
  191245. #endif
  191246. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191247. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191248. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191249. #endif
  191250. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191251. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191252. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191253. #endif
  191254. #if defined(PNG_READ_DITHER_SUPPORTED)
  191255. if (png_ptr->transformations & PNG_DITHER)
  191256. {
  191257. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191258. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191259. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191260. {
  191261. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191262. }
  191263. }
  191264. #endif
  191265. #if defined(PNG_READ_PACK_SUPPORTED)
  191266. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191267. info_ptr->bit_depth = 8;
  191268. #endif
  191269. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191270. info_ptr->channels = 1;
  191271. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191272. info_ptr->channels = 3;
  191273. else
  191274. info_ptr->channels = 1;
  191275. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191276. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191277. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191278. #endif
  191279. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191280. info_ptr->channels++;
  191281. #if defined(PNG_READ_FILLER_SUPPORTED)
  191282. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191283. if ((png_ptr->transformations & PNG_FILLER) &&
  191284. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191285. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191286. {
  191287. info_ptr->channels++;
  191288. /* if adding a true alpha channel not just filler */
  191289. #if !defined(PNG_1_0_X)
  191290. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191291. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191292. #endif
  191293. }
  191294. #endif
  191295. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191296. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191297. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191298. {
  191299. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191300. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191301. if(info_ptr->channels < png_ptr->user_transform_channels)
  191302. info_ptr->channels = png_ptr->user_transform_channels;
  191303. }
  191304. #endif
  191305. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191306. info_ptr->bit_depth);
  191307. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191308. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191309. if(png_ptr)
  191310. return;
  191311. #endif
  191312. }
  191313. /* Transform the row. The order of transformations is significant,
  191314. * and is very touchy. If you add a transformation, take care to
  191315. * decide how it fits in with the other transformations here.
  191316. */
  191317. void /* PRIVATE */
  191318. png_do_read_transformations(png_structp png_ptr)
  191319. {
  191320. png_debug(1, "in png_do_read_transformations\n");
  191321. if (png_ptr->row_buf == NULL)
  191322. {
  191323. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191324. char msg[50];
  191325. png_snprintf2(msg, 50,
  191326. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191327. png_ptr->pass);
  191328. png_error(png_ptr, msg);
  191329. #else
  191330. png_error(png_ptr, "NULL row buffer");
  191331. #endif
  191332. }
  191333. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191334. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191335. /* Application has failed to call either png_read_start_image()
  191336. * or png_read_update_info() after setting transforms that expand
  191337. * pixels. This check added to libpng-1.2.19 */
  191338. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191339. png_error(png_ptr, "Uninitialized row");
  191340. #else
  191341. png_warning(png_ptr, "Uninitialized row");
  191342. #endif
  191343. #endif
  191344. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191345. if (png_ptr->transformations & PNG_EXPAND)
  191346. {
  191347. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191348. {
  191349. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191350. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191351. }
  191352. else
  191353. {
  191354. if (png_ptr->num_trans &&
  191355. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191356. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191357. &(png_ptr->trans_values));
  191358. else
  191359. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191360. NULL);
  191361. }
  191362. }
  191363. #endif
  191364. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191365. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191366. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191367. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191368. #endif
  191369. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191370. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191371. {
  191372. int rgb_error =
  191373. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191374. if(rgb_error)
  191375. {
  191376. png_ptr->rgb_to_gray_status=1;
  191377. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191378. PNG_RGB_TO_GRAY_WARN)
  191379. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191380. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191381. PNG_RGB_TO_GRAY_ERR)
  191382. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191383. }
  191384. }
  191385. #endif
  191386. /*
  191387. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191388. In most cases, the "simple transparency" should be done prior to doing
  191389. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191390. pixel is transparent. You would also need to make sure that the
  191391. transparency information is upgraded to RGB.
  191392. To summarize, the current flow is:
  191393. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191394. with background "in place" if transparent,
  191395. convert to RGB if necessary
  191396. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191397. convert to RGB if necessary
  191398. To support RGB backgrounds for gray images we need:
  191399. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191400. 3 or 6 bytes and composite with background
  191401. "in place" if transparent (3x compare/pixel
  191402. compared to doing composite with gray bkgrnd)
  191403. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191404. remove alpha bytes (3x float operations/pixel
  191405. compared with composite on gray background)
  191406. Greg's change will do this. The reason it wasn't done before is for
  191407. performance, as this increases the per-pixel operations. If we would check
  191408. in advance if the background was gray or RGB, and position the gray-to-RGB
  191409. transform appropriately, then it would save a lot of work/time.
  191410. */
  191411. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191412. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191413. * for performance reasons */
  191414. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191415. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191416. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191417. #endif
  191418. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191419. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191420. ((png_ptr->num_trans != 0 ) ||
  191421. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191422. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191423. &(png_ptr->trans_values), &(png_ptr->background)
  191424. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191425. , &(png_ptr->background_1),
  191426. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191427. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191428. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191429. png_ptr->gamma_shift
  191430. #endif
  191431. );
  191432. #endif
  191433. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191434. if ((png_ptr->transformations & PNG_GAMMA) &&
  191435. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191436. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191437. ((png_ptr->num_trans != 0) ||
  191438. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191439. #endif
  191440. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191441. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191442. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191443. png_ptr->gamma_shift);
  191444. #endif
  191445. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191446. if (png_ptr->transformations & PNG_16_TO_8)
  191447. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191448. #endif
  191449. #if defined(PNG_READ_DITHER_SUPPORTED)
  191450. if (png_ptr->transformations & PNG_DITHER)
  191451. {
  191452. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191453. png_ptr->palette_lookup, png_ptr->dither_index);
  191454. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191455. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191456. }
  191457. #endif
  191458. #if defined(PNG_READ_INVERT_SUPPORTED)
  191459. if (png_ptr->transformations & PNG_INVERT_MONO)
  191460. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191461. #endif
  191462. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191463. if (png_ptr->transformations & PNG_SHIFT)
  191464. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191465. &(png_ptr->shift));
  191466. #endif
  191467. #if defined(PNG_READ_PACK_SUPPORTED)
  191468. if (png_ptr->transformations & PNG_PACK)
  191469. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191470. #endif
  191471. #if defined(PNG_READ_BGR_SUPPORTED)
  191472. if (png_ptr->transformations & PNG_BGR)
  191473. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191474. #endif
  191475. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191476. if (png_ptr->transformations & PNG_PACKSWAP)
  191477. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191478. #endif
  191479. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191480. /* if gray -> RGB, do so now only if we did not do so above */
  191481. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191482. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191483. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191484. #endif
  191485. #if defined(PNG_READ_FILLER_SUPPORTED)
  191486. if (png_ptr->transformations & PNG_FILLER)
  191487. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191488. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191489. #endif
  191490. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191491. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191492. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191493. #endif
  191494. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191495. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191496. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191497. #endif
  191498. #if defined(PNG_READ_SWAP_SUPPORTED)
  191499. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191500. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191501. #endif
  191502. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191503. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191504. {
  191505. if(png_ptr->read_user_transform_fn != NULL)
  191506. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191507. (png_ptr, /* png_ptr */
  191508. &(png_ptr->row_info), /* row_info: */
  191509. /* png_uint_32 width; width of row */
  191510. /* png_uint_32 rowbytes; number of bytes in row */
  191511. /* png_byte color_type; color type of pixels */
  191512. /* png_byte bit_depth; bit depth of samples */
  191513. /* png_byte channels; number of channels (1-4) */
  191514. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191515. png_ptr->row_buf + 1); /* start of pixel data for row */
  191516. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191517. if(png_ptr->user_transform_depth)
  191518. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191519. if(png_ptr->user_transform_channels)
  191520. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191521. #endif
  191522. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191523. png_ptr->row_info.channels);
  191524. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191525. png_ptr->row_info.width);
  191526. }
  191527. #endif
  191528. }
  191529. #if defined(PNG_READ_PACK_SUPPORTED)
  191530. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191531. * without changing the actual values. Thus, if you had a row with
  191532. * a bit depth of 1, you would end up with bytes that only contained
  191533. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191534. * png_do_shift() after this.
  191535. */
  191536. void /* PRIVATE */
  191537. png_do_unpack(png_row_infop row_info, png_bytep row)
  191538. {
  191539. png_debug(1, "in png_do_unpack\n");
  191540. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191541. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191542. #else
  191543. if (row_info->bit_depth < 8)
  191544. #endif
  191545. {
  191546. png_uint_32 i;
  191547. png_uint_32 row_width=row_info->width;
  191548. switch (row_info->bit_depth)
  191549. {
  191550. case 1:
  191551. {
  191552. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191553. png_bytep dp = row + (png_size_t)row_width - 1;
  191554. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191555. for (i = 0; i < row_width; i++)
  191556. {
  191557. *dp = (png_byte)((*sp >> shift) & 0x01);
  191558. if (shift == 7)
  191559. {
  191560. shift = 0;
  191561. sp--;
  191562. }
  191563. else
  191564. shift++;
  191565. dp--;
  191566. }
  191567. break;
  191568. }
  191569. case 2:
  191570. {
  191571. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191572. png_bytep dp = row + (png_size_t)row_width - 1;
  191573. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191574. for (i = 0; i < row_width; i++)
  191575. {
  191576. *dp = (png_byte)((*sp >> shift) & 0x03);
  191577. if (shift == 6)
  191578. {
  191579. shift = 0;
  191580. sp--;
  191581. }
  191582. else
  191583. shift += 2;
  191584. dp--;
  191585. }
  191586. break;
  191587. }
  191588. case 4:
  191589. {
  191590. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191591. png_bytep dp = row + (png_size_t)row_width - 1;
  191592. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191593. for (i = 0; i < row_width; i++)
  191594. {
  191595. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191596. if (shift == 4)
  191597. {
  191598. shift = 0;
  191599. sp--;
  191600. }
  191601. else
  191602. shift = 4;
  191603. dp--;
  191604. }
  191605. break;
  191606. }
  191607. }
  191608. row_info->bit_depth = 8;
  191609. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191610. row_info->rowbytes = row_width * row_info->channels;
  191611. }
  191612. }
  191613. #endif
  191614. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191615. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191616. * pixels back to their significant bits values. Thus, if you have
  191617. * a row of bit depth 8, but only 5 are significant, this will shift
  191618. * the values back to 0 through 31.
  191619. */
  191620. void /* PRIVATE */
  191621. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191622. {
  191623. png_debug(1, "in png_do_unshift\n");
  191624. if (
  191625. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191626. row != NULL && row_info != NULL && sig_bits != NULL &&
  191627. #endif
  191628. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191629. {
  191630. int shift[4];
  191631. int channels = 0;
  191632. int c;
  191633. png_uint_16 value = 0;
  191634. png_uint_32 row_width = row_info->width;
  191635. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191636. {
  191637. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191638. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191639. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191640. }
  191641. else
  191642. {
  191643. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191644. }
  191645. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191646. {
  191647. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191648. }
  191649. for (c = 0; c < channels; c++)
  191650. {
  191651. if (shift[c] <= 0)
  191652. shift[c] = 0;
  191653. else
  191654. value = 1;
  191655. }
  191656. if (!value)
  191657. return;
  191658. switch (row_info->bit_depth)
  191659. {
  191660. case 2:
  191661. {
  191662. png_bytep bp;
  191663. png_uint_32 i;
  191664. png_uint_32 istop = row_info->rowbytes;
  191665. for (bp = row, i = 0; i < istop; i++)
  191666. {
  191667. *bp >>= 1;
  191668. *bp++ &= 0x55;
  191669. }
  191670. break;
  191671. }
  191672. case 4:
  191673. {
  191674. png_bytep bp = row;
  191675. png_uint_32 i;
  191676. png_uint_32 istop = row_info->rowbytes;
  191677. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191678. (png_byte)((int)0xf >> shift[0]));
  191679. for (i = 0; i < istop; i++)
  191680. {
  191681. *bp >>= shift[0];
  191682. *bp++ &= mask;
  191683. }
  191684. break;
  191685. }
  191686. case 8:
  191687. {
  191688. png_bytep bp = row;
  191689. png_uint_32 i;
  191690. png_uint_32 istop = row_width * channels;
  191691. for (i = 0; i < istop; i++)
  191692. {
  191693. *bp++ >>= shift[i%channels];
  191694. }
  191695. break;
  191696. }
  191697. case 16:
  191698. {
  191699. png_bytep bp = row;
  191700. png_uint_32 i;
  191701. png_uint_32 istop = channels * row_width;
  191702. for (i = 0; i < istop; i++)
  191703. {
  191704. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191705. value >>= shift[i%channels];
  191706. *bp++ = (png_byte)(value >> 8);
  191707. *bp++ = (png_byte)(value & 0xff);
  191708. }
  191709. break;
  191710. }
  191711. }
  191712. }
  191713. }
  191714. #endif
  191715. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191716. /* chop rows of bit depth 16 down to 8 */
  191717. void /* PRIVATE */
  191718. png_do_chop(png_row_infop row_info, png_bytep row)
  191719. {
  191720. png_debug(1, "in png_do_chop\n");
  191721. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191722. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191723. #else
  191724. if (row_info->bit_depth == 16)
  191725. #endif
  191726. {
  191727. png_bytep sp = row;
  191728. png_bytep dp = row;
  191729. png_uint_32 i;
  191730. png_uint_32 istop = row_info->width * row_info->channels;
  191731. for (i = 0; i<istop; i++, sp += 2, dp++)
  191732. {
  191733. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191734. /* This does a more accurate scaling of the 16-bit color
  191735. * value, rather than a simple low-byte truncation.
  191736. *
  191737. * What the ideal calculation should be:
  191738. * *dp = (((((png_uint_32)(*sp) << 8) |
  191739. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191740. *
  191741. * GRR: no, I think this is what it really should be:
  191742. * *dp = (((((png_uint_32)(*sp) << 8) |
  191743. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191744. *
  191745. * GRR: here's the exact calculation with shifts:
  191746. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191747. * *dp = (temp - (temp >> 8)) >> 8;
  191748. *
  191749. * Approximate calculation with shift/add instead of multiply/divide:
  191750. * *dp = ((((png_uint_32)(*sp) << 8) |
  191751. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191752. *
  191753. * What we actually do to avoid extra shifting and conversion:
  191754. */
  191755. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191756. #else
  191757. /* Simply discard the low order byte */
  191758. *dp = *sp;
  191759. #endif
  191760. }
  191761. row_info->bit_depth = 8;
  191762. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191763. row_info->rowbytes = row_info->width * row_info->channels;
  191764. }
  191765. }
  191766. #endif
  191767. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191768. void /* PRIVATE */
  191769. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191770. {
  191771. png_debug(1, "in png_do_read_swap_alpha\n");
  191772. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191773. if (row != NULL && row_info != NULL)
  191774. #endif
  191775. {
  191776. png_uint_32 row_width = row_info->width;
  191777. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191778. {
  191779. /* This converts from RGBA to ARGB */
  191780. if (row_info->bit_depth == 8)
  191781. {
  191782. png_bytep sp = row + row_info->rowbytes;
  191783. png_bytep dp = sp;
  191784. png_byte save;
  191785. png_uint_32 i;
  191786. for (i = 0; i < row_width; i++)
  191787. {
  191788. save = *(--sp);
  191789. *(--dp) = *(--sp);
  191790. *(--dp) = *(--sp);
  191791. *(--dp) = *(--sp);
  191792. *(--dp) = save;
  191793. }
  191794. }
  191795. /* This converts from RRGGBBAA to AARRGGBB */
  191796. else
  191797. {
  191798. png_bytep sp = row + row_info->rowbytes;
  191799. png_bytep dp = sp;
  191800. png_byte save[2];
  191801. png_uint_32 i;
  191802. for (i = 0; i < row_width; i++)
  191803. {
  191804. save[0] = *(--sp);
  191805. save[1] = *(--sp);
  191806. *(--dp) = *(--sp);
  191807. *(--dp) = *(--sp);
  191808. *(--dp) = *(--sp);
  191809. *(--dp) = *(--sp);
  191810. *(--dp) = *(--sp);
  191811. *(--dp) = *(--sp);
  191812. *(--dp) = save[0];
  191813. *(--dp) = save[1];
  191814. }
  191815. }
  191816. }
  191817. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191818. {
  191819. /* This converts from GA to AG */
  191820. if (row_info->bit_depth == 8)
  191821. {
  191822. png_bytep sp = row + row_info->rowbytes;
  191823. png_bytep dp = sp;
  191824. png_byte save;
  191825. png_uint_32 i;
  191826. for (i = 0; i < row_width; i++)
  191827. {
  191828. save = *(--sp);
  191829. *(--dp) = *(--sp);
  191830. *(--dp) = save;
  191831. }
  191832. }
  191833. /* This converts from GGAA to AAGG */
  191834. else
  191835. {
  191836. png_bytep sp = row + row_info->rowbytes;
  191837. png_bytep dp = sp;
  191838. png_byte save[2];
  191839. png_uint_32 i;
  191840. for (i = 0; i < row_width; i++)
  191841. {
  191842. save[0] = *(--sp);
  191843. save[1] = *(--sp);
  191844. *(--dp) = *(--sp);
  191845. *(--dp) = *(--sp);
  191846. *(--dp) = save[0];
  191847. *(--dp) = save[1];
  191848. }
  191849. }
  191850. }
  191851. }
  191852. }
  191853. #endif
  191854. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191855. void /* PRIVATE */
  191856. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191857. {
  191858. png_debug(1, "in png_do_read_invert_alpha\n");
  191859. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191860. if (row != NULL && row_info != NULL)
  191861. #endif
  191862. {
  191863. png_uint_32 row_width = row_info->width;
  191864. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191865. {
  191866. /* This inverts the alpha channel in RGBA */
  191867. if (row_info->bit_depth == 8)
  191868. {
  191869. png_bytep sp = row + row_info->rowbytes;
  191870. png_bytep dp = sp;
  191871. png_uint_32 i;
  191872. for (i = 0; i < row_width; i++)
  191873. {
  191874. *(--dp) = (png_byte)(255 - *(--sp));
  191875. /* This does nothing:
  191876. *(--dp) = *(--sp);
  191877. *(--dp) = *(--sp);
  191878. *(--dp) = *(--sp);
  191879. We can replace it with:
  191880. */
  191881. sp-=3;
  191882. dp=sp;
  191883. }
  191884. }
  191885. /* This inverts the alpha channel in RRGGBBAA */
  191886. else
  191887. {
  191888. png_bytep sp = row + row_info->rowbytes;
  191889. png_bytep dp = sp;
  191890. png_uint_32 i;
  191891. for (i = 0; i < row_width; i++)
  191892. {
  191893. *(--dp) = (png_byte)(255 - *(--sp));
  191894. *(--dp) = (png_byte)(255 - *(--sp));
  191895. /* This does nothing:
  191896. *(--dp) = *(--sp);
  191897. *(--dp) = *(--sp);
  191898. *(--dp) = *(--sp);
  191899. *(--dp) = *(--sp);
  191900. *(--dp) = *(--sp);
  191901. *(--dp) = *(--sp);
  191902. We can replace it with:
  191903. */
  191904. sp-=6;
  191905. dp=sp;
  191906. }
  191907. }
  191908. }
  191909. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191910. {
  191911. /* This inverts the alpha channel in GA */
  191912. if (row_info->bit_depth == 8)
  191913. {
  191914. png_bytep sp = row + row_info->rowbytes;
  191915. png_bytep dp = sp;
  191916. png_uint_32 i;
  191917. for (i = 0; i < row_width; i++)
  191918. {
  191919. *(--dp) = (png_byte)(255 - *(--sp));
  191920. *(--dp) = *(--sp);
  191921. }
  191922. }
  191923. /* This inverts the alpha channel in GGAA */
  191924. else
  191925. {
  191926. png_bytep sp = row + row_info->rowbytes;
  191927. png_bytep dp = sp;
  191928. png_uint_32 i;
  191929. for (i = 0; i < row_width; i++)
  191930. {
  191931. *(--dp) = (png_byte)(255 - *(--sp));
  191932. *(--dp) = (png_byte)(255 - *(--sp));
  191933. /*
  191934. *(--dp) = *(--sp);
  191935. *(--dp) = *(--sp);
  191936. */
  191937. sp-=2;
  191938. dp=sp;
  191939. }
  191940. }
  191941. }
  191942. }
  191943. }
  191944. #endif
  191945. #if defined(PNG_READ_FILLER_SUPPORTED)
  191946. /* Add filler channel if we have RGB color */
  191947. void /* PRIVATE */
  191948. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191949. png_uint_32 filler, png_uint_32 flags)
  191950. {
  191951. png_uint_32 i;
  191952. png_uint_32 row_width = row_info->width;
  191953. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191954. png_byte lo_filler = (png_byte)(filler & 0xff);
  191955. png_debug(1, "in png_do_read_filler\n");
  191956. if (
  191957. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191958. row != NULL && row_info != NULL &&
  191959. #endif
  191960. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191961. {
  191962. if(row_info->bit_depth == 8)
  191963. {
  191964. /* This changes the data from G to GX */
  191965. if (flags & PNG_FLAG_FILLER_AFTER)
  191966. {
  191967. png_bytep sp = row + (png_size_t)row_width;
  191968. png_bytep dp = sp + (png_size_t)row_width;
  191969. for (i = 1; i < row_width; i++)
  191970. {
  191971. *(--dp) = lo_filler;
  191972. *(--dp) = *(--sp);
  191973. }
  191974. *(--dp) = lo_filler;
  191975. row_info->channels = 2;
  191976. row_info->pixel_depth = 16;
  191977. row_info->rowbytes = row_width * 2;
  191978. }
  191979. /* This changes the data from G to XG */
  191980. else
  191981. {
  191982. png_bytep sp = row + (png_size_t)row_width;
  191983. png_bytep dp = sp + (png_size_t)row_width;
  191984. for (i = 0; i < row_width; i++)
  191985. {
  191986. *(--dp) = *(--sp);
  191987. *(--dp) = lo_filler;
  191988. }
  191989. row_info->channels = 2;
  191990. row_info->pixel_depth = 16;
  191991. row_info->rowbytes = row_width * 2;
  191992. }
  191993. }
  191994. else if(row_info->bit_depth == 16)
  191995. {
  191996. /* This changes the data from GG to GGXX */
  191997. if (flags & PNG_FLAG_FILLER_AFTER)
  191998. {
  191999. png_bytep sp = row + (png_size_t)row_width * 2;
  192000. png_bytep dp = sp + (png_size_t)row_width * 2;
  192001. for (i = 1; i < row_width; i++)
  192002. {
  192003. *(--dp) = hi_filler;
  192004. *(--dp) = lo_filler;
  192005. *(--dp) = *(--sp);
  192006. *(--dp) = *(--sp);
  192007. }
  192008. *(--dp) = hi_filler;
  192009. *(--dp) = lo_filler;
  192010. row_info->channels = 2;
  192011. row_info->pixel_depth = 32;
  192012. row_info->rowbytes = row_width * 4;
  192013. }
  192014. /* This changes the data from GG to XXGG */
  192015. else
  192016. {
  192017. png_bytep sp = row + (png_size_t)row_width * 2;
  192018. png_bytep dp = sp + (png_size_t)row_width * 2;
  192019. for (i = 0; i < row_width; i++)
  192020. {
  192021. *(--dp) = *(--sp);
  192022. *(--dp) = *(--sp);
  192023. *(--dp) = hi_filler;
  192024. *(--dp) = lo_filler;
  192025. }
  192026. row_info->channels = 2;
  192027. row_info->pixel_depth = 32;
  192028. row_info->rowbytes = row_width * 4;
  192029. }
  192030. }
  192031. } /* COLOR_TYPE == GRAY */
  192032. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192033. {
  192034. if(row_info->bit_depth == 8)
  192035. {
  192036. /* This changes the data from RGB to RGBX */
  192037. if (flags & PNG_FLAG_FILLER_AFTER)
  192038. {
  192039. png_bytep sp = row + (png_size_t)row_width * 3;
  192040. png_bytep dp = sp + (png_size_t)row_width;
  192041. for (i = 1; i < row_width; i++)
  192042. {
  192043. *(--dp) = lo_filler;
  192044. *(--dp) = *(--sp);
  192045. *(--dp) = *(--sp);
  192046. *(--dp) = *(--sp);
  192047. }
  192048. *(--dp) = lo_filler;
  192049. row_info->channels = 4;
  192050. row_info->pixel_depth = 32;
  192051. row_info->rowbytes = row_width * 4;
  192052. }
  192053. /* This changes the data from RGB to XRGB */
  192054. else
  192055. {
  192056. png_bytep sp = row + (png_size_t)row_width * 3;
  192057. png_bytep dp = sp + (png_size_t)row_width;
  192058. for (i = 0; i < row_width; i++)
  192059. {
  192060. *(--dp) = *(--sp);
  192061. *(--dp) = *(--sp);
  192062. *(--dp) = *(--sp);
  192063. *(--dp) = lo_filler;
  192064. }
  192065. row_info->channels = 4;
  192066. row_info->pixel_depth = 32;
  192067. row_info->rowbytes = row_width * 4;
  192068. }
  192069. }
  192070. else if(row_info->bit_depth == 16)
  192071. {
  192072. /* This changes the data from RRGGBB to RRGGBBXX */
  192073. if (flags & PNG_FLAG_FILLER_AFTER)
  192074. {
  192075. png_bytep sp = row + (png_size_t)row_width * 6;
  192076. png_bytep dp = sp + (png_size_t)row_width * 2;
  192077. for (i = 1; i < row_width; i++)
  192078. {
  192079. *(--dp) = hi_filler;
  192080. *(--dp) = lo_filler;
  192081. *(--dp) = *(--sp);
  192082. *(--dp) = *(--sp);
  192083. *(--dp) = *(--sp);
  192084. *(--dp) = *(--sp);
  192085. *(--dp) = *(--sp);
  192086. *(--dp) = *(--sp);
  192087. }
  192088. *(--dp) = hi_filler;
  192089. *(--dp) = lo_filler;
  192090. row_info->channels = 4;
  192091. row_info->pixel_depth = 64;
  192092. row_info->rowbytes = row_width * 8;
  192093. }
  192094. /* This changes the data from RRGGBB to XXRRGGBB */
  192095. else
  192096. {
  192097. png_bytep sp = row + (png_size_t)row_width * 6;
  192098. png_bytep dp = sp + (png_size_t)row_width * 2;
  192099. for (i = 0; i < row_width; i++)
  192100. {
  192101. *(--dp) = *(--sp);
  192102. *(--dp) = *(--sp);
  192103. *(--dp) = *(--sp);
  192104. *(--dp) = *(--sp);
  192105. *(--dp) = *(--sp);
  192106. *(--dp) = *(--sp);
  192107. *(--dp) = hi_filler;
  192108. *(--dp) = lo_filler;
  192109. }
  192110. row_info->channels = 4;
  192111. row_info->pixel_depth = 64;
  192112. row_info->rowbytes = row_width * 8;
  192113. }
  192114. }
  192115. } /* COLOR_TYPE == RGB */
  192116. }
  192117. #endif
  192118. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192119. /* expand grayscale files to RGB, with or without alpha */
  192120. void /* PRIVATE */
  192121. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  192122. {
  192123. png_uint_32 i;
  192124. png_uint_32 row_width = row_info->width;
  192125. png_debug(1, "in png_do_gray_to_rgb\n");
  192126. if (row_info->bit_depth >= 8 &&
  192127. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192128. row != NULL && row_info != NULL &&
  192129. #endif
  192130. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  192131. {
  192132. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192133. {
  192134. if (row_info->bit_depth == 8)
  192135. {
  192136. png_bytep sp = row + (png_size_t)row_width - 1;
  192137. png_bytep dp = sp + (png_size_t)row_width * 2;
  192138. for (i = 0; i < row_width; i++)
  192139. {
  192140. *(dp--) = *sp;
  192141. *(dp--) = *sp;
  192142. *(dp--) = *(sp--);
  192143. }
  192144. }
  192145. else
  192146. {
  192147. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192148. png_bytep dp = sp + (png_size_t)row_width * 4;
  192149. for (i = 0; i < row_width; i++)
  192150. {
  192151. *(dp--) = *sp;
  192152. *(dp--) = *(sp - 1);
  192153. *(dp--) = *sp;
  192154. *(dp--) = *(sp - 1);
  192155. *(dp--) = *(sp--);
  192156. *(dp--) = *(sp--);
  192157. }
  192158. }
  192159. }
  192160. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192161. {
  192162. if (row_info->bit_depth == 8)
  192163. {
  192164. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192165. png_bytep dp = sp + (png_size_t)row_width * 2;
  192166. for (i = 0; i < row_width; i++)
  192167. {
  192168. *(dp--) = *(sp--);
  192169. *(dp--) = *sp;
  192170. *(dp--) = *sp;
  192171. *(dp--) = *(sp--);
  192172. }
  192173. }
  192174. else
  192175. {
  192176. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192177. png_bytep dp = sp + (png_size_t)row_width * 4;
  192178. for (i = 0; i < row_width; i++)
  192179. {
  192180. *(dp--) = *(sp--);
  192181. *(dp--) = *(sp--);
  192182. *(dp--) = *sp;
  192183. *(dp--) = *(sp - 1);
  192184. *(dp--) = *sp;
  192185. *(dp--) = *(sp - 1);
  192186. *(dp--) = *(sp--);
  192187. *(dp--) = *(sp--);
  192188. }
  192189. }
  192190. }
  192191. row_info->channels += (png_byte)2;
  192192. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192193. row_info->pixel_depth = (png_byte)(row_info->channels *
  192194. row_info->bit_depth);
  192195. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192196. }
  192197. }
  192198. #endif
  192199. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192200. /* reduce RGB files to grayscale, with or without alpha
  192201. * using the equation given in Poynton's ColorFAQ at
  192202. * <http://www.inforamp.net/~poynton/>
  192203. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192204. *
  192205. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192206. *
  192207. * We approximate this with
  192208. *
  192209. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192210. *
  192211. * which can be expressed with integers as
  192212. *
  192213. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192214. *
  192215. * The calculation is to be done in a linear colorspace.
  192216. *
  192217. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192218. */
  192219. int /* PRIVATE */
  192220. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192221. {
  192222. png_uint_32 i;
  192223. png_uint_32 row_width = row_info->width;
  192224. int rgb_error = 0;
  192225. png_debug(1, "in png_do_rgb_to_gray\n");
  192226. if (
  192227. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192228. row != NULL && row_info != NULL &&
  192229. #endif
  192230. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192231. {
  192232. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192233. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192234. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192235. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192236. {
  192237. if (row_info->bit_depth == 8)
  192238. {
  192239. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192240. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192241. {
  192242. png_bytep sp = row;
  192243. png_bytep dp = row;
  192244. for (i = 0; i < row_width; i++)
  192245. {
  192246. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192247. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192248. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192249. if(red != green || red != blue)
  192250. {
  192251. rgb_error |= 1;
  192252. *(dp++) = png_ptr->gamma_from_1[
  192253. (rc*red+gc*green+bc*blue)>>15];
  192254. }
  192255. else
  192256. *(dp++) = *(sp-1);
  192257. }
  192258. }
  192259. else
  192260. #endif
  192261. {
  192262. png_bytep sp = row;
  192263. png_bytep dp = row;
  192264. for (i = 0; i < row_width; i++)
  192265. {
  192266. png_byte red = *(sp++);
  192267. png_byte green = *(sp++);
  192268. png_byte blue = *(sp++);
  192269. if(red != green || red != blue)
  192270. {
  192271. rgb_error |= 1;
  192272. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192273. }
  192274. else
  192275. *(dp++) = *(sp-1);
  192276. }
  192277. }
  192278. }
  192279. else /* RGB bit_depth == 16 */
  192280. {
  192281. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192282. if (png_ptr->gamma_16_to_1 != NULL &&
  192283. png_ptr->gamma_16_from_1 != NULL)
  192284. {
  192285. png_bytep sp = row;
  192286. png_bytep dp = row;
  192287. for (i = 0; i < row_width; i++)
  192288. {
  192289. png_uint_16 red, green, blue, w;
  192290. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192291. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192292. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192293. if(red == green && red == blue)
  192294. w = red;
  192295. else
  192296. {
  192297. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192298. png_ptr->gamma_shift][red>>8];
  192299. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192300. png_ptr->gamma_shift][green>>8];
  192301. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192302. png_ptr->gamma_shift][blue>>8];
  192303. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192304. + bc*blue_1)>>15);
  192305. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192306. png_ptr->gamma_shift][gray16 >> 8];
  192307. rgb_error |= 1;
  192308. }
  192309. *(dp++) = (png_byte)((w>>8) & 0xff);
  192310. *(dp++) = (png_byte)(w & 0xff);
  192311. }
  192312. }
  192313. else
  192314. #endif
  192315. {
  192316. png_bytep sp = row;
  192317. png_bytep dp = row;
  192318. for (i = 0; i < row_width; i++)
  192319. {
  192320. png_uint_16 red, green, blue, gray16;
  192321. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192322. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192323. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192324. if(red != green || red != blue)
  192325. rgb_error |= 1;
  192326. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192327. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192328. *(dp++) = (png_byte)(gray16 & 0xff);
  192329. }
  192330. }
  192331. }
  192332. }
  192333. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192334. {
  192335. if (row_info->bit_depth == 8)
  192336. {
  192337. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192338. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192339. {
  192340. png_bytep sp = row;
  192341. png_bytep dp = row;
  192342. for (i = 0; i < row_width; i++)
  192343. {
  192344. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192345. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192346. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192347. if(red != green || red != blue)
  192348. rgb_error |= 1;
  192349. *(dp++) = png_ptr->gamma_from_1
  192350. [(rc*red + gc*green + bc*blue)>>15];
  192351. *(dp++) = *(sp++); /* alpha */
  192352. }
  192353. }
  192354. else
  192355. #endif
  192356. {
  192357. png_bytep sp = row;
  192358. png_bytep dp = row;
  192359. for (i = 0; i < row_width; i++)
  192360. {
  192361. png_byte red = *(sp++);
  192362. png_byte green = *(sp++);
  192363. png_byte blue = *(sp++);
  192364. if(red != green || red != blue)
  192365. rgb_error |= 1;
  192366. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192367. *(dp++) = *(sp++); /* alpha */
  192368. }
  192369. }
  192370. }
  192371. else /* RGBA bit_depth == 16 */
  192372. {
  192373. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192374. if (png_ptr->gamma_16_to_1 != NULL &&
  192375. png_ptr->gamma_16_from_1 != NULL)
  192376. {
  192377. png_bytep sp = row;
  192378. png_bytep dp = row;
  192379. for (i = 0; i < row_width; i++)
  192380. {
  192381. png_uint_16 red, green, blue, w;
  192382. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192383. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192384. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192385. if(red == green && red == blue)
  192386. w = red;
  192387. else
  192388. {
  192389. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192390. png_ptr->gamma_shift][red>>8];
  192391. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192392. png_ptr->gamma_shift][green>>8];
  192393. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192394. png_ptr->gamma_shift][blue>>8];
  192395. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192396. + gc * green_1 + bc * blue_1)>>15);
  192397. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192398. png_ptr->gamma_shift][gray16 >> 8];
  192399. rgb_error |= 1;
  192400. }
  192401. *(dp++) = (png_byte)((w>>8) & 0xff);
  192402. *(dp++) = (png_byte)(w & 0xff);
  192403. *(dp++) = *(sp++); /* alpha */
  192404. *(dp++) = *(sp++);
  192405. }
  192406. }
  192407. else
  192408. #endif
  192409. {
  192410. png_bytep sp = row;
  192411. png_bytep dp = row;
  192412. for (i = 0; i < row_width; i++)
  192413. {
  192414. png_uint_16 red, green, blue, gray16;
  192415. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192416. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192417. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192418. if(red != green || red != blue)
  192419. rgb_error |= 1;
  192420. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192421. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192422. *(dp++) = (png_byte)(gray16 & 0xff);
  192423. *(dp++) = *(sp++); /* alpha */
  192424. *(dp++) = *(sp++);
  192425. }
  192426. }
  192427. }
  192428. }
  192429. row_info->channels -= (png_byte)2;
  192430. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192431. row_info->pixel_depth = (png_byte)(row_info->channels *
  192432. row_info->bit_depth);
  192433. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192434. }
  192435. return rgb_error;
  192436. }
  192437. #endif
  192438. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192439. * large of png_color. This lets grayscale images be treated as
  192440. * paletted. Most useful for gamma correction and simplification
  192441. * of code.
  192442. */
  192443. void PNGAPI
  192444. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192445. {
  192446. int num_palette;
  192447. int color_inc;
  192448. int i;
  192449. int v;
  192450. png_debug(1, "in png_do_build_grayscale_palette\n");
  192451. if (palette == NULL)
  192452. return;
  192453. switch (bit_depth)
  192454. {
  192455. case 1:
  192456. num_palette = 2;
  192457. color_inc = 0xff;
  192458. break;
  192459. case 2:
  192460. num_palette = 4;
  192461. color_inc = 0x55;
  192462. break;
  192463. case 4:
  192464. num_palette = 16;
  192465. color_inc = 0x11;
  192466. break;
  192467. case 8:
  192468. num_palette = 256;
  192469. color_inc = 1;
  192470. break;
  192471. default:
  192472. num_palette = 0;
  192473. color_inc = 0;
  192474. break;
  192475. }
  192476. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192477. {
  192478. palette[i].red = (png_byte)v;
  192479. palette[i].green = (png_byte)v;
  192480. palette[i].blue = (png_byte)v;
  192481. }
  192482. }
  192483. /* This function is currently unused. Do we really need it? */
  192484. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192485. void /* PRIVATE */
  192486. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192487. int num_palette)
  192488. {
  192489. png_debug(1, "in png_correct_palette\n");
  192490. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192491. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192492. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192493. {
  192494. png_color back, back_1;
  192495. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192496. {
  192497. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192498. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192499. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192500. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192501. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192502. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192503. }
  192504. else
  192505. {
  192506. double g;
  192507. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192508. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192509. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192510. {
  192511. back.red = png_ptr->background.red;
  192512. back.green = png_ptr->background.green;
  192513. back.blue = png_ptr->background.blue;
  192514. }
  192515. else
  192516. {
  192517. back.red =
  192518. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192519. 255.0 + 0.5);
  192520. back.green =
  192521. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192522. 255.0 + 0.5);
  192523. back.blue =
  192524. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192525. 255.0 + 0.5);
  192526. }
  192527. g = 1.0 / png_ptr->background_gamma;
  192528. back_1.red =
  192529. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192530. 255.0 + 0.5);
  192531. back_1.green =
  192532. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192533. 255.0 + 0.5);
  192534. back_1.blue =
  192535. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192536. 255.0 + 0.5);
  192537. }
  192538. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192539. {
  192540. png_uint_32 i;
  192541. for (i = 0; i < (png_uint_32)num_palette; i++)
  192542. {
  192543. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192544. {
  192545. palette[i] = back;
  192546. }
  192547. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192548. {
  192549. png_byte v, w;
  192550. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192551. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192552. palette[i].red = png_ptr->gamma_from_1[w];
  192553. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192554. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192555. palette[i].green = png_ptr->gamma_from_1[w];
  192556. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192557. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192558. palette[i].blue = png_ptr->gamma_from_1[w];
  192559. }
  192560. else
  192561. {
  192562. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192563. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192564. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192565. }
  192566. }
  192567. }
  192568. else
  192569. {
  192570. int i;
  192571. for (i = 0; i < num_palette; i++)
  192572. {
  192573. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192574. {
  192575. palette[i] = back;
  192576. }
  192577. else
  192578. {
  192579. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192580. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192581. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192582. }
  192583. }
  192584. }
  192585. }
  192586. else
  192587. #endif
  192588. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192589. if (png_ptr->transformations & PNG_GAMMA)
  192590. {
  192591. int i;
  192592. for (i = 0; i < num_palette; i++)
  192593. {
  192594. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192595. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192596. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192597. }
  192598. }
  192599. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192600. else
  192601. #endif
  192602. #endif
  192603. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192604. if (png_ptr->transformations & PNG_BACKGROUND)
  192605. {
  192606. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192607. {
  192608. png_color back;
  192609. back.red = (png_byte)png_ptr->background.red;
  192610. back.green = (png_byte)png_ptr->background.green;
  192611. back.blue = (png_byte)png_ptr->background.blue;
  192612. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192613. {
  192614. if (png_ptr->trans[i] == 0)
  192615. {
  192616. palette[i].red = back.red;
  192617. palette[i].green = back.green;
  192618. palette[i].blue = back.blue;
  192619. }
  192620. else if (png_ptr->trans[i] != 0xff)
  192621. {
  192622. png_composite(palette[i].red, png_ptr->palette[i].red,
  192623. png_ptr->trans[i], back.red);
  192624. png_composite(palette[i].green, png_ptr->palette[i].green,
  192625. png_ptr->trans[i], back.green);
  192626. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192627. png_ptr->trans[i], back.blue);
  192628. }
  192629. }
  192630. }
  192631. else /* assume grayscale palette (what else could it be?) */
  192632. {
  192633. int i;
  192634. for (i = 0; i < num_palette; i++)
  192635. {
  192636. if (i == (png_byte)png_ptr->trans_values.gray)
  192637. {
  192638. palette[i].red = (png_byte)png_ptr->background.red;
  192639. palette[i].green = (png_byte)png_ptr->background.green;
  192640. palette[i].blue = (png_byte)png_ptr->background.blue;
  192641. }
  192642. }
  192643. }
  192644. }
  192645. #endif
  192646. }
  192647. #endif
  192648. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192649. /* Replace any alpha or transparency with the supplied background color.
  192650. * "background" is already in the screen gamma, while "background_1" is
  192651. * at a gamma of 1.0. Paletted files have already been taken care of.
  192652. */
  192653. void /* PRIVATE */
  192654. png_do_background(png_row_infop row_info, png_bytep row,
  192655. png_color_16p trans_values, png_color_16p background
  192656. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192657. , png_color_16p background_1,
  192658. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192659. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192660. png_uint_16pp gamma_16_to_1, int gamma_shift
  192661. #endif
  192662. )
  192663. {
  192664. png_bytep sp, dp;
  192665. png_uint_32 i;
  192666. png_uint_32 row_width=row_info->width;
  192667. int shift;
  192668. png_debug(1, "in png_do_background\n");
  192669. if (background != NULL &&
  192670. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192671. row != NULL && row_info != NULL &&
  192672. #endif
  192673. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192674. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192675. {
  192676. switch (row_info->color_type)
  192677. {
  192678. case PNG_COLOR_TYPE_GRAY:
  192679. {
  192680. switch (row_info->bit_depth)
  192681. {
  192682. case 1:
  192683. {
  192684. sp = row;
  192685. shift = 7;
  192686. for (i = 0; i < row_width; i++)
  192687. {
  192688. if ((png_uint_16)((*sp >> shift) & 0x01)
  192689. == trans_values->gray)
  192690. {
  192691. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192692. *sp |= (png_byte)(background->gray << shift);
  192693. }
  192694. if (!shift)
  192695. {
  192696. shift = 7;
  192697. sp++;
  192698. }
  192699. else
  192700. shift--;
  192701. }
  192702. break;
  192703. }
  192704. case 2:
  192705. {
  192706. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192707. if (gamma_table != NULL)
  192708. {
  192709. sp = row;
  192710. shift = 6;
  192711. for (i = 0; i < row_width; i++)
  192712. {
  192713. if ((png_uint_16)((*sp >> shift) & 0x03)
  192714. == trans_values->gray)
  192715. {
  192716. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192717. *sp |= (png_byte)(background->gray << shift);
  192718. }
  192719. else
  192720. {
  192721. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192722. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192723. (p << 4) | (p << 6)] >> 6) & 0x03);
  192724. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192725. *sp |= (png_byte)(g << shift);
  192726. }
  192727. if (!shift)
  192728. {
  192729. shift = 6;
  192730. sp++;
  192731. }
  192732. else
  192733. shift -= 2;
  192734. }
  192735. }
  192736. else
  192737. #endif
  192738. {
  192739. sp = row;
  192740. shift = 6;
  192741. for (i = 0; i < row_width; i++)
  192742. {
  192743. if ((png_uint_16)((*sp >> shift) & 0x03)
  192744. == trans_values->gray)
  192745. {
  192746. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192747. *sp |= (png_byte)(background->gray << shift);
  192748. }
  192749. if (!shift)
  192750. {
  192751. shift = 6;
  192752. sp++;
  192753. }
  192754. else
  192755. shift -= 2;
  192756. }
  192757. }
  192758. break;
  192759. }
  192760. case 4:
  192761. {
  192762. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192763. if (gamma_table != NULL)
  192764. {
  192765. sp = row;
  192766. shift = 4;
  192767. for (i = 0; i < row_width; i++)
  192768. {
  192769. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192770. == trans_values->gray)
  192771. {
  192772. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192773. *sp |= (png_byte)(background->gray << shift);
  192774. }
  192775. else
  192776. {
  192777. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192778. png_byte g = (png_byte)((gamma_table[p |
  192779. (p << 4)] >> 4) & 0x0f);
  192780. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192781. *sp |= (png_byte)(g << shift);
  192782. }
  192783. if (!shift)
  192784. {
  192785. shift = 4;
  192786. sp++;
  192787. }
  192788. else
  192789. shift -= 4;
  192790. }
  192791. }
  192792. else
  192793. #endif
  192794. {
  192795. sp = row;
  192796. shift = 4;
  192797. for (i = 0; i < row_width; i++)
  192798. {
  192799. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192800. == trans_values->gray)
  192801. {
  192802. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192803. *sp |= (png_byte)(background->gray << shift);
  192804. }
  192805. if (!shift)
  192806. {
  192807. shift = 4;
  192808. sp++;
  192809. }
  192810. else
  192811. shift -= 4;
  192812. }
  192813. }
  192814. break;
  192815. }
  192816. case 8:
  192817. {
  192818. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192819. if (gamma_table != NULL)
  192820. {
  192821. sp = row;
  192822. for (i = 0; i < row_width; i++, sp++)
  192823. {
  192824. if (*sp == trans_values->gray)
  192825. {
  192826. *sp = (png_byte)background->gray;
  192827. }
  192828. else
  192829. {
  192830. *sp = gamma_table[*sp];
  192831. }
  192832. }
  192833. }
  192834. else
  192835. #endif
  192836. {
  192837. sp = row;
  192838. for (i = 0; i < row_width; i++, sp++)
  192839. {
  192840. if (*sp == trans_values->gray)
  192841. {
  192842. *sp = (png_byte)background->gray;
  192843. }
  192844. }
  192845. }
  192846. break;
  192847. }
  192848. case 16:
  192849. {
  192850. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192851. if (gamma_16 != NULL)
  192852. {
  192853. sp = row;
  192854. for (i = 0; i < row_width; i++, sp += 2)
  192855. {
  192856. png_uint_16 v;
  192857. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192858. if (v == trans_values->gray)
  192859. {
  192860. /* background is already in screen gamma */
  192861. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192862. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192863. }
  192864. else
  192865. {
  192866. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192867. *sp = (png_byte)((v >> 8) & 0xff);
  192868. *(sp + 1) = (png_byte)(v & 0xff);
  192869. }
  192870. }
  192871. }
  192872. else
  192873. #endif
  192874. {
  192875. sp = row;
  192876. for (i = 0; i < row_width; i++, sp += 2)
  192877. {
  192878. png_uint_16 v;
  192879. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192880. if (v == trans_values->gray)
  192881. {
  192882. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192883. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192884. }
  192885. }
  192886. }
  192887. break;
  192888. }
  192889. }
  192890. break;
  192891. }
  192892. case PNG_COLOR_TYPE_RGB:
  192893. {
  192894. if (row_info->bit_depth == 8)
  192895. {
  192896. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192897. if (gamma_table != NULL)
  192898. {
  192899. sp = row;
  192900. for (i = 0; i < row_width; i++, sp += 3)
  192901. {
  192902. if (*sp == trans_values->red &&
  192903. *(sp + 1) == trans_values->green &&
  192904. *(sp + 2) == trans_values->blue)
  192905. {
  192906. *sp = (png_byte)background->red;
  192907. *(sp + 1) = (png_byte)background->green;
  192908. *(sp + 2) = (png_byte)background->blue;
  192909. }
  192910. else
  192911. {
  192912. *sp = gamma_table[*sp];
  192913. *(sp + 1) = gamma_table[*(sp + 1)];
  192914. *(sp + 2) = gamma_table[*(sp + 2)];
  192915. }
  192916. }
  192917. }
  192918. else
  192919. #endif
  192920. {
  192921. sp = row;
  192922. for (i = 0; i < row_width; i++, sp += 3)
  192923. {
  192924. if (*sp == trans_values->red &&
  192925. *(sp + 1) == trans_values->green &&
  192926. *(sp + 2) == trans_values->blue)
  192927. {
  192928. *sp = (png_byte)background->red;
  192929. *(sp + 1) = (png_byte)background->green;
  192930. *(sp + 2) = (png_byte)background->blue;
  192931. }
  192932. }
  192933. }
  192934. }
  192935. else /* if (row_info->bit_depth == 16) */
  192936. {
  192937. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192938. if (gamma_16 != NULL)
  192939. {
  192940. sp = row;
  192941. for (i = 0; i < row_width; i++, sp += 6)
  192942. {
  192943. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192944. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192945. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192946. if (r == trans_values->red && g == trans_values->green &&
  192947. b == trans_values->blue)
  192948. {
  192949. /* background is already in screen gamma */
  192950. *sp = (png_byte)((background->red >> 8) & 0xff);
  192951. *(sp + 1) = (png_byte)(background->red & 0xff);
  192952. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192953. *(sp + 3) = (png_byte)(background->green & 0xff);
  192954. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192955. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192956. }
  192957. else
  192958. {
  192959. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192960. *sp = (png_byte)((v >> 8) & 0xff);
  192961. *(sp + 1) = (png_byte)(v & 0xff);
  192962. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192963. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192964. *(sp + 3) = (png_byte)(v & 0xff);
  192965. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192966. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192967. *(sp + 5) = (png_byte)(v & 0xff);
  192968. }
  192969. }
  192970. }
  192971. else
  192972. #endif
  192973. {
  192974. sp = row;
  192975. for (i = 0; i < row_width; i++, sp += 6)
  192976. {
  192977. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192978. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192979. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192980. if (r == trans_values->red && g == trans_values->green &&
  192981. b == trans_values->blue)
  192982. {
  192983. *sp = (png_byte)((background->red >> 8) & 0xff);
  192984. *(sp + 1) = (png_byte)(background->red & 0xff);
  192985. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192986. *(sp + 3) = (png_byte)(background->green & 0xff);
  192987. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192988. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192989. }
  192990. }
  192991. }
  192992. }
  192993. break;
  192994. }
  192995. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192996. {
  192997. if (row_info->bit_depth == 8)
  192998. {
  192999. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193000. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193001. gamma_table != NULL)
  193002. {
  193003. sp = row;
  193004. dp = row;
  193005. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193006. {
  193007. png_uint_16 a = *(sp + 1);
  193008. if (a == 0xff)
  193009. {
  193010. *dp = gamma_table[*sp];
  193011. }
  193012. else if (a == 0)
  193013. {
  193014. /* background is already in screen gamma */
  193015. *dp = (png_byte)background->gray;
  193016. }
  193017. else
  193018. {
  193019. png_byte v, w;
  193020. v = gamma_to_1[*sp];
  193021. png_composite(w, v, a, background_1->gray);
  193022. *dp = gamma_from_1[w];
  193023. }
  193024. }
  193025. }
  193026. else
  193027. #endif
  193028. {
  193029. sp = row;
  193030. dp = row;
  193031. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193032. {
  193033. png_byte a = *(sp + 1);
  193034. if (a == 0xff)
  193035. {
  193036. *dp = *sp;
  193037. }
  193038. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193039. else if (a == 0)
  193040. {
  193041. *dp = (png_byte)background->gray;
  193042. }
  193043. else
  193044. {
  193045. png_composite(*dp, *sp, a, background_1->gray);
  193046. }
  193047. #else
  193048. *dp = (png_byte)background->gray;
  193049. #endif
  193050. }
  193051. }
  193052. }
  193053. else /* if (png_ptr->bit_depth == 16) */
  193054. {
  193055. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193056. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193057. gamma_16_to_1 != NULL)
  193058. {
  193059. sp = row;
  193060. dp = row;
  193061. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193062. {
  193063. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193064. if (a == (png_uint_16)0xffff)
  193065. {
  193066. png_uint_16 v;
  193067. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193068. *dp = (png_byte)((v >> 8) & 0xff);
  193069. *(dp + 1) = (png_byte)(v & 0xff);
  193070. }
  193071. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193072. else if (a == 0)
  193073. #else
  193074. else
  193075. #endif
  193076. {
  193077. /* background is already in screen gamma */
  193078. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193079. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193080. }
  193081. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193082. else
  193083. {
  193084. png_uint_16 g, v, w;
  193085. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193086. png_composite_16(v, g, a, background_1->gray);
  193087. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  193088. *dp = (png_byte)((w >> 8) & 0xff);
  193089. *(dp + 1) = (png_byte)(w & 0xff);
  193090. }
  193091. #endif
  193092. }
  193093. }
  193094. else
  193095. #endif
  193096. {
  193097. sp = row;
  193098. dp = row;
  193099. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193100. {
  193101. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193102. if (a == (png_uint_16)0xffff)
  193103. {
  193104. png_memcpy(dp, sp, 2);
  193105. }
  193106. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193107. else if (a == 0)
  193108. #else
  193109. else
  193110. #endif
  193111. {
  193112. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193113. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193114. }
  193115. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193116. else
  193117. {
  193118. png_uint_16 g, v;
  193119. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193120. png_composite_16(v, g, a, background_1->gray);
  193121. *dp = (png_byte)((v >> 8) & 0xff);
  193122. *(dp + 1) = (png_byte)(v & 0xff);
  193123. }
  193124. #endif
  193125. }
  193126. }
  193127. }
  193128. break;
  193129. }
  193130. case PNG_COLOR_TYPE_RGB_ALPHA:
  193131. {
  193132. if (row_info->bit_depth == 8)
  193133. {
  193134. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193135. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193136. gamma_table != NULL)
  193137. {
  193138. sp = row;
  193139. dp = row;
  193140. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193141. {
  193142. png_byte a = *(sp + 3);
  193143. if (a == 0xff)
  193144. {
  193145. *dp = gamma_table[*sp];
  193146. *(dp + 1) = gamma_table[*(sp + 1)];
  193147. *(dp + 2) = gamma_table[*(sp + 2)];
  193148. }
  193149. else if (a == 0)
  193150. {
  193151. /* background is already in screen gamma */
  193152. *dp = (png_byte)background->red;
  193153. *(dp + 1) = (png_byte)background->green;
  193154. *(dp + 2) = (png_byte)background->blue;
  193155. }
  193156. else
  193157. {
  193158. png_byte v, w;
  193159. v = gamma_to_1[*sp];
  193160. png_composite(w, v, a, background_1->red);
  193161. *dp = gamma_from_1[w];
  193162. v = gamma_to_1[*(sp + 1)];
  193163. png_composite(w, v, a, background_1->green);
  193164. *(dp + 1) = gamma_from_1[w];
  193165. v = gamma_to_1[*(sp + 2)];
  193166. png_composite(w, v, a, background_1->blue);
  193167. *(dp + 2) = gamma_from_1[w];
  193168. }
  193169. }
  193170. }
  193171. else
  193172. #endif
  193173. {
  193174. sp = row;
  193175. dp = row;
  193176. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193177. {
  193178. png_byte a = *(sp + 3);
  193179. if (a == 0xff)
  193180. {
  193181. *dp = *sp;
  193182. *(dp + 1) = *(sp + 1);
  193183. *(dp + 2) = *(sp + 2);
  193184. }
  193185. else if (a == 0)
  193186. {
  193187. *dp = (png_byte)background->red;
  193188. *(dp + 1) = (png_byte)background->green;
  193189. *(dp + 2) = (png_byte)background->blue;
  193190. }
  193191. else
  193192. {
  193193. png_composite(*dp, *sp, a, background->red);
  193194. png_composite(*(dp + 1), *(sp + 1), a,
  193195. background->green);
  193196. png_composite(*(dp + 2), *(sp + 2), a,
  193197. background->blue);
  193198. }
  193199. }
  193200. }
  193201. }
  193202. else /* if (row_info->bit_depth == 16) */
  193203. {
  193204. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193205. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193206. gamma_16_to_1 != NULL)
  193207. {
  193208. sp = row;
  193209. dp = row;
  193210. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193211. {
  193212. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193213. << 8) + (png_uint_16)(*(sp + 7)));
  193214. if (a == (png_uint_16)0xffff)
  193215. {
  193216. png_uint_16 v;
  193217. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193218. *dp = (png_byte)((v >> 8) & 0xff);
  193219. *(dp + 1) = (png_byte)(v & 0xff);
  193220. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193221. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193222. *(dp + 3) = (png_byte)(v & 0xff);
  193223. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193224. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193225. *(dp + 5) = (png_byte)(v & 0xff);
  193226. }
  193227. else if (a == 0)
  193228. {
  193229. /* background is already in screen gamma */
  193230. *dp = (png_byte)((background->red >> 8) & 0xff);
  193231. *(dp + 1) = (png_byte)(background->red & 0xff);
  193232. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193233. *(dp + 3) = (png_byte)(background->green & 0xff);
  193234. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193235. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193236. }
  193237. else
  193238. {
  193239. png_uint_16 v, w, x;
  193240. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193241. png_composite_16(w, v, a, background_1->red);
  193242. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193243. *dp = (png_byte)((x >> 8) & 0xff);
  193244. *(dp + 1) = (png_byte)(x & 0xff);
  193245. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193246. png_composite_16(w, v, a, background_1->green);
  193247. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193248. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193249. *(dp + 3) = (png_byte)(x & 0xff);
  193250. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193251. png_composite_16(w, v, a, background_1->blue);
  193252. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193253. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193254. *(dp + 5) = (png_byte)(x & 0xff);
  193255. }
  193256. }
  193257. }
  193258. else
  193259. #endif
  193260. {
  193261. sp = row;
  193262. dp = row;
  193263. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193264. {
  193265. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193266. << 8) + (png_uint_16)(*(sp + 7)));
  193267. if (a == (png_uint_16)0xffff)
  193268. {
  193269. png_memcpy(dp, sp, 6);
  193270. }
  193271. else if (a == 0)
  193272. {
  193273. *dp = (png_byte)((background->red >> 8) & 0xff);
  193274. *(dp + 1) = (png_byte)(background->red & 0xff);
  193275. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193276. *(dp + 3) = (png_byte)(background->green & 0xff);
  193277. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193278. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193279. }
  193280. else
  193281. {
  193282. png_uint_16 v;
  193283. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193284. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193285. + *(sp + 3));
  193286. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193287. + *(sp + 5));
  193288. png_composite_16(v, r, a, background->red);
  193289. *dp = (png_byte)((v >> 8) & 0xff);
  193290. *(dp + 1) = (png_byte)(v & 0xff);
  193291. png_composite_16(v, g, a, background->green);
  193292. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193293. *(dp + 3) = (png_byte)(v & 0xff);
  193294. png_composite_16(v, b, a, background->blue);
  193295. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193296. *(dp + 5) = (png_byte)(v & 0xff);
  193297. }
  193298. }
  193299. }
  193300. }
  193301. break;
  193302. }
  193303. }
  193304. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193305. {
  193306. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193307. row_info->channels--;
  193308. row_info->pixel_depth = (png_byte)(row_info->channels *
  193309. row_info->bit_depth);
  193310. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193311. }
  193312. }
  193313. }
  193314. #endif
  193315. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193316. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193317. * you do this after you deal with the transparency issue on grayscale
  193318. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193319. * is 16, use gamma_16_table and gamma_shift. Build these with
  193320. * build_gamma_table().
  193321. */
  193322. void /* PRIVATE */
  193323. png_do_gamma(png_row_infop row_info, png_bytep row,
  193324. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193325. int gamma_shift)
  193326. {
  193327. png_bytep sp;
  193328. png_uint_32 i;
  193329. png_uint_32 row_width=row_info->width;
  193330. png_debug(1, "in png_do_gamma\n");
  193331. if (
  193332. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193333. row != NULL && row_info != NULL &&
  193334. #endif
  193335. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193336. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193337. {
  193338. switch (row_info->color_type)
  193339. {
  193340. case PNG_COLOR_TYPE_RGB:
  193341. {
  193342. if (row_info->bit_depth == 8)
  193343. {
  193344. sp = row;
  193345. for (i = 0; i < row_width; i++)
  193346. {
  193347. *sp = gamma_table[*sp];
  193348. sp++;
  193349. *sp = gamma_table[*sp];
  193350. sp++;
  193351. *sp = gamma_table[*sp];
  193352. sp++;
  193353. }
  193354. }
  193355. else /* if (row_info->bit_depth == 16) */
  193356. {
  193357. sp = row;
  193358. for (i = 0; i < row_width; i++)
  193359. {
  193360. png_uint_16 v;
  193361. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193362. *sp = (png_byte)((v >> 8) & 0xff);
  193363. *(sp + 1) = (png_byte)(v & 0xff);
  193364. sp += 2;
  193365. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193366. *sp = (png_byte)((v >> 8) & 0xff);
  193367. *(sp + 1) = (png_byte)(v & 0xff);
  193368. sp += 2;
  193369. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193370. *sp = (png_byte)((v >> 8) & 0xff);
  193371. *(sp + 1) = (png_byte)(v & 0xff);
  193372. sp += 2;
  193373. }
  193374. }
  193375. break;
  193376. }
  193377. case PNG_COLOR_TYPE_RGB_ALPHA:
  193378. {
  193379. if (row_info->bit_depth == 8)
  193380. {
  193381. sp = row;
  193382. for (i = 0; i < row_width; i++)
  193383. {
  193384. *sp = gamma_table[*sp];
  193385. sp++;
  193386. *sp = gamma_table[*sp];
  193387. sp++;
  193388. *sp = gamma_table[*sp];
  193389. sp++;
  193390. sp++;
  193391. }
  193392. }
  193393. else /* if (row_info->bit_depth == 16) */
  193394. {
  193395. sp = row;
  193396. for (i = 0; i < row_width; i++)
  193397. {
  193398. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193399. *sp = (png_byte)((v >> 8) & 0xff);
  193400. *(sp + 1) = (png_byte)(v & 0xff);
  193401. sp += 2;
  193402. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193403. *sp = (png_byte)((v >> 8) & 0xff);
  193404. *(sp + 1) = (png_byte)(v & 0xff);
  193405. sp += 2;
  193406. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193407. *sp = (png_byte)((v >> 8) & 0xff);
  193408. *(sp + 1) = (png_byte)(v & 0xff);
  193409. sp += 4;
  193410. }
  193411. }
  193412. break;
  193413. }
  193414. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193415. {
  193416. if (row_info->bit_depth == 8)
  193417. {
  193418. sp = row;
  193419. for (i = 0; i < row_width; i++)
  193420. {
  193421. *sp = gamma_table[*sp];
  193422. sp += 2;
  193423. }
  193424. }
  193425. else /* if (row_info->bit_depth == 16) */
  193426. {
  193427. sp = row;
  193428. for (i = 0; i < row_width; i++)
  193429. {
  193430. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193431. *sp = (png_byte)((v >> 8) & 0xff);
  193432. *(sp + 1) = (png_byte)(v & 0xff);
  193433. sp += 4;
  193434. }
  193435. }
  193436. break;
  193437. }
  193438. case PNG_COLOR_TYPE_GRAY:
  193439. {
  193440. if (row_info->bit_depth == 2)
  193441. {
  193442. sp = row;
  193443. for (i = 0; i < row_width; i += 4)
  193444. {
  193445. int a = *sp & 0xc0;
  193446. int b = *sp & 0x30;
  193447. int c = *sp & 0x0c;
  193448. int d = *sp & 0x03;
  193449. *sp = (png_byte)(
  193450. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193451. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193452. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193453. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193454. sp++;
  193455. }
  193456. }
  193457. if (row_info->bit_depth == 4)
  193458. {
  193459. sp = row;
  193460. for (i = 0; i < row_width; i += 2)
  193461. {
  193462. int msb = *sp & 0xf0;
  193463. int lsb = *sp & 0x0f;
  193464. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193465. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193466. sp++;
  193467. }
  193468. }
  193469. else if (row_info->bit_depth == 8)
  193470. {
  193471. sp = row;
  193472. for (i = 0; i < row_width; i++)
  193473. {
  193474. *sp = gamma_table[*sp];
  193475. sp++;
  193476. }
  193477. }
  193478. else if (row_info->bit_depth == 16)
  193479. {
  193480. sp = row;
  193481. for (i = 0; i < row_width; i++)
  193482. {
  193483. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193484. *sp = (png_byte)((v >> 8) & 0xff);
  193485. *(sp + 1) = (png_byte)(v & 0xff);
  193486. sp += 2;
  193487. }
  193488. }
  193489. break;
  193490. }
  193491. }
  193492. }
  193493. }
  193494. #endif
  193495. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193496. /* Expands a palette row to an RGB or RGBA row depending
  193497. * upon whether you supply trans and num_trans.
  193498. */
  193499. void /* PRIVATE */
  193500. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193501. png_colorp palette, png_bytep trans, int num_trans)
  193502. {
  193503. int shift, value;
  193504. png_bytep sp, dp;
  193505. png_uint_32 i;
  193506. png_uint_32 row_width=row_info->width;
  193507. png_debug(1, "in png_do_expand_palette\n");
  193508. if (
  193509. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193510. row != NULL && row_info != NULL &&
  193511. #endif
  193512. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193513. {
  193514. if (row_info->bit_depth < 8)
  193515. {
  193516. switch (row_info->bit_depth)
  193517. {
  193518. case 1:
  193519. {
  193520. sp = row + (png_size_t)((row_width - 1) >> 3);
  193521. dp = row + (png_size_t)row_width - 1;
  193522. shift = 7 - (int)((row_width + 7) & 0x07);
  193523. for (i = 0; i < row_width; i++)
  193524. {
  193525. if ((*sp >> shift) & 0x01)
  193526. *dp = 1;
  193527. else
  193528. *dp = 0;
  193529. if (shift == 7)
  193530. {
  193531. shift = 0;
  193532. sp--;
  193533. }
  193534. else
  193535. shift++;
  193536. dp--;
  193537. }
  193538. break;
  193539. }
  193540. case 2:
  193541. {
  193542. sp = row + (png_size_t)((row_width - 1) >> 2);
  193543. dp = row + (png_size_t)row_width - 1;
  193544. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193545. for (i = 0; i < row_width; i++)
  193546. {
  193547. value = (*sp >> shift) & 0x03;
  193548. *dp = (png_byte)value;
  193549. if (shift == 6)
  193550. {
  193551. shift = 0;
  193552. sp--;
  193553. }
  193554. else
  193555. shift += 2;
  193556. dp--;
  193557. }
  193558. break;
  193559. }
  193560. case 4:
  193561. {
  193562. sp = row + (png_size_t)((row_width - 1) >> 1);
  193563. dp = row + (png_size_t)row_width - 1;
  193564. shift = (int)((row_width & 0x01) << 2);
  193565. for (i = 0; i < row_width; i++)
  193566. {
  193567. value = (*sp >> shift) & 0x0f;
  193568. *dp = (png_byte)value;
  193569. if (shift == 4)
  193570. {
  193571. shift = 0;
  193572. sp--;
  193573. }
  193574. else
  193575. shift += 4;
  193576. dp--;
  193577. }
  193578. break;
  193579. }
  193580. }
  193581. row_info->bit_depth = 8;
  193582. row_info->pixel_depth = 8;
  193583. row_info->rowbytes = row_width;
  193584. }
  193585. switch (row_info->bit_depth)
  193586. {
  193587. case 8:
  193588. {
  193589. if (trans != NULL)
  193590. {
  193591. sp = row + (png_size_t)row_width - 1;
  193592. dp = row + (png_size_t)(row_width << 2) - 1;
  193593. for (i = 0; i < row_width; i++)
  193594. {
  193595. if ((int)(*sp) >= num_trans)
  193596. *dp-- = 0xff;
  193597. else
  193598. *dp-- = trans[*sp];
  193599. *dp-- = palette[*sp].blue;
  193600. *dp-- = palette[*sp].green;
  193601. *dp-- = palette[*sp].red;
  193602. sp--;
  193603. }
  193604. row_info->bit_depth = 8;
  193605. row_info->pixel_depth = 32;
  193606. row_info->rowbytes = row_width * 4;
  193607. row_info->color_type = 6;
  193608. row_info->channels = 4;
  193609. }
  193610. else
  193611. {
  193612. sp = row + (png_size_t)row_width - 1;
  193613. dp = row + (png_size_t)(row_width * 3) - 1;
  193614. for (i = 0; i < row_width; i++)
  193615. {
  193616. *dp-- = palette[*sp].blue;
  193617. *dp-- = palette[*sp].green;
  193618. *dp-- = palette[*sp].red;
  193619. sp--;
  193620. }
  193621. row_info->bit_depth = 8;
  193622. row_info->pixel_depth = 24;
  193623. row_info->rowbytes = row_width * 3;
  193624. row_info->color_type = 2;
  193625. row_info->channels = 3;
  193626. }
  193627. break;
  193628. }
  193629. }
  193630. }
  193631. }
  193632. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193633. * expanded transparency value is supplied, an alpha channel is built.
  193634. */
  193635. void /* PRIVATE */
  193636. png_do_expand(png_row_infop row_info, png_bytep row,
  193637. png_color_16p trans_value)
  193638. {
  193639. int shift, value;
  193640. png_bytep sp, dp;
  193641. png_uint_32 i;
  193642. png_uint_32 row_width=row_info->width;
  193643. png_debug(1, "in png_do_expand\n");
  193644. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193645. if (row != NULL && row_info != NULL)
  193646. #endif
  193647. {
  193648. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193649. {
  193650. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193651. if (row_info->bit_depth < 8)
  193652. {
  193653. switch (row_info->bit_depth)
  193654. {
  193655. case 1:
  193656. {
  193657. gray = (png_uint_16)((gray&0x01)*0xff);
  193658. sp = row + (png_size_t)((row_width - 1) >> 3);
  193659. dp = row + (png_size_t)row_width - 1;
  193660. shift = 7 - (int)((row_width + 7) & 0x07);
  193661. for (i = 0; i < row_width; i++)
  193662. {
  193663. if ((*sp >> shift) & 0x01)
  193664. *dp = 0xff;
  193665. else
  193666. *dp = 0;
  193667. if (shift == 7)
  193668. {
  193669. shift = 0;
  193670. sp--;
  193671. }
  193672. else
  193673. shift++;
  193674. dp--;
  193675. }
  193676. break;
  193677. }
  193678. case 2:
  193679. {
  193680. gray = (png_uint_16)((gray&0x03)*0x55);
  193681. sp = row + (png_size_t)((row_width - 1) >> 2);
  193682. dp = row + (png_size_t)row_width - 1;
  193683. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193684. for (i = 0; i < row_width; i++)
  193685. {
  193686. value = (*sp >> shift) & 0x03;
  193687. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193688. (value << 6));
  193689. if (shift == 6)
  193690. {
  193691. shift = 0;
  193692. sp--;
  193693. }
  193694. else
  193695. shift += 2;
  193696. dp--;
  193697. }
  193698. break;
  193699. }
  193700. case 4:
  193701. {
  193702. gray = (png_uint_16)((gray&0x0f)*0x11);
  193703. sp = row + (png_size_t)((row_width - 1) >> 1);
  193704. dp = row + (png_size_t)row_width - 1;
  193705. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193706. for (i = 0; i < row_width; i++)
  193707. {
  193708. value = (*sp >> shift) & 0x0f;
  193709. *dp = (png_byte)(value | (value << 4));
  193710. if (shift == 4)
  193711. {
  193712. shift = 0;
  193713. sp--;
  193714. }
  193715. else
  193716. shift = 4;
  193717. dp--;
  193718. }
  193719. break;
  193720. }
  193721. }
  193722. row_info->bit_depth = 8;
  193723. row_info->pixel_depth = 8;
  193724. row_info->rowbytes = row_width;
  193725. }
  193726. if (trans_value != NULL)
  193727. {
  193728. if (row_info->bit_depth == 8)
  193729. {
  193730. gray = gray & 0xff;
  193731. sp = row + (png_size_t)row_width - 1;
  193732. dp = row + (png_size_t)(row_width << 1) - 1;
  193733. for (i = 0; i < row_width; i++)
  193734. {
  193735. if (*sp == gray)
  193736. *dp-- = 0;
  193737. else
  193738. *dp-- = 0xff;
  193739. *dp-- = *sp--;
  193740. }
  193741. }
  193742. else if (row_info->bit_depth == 16)
  193743. {
  193744. png_byte gray_high = (gray >> 8) & 0xff;
  193745. png_byte gray_low = gray & 0xff;
  193746. sp = row + row_info->rowbytes - 1;
  193747. dp = row + (row_info->rowbytes << 1) - 1;
  193748. for (i = 0; i < row_width; i++)
  193749. {
  193750. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193751. {
  193752. *dp-- = 0;
  193753. *dp-- = 0;
  193754. }
  193755. else
  193756. {
  193757. *dp-- = 0xff;
  193758. *dp-- = 0xff;
  193759. }
  193760. *dp-- = *sp--;
  193761. *dp-- = *sp--;
  193762. }
  193763. }
  193764. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193765. row_info->channels = 2;
  193766. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193767. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193768. row_width);
  193769. }
  193770. }
  193771. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193772. {
  193773. if (row_info->bit_depth == 8)
  193774. {
  193775. png_byte red = trans_value->red & 0xff;
  193776. png_byte green = trans_value->green & 0xff;
  193777. png_byte blue = trans_value->blue & 0xff;
  193778. sp = row + (png_size_t)row_info->rowbytes - 1;
  193779. dp = row + (png_size_t)(row_width << 2) - 1;
  193780. for (i = 0; i < row_width; i++)
  193781. {
  193782. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193783. *dp-- = 0;
  193784. else
  193785. *dp-- = 0xff;
  193786. *dp-- = *sp--;
  193787. *dp-- = *sp--;
  193788. *dp-- = *sp--;
  193789. }
  193790. }
  193791. else if (row_info->bit_depth == 16)
  193792. {
  193793. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193794. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193795. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193796. png_byte red_low = trans_value->red & 0xff;
  193797. png_byte green_low = trans_value->green & 0xff;
  193798. png_byte blue_low = trans_value->blue & 0xff;
  193799. sp = row + row_info->rowbytes - 1;
  193800. dp = row + (png_size_t)(row_width << 3) - 1;
  193801. for (i = 0; i < row_width; i++)
  193802. {
  193803. if (*(sp - 5) == red_high &&
  193804. *(sp - 4) == red_low &&
  193805. *(sp - 3) == green_high &&
  193806. *(sp - 2) == green_low &&
  193807. *(sp - 1) == blue_high &&
  193808. *(sp ) == blue_low)
  193809. {
  193810. *dp-- = 0;
  193811. *dp-- = 0;
  193812. }
  193813. else
  193814. {
  193815. *dp-- = 0xff;
  193816. *dp-- = 0xff;
  193817. }
  193818. *dp-- = *sp--;
  193819. *dp-- = *sp--;
  193820. *dp-- = *sp--;
  193821. *dp-- = *sp--;
  193822. *dp-- = *sp--;
  193823. *dp-- = *sp--;
  193824. }
  193825. }
  193826. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193827. row_info->channels = 4;
  193828. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193829. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193830. }
  193831. }
  193832. }
  193833. #endif
  193834. #if defined(PNG_READ_DITHER_SUPPORTED)
  193835. void /* PRIVATE */
  193836. png_do_dither(png_row_infop row_info, png_bytep row,
  193837. png_bytep palette_lookup, png_bytep dither_lookup)
  193838. {
  193839. png_bytep sp, dp;
  193840. png_uint_32 i;
  193841. png_uint_32 row_width=row_info->width;
  193842. png_debug(1, "in png_do_dither\n");
  193843. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193844. if (row != NULL && row_info != NULL)
  193845. #endif
  193846. {
  193847. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193848. palette_lookup && row_info->bit_depth == 8)
  193849. {
  193850. int r, g, b, p;
  193851. sp = row;
  193852. dp = row;
  193853. for (i = 0; i < row_width; i++)
  193854. {
  193855. r = *sp++;
  193856. g = *sp++;
  193857. b = *sp++;
  193858. /* this looks real messy, but the compiler will reduce
  193859. it down to a reasonable formula. For example, with
  193860. 5 bits per color, we get:
  193861. p = (((r >> 3) & 0x1f) << 10) |
  193862. (((g >> 3) & 0x1f) << 5) |
  193863. ((b >> 3) & 0x1f);
  193864. */
  193865. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193866. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193867. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193868. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193869. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193870. (PNG_DITHER_BLUE_BITS)) |
  193871. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193872. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193873. *dp++ = palette_lookup[p];
  193874. }
  193875. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193876. row_info->channels = 1;
  193877. row_info->pixel_depth = row_info->bit_depth;
  193878. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193879. }
  193880. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193881. palette_lookup != NULL && row_info->bit_depth == 8)
  193882. {
  193883. int r, g, b, p;
  193884. sp = row;
  193885. dp = row;
  193886. for (i = 0; i < row_width; i++)
  193887. {
  193888. r = *sp++;
  193889. g = *sp++;
  193890. b = *sp++;
  193891. sp++;
  193892. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193893. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193894. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193895. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193896. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193897. (PNG_DITHER_BLUE_BITS)) |
  193898. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193899. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193900. *dp++ = palette_lookup[p];
  193901. }
  193902. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193903. row_info->channels = 1;
  193904. row_info->pixel_depth = row_info->bit_depth;
  193905. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193906. }
  193907. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193908. dither_lookup && row_info->bit_depth == 8)
  193909. {
  193910. sp = row;
  193911. for (i = 0; i < row_width; i++, sp++)
  193912. {
  193913. *sp = dither_lookup[*sp];
  193914. }
  193915. }
  193916. }
  193917. }
  193918. #endif
  193919. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193920. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193921. static PNG_CONST int png_gamma_shift[] =
  193922. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193923. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193924. * tables, we don't make a full table if we are reducing to 8-bit in
  193925. * the future. Note also how the gamma_16 tables are segmented so that
  193926. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193927. */
  193928. void /* PRIVATE */
  193929. png_build_gamma_table(png_structp png_ptr)
  193930. {
  193931. png_debug(1, "in png_build_gamma_table\n");
  193932. if (png_ptr->bit_depth <= 8)
  193933. {
  193934. int i;
  193935. double g;
  193936. if (png_ptr->screen_gamma > .000001)
  193937. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193938. else
  193939. g = 1.0;
  193940. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193941. (png_uint_32)256);
  193942. for (i = 0; i < 256; i++)
  193943. {
  193944. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193945. g) * 255.0 + .5);
  193946. }
  193947. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193948. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193949. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193950. {
  193951. g = 1.0 / (png_ptr->gamma);
  193952. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193953. (png_uint_32)256);
  193954. for (i = 0; i < 256; i++)
  193955. {
  193956. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193957. g) * 255.0 + .5);
  193958. }
  193959. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193960. (png_uint_32)256);
  193961. if(png_ptr->screen_gamma > 0.000001)
  193962. g = 1.0 / png_ptr->screen_gamma;
  193963. else
  193964. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193965. for (i = 0; i < 256; i++)
  193966. {
  193967. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193968. g) * 255.0 + .5);
  193969. }
  193970. }
  193971. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193972. }
  193973. else
  193974. {
  193975. double g;
  193976. int i, j, shift, num;
  193977. int sig_bit;
  193978. png_uint_32 ig;
  193979. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193980. {
  193981. sig_bit = (int)png_ptr->sig_bit.red;
  193982. if ((int)png_ptr->sig_bit.green > sig_bit)
  193983. sig_bit = png_ptr->sig_bit.green;
  193984. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193985. sig_bit = png_ptr->sig_bit.blue;
  193986. }
  193987. else
  193988. {
  193989. sig_bit = (int)png_ptr->sig_bit.gray;
  193990. }
  193991. if (sig_bit > 0)
  193992. shift = 16 - sig_bit;
  193993. else
  193994. shift = 0;
  193995. if (png_ptr->transformations & PNG_16_TO_8)
  193996. {
  193997. if (shift < (16 - PNG_MAX_GAMMA_8))
  193998. shift = (16 - PNG_MAX_GAMMA_8);
  193999. }
  194000. if (shift > 8)
  194001. shift = 8;
  194002. if (shift < 0)
  194003. shift = 0;
  194004. png_ptr->gamma_shift = (png_byte)shift;
  194005. num = (1 << (8 - shift));
  194006. if (png_ptr->screen_gamma > .000001)
  194007. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  194008. else
  194009. g = 1.0;
  194010. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  194011. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194012. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  194013. {
  194014. double fin, fout;
  194015. png_uint_32 last, max;
  194016. for (i = 0; i < num; i++)
  194017. {
  194018. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194019. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194020. }
  194021. g = 1.0 / g;
  194022. last = 0;
  194023. for (i = 0; i < 256; i++)
  194024. {
  194025. fout = ((double)i + 0.5) / 256.0;
  194026. fin = pow(fout, g);
  194027. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  194028. while (last <= max)
  194029. {
  194030. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194031. [(int)(last >> (8 - shift))] = (png_uint_16)(
  194032. (png_uint_16)i | ((png_uint_16)i << 8));
  194033. last++;
  194034. }
  194035. }
  194036. while (last < ((png_uint_32)num << 8))
  194037. {
  194038. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194039. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  194040. last++;
  194041. }
  194042. }
  194043. else
  194044. {
  194045. for (i = 0; i < num; i++)
  194046. {
  194047. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194048. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194049. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  194050. for (j = 0; j < 256; j++)
  194051. {
  194052. png_ptr->gamma_16_table[i][j] =
  194053. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194054. 65535.0, g) * 65535.0 + .5);
  194055. }
  194056. }
  194057. }
  194058. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194059. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194060. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  194061. {
  194062. g = 1.0 / (png_ptr->gamma);
  194063. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  194064. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  194065. for (i = 0; i < num; i++)
  194066. {
  194067. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194068. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194069. ig = (((png_uint_32)i *
  194070. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194071. for (j = 0; j < 256; j++)
  194072. {
  194073. png_ptr->gamma_16_to_1[i][j] =
  194074. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194075. 65535.0, g) * 65535.0 + .5);
  194076. }
  194077. }
  194078. if(png_ptr->screen_gamma > 0.000001)
  194079. g = 1.0 / png_ptr->screen_gamma;
  194080. else
  194081. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194082. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  194083. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194084. for (i = 0; i < num; i++)
  194085. {
  194086. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194087. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194088. ig = (((png_uint_32)i *
  194089. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194090. for (j = 0; j < 256; j++)
  194091. {
  194092. png_ptr->gamma_16_from_1[i][j] =
  194093. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194094. 65535.0, g) * 65535.0 + .5);
  194095. }
  194096. }
  194097. }
  194098. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194099. }
  194100. }
  194101. #endif
  194102. /* To do: install integer version of png_build_gamma_table here */
  194103. #endif
  194104. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194105. /* undoes intrapixel differencing */
  194106. void /* PRIVATE */
  194107. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  194108. {
  194109. png_debug(1, "in png_do_read_intrapixel\n");
  194110. if (
  194111. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194112. row != NULL && row_info != NULL &&
  194113. #endif
  194114. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194115. {
  194116. int bytes_per_pixel;
  194117. png_uint_32 row_width = row_info->width;
  194118. if (row_info->bit_depth == 8)
  194119. {
  194120. png_bytep rp;
  194121. png_uint_32 i;
  194122. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194123. bytes_per_pixel = 3;
  194124. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194125. bytes_per_pixel = 4;
  194126. else
  194127. return;
  194128. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194129. {
  194130. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  194131. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  194132. }
  194133. }
  194134. else if (row_info->bit_depth == 16)
  194135. {
  194136. png_bytep rp;
  194137. png_uint_32 i;
  194138. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194139. bytes_per_pixel = 6;
  194140. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194141. bytes_per_pixel = 8;
  194142. else
  194143. return;
  194144. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194145. {
  194146. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194147. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194148. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194149. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194150. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194151. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194152. *(rp+1) = (png_byte)(red & 0xff);
  194153. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194154. *(rp+5) = (png_byte)(blue & 0xff);
  194155. }
  194156. }
  194157. }
  194158. }
  194159. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194160. #endif /* PNG_READ_SUPPORTED */
  194161. /*** End of inlined file: pngrtran.c ***/
  194162. /*** Start of inlined file: pngrutil.c ***/
  194163. /* pngrutil.c - utilities to read a PNG file
  194164. *
  194165. * Last changed in libpng 1.2.21 [October 4, 2007]
  194166. * For conditions of distribution and use, see copyright notice in png.h
  194167. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194168. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194169. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194170. *
  194171. * This file contains routines that are only called from within
  194172. * libpng itself during the course of reading an image.
  194173. */
  194174. #define PNG_INTERNAL
  194175. #if defined(PNG_READ_SUPPORTED)
  194176. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194177. # define WIN32_WCE_OLD
  194178. #endif
  194179. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194180. # if defined(WIN32_WCE_OLD)
  194181. /* strtod() function is not supported on WindowsCE */
  194182. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194183. {
  194184. double result = 0;
  194185. int len;
  194186. wchar_t *str, *end;
  194187. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194188. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194189. if ( NULL != str )
  194190. {
  194191. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194192. result = wcstod(str, &end);
  194193. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194194. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194195. png_free(png_ptr, str);
  194196. }
  194197. return result;
  194198. }
  194199. # else
  194200. # define png_strtod(p,a,b) strtod(a,b)
  194201. # endif
  194202. #endif
  194203. png_uint_32 PNGAPI
  194204. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194205. {
  194206. png_uint_32 i = png_get_uint_32(buf);
  194207. if (i > PNG_UINT_31_MAX)
  194208. png_error(png_ptr, "PNG unsigned integer out of range.");
  194209. return (i);
  194210. }
  194211. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194212. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194213. png_uint_32 PNGAPI
  194214. png_get_uint_32(png_bytep buf)
  194215. {
  194216. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194217. ((png_uint_32)(*(buf + 1)) << 16) +
  194218. ((png_uint_32)(*(buf + 2)) << 8) +
  194219. (png_uint_32)(*(buf + 3));
  194220. return (i);
  194221. }
  194222. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194223. * data is stored in the PNG file in two's complement format, and it is
  194224. * assumed that the machine format for signed integers is the same. */
  194225. png_int_32 PNGAPI
  194226. png_get_int_32(png_bytep buf)
  194227. {
  194228. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194229. ((png_int_32)(*(buf + 1)) << 16) +
  194230. ((png_int_32)(*(buf + 2)) << 8) +
  194231. (png_int_32)(*(buf + 3));
  194232. return (i);
  194233. }
  194234. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194235. png_uint_16 PNGAPI
  194236. png_get_uint_16(png_bytep buf)
  194237. {
  194238. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194239. (png_uint_16)(*(buf + 1)));
  194240. return (i);
  194241. }
  194242. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194243. /* Read data, and (optionally) run it through the CRC. */
  194244. void /* PRIVATE */
  194245. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194246. {
  194247. if(png_ptr == NULL) return;
  194248. png_read_data(png_ptr, buf, length);
  194249. png_calculate_crc(png_ptr, buf, length);
  194250. }
  194251. /* Optionally skip data and then check the CRC. Depending on whether we
  194252. are reading a ancillary or critical chunk, and how the program has set
  194253. things up, we may calculate the CRC on the data and print a message.
  194254. Returns '1' if there was a CRC error, '0' otherwise. */
  194255. int /* PRIVATE */
  194256. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194257. {
  194258. png_size_t i;
  194259. png_size_t istop = png_ptr->zbuf_size;
  194260. for (i = (png_size_t)skip; i > istop; i -= istop)
  194261. {
  194262. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194263. }
  194264. if (i)
  194265. {
  194266. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194267. }
  194268. if (png_crc_error(png_ptr))
  194269. {
  194270. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194271. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194272. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194273. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194274. {
  194275. png_chunk_warning(png_ptr, "CRC error");
  194276. }
  194277. else
  194278. {
  194279. png_chunk_error(png_ptr, "CRC error");
  194280. }
  194281. return (1);
  194282. }
  194283. return (0);
  194284. }
  194285. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194286. the data it has read thus far. */
  194287. int /* PRIVATE */
  194288. png_crc_error(png_structp png_ptr)
  194289. {
  194290. png_byte crc_bytes[4];
  194291. png_uint_32 crc;
  194292. int need_crc = 1;
  194293. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194294. {
  194295. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194296. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194297. need_crc = 0;
  194298. }
  194299. else /* critical */
  194300. {
  194301. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194302. need_crc = 0;
  194303. }
  194304. png_read_data(png_ptr, crc_bytes, 4);
  194305. if (need_crc)
  194306. {
  194307. crc = png_get_uint_32(crc_bytes);
  194308. return ((int)(crc != png_ptr->crc));
  194309. }
  194310. else
  194311. return (0);
  194312. }
  194313. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194314. defined(PNG_READ_iCCP_SUPPORTED)
  194315. /*
  194316. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194317. * points at an allocated area holding the contents of a chunk with a
  194318. * trailing compressed part. What we get back is an allocated area
  194319. * holding the original prefix part and an uncompressed version of the
  194320. * trailing part (the malloc area passed in is freed).
  194321. */
  194322. png_charp /* PRIVATE */
  194323. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194324. png_charp chunkdata, png_size_t chunklength,
  194325. png_size_t prefix_size, png_size_t *newlength)
  194326. {
  194327. static PNG_CONST char msg[] = "Error decoding compressed text";
  194328. png_charp text;
  194329. png_size_t text_size;
  194330. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194331. {
  194332. int ret = Z_OK;
  194333. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194334. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194335. png_ptr->zstream.next_out = png_ptr->zbuf;
  194336. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194337. text_size = 0;
  194338. text = NULL;
  194339. while (png_ptr->zstream.avail_in)
  194340. {
  194341. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194342. if (ret != Z_OK && ret != Z_STREAM_END)
  194343. {
  194344. if (png_ptr->zstream.msg != NULL)
  194345. png_warning(png_ptr, png_ptr->zstream.msg);
  194346. else
  194347. png_warning(png_ptr, msg);
  194348. inflateReset(&png_ptr->zstream);
  194349. png_ptr->zstream.avail_in = 0;
  194350. if (text == NULL)
  194351. {
  194352. text_size = prefix_size + png_sizeof(msg) + 1;
  194353. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194354. if (text == NULL)
  194355. {
  194356. png_free(png_ptr,chunkdata);
  194357. png_error(png_ptr,"Not enough memory to decompress chunk");
  194358. }
  194359. png_memcpy(text, chunkdata, prefix_size);
  194360. }
  194361. text[text_size - 1] = 0x00;
  194362. /* Copy what we can of the error message into the text chunk */
  194363. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194364. text_size = png_sizeof(msg) > text_size ? text_size :
  194365. png_sizeof(msg);
  194366. png_memcpy(text + prefix_size, msg, text_size + 1);
  194367. break;
  194368. }
  194369. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194370. {
  194371. if (text == NULL)
  194372. {
  194373. text_size = prefix_size +
  194374. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194375. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194376. if (text == NULL)
  194377. {
  194378. png_free(png_ptr,chunkdata);
  194379. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194380. }
  194381. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194382. text_size - prefix_size);
  194383. png_memcpy(text, chunkdata, prefix_size);
  194384. *(text + text_size) = 0x00;
  194385. }
  194386. else
  194387. {
  194388. png_charp tmp;
  194389. tmp = text;
  194390. text = (png_charp)png_malloc_warn(png_ptr,
  194391. (png_uint_32)(text_size +
  194392. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194393. if (text == NULL)
  194394. {
  194395. png_free(png_ptr, tmp);
  194396. png_free(png_ptr, chunkdata);
  194397. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194398. }
  194399. png_memcpy(text, tmp, text_size);
  194400. png_free(png_ptr, tmp);
  194401. png_memcpy(text + text_size, png_ptr->zbuf,
  194402. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194403. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194404. *(text + text_size) = 0x00;
  194405. }
  194406. if (ret == Z_STREAM_END)
  194407. break;
  194408. else
  194409. {
  194410. png_ptr->zstream.next_out = png_ptr->zbuf;
  194411. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194412. }
  194413. }
  194414. }
  194415. if (ret != Z_STREAM_END)
  194416. {
  194417. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194418. char umsg[52];
  194419. if (ret == Z_BUF_ERROR)
  194420. png_snprintf(umsg, 52,
  194421. "Buffer error in compressed datastream in %s chunk",
  194422. png_ptr->chunk_name);
  194423. else if (ret == Z_DATA_ERROR)
  194424. png_snprintf(umsg, 52,
  194425. "Data error in compressed datastream in %s chunk",
  194426. png_ptr->chunk_name);
  194427. else
  194428. png_snprintf(umsg, 52,
  194429. "Incomplete compressed datastream in %s chunk",
  194430. png_ptr->chunk_name);
  194431. png_warning(png_ptr, umsg);
  194432. #else
  194433. png_warning(png_ptr,
  194434. "Incomplete compressed datastream in chunk other than IDAT");
  194435. #endif
  194436. text_size=prefix_size;
  194437. if (text == NULL)
  194438. {
  194439. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194440. if (text == NULL)
  194441. {
  194442. png_free(png_ptr, chunkdata);
  194443. png_error(png_ptr,"Not enough memory for text.");
  194444. }
  194445. png_memcpy(text, chunkdata, prefix_size);
  194446. }
  194447. *(text + text_size) = 0x00;
  194448. }
  194449. inflateReset(&png_ptr->zstream);
  194450. png_ptr->zstream.avail_in = 0;
  194451. png_free(png_ptr, chunkdata);
  194452. chunkdata = text;
  194453. *newlength=text_size;
  194454. }
  194455. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194456. {
  194457. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194458. char umsg[50];
  194459. png_snprintf(umsg, 50,
  194460. "Unknown zTXt compression type %d", comp_type);
  194461. png_warning(png_ptr, umsg);
  194462. #else
  194463. png_warning(png_ptr, "Unknown zTXt compression type");
  194464. #endif
  194465. *(chunkdata + prefix_size) = 0x00;
  194466. *newlength=prefix_size;
  194467. }
  194468. return chunkdata;
  194469. }
  194470. #endif
  194471. /* read and check the IDHR chunk */
  194472. void /* PRIVATE */
  194473. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194474. {
  194475. png_byte buf[13];
  194476. png_uint_32 width, height;
  194477. int bit_depth, color_type, compression_type, filter_type;
  194478. int interlace_type;
  194479. png_debug(1, "in png_handle_IHDR\n");
  194480. if (png_ptr->mode & PNG_HAVE_IHDR)
  194481. png_error(png_ptr, "Out of place IHDR");
  194482. /* check the length */
  194483. if (length != 13)
  194484. png_error(png_ptr, "Invalid IHDR chunk");
  194485. png_ptr->mode |= PNG_HAVE_IHDR;
  194486. png_crc_read(png_ptr, buf, 13);
  194487. png_crc_finish(png_ptr, 0);
  194488. width = png_get_uint_31(png_ptr, buf);
  194489. height = png_get_uint_31(png_ptr, buf + 4);
  194490. bit_depth = buf[8];
  194491. color_type = buf[9];
  194492. compression_type = buf[10];
  194493. filter_type = buf[11];
  194494. interlace_type = buf[12];
  194495. /* set internal variables */
  194496. png_ptr->width = width;
  194497. png_ptr->height = height;
  194498. png_ptr->bit_depth = (png_byte)bit_depth;
  194499. png_ptr->interlaced = (png_byte)interlace_type;
  194500. png_ptr->color_type = (png_byte)color_type;
  194501. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194502. png_ptr->filter_type = (png_byte)filter_type;
  194503. #endif
  194504. png_ptr->compression_type = (png_byte)compression_type;
  194505. /* find number of channels */
  194506. switch (png_ptr->color_type)
  194507. {
  194508. case PNG_COLOR_TYPE_GRAY:
  194509. case PNG_COLOR_TYPE_PALETTE:
  194510. png_ptr->channels = 1;
  194511. break;
  194512. case PNG_COLOR_TYPE_RGB:
  194513. png_ptr->channels = 3;
  194514. break;
  194515. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194516. png_ptr->channels = 2;
  194517. break;
  194518. case PNG_COLOR_TYPE_RGB_ALPHA:
  194519. png_ptr->channels = 4;
  194520. break;
  194521. }
  194522. /* set up other useful info */
  194523. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194524. png_ptr->channels);
  194525. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194526. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194527. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194528. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194529. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194530. color_type, interlace_type, compression_type, filter_type);
  194531. }
  194532. /* read and check the palette */
  194533. void /* PRIVATE */
  194534. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194535. {
  194536. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194537. int num, i;
  194538. #ifndef PNG_NO_POINTER_INDEXING
  194539. png_colorp pal_ptr;
  194540. #endif
  194541. png_debug(1, "in png_handle_PLTE\n");
  194542. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194543. png_error(png_ptr, "Missing IHDR before PLTE");
  194544. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194545. {
  194546. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194547. png_crc_finish(png_ptr, length);
  194548. return;
  194549. }
  194550. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194551. png_error(png_ptr, "Duplicate PLTE chunk");
  194552. png_ptr->mode |= PNG_HAVE_PLTE;
  194553. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194554. {
  194555. png_warning(png_ptr,
  194556. "Ignoring PLTE chunk in grayscale PNG");
  194557. png_crc_finish(png_ptr, length);
  194558. return;
  194559. }
  194560. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194561. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194562. {
  194563. png_crc_finish(png_ptr, length);
  194564. return;
  194565. }
  194566. #endif
  194567. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194568. {
  194569. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194570. {
  194571. png_warning(png_ptr, "Invalid palette chunk");
  194572. png_crc_finish(png_ptr, length);
  194573. return;
  194574. }
  194575. else
  194576. {
  194577. png_error(png_ptr, "Invalid palette chunk");
  194578. }
  194579. }
  194580. num = (int)length / 3;
  194581. #ifndef PNG_NO_POINTER_INDEXING
  194582. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194583. {
  194584. png_byte buf[3];
  194585. png_crc_read(png_ptr, buf, 3);
  194586. pal_ptr->red = buf[0];
  194587. pal_ptr->green = buf[1];
  194588. pal_ptr->blue = buf[2];
  194589. }
  194590. #else
  194591. for (i = 0; i < num; i++)
  194592. {
  194593. png_byte buf[3];
  194594. png_crc_read(png_ptr, buf, 3);
  194595. /* don't depend upon png_color being any order */
  194596. palette[i].red = buf[0];
  194597. palette[i].green = buf[1];
  194598. palette[i].blue = buf[2];
  194599. }
  194600. #endif
  194601. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194602. whatever the normal CRC configuration tells us. However, if we
  194603. have an RGB image, the PLTE can be considered ancillary, so
  194604. we will act as though it is. */
  194605. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194606. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194607. #endif
  194608. {
  194609. png_crc_finish(png_ptr, 0);
  194610. }
  194611. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194612. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194613. {
  194614. /* If we don't want to use the data from an ancillary chunk,
  194615. we have two options: an error abort, or a warning and we
  194616. ignore the data in this chunk (which should be OK, since
  194617. it's considered ancillary for a RGB or RGBA image). */
  194618. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194619. {
  194620. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194621. {
  194622. png_chunk_error(png_ptr, "CRC error");
  194623. }
  194624. else
  194625. {
  194626. png_chunk_warning(png_ptr, "CRC error");
  194627. return;
  194628. }
  194629. }
  194630. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194631. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194632. {
  194633. png_chunk_warning(png_ptr, "CRC error");
  194634. }
  194635. }
  194636. #endif
  194637. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194638. #if defined(PNG_READ_tRNS_SUPPORTED)
  194639. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194640. {
  194641. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194642. {
  194643. if (png_ptr->num_trans > (png_uint_16)num)
  194644. {
  194645. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194646. png_ptr->num_trans = (png_uint_16)num;
  194647. }
  194648. if (info_ptr->num_trans > (png_uint_16)num)
  194649. {
  194650. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194651. info_ptr->num_trans = (png_uint_16)num;
  194652. }
  194653. }
  194654. }
  194655. #endif
  194656. }
  194657. void /* PRIVATE */
  194658. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194659. {
  194660. png_debug(1, "in png_handle_IEND\n");
  194661. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194662. {
  194663. png_error(png_ptr, "No image in file");
  194664. }
  194665. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194666. if (length != 0)
  194667. {
  194668. png_warning(png_ptr, "Incorrect IEND chunk length");
  194669. }
  194670. png_crc_finish(png_ptr, length);
  194671. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194672. }
  194673. #if defined(PNG_READ_gAMA_SUPPORTED)
  194674. void /* PRIVATE */
  194675. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194676. {
  194677. png_fixed_point igamma;
  194678. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194679. float file_gamma;
  194680. #endif
  194681. png_byte buf[4];
  194682. png_debug(1, "in png_handle_gAMA\n");
  194683. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194684. png_error(png_ptr, "Missing IHDR before gAMA");
  194685. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194686. {
  194687. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194688. png_crc_finish(png_ptr, length);
  194689. return;
  194690. }
  194691. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194692. /* Should be an error, but we can cope with it */
  194693. png_warning(png_ptr, "Out of place gAMA chunk");
  194694. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194695. #if defined(PNG_READ_sRGB_SUPPORTED)
  194696. && !(info_ptr->valid & PNG_INFO_sRGB)
  194697. #endif
  194698. )
  194699. {
  194700. png_warning(png_ptr, "Duplicate gAMA chunk");
  194701. png_crc_finish(png_ptr, length);
  194702. return;
  194703. }
  194704. if (length != 4)
  194705. {
  194706. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194707. png_crc_finish(png_ptr, length);
  194708. return;
  194709. }
  194710. png_crc_read(png_ptr, buf, 4);
  194711. if (png_crc_finish(png_ptr, 0))
  194712. return;
  194713. igamma = (png_fixed_point)png_get_uint_32(buf);
  194714. /* check for zero gamma */
  194715. if (igamma == 0)
  194716. {
  194717. png_warning(png_ptr,
  194718. "Ignoring gAMA chunk with gamma=0");
  194719. return;
  194720. }
  194721. #if defined(PNG_READ_sRGB_SUPPORTED)
  194722. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194723. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194724. {
  194725. png_warning(png_ptr,
  194726. "Ignoring incorrect gAMA value when sRGB is also present");
  194727. #ifndef PNG_NO_CONSOLE_IO
  194728. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194729. #endif
  194730. return;
  194731. }
  194732. #endif /* PNG_READ_sRGB_SUPPORTED */
  194733. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194734. file_gamma = (float)igamma / (float)100000.0;
  194735. # ifdef PNG_READ_GAMMA_SUPPORTED
  194736. png_ptr->gamma = file_gamma;
  194737. # endif
  194738. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194739. #endif
  194740. #ifdef PNG_FIXED_POINT_SUPPORTED
  194741. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194742. #endif
  194743. }
  194744. #endif
  194745. #if defined(PNG_READ_sBIT_SUPPORTED)
  194746. void /* PRIVATE */
  194747. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194748. {
  194749. png_size_t truelen;
  194750. png_byte buf[4];
  194751. png_debug(1, "in png_handle_sBIT\n");
  194752. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194753. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194754. png_error(png_ptr, "Missing IHDR before sBIT");
  194755. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194756. {
  194757. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194758. png_crc_finish(png_ptr, length);
  194759. return;
  194760. }
  194761. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194762. {
  194763. /* Should be an error, but we can cope with it */
  194764. png_warning(png_ptr, "Out of place sBIT chunk");
  194765. }
  194766. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194767. {
  194768. png_warning(png_ptr, "Duplicate sBIT chunk");
  194769. png_crc_finish(png_ptr, length);
  194770. return;
  194771. }
  194772. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194773. truelen = 3;
  194774. else
  194775. truelen = (png_size_t)png_ptr->channels;
  194776. if (length != truelen || length > 4)
  194777. {
  194778. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194779. png_crc_finish(png_ptr, length);
  194780. return;
  194781. }
  194782. png_crc_read(png_ptr, buf, truelen);
  194783. if (png_crc_finish(png_ptr, 0))
  194784. return;
  194785. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194786. {
  194787. png_ptr->sig_bit.red = buf[0];
  194788. png_ptr->sig_bit.green = buf[1];
  194789. png_ptr->sig_bit.blue = buf[2];
  194790. png_ptr->sig_bit.alpha = buf[3];
  194791. }
  194792. else
  194793. {
  194794. png_ptr->sig_bit.gray = buf[0];
  194795. png_ptr->sig_bit.red = buf[0];
  194796. png_ptr->sig_bit.green = buf[0];
  194797. png_ptr->sig_bit.blue = buf[0];
  194798. png_ptr->sig_bit.alpha = buf[1];
  194799. }
  194800. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194801. }
  194802. #endif
  194803. #if defined(PNG_READ_cHRM_SUPPORTED)
  194804. void /* PRIVATE */
  194805. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194806. {
  194807. png_byte buf[4];
  194808. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194809. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194810. #endif
  194811. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194812. int_y_green, int_x_blue, int_y_blue;
  194813. png_uint_32 uint_x, uint_y;
  194814. png_debug(1, "in png_handle_cHRM\n");
  194815. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194816. png_error(png_ptr, "Missing IHDR before cHRM");
  194817. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194818. {
  194819. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194820. png_crc_finish(png_ptr, length);
  194821. return;
  194822. }
  194823. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194824. /* Should be an error, but we can cope with it */
  194825. png_warning(png_ptr, "Missing PLTE before cHRM");
  194826. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194827. #if defined(PNG_READ_sRGB_SUPPORTED)
  194828. && !(info_ptr->valid & PNG_INFO_sRGB)
  194829. #endif
  194830. )
  194831. {
  194832. png_warning(png_ptr, "Duplicate cHRM chunk");
  194833. png_crc_finish(png_ptr, length);
  194834. return;
  194835. }
  194836. if (length != 32)
  194837. {
  194838. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194839. png_crc_finish(png_ptr, length);
  194840. return;
  194841. }
  194842. png_crc_read(png_ptr, buf, 4);
  194843. uint_x = png_get_uint_32(buf);
  194844. png_crc_read(png_ptr, buf, 4);
  194845. uint_y = png_get_uint_32(buf);
  194846. if (uint_x > 80000L || uint_y > 80000L ||
  194847. uint_x + uint_y > 100000L)
  194848. {
  194849. png_warning(png_ptr, "Invalid cHRM white point");
  194850. png_crc_finish(png_ptr, 24);
  194851. return;
  194852. }
  194853. int_x_white = (png_fixed_point)uint_x;
  194854. int_y_white = (png_fixed_point)uint_y;
  194855. png_crc_read(png_ptr, buf, 4);
  194856. uint_x = png_get_uint_32(buf);
  194857. png_crc_read(png_ptr, buf, 4);
  194858. uint_y = png_get_uint_32(buf);
  194859. if (uint_x + uint_y > 100000L)
  194860. {
  194861. png_warning(png_ptr, "Invalid cHRM red point");
  194862. png_crc_finish(png_ptr, 16);
  194863. return;
  194864. }
  194865. int_x_red = (png_fixed_point)uint_x;
  194866. int_y_red = (png_fixed_point)uint_y;
  194867. png_crc_read(png_ptr, buf, 4);
  194868. uint_x = png_get_uint_32(buf);
  194869. png_crc_read(png_ptr, buf, 4);
  194870. uint_y = png_get_uint_32(buf);
  194871. if (uint_x + uint_y > 100000L)
  194872. {
  194873. png_warning(png_ptr, "Invalid cHRM green point");
  194874. png_crc_finish(png_ptr, 8);
  194875. return;
  194876. }
  194877. int_x_green = (png_fixed_point)uint_x;
  194878. int_y_green = (png_fixed_point)uint_y;
  194879. png_crc_read(png_ptr, buf, 4);
  194880. uint_x = png_get_uint_32(buf);
  194881. png_crc_read(png_ptr, buf, 4);
  194882. uint_y = png_get_uint_32(buf);
  194883. if (uint_x + uint_y > 100000L)
  194884. {
  194885. png_warning(png_ptr, "Invalid cHRM blue point");
  194886. png_crc_finish(png_ptr, 0);
  194887. return;
  194888. }
  194889. int_x_blue = (png_fixed_point)uint_x;
  194890. int_y_blue = (png_fixed_point)uint_y;
  194891. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194892. white_x = (float)int_x_white / (float)100000.0;
  194893. white_y = (float)int_y_white / (float)100000.0;
  194894. red_x = (float)int_x_red / (float)100000.0;
  194895. red_y = (float)int_y_red / (float)100000.0;
  194896. green_x = (float)int_x_green / (float)100000.0;
  194897. green_y = (float)int_y_green / (float)100000.0;
  194898. blue_x = (float)int_x_blue / (float)100000.0;
  194899. blue_y = (float)int_y_blue / (float)100000.0;
  194900. #endif
  194901. #if defined(PNG_READ_sRGB_SUPPORTED)
  194902. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194903. {
  194904. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194905. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194906. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194907. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194908. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194909. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194910. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194911. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194912. {
  194913. png_warning(png_ptr,
  194914. "Ignoring incorrect cHRM value when sRGB is also present");
  194915. #ifndef PNG_NO_CONSOLE_IO
  194916. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194917. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194918. white_x, white_y, red_x, red_y);
  194919. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194920. green_x, green_y, blue_x, blue_y);
  194921. #else
  194922. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194923. int_x_white, int_y_white, int_x_red, int_y_red);
  194924. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194925. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194926. #endif
  194927. #endif /* PNG_NO_CONSOLE_IO */
  194928. }
  194929. png_crc_finish(png_ptr, 0);
  194930. return;
  194931. }
  194932. #endif /* PNG_READ_sRGB_SUPPORTED */
  194933. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194934. png_set_cHRM(png_ptr, info_ptr,
  194935. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194936. #endif
  194937. #ifdef PNG_FIXED_POINT_SUPPORTED
  194938. png_set_cHRM_fixed(png_ptr, info_ptr,
  194939. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194940. int_y_green, int_x_blue, int_y_blue);
  194941. #endif
  194942. if (png_crc_finish(png_ptr, 0))
  194943. return;
  194944. }
  194945. #endif
  194946. #if defined(PNG_READ_sRGB_SUPPORTED)
  194947. void /* PRIVATE */
  194948. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194949. {
  194950. int intent;
  194951. png_byte buf[1];
  194952. png_debug(1, "in png_handle_sRGB\n");
  194953. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194954. png_error(png_ptr, "Missing IHDR before sRGB");
  194955. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194956. {
  194957. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194958. png_crc_finish(png_ptr, length);
  194959. return;
  194960. }
  194961. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194962. /* Should be an error, but we can cope with it */
  194963. png_warning(png_ptr, "Out of place sRGB chunk");
  194964. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194965. {
  194966. png_warning(png_ptr, "Duplicate sRGB chunk");
  194967. png_crc_finish(png_ptr, length);
  194968. return;
  194969. }
  194970. if (length != 1)
  194971. {
  194972. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194973. png_crc_finish(png_ptr, length);
  194974. return;
  194975. }
  194976. png_crc_read(png_ptr, buf, 1);
  194977. if (png_crc_finish(png_ptr, 0))
  194978. return;
  194979. intent = buf[0];
  194980. /* check for bad intent */
  194981. if (intent >= PNG_sRGB_INTENT_LAST)
  194982. {
  194983. png_warning(png_ptr, "Unknown sRGB intent");
  194984. return;
  194985. }
  194986. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194987. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194988. {
  194989. png_fixed_point igamma;
  194990. #ifdef PNG_FIXED_POINT_SUPPORTED
  194991. igamma=info_ptr->int_gamma;
  194992. #else
  194993. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194994. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194995. # endif
  194996. #endif
  194997. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194998. {
  194999. png_warning(png_ptr,
  195000. "Ignoring incorrect gAMA value when sRGB is also present");
  195001. #ifndef PNG_NO_CONSOLE_IO
  195002. # ifdef PNG_FIXED_POINT_SUPPORTED
  195003. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  195004. # else
  195005. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195006. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  195007. # endif
  195008. # endif
  195009. #endif
  195010. }
  195011. }
  195012. #endif /* PNG_READ_gAMA_SUPPORTED */
  195013. #ifdef PNG_READ_cHRM_SUPPORTED
  195014. #ifdef PNG_FIXED_POINT_SUPPORTED
  195015. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  195016. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  195017. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  195018. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  195019. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  195020. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  195021. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  195022. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  195023. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  195024. {
  195025. png_warning(png_ptr,
  195026. "Ignoring incorrect cHRM value when sRGB is also present");
  195027. }
  195028. #endif /* PNG_FIXED_POINT_SUPPORTED */
  195029. #endif /* PNG_READ_cHRM_SUPPORTED */
  195030. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  195031. }
  195032. #endif /* PNG_READ_sRGB_SUPPORTED */
  195033. #if defined(PNG_READ_iCCP_SUPPORTED)
  195034. void /* PRIVATE */
  195035. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195036. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195037. {
  195038. png_charp chunkdata;
  195039. png_byte compression_type;
  195040. png_bytep pC;
  195041. png_charp profile;
  195042. png_uint_32 skip = 0;
  195043. png_uint_32 profile_size, profile_length;
  195044. png_size_t slength, prefix_length, data_length;
  195045. png_debug(1, "in png_handle_iCCP\n");
  195046. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195047. png_error(png_ptr, "Missing IHDR before iCCP");
  195048. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195049. {
  195050. png_warning(png_ptr, "Invalid iCCP after IDAT");
  195051. png_crc_finish(png_ptr, length);
  195052. return;
  195053. }
  195054. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195055. /* Should be an error, but we can cope with it */
  195056. png_warning(png_ptr, "Out of place iCCP chunk");
  195057. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  195058. {
  195059. png_warning(png_ptr, "Duplicate iCCP chunk");
  195060. png_crc_finish(png_ptr, length);
  195061. return;
  195062. }
  195063. #ifdef PNG_MAX_MALLOC_64K
  195064. if (length > (png_uint_32)65535L)
  195065. {
  195066. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  195067. skip = length - (png_uint_32)65535L;
  195068. length = (png_uint_32)65535L;
  195069. }
  195070. #endif
  195071. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  195072. slength = (png_size_t)length;
  195073. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195074. if (png_crc_finish(png_ptr, skip))
  195075. {
  195076. png_free(png_ptr, chunkdata);
  195077. return;
  195078. }
  195079. chunkdata[slength] = 0x00;
  195080. for (profile = chunkdata; *profile; profile++)
  195081. /* empty loop to find end of name */ ;
  195082. ++profile;
  195083. /* there should be at least one zero (the compression type byte)
  195084. following the separator, and we should be on it */
  195085. if ( profile >= chunkdata + slength - 1)
  195086. {
  195087. png_free(png_ptr, chunkdata);
  195088. png_warning(png_ptr, "Malformed iCCP chunk");
  195089. return;
  195090. }
  195091. /* compression_type should always be zero */
  195092. compression_type = *profile++;
  195093. if (compression_type)
  195094. {
  195095. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  195096. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  195097. wrote nonzero) */
  195098. }
  195099. prefix_length = profile - chunkdata;
  195100. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  195101. slength, prefix_length, &data_length);
  195102. profile_length = data_length - prefix_length;
  195103. if ( prefix_length > data_length || profile_length < 4)
  195104. {
  195105. png_free(png_ptr, chunkdata);
  195106. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  195107. return;
  195108. }
  195109. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  195110. pC = (png_bytep)(chunkdata+prefix_length);
  195111. profile_size = ((*(pC ))<<24) |
  195112. ((*(pC+1))<<16) |
  195113. ((*(pC+2))<< 8) |
  195114. ((*(pC+3)) );
  195115. if(profile_size < profile_length)
  195116. profile_length = profile_size;
  195117. if(profile_size > profile_length)
  195118. {
  195119. png_free(png_ptr, chunkdata);
  195120. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  195121. return;
  195122. }
  195123. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  195124. chunkdata + prefix_length, profile_length);
  195125. png_free(png_ptr, chunkdata);
  195126. }
  195127. #endif /* PNG_READ_iCCP_SUPPORTED */
  195128. #if defined(PNG_READ_sPLT_SUPPORTED)
  195129. void /* PRIVATE */
  195130. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195131. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195132. {
  195133. png_bytep chunkdata;
  195134. png_bytep entry_start;
  195135. png_sPLT_t new_palette;
  195136. #ifdef PNG_NO_POINTER_INDEXING
  195137. png_sPLT_entryp pp;
  195138. #endif
  195139. int data_length, entry_size, i;
  195140. png_uint_32 skip = 0;
  195141. png_size_t slength;
  195142. png_debug(1, "in png_handle_sPLT\n");
  195143. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195144. png_error(png_ptr, "Missing IHDR before sPLT");
  195145. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195146. {
  195147. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195148. png_crc_finish(png_ptr, length);
  195149. return;
  195150. }
  195151. #ifdef PNG_MAX_MALLOC_64K
  195152. if (length > (png_uint_32)65535L)
  195153. {
  195154. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195155. skip = length - (png_uint_32)65535L;
  195156. length = (png_uint_32)65535L;
  195157. }
  195158. #endif
  195159. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195160. slength = (png_size_t)length;
  195161. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195162. if (png_crc_finish(png_ptr, skip))
  195163. {
  195164. png_free(png_ptr, chunkdata);
  195165. return;
  195166. }
  195167. chunkdata[slength] = 0x00;
  195168. for (entry_start = chunkdata; *entry_start; entry_start++)
  195169. /* empty loop to find end of name */ ;
  195170. ++entry_start;
  195171. /* a sample depth should follow the separator, and we should be on it */
  195172. if (entry_start > chunkdata + slength - 2)
  195173. {
  195174. png_free(png_ptr, chunkdata);
  195175. png_warning(png_ptr, "malformed sPLT chunk");
  195176. return;
  195177. }
  195178. new_palette.depth = *entry_start++;
  195179. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195180. data_length = (slength - (entry_start - chunkdata));
  195181. /* integrity-check the data length */
  195182. if (data_length % entry_size)
  195183. {
  195184. png_free(png_ptr, chunkdata);
  195185. png_warning(png_ptr, "sPLT chunk has bad length");
  195186. return;
  195187. }
  195188. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195189. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195190. png_sizeof(png_sPLT_entry)))
  195191. {
  195192. png_warning(png_ptr, "sPLT chunk too long");
  195193. return;
  195194. }
  195195. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195196. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195197. if (new_palette.entries == NULL)
  195198. {
  195199. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195200. return;
  195201. }
  195202. #ifndef PNG_NO_POINTER_INDEXING
  195203. for (i = 0; i < new_palette.nentries; i++)
  195204. {
  195205. png_sPLT_entryp pp = new_palette.entries + i;
  195206. if (new_palette.depth == 8)
  195207. {
  195208. pp->red = *entry_start++;
  195209. pp->green = *entry_start++;
  195210. pp->blue = *entry_start++;
  195211. pp->alpha = *entry_start++;
  195212. }
  195213. else
  195214. {
  195215. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195216. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195217. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195218. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195219. }
  195220. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195221. }
  195222. #else
  195223. pp = new_palette.entries;
  195224. for (i = 0; i < new_palette.nentries; i++)
  195225. {
  195226. if (new_palette.depth == 8)
  195227. {
  195228. pp[i].red = *entry_start++;
  195229. pp[i].green = *entry_start++;
  195230. pp[i].blue = *entry_start++;
  195231. pp[i].alpha = *entry_start++;
  195232. }
  195233. else
  195234. {
  195235. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195236. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195237. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195238. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195239. }
  195240. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195241. }
  195242. #endif
  195243. /* discard all chunk data except the name and stash that */
  195244. new_palette.name = (png_charp)chunkdata;
  195245. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195246. png_free(png_ptr, chunkdata);
  195247. png_free(png_ptr, new_palette.entries);
  195248. }
  195249. #endif /* PNG_READ_sPLT_SUPPORTED */
  195250. #if defined(PNG_READ_tRNS_SUPPORTED)
  195251. void /* PRIVATE */
  195252. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195253. {
  195254. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195255. int bit_mask;
  195256. png_debug(1, "in png_handle_tRNS\n");
  195257. /* For non-indexed color, mask off any bits in the tRNS value that
  195258. * exceed the bit depth. Some creators were writing extra bits there.
  195259. * This is not needed for indexed color. */
  195260. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195261. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195262. png_error(png_ptr, "Missing IHDR before tRNS");
  195263. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195264. {
  195265. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195266. png_crc_finish(png_ptr, length);
  195267. return;
  195268. }
  195269. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195270. {
  195271. png_warning(png_ptr, "Duplicate tRNS chunk");
  195272. png_crc_finish(png_ptr, length);
  195273. return;
  195274. }
  195275. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195276. {
  195277. png_byte buf[2];
  195278. if (length != 2)
  195279. {
  195280. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195281. png_crc_finish(png_ptr, length);
  195282. return;
  195283. }
  195284. png_crc_read(png_ptr, buf, 2);
  195285. png_ptr->num_trans = 1;
  195286. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195287. }
  195288. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195289. {
  195290. png_byte buf[6];
  195291. if (length != 6)
  195292. {
  195293. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195294. png_crc_finish(png_ptr, length);
  195295. return;
  195296. }
  195297. png_crc_read(png_ptr, buf, (png_size_t)length);
  195298. png_ptr->num_trans = 1;
  195299. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195300. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195301. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195302. }
  195303. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195304. {
  195305. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195306. {
  195307. /* Should be an error, but we can cope with it. */
  195308. png_warning(png_ptr, "Missing PLTE before tRNS");
  195309. }
  195310. if (length > (png_uint_32)png_ptr->num_palette ||
  195311. length > PNG_MAX_PALETTE_LENGTH)
  195312. {
  195313. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195314. png_crc_finish(png_ptr, length);
  195315. return;
  195316. }
  195317. if (length == 0)
  195318. {
  195319. png_warning(png_ptr, "Zero length tRNS chunk");
  195320. png_crc_finish(png_ptr, length);
  195321. return;
  195322. }
  195323. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195324. png_ptr->num_trans = (png_uint_16)length;
  195325. }
  195326. else
  195327. {
  195328. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195329. png_crc_finish(png_ptr, length);
  195330. return;
  195331. }
  195332. if (png_crc_finish(png_ptr, 0))
  195333. {
  195334. png_ptr->num_trans = 0;
  195335. return;
  195336. }
  195337. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195338. &(png_ptr->trans_values));
  195339. }
  195340. #endif
  195341. #if defined(PNG_READ_bKGD_SUPPORTED)
  195342. void /* PRIVATE */
  195343. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195344. {
  195345. png_size_t truelen;
  195346. png_byte buf[6];
  195347. png_debug(1, "in png_handle_bKGD\n");
  195348. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195349. png_error(png_ptr, "Missing IHDR before bKGD");
  195350. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195351. {
  195352. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195353. png_crc_finish(png_ptr, length);
  195354. return;
  195355. }
  195356. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195357. !(png_ptr->mode & PNG_HAVE_PLTE))
  195358. {
  195359. png_warning(png_ptr, "Missing PLTE before bKGD");
  195360. png_crc_finish(png_ptr, length);
  195361. return;
  195362. }
  195363. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195364. {
  195365. png_warning(png_ptr, "Duplicate bKGD chunk");
  195366. png_crc_finish(png_ptr, length);
  195367. return;
  195368. }
  195369. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195370. truelen = 1;
  195371. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195372. truelen = 6;
  195373. else
  195374. truelen = 2;
  195375. if (length != truelen)
  195376. {
  195377. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195378. png_crc_finish(png_ptr, length);
  195379. return;
  195380. }
  195381. png_crc_read(png_ptr, buf, truelen);
  195382. if (png_crc_finish(png_ptr, 0))
  195383. return;
  195384. /* We convert the index value into RGB components so that we can allow
  195385. * arbitrary RGB values for background when we have transparency, and
  195386. * so it is easy to determine the RGB values of the background color
  195387. * from the info_ptr struct. */
  195388. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195389. {
  195390. png_ptr->background.index = buf[0];
  195391. if(info_ptr->num_palette)
  195392. {
  195393. if(buf[0] > info_ptr->num_palette)
  195394. {
  195395. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195396. return;
  195397. }
  195398. png_ptr->background.red =
  195399. (png_uint_16)png_ptr->palette[buf[0]].red;
  195400. png_ptr->background.green =
  195401. (png_uint_16)png_ptr->palette[buf[0]].green;
  195402. png_ptr->background.blue =
  195403. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195404. }
  195405. }
  195406. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195407. {
  195408. png_ptr->background.red =
  195409. png_ptr->background.green =
  195410. png_ptr->background.blue =
  195411. png_ptr->background.gray = png_get_uint_16(buf);
  195412. }
  195413. else
  195414. {
  195415. png_ptr->background.red = png_get_uint_16(buf);
  195416. png_ptr->background.green = png_get_uint_16(buf + 2);
  195417. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195418. }
  195419. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195420. }
  195421. #endif
  195422. #if defined(PNG_READ_hIST_SUPPORTED)
  195423. void /* PRIVATE */
  195424. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195425. {
  195426. unsigned int num, i;
  195427. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195428. png_debug(1, "in png_handle_hIST\n");
  195429. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195430. png_error(png_ptr, "Missing IHDR before hIST");
  195431. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195432. {
  195433. png_warning(png_ptr, "Invalid hIST after IDAT");
  195434. png_crc_finish(png_ptr, length);
  195435. return;
  195436. }
  195437. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195438. {
  195439. png_warning(png_ptr, "Missing PLTE before hIST");
  195440. png_crc_finish(png_ptr, length);
  195441. return;
  195442. }
  195443. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195444. {
  195445. png_warning(png_ptr, "Duplicate hIST chunk");
  195446. png_crc_finish(png_ptr, length);
  195447. return;
  195448. }
  195449. num = length / 2 ;
  195450. if (num != (unsigned int) png_ptr->num_palette || num >
  195451. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195452. {
  195453. png_warning(png_ptr, "Incorrect hIST chunk length");
  195454. png_crc_finish(png_ptr, length);
  195455. return;
  195456. }
  195457. for (i = 0; i < num; i++)
  195458. {
  195459. png_byte buf[2];
  195460. png_crc_read(png_ptr, buf, 2);
  195461. readbuf[i] = png_get_uint_16(buf);
  195462. }
  195463. if (png_crc_finish(png_ptr, 0))
  195464. return;
  195465. png_set_hIST(png_ptr, info_ptr, readbuf);
  195466. }
  195467. #endif
  195468. #if defined(PNG_READ_pHYs_SUPPORTED)
  195469. void /* PRIVATE */
  195470. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195471. {
  195472. png_byte buf[9];
  195473. png_uint_32 res_x, res_y;
  195474. int unit_type;
  195475. png_debug(1, "in png_handle_pHYs\n");
  195476. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195477. png_error(png_ptr, "Missing IHDR before pHYs");
  195478. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195479. {
  195480. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195481. png_crc_finish(png_ptr, length);
  195482. return;
  195483. }
  195484. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195485. {
  195486. png_warning(png_ptr, "Duplicate pHYs chunk");
  195487. png_crc_finish(png_ptr, length);
  195488. return;
  195489. }
  195490. if (length != 9)
  195491. {
  195492. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195493. png_crc_finish(png_ptr, length);
  195494. return;
  195495. }
  195496. png_crc_read(png_ptr, buf, 9);
  195497. if (png_crc_finish(png_ptr, 0))
  195498. return;
  195499. res_x = png_get_uint_32(buf);
  195500. res_y = png_get_uint_32(buf + 4);
  195501. unit_type = buf[8];
  195502. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195503. }
  195504. #endif
  195505. #if defined(PNG_READ_oFFs_SUPPORTED)
  195506. void /* PRIVATE */
  195507. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195508. {
  195509. png_byte buf[9];
  195510. png_int_32 offset_x, offset_y;
  195511. int unit_type;
  195512. png_debug(1, "in png_handle_oFFs\n");
  195513. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195514. png_error(png_ptr, "Missing IHDR before oFFs");
  195515. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195516. {
  195517. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195518. png_crc_finish(png_ptr, length);
  195519. return;
  195520. }
  195521. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195522. {
  195523. png_warning(png_ptr, "Duplicate oFFs chunk");
  195524. png_crc_finish(png_ptr, length);
  195525. return;
  195526. }
  195527. if (length != 9)
  195528. {
  195529. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195530. png_crc_finish(png_ptr, length);
  195531. return;
  195532. }
  195533. png_crc_read(png_ptr, buf, 9);
  195534. if (png_crc_finish(png_ptr, 0))
  195535. return;
  195536. offset_x = png_get_int_32(buf);
  195537. offset_y = png_get_int_32(buf + 4);
  195538. unit_type = buf[8];
  195539. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195540. }
  195541. #endif
  195542. #if defined(PNG_READ_pCAL_SUPPORTED)
  195543. /* read the pCAL chunk (described in the PNG Extensions document) */
  195544. void /* PRIVATE */
  195545. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195546. {
  195547. png_charp purpose;
  195548. png_int_32 X0, X1;
  195549. png_byte type, nparams;
  195550. png_charp buf, units, endptr;
  195551. png_charpp params;
  195552. png_size_t slength;
  195553. int i;
  195554. png_debug(1, "in png_handle_pCAL\n");
  195555. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195556. png_error(png_ptr, "Missing IHDR before pCAL");
  195557. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195558. {
  195559. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195560. png_crc_finish(png_ptr, length);
  195561. return;
  195562. }
  195563. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195564. {
  195565. png_warning(png_ptr, "Duplicate pCAL chunk");
  195566. png_crc_finish(png_ptr, length);
  195567. return;
  195568. }
  195569. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195570. length + 1);
  195571. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195572. if (purpose == NULL)
  195573. {
  195574. png_warning(png_ptr, "No memory for pCAL purpose.");
  195575. return;
  195576. }
  195577. slength = (png_size_t)length;
  195578. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195579. if (png_crc_finish(png_ptr, 0))
  195580. {
  195581. png_free(png_ptr, purpose);
  195582. return;
  195583. }
  195584. purpose[slength] = 0x00; /* null terminate the last string */
  195585. png_debug(3, "Finding end of pCAL purpose string\n");
  195586. for (buf = purpose; *buf; buf++)
  195587. /* empty loop */ ;
  195588. endptr = purpose + slength;
  195589. /* We need to have at least 12 bytes after the purpose string
  195590. in order to get the parameter information. */
  195591. if (endptr <= buf + 12)
  195592. {
  195593. png_warning(png_ptr, "Invalid pCAL data");
  195594. png_free(png_ptr, purpose);
  195595. return;
  195596. }
  195597. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195598. X0 = png_get_int_32((png_bytep)buf+1);
  195599. X1 = png_get_int_32((png_bytep)buf+5);
  195600. type = buf[9];
  195601. nparams = buf[10];
  195602. units = buf + 11;
  195603. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195604. /* Check that we have the right number of parameters for known
  195605. equation types. */
  195606. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195607. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195608. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195609. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195610. {
  195611. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195612. png_free(png_ptr, purpose);
  195613. return;
  195614. }
  195615. else if (type >= PNG_EQUATION_LAST)
  195616. {
  195617. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195618. }
  195619. for (buf = units; *buf; buf++)
  195620. /* Empty loop to move past the units string. */ ;
  195621. png_debug(3, "Allocating pCAL parameters array\n");
  195622. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195623. *png_sizeof(png_charp))) ;
  195624. if (params == NULL)
  195625. {
  195626. png_free(png_ptr, purpose);
  195627. png_warning(png_ptr, "No memory for pCAL params.");
  195628. return;
  195629. }
  195630. /* Get pointers to the start of each parameter string. */
  195631. for (i = 0; i < (int)nparams; i++)
  195632. {
  195633. buf++; /* Skip the null string terminator from previous parameter. */
  195634. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195635. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195636. /* Empty loop to move past each parameter string */ ;
  195637. /* Make sure we haven't run out of data yet */
  195638. if (buf > endptr)
  195639. {
  195640. png_warning(png_ptr, "Invalid pCAL data");
  195641. png_free(png_ptr, purpose);
  195642. png_free(png_ptr, params);
  195643. return;
  195644. }
  195645. }
  195646. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195647. units, params);
  195648. png_free(png_ptr, purpose);
  195649. png_free(png_ptr, params);
  195650. }
  195651. #endif
  195652. #if defined(PNG_READ_sCAL_SUPPORTED)
  195653. /* read the sCAL chunk */
  195654. void /* PRIVATE */
  195655. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195656. {
  195657. png_charp buffer, ep;
  195658. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195659. double width, height;
  195660. png_charp vp;
  195661. #else
  195662. #ifdef PNG_FIXED_POINT_SUPPORTED
  195663. png_charp swidth, sheight;
  195664. #endif
  195665. #endif
  195666. png_size_t slength;
  195667. png_debug(1, "in png_handle_sCAL\n");
  195668. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195669. png_error(png_ptr, "Missing IHDR before sCAL");
  195670. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195671. {
  195672. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195673. png_crc_finish(png_ptr, length);
  195674. return;
  195675. }
  195676. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195677. {
  195678. png_warning(png_ptr, "Duplicate sCAL chunk");
  195679. png_crc_finish(png_ptr, length);
  195680. return;
  195681. }
  195682. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195683. length + 1);
  195684. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195685. if (buffer == NULL)
  195686. {
  195687. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195688. return;
  195689. }
  195690. slength = (png_size_t)length;
  195691. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195692. if (png_crc_finish(png_ptr, 0))
  195693. {
  195694. png_free(png_ptr, buffer);
  195695. return;
  195696. }
  195697. buffer[slength] = 0x00; /* null terminate the last string */
  195698. ep = buffer + 1; /* skip unit byte */
  195699. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195700. width = png_strtod(png_ptr, ep, &vp);
  195701. if (*vp)
  195702. {
  195703. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195704. return;
  195705. }
  195706. #else
  195707. #ifdef PNG_FIXED_POINT_SUPPORTED
  195708. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195709. if (swidth == NULL)
  195710. {
  195711. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195712. return;
  195713. }
  195714. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195715. #endif
  195716. #endif
  195717. for (ep = buffer; *ep; ep++)
  195718. /* empty loop */ ;
  195719. ep++;
  195720. if (buffer + slength < ep)
  195721. {
  195722. png_warning(png_ptr, "Truncated sCAL chunk");
  195723. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195724. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195725. png_free(png_ptr, swidth);
  195726. #endif
  195727. png_free(png_ptr, buffer);
  195728. return;
  195729. }
  195730. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195731. height = png_strtod(png_ptr, ep, &vp);
  195732. if (*vp)
  195733. {
  195734. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195735. return;
  195736. }
  195737. #else
  195738. #ifdef PNG_FIXED_POINT_SUPPORTED
  195739. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195740. if (swidth == NULL)
  195741. {
  195742. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195743. return;
  195744. }
  195745. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195746. #endif
  195747. #endif
  195748. if (buffer + slength < ep
  195749. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195750. || width <= 0. || height <= 0.
  195751. #endif
  195752. )
  195753. {
  195754. png_warning(png_ptr, "Invalid sCAL data");
  195755. png_free(png_ptr, buffer);
  195756. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195757. png_free(png_ptr, swidth);
  195758. png_free(png_ptr, sheight);
  195759. #endif
  195760. return;
  195761. }
  195762. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195763. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195764. #else
  195765. #ifdef PNG_FIXED_POINT_SUPPORTED
  195766. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195767. #endif
  195768. #endif
  195769. png_free(png_ptr, buffer);
  195770. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195771. png_free(png_ptr, swidth);
  195772. png_free(png_ptr, sheight);
  195773. #endif
  195774. }
  195775. #endif
  195776. #if defined(PNG_READ_tIME_SUPPORTED)
  195777. void /* PRIVATE */
  195778. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195779. {
  195780. png_byte buf[7];
  195781. png_time mod_time;
  195782. png_debug(1, "in png_handle_tIME\n");
  195783. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195784. png_error(png_ptr, "Out of place tIME chunk");
  195785. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195786. {
  195787. png_warning(png_ptr, "Duplicate tIME chunk");
  195788. png_crc_finish(png_ptr, length);
  195789. return;
  195790. }
  195791. if (png_ptr->mode & PNG_HAVE_IDAT)
  195792. png_ptr->mode |= PNG_AFTER_IDAT;
  195793. if (length != 7)
  195794. {
  195795. png_warning(png_ptr, "Incorrect tIME chunk length");
  195796. png_crc_finish(png_ptr, length);
  195797. return;
  195798. }
  195799. png_crc_read(png_ptr, buf, 7);
  195800. if (png_crc_finish(png_ptr, 0))
  195801. return;
  195802. mod_time.second = buf[6];
  195803. mod_time.minute = buf[5];
  195804. mod_time.hour = buf[4];
  195805. mod_time.day = buf[3];
  195806. mod_time.month = buf[2];
  195807. mod_time.year = png_get_uint_16(buf);
  195808. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195809. }
  195810. #endif
  195811. #if defined(PNG_READ_tEXt_SUPPORTED)
  195812. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195813. void /* PRIVATE */
  195814. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195815. {
  195816. png_textp text_ptr;
  195817. png_charp key;
  195818. png_charp text;
  195819. png_uint_32 skip = 0;
  195820. png_size_t slength;
  195821. int ret;
  195822. png_debug(1, "in png_handle_tEXt\n");
  195823. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195824. png_error(png_ptr, "Missing IHDR before tEXt");
  195825. if (png_ptr->mode & PNG_HAVE_IDAT)
  195826. png_ptr->mode |= PNG_AFTER_IDAT;
  195827. #ifdef PNG_MAX_MALLOC_64K
  195828. if (length > (png_uint_32)65535L)
  195829. {
  195830. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195831. skip = length - (png_uint_32)65535L;
  195832. length = (png_uint_32)65535L;
  195833. }
  195834. #endif
  195835. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195836. if (key == NULL)
  195837. {
  195838. png_warning(png_ptr, "No memory to process text chunk.");
  195839. return;
  195840. }
  195841. slength = (png_size_t)length;
  195842. png_crc_read(png_ptr, (png_bytep)key, slength);
  195843. if (png_crc_finish(png_ptr, skip))
  195844. {
  195845. png_free(png_ptr, key);
  195846. return;
  195847. }
  195848. key[slength] = 0x00;
  195849. for (text = key; *text; text++)
  195850. /* empty loop to find end of key */ ;
  195851. if (text != key + slength)
  195852. text++;
  195853. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195854. (png_uint_32)png_sizeof(png_text));
  195855. if (text_ptr == NULL)
  195856. {
  195857. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195858. png_free(png_ptr, key);
  195859. return;
  195860. }
  195861. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195862. text_ptr->key = key;
  195863. #ifdef PNG_iTXt_SUPPORTED
  195864. text_ptr->lang = NULL;
  195865. text_ptr->lang_key = NULL;
  195866. text_ptr->itxt_length = 0;
  195867. #endif
  195868. text_ptr->text = text;
  195869. text_ptr->text_length = png_strlen(text);
  195870. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195871. png_free(png_ptr, key);
  195872. png_free(png_ptr, text_ptr);
  195873. if (ret)
  195874. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195875. }
  195876. #endif
  195877. #if defined(PNG_READ_zTXt_SUPPORTED)
  195878. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195879. void /* PRIVATE */
  195880. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195881. {
  195882. png_textp text_ptr;
  195883. png_charp chunkdata;
  195884. png_charp text;
  195885. int comp_type;
  195886. int ret;
  195887. png_size_t slength, prefix_len, data_len;
  195888. png_debug(1, "in png_handle_zTXt\n");
  195889. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195890. png_error(png_ptr, "Missing IHDR before zTXt");
  195891. if (png_ptr->mode & PNG_HAVE_IDAT)
  195892. png_ptr->mode |= PNG_AFTER_IDAT;
  195893. #ifdef PNG_MAX_MALLOC_64K
  195894. /* We will no doubt have problems with chunks even half this size, but
  195895. there is no hard and fast rule to tell us where to stop. */
  195896. if (length > (png_uint_32)65535L)
  195897. {
  195898. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195899. png_crc_finish(png_ptr, length);
  195900. return;
  195901. }
  195902. #endif
  195903. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195904. if (chunkdata == NULL)
  195905. {
  195906. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195907. return;
  195908. }
  195909. slength = (png_size_t)length;
  195910. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195911. if (png_crc_finish(png_ptr, 0))
  195912. {
  195913. png_free(png_ptr, chunkdata);
  195914. return;
  195915. }
  195916. chunkdata[slength] = 0x00;
  195917. for (text = chunkdata; *text; text++)
  195918. /* empty loop */ ;
  195919. /* zTXt must have some text after the chunkdataword */
  195920. if (text >= chunkdata + slength - 2)
  195921. {
  195922. png_warning(png_ptr, "Truncated zTXt chunk");
  195923. png_free(png_ptr, chunkdata);
  195924. return;
  195925. }
  195926. else
  195927. {
  195928. comp_type = *(++text);
  195929. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195930. {
  195931. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195932. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195933. }
  195934. text++; /* skip the compression_method byte */
  195935. }
  195936. prefix_len = text - chunkdata;
  195937. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195938. (png_size_t)length, prefix_len, &data_len);
  195939. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195940. (png_uint_32)png_sizeof(png_text));
  195941. if (text_ptr == NULL)
  195942. {
  195943. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195944. png_free(png_ptr, chunkdata);
  195945. return;
  195946. }
  195947. text_ptr->compression = comp_type;
  195948. text_ptr->key = chunkdata;
  195949. #ifdef PNG_iTXt_SUPPORTED
  195950. text_ptr->lang = NULL;
  195951. text_ptr->lang_key = NULL;
  195952. text_ptr->itxt_length = 0;
  195953. #endif
  195954. text_ptr->text = chunkdata + prefix_len;
  195955. text_ptr->text_length = data_len;
  195956. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195957. png_free(png_ptr, text_ptr);
  195958. png_free(png_ptr, chunkdata);
  195959. if (ret)
  195960. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195961. }
  195962. #endif
  195963. #if defined(PNG_READ_iTXt_SUPPORTED)
  195964. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195965. void /* PRIVATE */
  195966. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195967. {
  195968. png_textp text_ptr;
  195969. png_charp chunkdata;
  195970. png_charp key, lang, text, lang_key;
  195971. int comp_flag;
  195972. int comp_type = 0;
  195973. int ret;
  195974. png_size_t slength, prefix_len, data_len;
  195975. png_debug(1, "in png_handle_iTXt\n");
  195976. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195977. png_error(png_ptr, "Missing IHDR before iTXt");
  195978. if (png_ptr->mode & PNG_HAVE_IDAT)
  195979. png_ptr->mode |= PNG_AFTER_IDAT;
  195980. #ifdef PNG_MAX_MALLOC_64K
  195981. /* We will no doubt have problems with chunks even half this size, but
  195982. there is no hard and fast rule to tell us where to stop. */
  195983. if (length > (png_uint_32)65535L)
  195984. {
  195985. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195986. png_crc_finish(png_ptr, length);
  195987. return;
  195988. }
  195989. #endif
  195990. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195991. if (chunkdata == NULL)
  195992. {
  195993. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195994. return;
  195995. }
  195996. slength = (png_size_t)length;
  195997. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195998. if (png_crc_finish(png_ptr, 0))
  195999. {
  196000. png_free(png_ptr, chunkdata);
  196001. return;
  196002. }
  196003. chunkdata[slength] = 0x00;
  196004. for (lang = chunkdata; *lang; lang++)
  196005. /* empty loop */ ;
  196006. lang++; /* skip NUL separator */
  196007. /* iTXt must have a language tag (possibly empty), two compression bytes,
  196008. translated keyword (possibly empty), and possibly some text after the
  196009. keyword */
  196010. if (lang >= chunkdata + slength - 3)
  196011. {
  196012. png_warning(png_ptr, "Truncated iTXt chunk");
  196013. png_free(png_ptr, chunkdata);
  196014. return;
  196015. }
  196016. else
  196017. {
  196018. comp_flag = *lang++;
  196019. comp_type = *lang++;
  196020. }
  196021. for (lang_key = lang; *lang_key; lang_key++)
  196022. /* empty loop */ ;
  196023. lang_key++; /* skip NUL separator */
  196024. if (lang_key >= chunkdata + slength)
  196025. {
  196026. png_warning(png_ptr, "Truncated iTXt chunk");
  196027. png_free(png_ptr, chunkdata);
  196028. return;
  196029. }
  196030. for (text = lang_key; *text; text++)
  196031. /* empty loop */ ;
  196032. text++; /* skip NUL separator */
  196033. if (text >= chunkdata + slength)
  196034. {
  196035. png_warning(png_ptr, "Malformed iTXt chunk");
  196036. png_free(png_ptr, chunkdata);
  196037. return;
  196038. }
  196039. prefix_len = text - chunkdata;
  196040. key=chunkdata;
  196041. if (comp_flag)
  196042. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196043. (size_t)length, prefix_len, &data_len);
  196044. else
  196045. data_len=png_strlen(chunkdata + prefix_len);
  196046. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196047. (png_uint_32)png_sizeof(png_text));
  196048. if (text_ptr == NULL)
  196049. {
  196050. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  196051. png_free(png_ptr, chunkdata);
  196052. return;
  196053. }
  196054. text_ptr->compression = (int)comp_flag + 1;
  196055. text_ptr->lang_key = chunkdata+(lang_key-key);
  196056. text_ptr->lang = chunkdata+(lang-key);
  196057. text_ptr->itxt_length = data_len;
  196058. text_ptr->text_length = 0;
  196059. text_ptr->key = chunkdata;
  196060. text_ptr->text = chunkdata + prefix_len;
  196061. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196062. png_free(png_ptr, text_ptr);
  196063. png_free(png_ptr, chunkdata);
  196064. if (ret)
  196065. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  196066. }
  196067. #endif
  196068. /* This function is called when we haven't found a handler for a
  196069. chunk. If there isn't a problem with the chunk itself (ie bad
  196070. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  196071. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  196072. case it will be saved away to be written out later. */
  196073. void /* PRIVATE */
  196074. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196075. {
  196076. png_uint_32 skip = 0;
  196077. png_debug(1, "in png_handle_unknown\n");
  196078. if (png_ptr->mode & PNG_HAVE_IDAT)
  196079. {
  196080. #ifdef PNG_USE_LOCAL_ARRAYS
  196081. PNG_CONST PNG_IDAT;
  196082. #endif
  196083. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  196084. png_ptr->mode |= PNG_AFTER_IDAT;
  196085. }
  196086. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  196087. if (!(png_ptr->chunk_name[0] & 0x20))
  196088. {
  196089. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196090. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196091. PNG_HANDLE_CHUNK_ALWAYS
  196092. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196093. && png_ptr->read_user_chunk_fn == NULL
  196094. #endif
  196095. )
  196096. #endif
  196097. png_chunk_error(png_ptr, "unknown critical chunk");
  196098. }
  196099. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196100. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  196101. (png_ptr->read_user_chunk_fn != NULL))
  196102. {
  196103. #ifdef PNG_MAX_MALLOC_64K
  196104. if (length > (png_uint_32)65535L)
  196105. {
  196106. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  196107. skip = length - (png_uint_32)65535L;
  196108. length = (png_uint_32)65535L;
  196109. }
  196110. #endif
  196111. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  196112. (png_charp)png_ptr->chunk_name, 5);
  196113. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  196114. png_ptr->unknown_chunk.size = (png_size_t)length;
  196115. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  196116. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196117. if(png_ptr->read_user_chunk_fn != NULL)
  196118. {
  196119. /* callback to user unknown chunk handler */
  196120. int ret;
  196121. ret = (*(png_ptr->read_user_chunk_fn))
  196122. (png_ptr, &png_ptr->unknown_chunk);
  196123. if (ret < 0)
  196124. png_chunk_error(png_ptr, "error in user chunk");
  196125. if (ret == 0)
  196126. {
  196127. if (!(png_ptr->chunk_name[0] & 0x20))
  196128. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196129. PNG_HANDLE_CHUNK_ALWAYS)
  196130. png_chunk_error(png_ptr, "unknown critical chunk");
  196131. png_set_unknown_chunks(png_ptr, info_ptr,
  196132. &png_ptr->unknown_chunk, 1);
  196133. }
  196134. }
  196135. #else
  196136. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  196137. #endif
  196138. png_free(png_ptr, png_ptr->unknown_chunk.data);
  196139. png_ptr->unknown_chunk.data = NULL;
  196140. }
  196141. else
  196142. #endif
  196143. skip = length;
  196144. png_crc_finish(png_ptr, skip);
  196145. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196146. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196147. #endif
  196148. }
  196149. /* This function is called to verify that a chunk name is valid.
  196150. This function can't have the "critical chunk check" incorporated
  196151. into it, since in the future we will need to be able to call user
  196152. functions to handle unknown critical chunks after we check that
  196153. the chunk name itself is valid. */
  196154. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196155. void /* PRIVATE */
  196156. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196157. {
  196158. png_debug(1, "in png_check_chunk_name\n");
  196159. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196160. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196161. {
  196162. png_chunk_error(png_ptr, "invalid chunk type");
  196163. }
  196164. }
  196165. /* Combines the row recently read in with the existing pixels in the
  196166. row. This routine takes care of alpha and transparency if requested.
  196167. This routine also handles the two methods of progressive display
  196168. of interlaced images, depending on the mask value.
  196169. The mask value describes which pixels are to be combined with
  196170. the row. The pattern always repeats every 8 pixels, so just 8
  196171. bits are needed. A one indicates the pixel is to be combined,
  196172. a zero indicates the pixel is to be skipped. This is in addition
  196173. to any alpha or transparency value associated with the pixel. If
  196174. you want all pixels to be combined, pass 0xff (255) in mask. */
  196175. void /* PRIVATE */
  196176. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196177. {
  196178. png_debug(1,"in png_combine_row\n");
  196179. if (mask == 0xff)
  196180. {
  196181. png_memcpy(row, png_ptr->row_buf + 1,
  196182. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196183. }
  196184. else
  196185. {
  196186. switch (png_ptr->row_info.pixel_depth)
  196187. {
  196188. case 1:
  196189. {
  196190. png_bytep sp = png_ptr->row_buf + 1;
  196191. png_bytep dp = row;
  196192. int s_inc, s_start, s_end;
  196193. int m = 0x80;
  196194. int shift;
  196195. png_uint_32 i;
  196196. png_uint_32 row_width = png_ptr->width;
  196197. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196198. if (png_ptr->transformations & PNG_PACKSWAP)
  196199. {
  196200. s_start = 0;
  196201. s_end = 7;
  196202. s_inc = 1;
  196203. }
  196204. else
  196205. #endif
  196206. {
  196207. s_start = 7;
  196208. s_end = 0;
  196209. s_inc = -1;
  196210. }
  196211. shift = s_start;
  196212. for (i = 0; i < row_width; i++)
  196213. {
  196214. if (m & mask)
  196215. {
  196216. int value;
  196217. value = (*sp >> shift) & 0x01;
  196218. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196219. *dp |= (png_byte)(value << shift);
  196220. }
  196221. if (shift == s_end)
  196222. {
  196223. shift = s_start;
  196224. sp++;
  196225. dp++;
  196226. }
  196227. else
  196228. shift += s_inc;
  196229. if (m == 1)
  196230. m = 0x80;
  196231. else
  196232. m >>= 1;
  196233. }
  196234. break;
  196235. }
  196236. case 2:
  196237. {
  196238. png_bytep sp = png_ptr->row_buf + 1;
  196239. png_bytep dp = row;
  196240. int s_start, s_end, s_inc;
  196241. int m = 0x80;
  196242. int shift;
  196243. png_uint_32 i;
  196244. png_uint_32 row_width = png_ptr->width;
  196245. int value;
  196246. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196247. if (png_ptr->transformations & PNG_PACKSWAP)
  196248. {
  196249. s_start = 0;
  196250. s_end = 6;
  196251. s_inc = 2;
  196252. }
  196253. else
  196254. #endif
  196255. {
  196256. s_start = 6;
  196257. s_end = 0;
  196258. s_inc = -2;
  196259. }
  196260. shift = s_start;
  196261. for (i = 0; i < row_width; i++)
  196262. {
  196263. if (m & mask)
  196264. {
  196265. value = (*sp >> shift) & 0x03;
  196266. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196267. *dp |= (png_byte)(value << shift);
  196268. }
  196269. if (shift == s_end)
  196270. {
  196271. shift = s_start;
  196272. sp++;
  196273. dp++;
  196274. }
  196275. else
  196276. shift += s_inc;
  196277. if (m == 1)
  196278. m = 0x80;
  196279. else
  196280. m >>= 1;
  196281. }
  196282. break;
  196283. }
  196284. case 4:
  196285. {
  196286. png_bytep sp = png_ptr->row_buf + 1;
  196287. png_bytep dp = row;
  196288. int s_start, s_end, s_inc;
  196289. int m = 0x80;
  196290. int shift;
  196291. png_uint_32 i;
  196292. png_uint_32 row_width = png_ptr->width;
  196293. int value;
  196294. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196295. if (png_ptr->transformations & PNG_PACKSWAP)
  196296. {
  196297. s_start = 0;
  196298. s_end = 4;
  196299. s_inc = 4;
  196300. }
  196301. else
  196302. #endif
  196303. {
  196304. s_start = 4;
  196305. s_end = 0;
  196306. s_inc = -4;
  196307. }
  196308. shift = s_start;
  196309. for (i = 0; i < row_width; i++)
  196310. {
  196311. if (m & mask)
  196312. {
  196313. value = (*sp >> shift) & 0xf;
  196314. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196315. *dp |= (png_byte)(value << shift);
  196316. }
  196317. if (shift == s_end)
  196318. {
  196319. shift = s_start;
  196320. sp++;
  196321. dp++;
  196322. }
  196323. else
  196324. shift += s_inc;
  196325. if (m == 1)
  196326. m = 0x80;
  196327. else
  196328. m >>= 1;
  196329. }
  196330. break;
  196331. }
  196332. default:
  196333. {
  196334. png_bytep sp = png_ptr->row_buf + 1;
  196335. png_bytep dp = row;
  196336. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196337. png_uint_32 i;
  196338. png_uint_32 row_width = png_ptr->width;
  196339. png_byte m = 0x80;
  196340. for (i = 0; i < row_width; i++)
  196341. {
  196342. if (m & mask)
  196343. {
  196344. png_memcpy(dp, sp, pixel_bytes);
  196345. }
  196346. sp += pixel_bytes;
  196347. dp += pixel_bytes;
  196348. if (m == 1)
  196349. m = 0x80;
  196350. else
  196351. m >>= 1;
  196352. }
  196353. break;
  196354. }
  196355. }
  196356. }
  196357. }
  196358. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196359. /* OLD pre-1.0.9 interface:
  196360. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196361. png_uint_32 transformations)
  196362. */
  196363. void /* PRIVATE */
  196364. png_do_read_interlace(png_structp png_ptr)
  196365. {
  196366. png_row_infop row_info = &(png_ptr->row_info);
  196367. png_bytep row = png_ptr->row_buf + 1;
  196368. int pass = png_ptr->pass;
  196369. png_uint_32 transformations = png_ptr->transformations;
  196370. #ifdef PNG_USE_LOCAL_ARRAYS
  196371. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196372. /* offset to next interlace block */
  196373. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196374. #endif
  196375. png_debug(1,"in png_do_read_interlace\n");
  196376. if (row != NULL && row_info != NULL)
  196377. {
  196378. png_uint_32 final_width;
  196379. final_width = row_info->width * png_pass_inc[pass];
  196380. switch (row_info->pixel_depth)
  196381. {
  196382. case 1:
  196383. {
  196384. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196385. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196386. int sshift, dshift;
  196387. int s_start, s_end, s_inc;
  196388. int jstop = png_pass_inc[pass];
  196389. png_byte v;
  196390. png_uint_32 i;
  196391. int j;
  196392. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196393. if (transformations & PNG_PACKSWAP)
  196394. {
  196395. sshift = (int)((row_info->width + 7) & 0x07);
  196396. dshift = (int)((final_width + 7) & 0x07);
  196397. s_start = 7;
  196398. s_end = 0;
  196399. s_inc = -1;
  196400. }
  196401. else
  196402. #endif
  196403. {
  196404. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196405. dshift = 7 - (int)((final_width + 7) & 0x07);
  196406. s_start = 0;
  196407. s_end = 7;
  196408. s_inc = 1;
  196409. }
  196410. for (i = 0; i < row_info->width; i++)
  196411. {
  196412. v = (png_byte)((*sp >> sshift) & 0x01);
  196413. for (j = 0; j < jstop; j++)
  196414. {
  196415. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196416. *dp |= (png_byte)(v << dshift);
  196417. if (dshift == s_end)
  196418. {
  196419. dshift = s_start;
  196420. dp--;
  196421. }
  196422. else
  196423. dshift += s_inc;
  196424. }
  196425. if (sshift == s_end)
  196426. {
  196427. sshift = s_start;
  196428. sp--;
  196429. }
  196430. else
  196431. sshift += s_inc;
  196432. }
  196433. break;
  196434. }
  196435. case 2:
  196436. {
  196437. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196438. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196439. int sshift, dshift;
  196440. int s_start, s_end, s_inc;
  196441. int jstop = png_pass_inc[pass];
  196442. png_uint_32 i;
  196443. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196444. if (transformations & PNG_PACKSWAP)
  196445. {
  196446. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196447. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196448. s_start = 6;
  196449. s_end = 0;
  196450. s_inc = -2;
  196451. }
  196452. else
  196453. #endif
  196454. {
  196455. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196456. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196457. s_start = 0;
  196458. s_end = 6;
  196459. s_inc = 2;
  196460. }
  196461. for (i = 0; i < row_info->width; i++)
  196462. {
  196463. png_byte v;
  196464. int j;
  196465. v = (png_byte)((*sp >> sshift) & 0x03);
  196466. for (j = 0; j < jstop; j++)
  196467. {
  196468. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196469. *dp |= (png_byte)(v << dshift);
  196470. if (dshift == s_end)
  196471. {
  196472. dshift = s_start;
  196473. dp--;
  196474. }
  196475. else
  196476. dshift += s_inc;
  196477. }
  196478. if (sshift == s_end)
  196479. {
  196480. sshift = s_start;
  196481. sp--;
  196482. }
  196483. else
  196484. sshift += s_inc;
  196485. }
  196486. break;
  196487. }
  196488. case 4:
  196489. {
  196490. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196491. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196492. int sshift, dshift;
  196493. int s_start, s_end, s_inc;
  196494. png_uint_32 i;
  196495. int jstop = png_pass_inc[pass];
  196496. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196497. if (transformations & PNG_PACKSWAP)
  196498. {
  196499. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196500. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196501. s_start = 4;
  196502. s_end = 0;
  196503. s_inc = -4;
  196504. }
  196505. else
  196506. #endif
  196507. {
  196508. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196509. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196510. s_start = 0;
  196511. s_end = 4;
  196512. s_inc = 4;
  196513. }
  196514. for (i = 0; i < row_info->width; i++)
  196515. {
  196516. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196517. int j;
  196518. for (j = 0; j < jstop; j++)
  196519. {
  196520. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196521. *dp |= (png_byte)(v << dshift);
  196522. if (dshift == s_end)
  196523. {
  196524. dshift = s_start;
  196525. dp--;
  196526. }
  196527. else
  196528. dshift += s_inc;
  196529. }
  196530. if (sshift == s_end)
  196531. {
  196532. sshift = s_start;
  196533. sp--;
  196534. }
  196535. else
  196536. sshift += s_inc;
  196537. }
  196538. break;
  196539. }
  196540. default:
  196541. {
  196542. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196543. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196544. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196545. int jstop = png_pass_inc[pass];
  196546. png_uint_32 i;
  196547. for (i = 0; i < row_info->width; i++)
  196548. {
  196549. png_byte v[8];
  196550. int j;
  196551. png_memcpy(v, sp, pixel_bytes);
  196552. for (j = 0; j < jstop; j++)
  196553. {
  196554. png_memcpy(dp, v, pixel_bytes);
  196555. dp -= pixel_bytes;
  196556. }
  196557. sp -= pixel_bytes;
  196558. }
  196559. break;
  196560. }
  196561. }
  196562. row_info->width = final_width;
  196563. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196564. }
  196565. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196566. transformations = transformations; /* silence compiler warning */
  196567. #endif
  196568. }
  196569. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196570. void /* PRIVATE */
  196571. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196572. png_bytep prev_row, int filter)
  196573. {
  196574. png_debug(1, "in png_read_filter_row\n");
  196575. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196576. switch (filter)
  196577. {
  196578. case PNG_FILTER_VALUE_NONE:
  196579. break;
  196580. case PNG_FILTER_VALUE_SUB:
  196581. {
  196582. png_uint_32 i;
  196583. png_uint_32 istop = row_info->rowbytes;
  196584. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196585. png_bytep rp = row + bpp;
  196586. png_bytep lp = row;
  196587. for (i = bpp; i < istop; i++)
  196588. {
  196589. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196590. rp++;
  196591. }
  196592. break;
  196593. }
  196594. case PNG_FILTER_VALUE_UP:
  196595. {
  196596. png_uint_32 i;
  196597. png_uint_32 istop = row_info->rowbytes;
  196598. png_bytep rp = row;
  196599. png_bytep pp = prev_row;
  196600. for (i = 0; i < istop; i++)
  196601. {
  196602. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196603. rp++;
  196604. }
  196605. break;
  196606. }
  196607. case PNG_FILTER_VALUE_AVG:
  196608. {
  196609. png_uint_32 i;
  196610. png_bytep rp = row;
  196611. png_bytep pp = prev_row;
  196612. png_bytep lp = row;
  196613. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196614. png_uint_32 istop = row_info->rowbytes - bpp;
  196615. for (i = 0; i < bpp; i++)
  196616. {
  196617. *rp = (png_byte)(((int)(*rp) +
  196618. ((int)(*pp++) / 2 )) & 0xff);
  196619. rp++;
  196620. }
  196621. for (i = 0; i < istop; i++)
  196622. {
  196623. *rp = (png_byte)(((int)(*rp) +
  196624. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196625. rp++;
  196626. }
  196627. break;
  196628. }
  196629. case PNG_FILTER_VALUE_PAETH:
  196630. {
  196631. png_uint_32 i;
  196632. png_bytep rp = row;
  196633. png_bytep pp = prev_row;
  196634. png_bytep lp = row;
  196635. png_bytep cp = prev_row;
  196636. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196637. png_uint_32 istop=row_info->rowbytes - bpp;
  196638. for (i = 0; i < bpp; i++)
  196639. {
  196640. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196641. rp++;
  196642. }
  196643. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196644. {
  196645. int a, b, c, pa, pb, pc, p;
  196646. a = *lp++;
  196647. b = *pp++;
  196648. c = *cp++;
  196649. p = b - c;
  196650. pc = a - c;
  196651. #ifdef PNG_USE_ABS
  196652. pa = abs(p);
  196653. pb = abs(pc);
  196654. pc = abs(p + pc);
  196655. #else
  196656. pa = p < 0 ? -p : p;
  196657. pb = pc < 0 ? -pc : pc;
  196658. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196659. #endif
  196660. /*
  196661. if (pa <= pb && pa <= pc)
  196662. p = a;
  196663. else if (pb <= pc)
  196664. p = b;
  196665. else
  196666. p = c;
  196667. */
  196668. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196669. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196670. rp++;
  196671. }
  196672. break;
  196673. }
  196674. default:
  196675. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196676. *row=0;
  196677. break;
  196678. }
  196679. }
  196680. void /* PRIVATE */
  196681. png_read_finish_row(png_structp png_ptr)
  196682. {
  196683. #ifdef PNG_USE_LOCAL_ARRAYS
  196684. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196685. /* start of interlace block */
  196686. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196687. /* offset to next interlace block */
  196688. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196689. /* start of interlace block in the y direction */
  196690. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196691. /* offset to next interlace block in the y direction */
  196692. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196693. #endif
  196694. png_debug(1, "in png_read_finish_row\n");
  196695. png_ptr->row_number++;
  196696. if (png_ptr->row_number < png_ptr->num_rows)
  196697. return;
  196698. if (png_ptr->interlaced)
  196699. {
  196700. png_ptr->row_number = 0;
  196701. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196702. png_ptr->rowbytes + 1);
  196703. do
  196704. {
  196705. png_ptr->pass++;
  196706. if (png_ptr->pass >= 7)
  196707. break;
  196708. png_ptr->iwidth = (png_ptr->width +
  196709. png_pass_inc[png_ptr->pass] - 1 -
  196710. png_pass_start[png_ptr->pass]) /
  196711. png_pass_inc[png_ptr->pass];
  196712. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196713. png_ptr->iwidth) + 1;
  196714. if (!(png_ptr->transformations & PNG_INTERLACE))
  196715. {
  196716. png_ptr->num_rows = (png_ptr->height +
  196717. png_pass_yinc[png_ptr->pass] - 1 -
  196718. png_pass_ystart[png_ptr->pass]) /
  196719. png_pass_yinc[png_ptr->pass];
  196720. if (!(png_ptr->num_rows))
  196721. continue;
  196722. }
  196723. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196724. break;
  196725. } while (png_ptr->iwidth == 0);
  196726. if (png_ptr->pass < 7)
  196727. return;
  196728. }
  196729. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196730. {
  196731. #ifdef PNG_USE_LOCAL_ARRAYS
  196732. PNG_CONST PNG_IDAT;
  196733. #endif
  196734. char extra;
  196735. int ret;
  196736. png_ptr->zstream.next_out = (Bytef *)&extra;
  196737. png_ptr->zstream.avail_out = (uInt)1;
  196738. for(;;)
  196739. {
  196740. if (!(png_ptr->zstream.avail_in))
  196741. {
  196742. while (!png_ptr->idat_size)
  196743. {
  196744. png_byte chunk_length[4];
  196745. png_crc_finish(png_ptr, 0);
  196746. png_read_data(png_ptr, chunk_length, 4);
  196747. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196748. png_reset_crc(png_ptr);
  196749. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196750. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196751. png_error(png_ptr, "Not enough image data");
  196752. }
  196753. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196754. png_ptr->zstream.next_in = png_ptr->zbuf;
  196755. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196756. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196757. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196758. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196759. }
  196760. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196761. if (ret == Z_STREAM_END)
  196762. {
  196763. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196764. png_ptr->idat_size)
  196765. png_warning(png_ptr, "Extra compressed data");
  196766. png_ptr->mode |= PNG_AFTER_IDAT;
  196767. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196768. break;
  196769. }
  196770. if (ret != Z_OK)
  196771. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196772. "Decompression Error");
  196773. if (!(png_ptr->zstream.avail_out))
  196774. {
  196775. png_warning(png_ptr, "Extra compressed data.");
  196776. png_ptr->mode |= PNG_AFTER_IDAT;
  196777. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196778. break;
  196779. }
  196780. }
  196781. png_ptr->zstream.avail_out = 0;
  196782. }
  196783. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196784. png_warning(png_ptr, "Extra compression data");
  196785. inflateReset(&png_ptr->zstream);
  196786. png_ptr->mode |= PNG_AFTER_IDAT;
  196787. }
  196788. void /* PRIVATE */
  196789. png_read_start_row(png_structp png_ptr)
  196790. {
  196791. #ifdef PNG_USE_LOCAL_ARRAYS
  196792. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196793. /* start of interlace block */
  196794. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196795. /* offset to next interlace block */
  196796. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196797. /* start of interlace block in the y direction */
  196798. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196799. /* offset to next interlace block in the y direction */
  196800. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196801. #endif
  196802. int max_pixel_depth;
  196803. png_uint_32 row_bytes;
  196804. png_debug(1, "in png_read_start_row\n");
  196805. png_ptr->zstream.avail_in = 0;
  196806. png_init_read_transformations(png_ptr);
  196807. if (png_ptr->interlaced)
  196808. {
  196809. if (!(png_ptr->transformations & PNG_INTERLACE))
  196810. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196811. png_pass_ystart[0]) / png_pass_yinc[0];
  196812. else
  196813. png_ptr->num_rows = png_ptr->height;
  196814. png_ptr->iwidth = (png_ptr->width +
  196815. png_pass_inc[png_ptr->pass] - 1 -
  196816. png_pass_start[png_ptr->pass]) /
  196817. png_pass_inc[png_ptr->pass];
  196818. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196819. png_ptr->irowbytes = (png_size_t)row_bytes;
  196820. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196821. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196822. }
  196823. else
  196824. {
  196825. png_ptr->num_rows = png_ptr->height;
  196826. png_ptr->iwidth = png_ptr->width;
  196827. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196828. }
  196829. max_pixel_depth = png_ptr->pixel_depth;
  196830. #if defined(PNG_READ_PACK_SUPPORTED)
  196831. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196832. max_pixel_depth = 8;
  196833. #endif
  196834. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196835. if (png_ptr->transformations & PNG_EXPAND)
  196836. {
  196837. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196838. {
  196839. if (png_ptr->num_trans)
  196840. max_pixel_depth = 32;
  196841. else
  196842. max_pixel_depth = 24;
  196843. }
  196844. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196845. {
  196846. if (max_pixel_depth < 8)
  196847. max_pixel_depth = 8;
  196848. if (png_ptr->num_trans)
  196849. max_pixel_depth *= 2;
  196850. }
  196851. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196852. {
  196853. if (png_ptr->num_trans)
  196854. {
  196855. max_pixel_depth *= 4;
  196856. max_pixel_depth /= 3;
  196857. }
  196858. }
  196859. }
  196860. #endif
  196861. #if defined(PNG_READ_FILLER_SUPPORTED)
  196862. if (png_ptr->transformations & (PNG_FILLER))
  196863. {
  196864. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196865. max_pixel_depth = 32;
  196866. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196867. {
  196868. if (max_pixel_depth <= 8)
  196869. max_pixel_depth = 16;
  196870. else
  196871. max_pixel_depth = 32;
  196872. }
  196873. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196874. {
  196875. if (max_pixel_depth <= 32)
  196876. max_pixel_depth = 32;
  196877. else
  196878. max_pixel_depth = 64;
  196879. }
  196880. }
  196881. #endif
  196882. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196883. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196884. {
  196885. if (
  196886. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196887. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196888. #endif
  196889. #if defined(PNG_READ_FILLER_SUPPORTED)
  196890. (png_ptr->transformations & (PNG_FILLER)) ||
  196891. #endif
  196892. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196893. {
  196894. if (max_pixel_depth <= 16)
  196895. max_pixel_depth = 32;
  196896. else
  196897. max_pixel_depth = 64;
  196898. }
  196899. else
  196900. {
  196901. if (max_pixel_depth <= 8)
  196902. {
  196903. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196904. max_pixel_depth = 32;
  196905. else
  196906. max_pixel_depth = 24;
  196907. }
  196908. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196909. max_pixel_depth = 64;
  196910. else
  196911. max_pixel_depth = 48;
  196912. }
  196913. }
  196914. #endif
  196915. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196916. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196917. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196918. {
  196919. int user_pixel_depth=png_ptr->user_transform_depth*
  196920. png_ptr->user_transform_channels;
  196921. if(user_pixel_depth > max_pixel_depth)
  196922. max_pixel_depth=user_pixel_depth;
  196923. }
  196924. #endif
  196925. /* align the width on the next larger 8 pixels. Mainly used
  196926. for interlacing */
  196927. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196928. /* calculate the maximum bytes needed, adding a byte and a pixel
  196929. for safety's sake */
  196930. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196931. 1 + ((max_pixel_depth + 7) >> 3);
  196932. #ifdef PNG_MAX_MALLOC_64K
  196933. if (row_bytes > (png_uint_32)65536L)
  196934. png_error(png_ptr, "This image requires a row greater than 64KB");
  196935. #endif
  196936. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196937. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196938. #ifdef PNG_MAX_MALLOC_64K
  196939. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196940. png_error(png_ptr, "This image requires a row greater than 64KB");
  196941. #endif
  196942. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196943. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196944. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196945. png_ptr->rowbytes + 1));
  196946. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196947. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196948. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196949. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196950. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196951. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196952. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196953. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196954. }
  196955. #endif /* PNG_READ_SUPPORTED */
  196956. /*** End of inlined file: pngrutil.c ***/
  196957. /*** Start of inlined file: pngset.c ***/
  196958. /* pngset.c - storage of image information into info struct
  196959. *
  196960. * Last changed in libpng 1.2.21 [October 4, 2007]
  196961. * For conditions of distribution and use, see copyright notice in png.h
  196962. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196963. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196964. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196965. *
  196966. * The functions here are used during reads to store data from the file
  196967. * into the info struct, and during writes to store application data
  196968. * into the info struct for writing into the file. This abstracts the
  196969. * info struct and allows us to change the structure in the future.
  196970. */
  196971. #define PNG_INTERNAL
  196972. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196973. #if defined(PNG_bKGD_SUPPORTED)
  196974. void PNGAPI
  196975. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196976. {
  196977. png_debug1(1, "in %s storage function\n", "bKGD");
  196978. if (png_ptr == NULL || info_ptr == NULL)
  196979. return;
  196980. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196981. info_ptr->valid |= PNG_INFO_bKGD;
  196982. }
  196983. #endif
  196984. #if defined(PNG_cHRM_SUPPORTED)
  196985. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196986. void PNGAPI
  196987. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196988. double white_x, double white_y, double red_x, double red_y,
  196989. double green_x, double green_y, double blue_x, double blue_y)
  196990. {
  196991. png_debug1(1, "in %s storage function\n", "cHRM");
  196992. if (png_ptr == NULL || info_ptr == NULL)
  196993. return;
  196994. if (white_x < 0.0 || white_y < 0.0 ||
  196995. red_x < 0.0 || red_y < 0.0 ||
  196996. green_x < 0.0 || green_y < 0.0 ||
  196997. blue_x < 0.0 || blue_y < 0.0)
  196998. {
  196999. png_warning(png_ptr,
  197000. "Ignoring attempt to set negative chromaticity value");
  197001. return;
  197002. }
  197003. if (white_x > 21474.83 || white_y > 21474.83 ||
  197004. red_x > 21474.83 || red_y > 21474.83 ||
  197005. green_x > 21474.83 || green_y > 21474.83 ||
  197006. blue_x > 21474.83 || blue_y > 21474.83)
  197007. {
  197008. png_warning(png_ptr,
  197009. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197010. return;
  197011. }
  197012. info_ptr->x_white = (float)white_x;
  197013. info_ptr->y_white = (float)white_y;
  197014. info_ptr->x_red = (float)red_x;
  197015. info_ptr->y_red = (float)red_y;
  197016. info_ptr->x_green = (float)green_x;
  197017. info_ptr->y_green = (float)green_y;
  197018. info_ptr->x_blue = (float)blue_x;
  197019. info_ptr->y_blue = (float)blue_y;
  197020. #ifdef PNG_FIXED_POINT_SUPPORTED
  197021. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  197022. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  197023. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  197024. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  197025. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  197026. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  197027. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  197028. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  197029. #endif
  197030. info_ptr->valid |= PNG_INFO_cHRM;
  197031. }
  197032. #endif
  197033. #ifdef PNG_FIXED_POINT_SUPPORTED
  197034. void PNGAPI
  197035. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  197036. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  197037. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  197038. png_fixed_point blue_x, png_fixed_point blue_y)
  197039. {
  197040. png_debug1(1, "in %s storage function\n", "cHRM");
  197041. if (png_ptr == NULL || info_ptr == NULL)
  197042. return;
  197043. if (white_x < 0 || white_y < 0 ||
  197044. red_x < 0 || red_y < 0 ||
  197045. green_x < 0 || green_y < 0 ||
  197046. blue_x < 0 || blue_y < 0)
  197047. {
  197048. png_warning(png_ptr,
  197049. "Ignoring attempt to set negative chromaticity value");
  197050. return;
  197051. }
  197052. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197053. if (white_x > (double) PNG_UINT_31_MAX ||
  197054. white_y > (double) PNG_UINT_31_MAX ||
  197055. red_x > (double) PNG_UINT_31_MAX ||
  197056. red_y > (double) PNG_UINT_31_MAX ||
  197057. green_x > (double) PNG_UINT_31_MAX ||
  197058. green_y > (double) PNG_UINT_31_MAX ||
  197059. blue_x > (double) PNG_UINT_31_MAX ||
  197060. blue_y > (double) PNG_UINT_31_MAX)
  197061. #else
  197062. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197063. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197064. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197065. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197066. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197067. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197068. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197069. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  197070. #endif
  197071. {
  197072. png_warning(png_ptr,
  197073. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197074. return;
  197075. }
  197076. info_ptr->int_x_white = white_x;
  197077. info_ptr->int_y_white = white_y;
  197078. info_ptr->int_x_red = red_x;
  197079. info_ptr->int_y_red = red_y;
  197080. info_ptr->int_x_green = green_x;
  197081. info_ptr->int_y_green = green_y;
  197082. info_ptr->int_x_blue = blue_x;
  197083. info_ptr->int_y_blue = blue_y;
  197084. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197085. info_ptr->x_white = (float)(white_x/100000.);
  197086. info_ptr->y_white = (float)(white_y/100000.);
  197087. info_ptr->x_red = (float)( red_x/100000.);
  197088. info_ptr->y_red = (float)( red_y/100000.);
  197089. info_ptr->x_green = (float)(green_x/100000.);
  197090. info_ptr->y_green = (float)(green_y/100000.);
  197091. info_ptr->x_blue = (float)( blue_x/100000.);
  197092. info_ptr->y_blue = (float)( blue_y/100000.);
  197093. #endif
  197094. info_ptr->valid |= PNG_INFO_cHRM;
  197095. }
  197096. #endif
  197097. #endif
  197098. #if defined(PNG_gAMA_SUPPORTED)
  197099. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197100. void PNGAPI
  197101. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  197102. {
  197103. double gamma;
  197104. png_debug1(1, "in %s storage function\n", "gAMA");
  197105. if (png_ptr == NULL || info_ptr == NULL)
  197106. return;
  197107. /* Check for overflow */
  197108. if (file_gamma > 21474.83)
  197109. {
  197110. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197111. gamma=21474.83;
  197112. }
  197113. else
  197114. gamma=file_gamma;
  197115. info_ptr->gamma = (float)gamma;
  197116. #ifdef PNG_FIXED_POINT_SUPPORTED
  197117. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  197118. #endif
  197119. info_ptr->valid |= PNG_INFO_gAMA;
  197120. if(gamma == 0.0)
  197121. png_warning(png_ptr, "Setting gamma=0");
  197122. }
  197123. #endif
  197124. void PNGAPI
  197125. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  197126. int_gamma)
  197127. {
  197128. png_fixed_point gamma;
  197129. png_debug1(1, "in %s storage function\n", "gAMA");
  197130. if (png_ptr == NULL || info_ptr == NULL)
  197131. return;
  197132. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  197133. {
  197134. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197135. gamma=PNG_UINT_31_MAX;
  197136. }
  197137. else
  197138. {
  197139. if (int_gamma < 0)
  197140. {
  197141. png_warning(png_ptr, "Setting negative gamma to zero");
  197142. gamma=0;
  197143. }
  197144. else
  197145. gamma=int_gamma;
  197146. }
  197147. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197148. info_ptr->gamma = (float)(gamma/100000.);
  197149. #endif
  197150. #ifdef PNG_FIXED_POINT_SUPPORTED
  197151. info_ptr->int_gamma = gamma;
  197152. #endif
  197153. info_ptr->valid |= PNG_INFO_gAMA;
  197154. if(gamma == 0)
  197155. png_warning(png_ptr, "Setting gamma=0");
  197156. }
  197157. #endif
  197158. #if defined(PNG_hIST_SUPPORTED)
  197159. void PNGAPI
  197160. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197161. {
  197162. int i;
  197163. png_debug1(1, "in %s storage function\n", "hIST");
  197164. if (png_ptr == NULL || info_ptr == NULL)
  197165. return;
  197166. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197167. > PNG_MAX_PALETTE_LENGTH)
  197168. {
  197169. png_warning(png_ptr,
  197170. "Invalid palette size, hIST allocation skipped.");
  197171. return;
  197172. }
  197173. #ifdef PNG_FREE_ME_SUPPORTED
  197174. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197175. #endif
  197176. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197177. 1.2.1 */
  197178. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197179. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197180. if (png_ptr->hist == NULL)
  197181. {
  197182. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197183. return;
  197184. }
  197185. for (i = 0; i < info_ptr->num_palette; i++)
  197186. png_ptr->hist[i] = hist[i];
  197187. info_ptr->hist = png_ptr->hist;
  197188. info_ptr->valid |= PNG_INFO_hIST;
  197189. #ifdef PNG_FREE_ME_SUPPORTED
  197190. info_ptr->free_me |= PNG_FREE_HIST;
  197191. #else
  197192. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197193. #endif
  197194. }
  197195. #endif
  197196. void PNGAPI
  197197. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197198. png_uint_32 width, png_uint_32 height, int bit_depth,
  197199. int color_type, int interlace_type, int compression_type,
  197200. int filter_type)
  197201. {
  197202. png_debug1(1, "in %s storage function\n", "IHDR");
  197203. if (png_ptr == NULL || info_ptr == NULL)
  197204. return;
  197205. /* check for width and height valid values */
  197206. if (width == 0 || height == 0)
  197207. png_error(png_ptr, "Image width or height is zero in IHDR");
  197208. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197209. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197210. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197211. #else
  197212. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197213. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197214. #endif
  197215. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197216. png_error(png_ptr, "Invalid image size in IHDR");
  197217. if ( width > (PNG_UINT_32_MAX
  197218. >> 3) /* 8-byte RGBA pixels */
  197219. - 64 /* bigrowbuf hack */
  197220. - 1 /* filter byte */
  197221. - 7*8 /* rounding of width to multiple of 8 pixels */
  197222. - 8) /* extra max_pixel_depth pad */
  197223. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197224. /* check other values */
  197225. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197226. bit_depth != 8 && bit_depth != 16)
  197227. png_error(png_ptr, "Invalid bit depth in IHDR");
  197228. if (color_type < 0 || color_type == 1 ||
  197229. color_type == 5 || color_type > 6)
  197230. png_error(png_ptr, "Invalid color type in IHDR");
  197231. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197232. ((color_type == PNG_COLOR_TYPE_RGB ||
  197233. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197234. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197235. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197236. if (interlace_type >= PNG_INTERLACE_LAST)
  197237. png_error(png_ptr, "Unknown interlace method in IHDR");
  197238. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197239. png_error(png_ptr, "Unknown compression method in IHDR");
  197240. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197241. /* Accept filter_method 64 (intrapixel differencing) only if
  197242. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197243. * 2. Libpng did not read a PNG signature (this filter_method is only
  197244. * used in PNG datastreams that are embedded in MNG datastreams) and
  197245. * 3. The application called png_permit_mng_features with a mask that
  197246. * included PNG_FLAG_MNG_FILTER_64 and
  197247. * 4. The filter_method is 64 and
  197248. * 5. The color_type is RGB or RGBA
  197249. */
  197250. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197251. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197252. if(filter_type != PNG_FILTER_TYPE_BASE)
  197253. {
  197254. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197255. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197256. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197257. (color_type == PNG_COLOR_TYPE_RGB ||
  197258. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197259. png_error(png_ptr, "Unknown filter method in IHDR");
  197260. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197261. png_warning(png_ptr, "Invalid filter method in IHDR");
  197262. }
  197263. #else
  197264. if(filter_type != PNG_FILTER_TYPE_BASE)
  197265. png_error(png_ptr, "Unknown filter method in IHDR");
  197266. #endif
  197267. info_ptr->width = width;
  197268. info_ptr->height = height;
  197269. info_ptr->bit_depth = (png_byte)bit_depth;
  197270. info_ptr->color_type =(png_byte) color_type;
  197271. info_ptr->compression_type = (png_byte)compression_type;
  197272. info_ptr->filter_type = (png_byte)filter_type;
  197273. info_ptr->interlace_type = (png_byte)interlace_type;
  197274. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197275. info_ptr->channels = 1;
  197276. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197277. info_ptr->channels = 3;
  197278. else
  197279. info_ptr->channels = 1;
  197280. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197281. info_ptr->channels++;
  197282. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197283. /* check for potential overflow */
  197284. if (width > (PNG_UINT_32_MAX
  197285. >> 3) /* 8-byte RGBA pixels */
  197286. - 64 /* bigrowbuf hack */
  197287. - 1 /* filter byte */
  197288. - 7*8 /* rounding of width to multiple of 8 pixels */
  197289. - 8) /* extra max_pixel_depth pad */
  197290. info_ptr->rowbytes = (png_size_t)0;
  197291. else
  197292. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197293. }
  197294. #if defined(PNG_oFFs_SUPPORTED)
  197295. void PNGAPI
  197296. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197297. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197298. {
  197299. png_debug1(1, "in %s storage function\n", "oFFs");
  197300. if (png_ptr == NULL || info_ptr == NULL)
  197301. return;
  197302. info_ptr->x_offset = offset_x;
  197303. info_ptr->y_offset = offset_y;
  197304. info_ptr->offset_unit_type = (png_byte)unit_type;
  197305. info_ptr->valid |= PNG_INFO_oFFs;
  197306. }
  197307. #endif
  197308. #if defined(PNG_pCAL_SUPPORTED)
  197309. void PNGAPI
  197310. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197311. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197312. png_charp units, png_charpp params)
  197313. {
  197314. png_uint_32 length;
  197315. int i;
  197316. png_debug1(1, "in %s storage function\n", "pCAL");
  197317. if (png_ptr == NULL || info_ptr == NULL)
  197318. return;
  197319. length = png_strlen(purpose) + 1;
  197320. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197321. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197322. if (info_ptr->pcal_purpose == NULL)
  197323. {
  197324. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197325. return;
  197326. }
  197327. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197328. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197329. info_ptr->pcal_X0 = X0;
  197330. info_ptr->pcal_X1 = X1;
  197331. info_ptr->pcal_type = (png_byte)type;
  197332. info_ptr->pcal_nparams = (png_byte)nparams;
  197333. length = png_strlen(units) + 1;
  197334. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197335. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197336. if (info_ptr->pcal_units == NULL)
  197337. {
  197338. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197339. return;
  197340. }
  197341. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197342. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197343. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197344. if (info_ptr->pcal_params == NULL)
  197345. {
  197346. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197347. return;
  197348. }
  197349. info_ptr->pcal_params[nparams] = NULL;
  197350. for (i = 0; i < nparams; i++)
  197351. {
  197352. length = png_strlen(params[i]) + 1;
  197353. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197354. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197355. if (info_ptr->pcal_params[i] == NULL)
  197356. {
  197357. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197358. return;
  197359. }
  197360. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197361. }
  197362. info_ptr->valid |= PNG_INFO_pCAL;
  197363. #ifdef PNG_FREE_ME_SUPPORTED
  197364. info_ptr->free_me |= PNG_FREE_PCAL;
  197365. #endif
  197366. }
  197367. #endif
  197368. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197369. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197370. void PNGAPI
  197371. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197372. int unit, double width, double height)
  197373. {
  197374. png_debug1(1, "in %s storage function\n", "sCAL");
  197375. if (png_ptr == NULL || info_ptr == NULL)
  197376. return;
  197377. info_ptr->scal_unit = (png_byte)unit;
  197378. info_ptr->scal_pixel_width = width;
  197379. info_ptr->scal_pixel_height = height;
  197380. info_ptr->valid |= PNG_INFO_sCAL;
  197381. }
  197382. #else
  197383. #ifdef PNG_FIXED_POINT_SUPPORTED
  197384. void PNGAPI
  197385. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197386. int unit, png_charp swidth, png_charp sheight)
  197387. {
  197388. png_uint_32 length;
  197389. png_debug1(1, "in %s storage function\n", "sCAL");
  197390. if (png_ptr == NULL || info_ptr == NULL)
  197391. return;
  197392. info_ptr->scal_unit = (png_byte)unit;
  197393. length = png_strlen(swidth) + 1;
  197394. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197395. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197396. if (info_ptr->scal_s_width == NULL)
  197397. {
  197398. png_warning(png_ptr,
  197399. "Memory allocation failed while processing sCAL.");
  197400. }
  197401. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197402. length = png_strlen(sheight) + 1;
  197403. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197404. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197405. if (info_ptr->scal_s_height == NULL)
  197406. {
  197407. png_free (png_ptr, info_ptr->scal_s_width);
  197408. png_warning(png_ptr,
  197409. "Memory allocation failed while processing sCAL.");
  197410. }
  197411. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197412. info_ptr->valid |= PNG_INFO_sCAL;
  197413. #ifdef PNG_FREE_ME_SUPPORTED
  197414. info_ptr->free_me |= PNG_FREE_SCAL;
  197415. #endif
  197416. }
  197417. #endif
  197418. #endif
  197419. #endif
  197420. #if defined(PNG_pHYs_SUPPORTED)
  197421. void PNGAPI
  197422. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197423. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197424. {
  197425. png_debug1(1, "in %s storage function\n", "pHYs");
  197426. if (png_ptr == NULL || info_ptr == NULL)
  197427. return;
  197428. info_ptr->x_pixels_per_unit = res_x;
  197429. info_ptr->y_pixels_per_unit = res_y;
  197430. info_ptr->phys_unit_type = (png_byte)unit_type;
  197431. info_ptr->valid |= PNG_INFO_pHYs;
  197432. }
  197433. #endif
  197434. void PNGAPI
  197435. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197436. png_colorp palette, int num_palette)
  197437. {
  197438. png_debug1(1, "in %s storage function\n", "PLTE");
  197439. if (png_ptr == NULL || info_ptr == NULL)
  197440. return;
  197441. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197442. {
  197443. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197444. png_error(png_ptr, "Invalid palette length");
  197445. else
  197446. {
  197447. png_warning(png_ptr, "Invalid palette length");
  197448. return;
  197449. }
  197450. }
  197451. /*
  197452. * It may not actually be necessary to set png_ptr->palette here;
  197453. * we do it for backward compatibility with the way the png_handle_tRNS
  197454. * function used to do the allocation.
  197455. */
  197456. #ifdef PNG_FREE_ME_SUPPORTED
  197457. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197458. #endif
  197459. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197460. of num_palette entries,
  197461. in case of an invalid PNG file that has too-large sample values. */
  197462. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197463. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197464. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197465. png_sizeof(png_color));
  197466. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197467. info_ptr->palette = png_ptr->palette;
  197468. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197469. #ifdef PNG_FREE_ME_SUPPORTED
  197470. info_ptr->free_me |= PNG_FREE_PLTE;
  197471. #else
  197472. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197473. #endif
  197474. info_ptr->valid |= PNG_INFO_PLTE;
  197475. }
  197476. #if defined(PNG_sBIT_SUPPORTED)
  197477. void PNGAPI
  197478. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197479. png_color_8p sig_bit)
  197480. {
  197481. png_debug1(1, "in %s storage function\n", "sBIT");
  197482. if (png_ptr == NULL || info_ptr == NULL)
  197483. return;
  197484. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197485. info_ptr->valid |= PNG_INFO_sBIT;
  197486. }
  197487. #endif
  197488. #if defined(PNG_sRGB_SUPPORTED)
  197489. void PNGAPI
  197490. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197491. {
  197492. png_debug1(1, "in %s storage function\n", "sRGB");
  197493. if (png_ptr == NULL || info_ptr == NULL)
  197494. return;
  197495. info_ptr->srgb_intent = (png_byte)intent;
  197496. info_ptr->valid |= PNG_INFO_sRGB;
  197497. }
  197498. void PNGAPI
  197499. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197500. int intent)
  197501. {
  197502. #if defined(PNG_gAMA_SUPPORTED)
  197503. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197504. float file_gamma;
  197505. #endif
  197506. #ifdef PNG_FIXED_POINT_SUPPORTED
  197507. png_fixed_point int_file_gamma;
  197508. #endif
  197509. #endif
  197510. #if defined(PNG_cHRM_SUPPORTED)
  197511. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197512. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197513. #endif
  197514. #ifdef PNG_FIXED_POINT_SUPPORTED
  197515. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197516. int_green_y, int_blue_x, int_blue_y;
  197517. #endif
  197518. #endif
  197519. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197520. if (png_ptr == NULL || info_ptr == NULL)
  197521. return;
  197522. png_set_sRGB(png_ptr, info_ptr, intent);
  197523. #if defined(PNG_gAMA_SUPPORTED)
  197524. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197525. file_gamma = (float).45455;
  197526. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197527. #endif
  197528. #ifdef PNG_FIXED_POINT_SUPPORTED
  197529. int_file_gamma = 45455L;
  197530. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197531. #endif
  197532. #endif
  197533. #if defined(PNG_cHRM_SUPPORTED)
  197534. #ifdef PNG_FIXED_POINT_SUPPORTED
  197535. int_white_x = 31270L;
  197536. int_white_y = 32900L;
  197537. int_red_x = 64000L;
  197538. int_red_y = 33000L;
  197539. int_green_x = 30000L;
  197540. int_green_y = 60000L;
  197541. int_blue_x = 15000L;
  197542. int_blue_y = 6000L;
  197543. png_set_cHRM_fixed(png_ptr, info_ptr,
  197544. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197545. int_blue_x, int_blue_y);
  197546. #endif
  197547. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197548. white_x = (float).3127;
  197549. white_y = (float).3290;
  197550. red_x = (float).64;
  197551. red_y = (float).33;
  197552. green_x = (float).30;
  197553. green_y = (float).60;
  197554. blue_x = (float).15;
  197555. blue_y = (float).06;
  197556. png_set_cHRM(png_ptr, info_ptr,
  197557. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197558. #endif
  197559. #endif
  197560. }
  197561. #endif
  197562. #if defined(PNG_iCCP_SUPPORTED)
  197563. void PNGAPI
  197564. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197565. png_charp name, int compression_type,
  197566. png_charp profile, png_uint_32 proflen)
  197567. {
  197568. png_charp new_iccp_name;
  197569. png_charp new_iccp_profile;
  197570. png_debug1(1, "in %s storage function\n", "iCCP");
  197571. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197572. return;
  197573. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197574. if (new_iccp_name == NULL)
  197575. {
  197576. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197577. return;
  197578. }
  197579. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197580. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197581. if (new_iccp_profile == NULL)
  197582. {
  197583. png_free (png_ptr, new_iccp_name);
  197584. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197585. return;
  197586. }
  197587. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197588. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197589. info_ptr->iccp_proflen = proflen;
  197590. info_ptr->iccp_name = new_iccp_name;
  197591. info_ptr->iccp_profile = new_iccp_profile;
  197592. /* Compression is always zero but is here so the API and info structure
  197593. * does not have to change if we introduce multiple compression types */
  197594. info_ptr->iccp_compression = (png_byte)compression_type;
  197595. #ifdef PNG_FREE_ME_SUPPORTED
  197596. info_ptr->free_me |= PNG_FREE_ICCP;
  197597. #endif
  197598. info_ptr->valid |= PNG_INFO_iCCP;
  197599. }
  197600. #endif
  197601. #if defined(PNG_TEXT_SUPPORTED)
  197602. void PNGAPI
  197603. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197604. int num_text)
  197605. {
  197606. int ret;
  197607. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197608. if (ret)
  197609. png_error(png_ptr, "Insufficient memory to store text");
  197610. }
  197611. int /* PRIVATE */
  197612. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197613. int num_text)
  197614. {
  197615. int i;
  197616. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197617. "text" : (png_const_charp)png_ptr->chunk_name));
  197618. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197619. return(0);
  197620. /* Make sure we have enough space in the "text" array in info_struct
  197621. * to hold all of the incoming text_ptr objects.
  197622. */
  197623. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197624. {
  197625. if (info_ptr->text != NULL)
  197626. {
  197627. png_textp old_text;
  197628. int old_max;
  197629. old_max = info_ptr->max_text;
  197630. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197631. old_text = info_ptr->text;
  197632. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197633. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197634. if (info_ptr->text == NULL)
  197635. {
  197636. png_free(png_ptr, old_text);
  197637. return(1);
  197638. }
  197639. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197640. png_sizeof(png_text)));
  197641. png_free(png_ptr, old_text);
  197642. }
  197643. else
  197644. {
  197645. info_ptr->max_text = num_text + 8;
  197646. info_ptr->num_text = 0;
  197647. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197648. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197649. if (info_ptr->text == NULL)
  197650. return(1);
  197651. #ifdef PNG_FREE_ME_SUPPORTED
  197652. info_ptr->free_me |= PNG_FREE_TEXT;
  197653. #endif
  197654. }
  197655. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197656. info_ptr->max_text);
  197657. }
  197658. for (i = 0; i < num_text; i++)
  197659. {
  197660. png_size_t text_length,key_len;
  197661. png_size_t lang_len,lang_key_len;
  197662. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197663. if (text_ptr[i].key == NULL)
  197664. continue;
  197665. key_len = png_strlen(text_ptr[i].key);
  197666. if(text_ptr[i].compression <= 0)
  197667. {
  197668. lang_len = 0;
  197669. lang_key_len = 0;
  197670. }
  197671. else
  197672. #ifdef PNG_iTXt_SUPPORTED
  197673. {
  197674. /* set iTXt data */
  197675. if (text_ptr[i].lang != NULL)
  197676. lang_len = png_strlen(text_ptr[i].lang);
  197677. else
  197678. lang_len = 0;
  197679. if (text_ptr[i].lang_key != NULL)
  197680. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197681. else
  197682. lang_key_len = 0;
  197683. }
  197684. #else
  197685. {
  197686. png_warning(png_ptr, "iTXt chunk not supported.");
  197687. continue;
  197688. }
  197689. #endif
  197690. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197691. {
  197692. text_length = 0;
  197693. #ifdef PNG_iTXt_SUPPORTED
  197694. if(text_ptr[i].compression > 0)
  197695. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197696. else
  197697. #endif
  197698. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197699. }
  197700. else
  197701. {
  197702. text_length = png_strlen(text_ptr[i].text);
  197703. textp->compression = text_ptr[i].compression;
  197704. }
  197705. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197706. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197707. if (textp->key == NULL)
  197708. return(1);
  197709. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197710. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197711. (int)textp->key);
  197712. png_memcpy(textp->key, text_ptr[i].key,
  197713. (png_size_t)(key_len));
  197714. *(textp->key+key_len) = '\0';
  197715. #ifdef PNG_iTXt_SUPPORTED
  197716. if (text_ptr[i].compression > 0)
  197717. {
  197718. textp->lang=textp->key + key_len + 1;
  197719. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197720. *(textp->lang+lang_len) = '\0';
  197721. textp->lang_key=textp->lang + lang_len + 1;
  197722. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197723. *(textp->lang_key+lang_key_len) = '\0';
  197724. textp->text=textp->lang_key + lang_key_len + 1;
  197725. }
  197726. else
  197727. #endif
  197728. {
  197729. #ifdef PNG_iTXt_SUPPORTED
  197730. textp->lang=NULL;
  197731. textp->lang_key=NULL;
  197732. #endif
  197733. textp->text=textp->key + key_len + 1;
  197734. }
  197735. if(text_length)
  197736. png_memcpy(textp->text, text_ptr[i].text,
  197737. (png_size_t)(text_length));
  197738. *(textp->text+text_length) = '\0';
  197739. #ifdef PNG_iTXt_SUPPORTED
  197740. if(textp->compression > 0)
  197741. {
  197742. textp->text_length = 0;
  197743. textp->itxt_length = text_length;
  197744. }
  197745. else
  197746. #endif
  197747. {
  197748. textp->text_length = text_length;
  197749. #ifdef PNG_iTXt_SUPPORTED
  197750. textp->itxt_length = 0;
  197751. #endif
  197752. }
  197753. info_ptr->num_text++;
  197754. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197755. }
  197756. return(0);
  197757. }
  197758. #endif
  197759. #if defined(PNG_tIME_SUPPORTED)
  197760. void PNGAPI
  197761. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197762. {
  197763. png_debug1(1, "in %s storage function\n", "tIME");
  197764. if (png_ptr == NULL || info_ptr == NULL ||
  197765. (png_ptr->mode & PNG_WROTE_tIME))
  197766. return;
  197767. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197768. info_ptr->valid |= PNG_INFO_tIME;
  197769. }
  197770. #endif
  197771. #if defined(PNG_tRNS_SUPPORTED)
  197772. void PNGAPI
  197773. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197774. png_bytep trans, int num_trans, png_color_16p trans_values)
  197775. {
  197776. png_debug1(1, "in %s storage function\n", "tRNS");
  197777. if (png_ptr == NULL || info_ptr == NULL)
  197778. return;
  197779. if (trans != NULL)
  197780. {
  197781. /*
  197782. * It may not actually be necessary to set png_ptr->trans here;
  197783. * we do it for backward compatibility with the way the png_handle_tRNS
  197784. * function used to do the allocation.
  197785. */
  197786. #ifdef PNG_FREE_ME_SUPPORTED
  197787. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197788. #endif
  197789. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197790. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197791. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197792. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197793. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197794. #ifdef PNG_FREE_ME_SUPPORTED
  197795. info_ptr->free_me |= PNG_FREE_TRNS;
  197796. #else
  197797. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197798. #endif
  197799. }
  197800. if (trans_values != NULL)
  197801. {
  197802. png_memcpy(&(info_ptr->trans_values), trans_values,
  197803. png_sizeof(png_color_16));
  197804. if (num_trans == 0)
  197805. num_trans = 1;
  197806. }
  197807. info_ptr->num_trans = (png_uint_16)num_trans;
  197808. info_ptr->valid |= PNG_INFO_tRNS;
  197809. }
  197810. #endif
  197811. #if defined(PNG_sPLT_SUPPORTED)
  197812. void PNGAPI
  197813. png_set_sPLT(png_structp png_ptr,
  197814. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197815. {
  197816. png_sPLT_tp np;
  197817. int i;
  197818. if (png_ptr == NULL || info_ptr == NULL)
  197819. return;
  197820. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197821. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197822. if (np == NULL)
  197823. {
  197824. png_warning(png_ptr, "No memory for sPLT palettes.");
  197825. return;
  197826. }
  197827. png_memcpy(np, info_ptr->splt_palettes,
  197828. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197829. png_free(png_ptr, info_ptr->splt_palettes);
  197830. info_ptr->splt_palettes=NULL;
  197831. for (i = 0; i < nentries; i++)
  197832. {
  197833. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197834. png_sPLT_tp from = entries + i;
  197835. to->name = (png_charp)png_malloc_warn(png_ptr,
  197836. png_strlen(from->name) + 1);
  197837. if (to->name == NULL)
  197838. {
  197839. png_warning(png_ptr,
  197840. "Out of memory while processing sPLT chunk");
  197841. }
  197842. /* TODO: use png_malloc_warn */
  197843. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197844. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197845. from->nentries * png_sizeof(png_sPLT_entry));
  197846. /* TODO: use png_malloc_warn */
  197847. png_memcpy(to->entries, from->entries,
  197848. from->nentries * png_sizeof(png_sPLT_entry));
  197849. if (to->entries == NULL)
  197850. {
  197851. png_warning(png_ptr,
  197852. "Out of memory while processing sPLT chunk");
  197853. png_free(png_ptr,to->name);
  197854. to->name = NULL;
  197855. }
  197856. to->nentries = from->nentries;
  197857. to->depth = from->depth;
  197858. }
  197859. info_ptr->splt_palettes = np;
  197860. info_ptr->splt_palettes_num += nentries;
  197861. info_ptr->valid |= PNG_INFO_sPLT;
  197862. #ifdef PNG_FREE_ME_SUPPORTED
  197863. info_ptr->free_me |= PNG_FREE_SPLT;
  197864. #endif
  197865. }
  197866. #endif /* PNG_sPLT_SUPPORTED */
  197867. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197868. void PNGAPI
  197869. png_set_unknown_chunks(png_structp png_ptr,
  197870. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197871. {
  197872. png_unknown_chunkp np;
  197873. int i;
  197874. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197875. return;
  197876. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197877. (info_ptr->unknown_chunks_num + num_unknowns) *
  197878. png_sizeof(png_unknown_chunk));
  197879. if (np == NULL)
  197880. {
  197881. png_warning(png_ptr,
  197882. "Out of memory while processing unknown chunk.");
  197883. return;
  197884. }
  197885. png_memcpy(np, info_ptr->unknown_chunks,
  197886. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197887. png_free(png_ptr, info_ptr->unknown_chunks);
  197888. info_ptr->unknown_chunks=NULL;
  197889. for (i = 0; i < num_unknowns; i++)
  197890. {
  197891. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197892. png_unknown_chunkp from = unknowns + i;
  197893. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197894. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197895. if (to->data == NULL)
  197896. {
  197897. png_warning(png_ptr,
  197898. "Out of memory while processing unknown chunk.");
  197899. }
  197900. else
  197901. {
  197902. png_memcpy(to->data, from->data, from->size);
  197903. to->size = from->size;
  197904. /* note our location in the read or write sequence */
  197905. to->location = (png_byte)(png_ptr->mode & 0xff);
  197906. }
  197907. }
  197908. info_ptr->unknown_chunks = np;
  197909. info_ptr->unknown_chunks_num += num_unknowns;
  197910. #ifdef PNG_FREE_ME_SUPPORTED
  197911. info_ptr->free_me |= PNG_FREE_UNKN;
  197912. #endif
  197913. }
  197914. void PNGAPI
  197915. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197916. int chunk, int location)
  197917. {
  197918. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197919. (int)info_ptr->unknown_chunks_num)
  197920. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197921. }
  197922. #endif
  197923. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197924. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197925. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197926. void PNGAPI
  197927. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197928. {
  197929. /* This function is deprecated in favor of png_permit_mng_features()
  197930. and will be removed from libpng-1.3.0 */
  197931. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197932. if (png_ptr == NULL)
  197933. return;
  197934. png_ptr->mng_features_permitted = (png_byte)
  197935. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197936. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197937. }
  197938. #endif
  197939. #endif
  197940. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197941. png_uint_32 PNGAPI
  197942. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197943. {
  197944. png_debug(1, "in png_permit_mng_features\n");
  197945. if (png_ptr == NULL)
  197946. return (png_uint_32)0;
  197947. png_ptr->mng_features_permitted =
  197948. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197949. return (png_uint_32)png_ptr->mng_features_permitted;
  197950. }
  197951. #endif
  197952. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197953. void PNGAPI
  197954. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197955. chunk_list, int num_chunks)
  197956. {
  197957. png_bytep new_list, p;
  197958. int i, old_num_chunks;
  197959. if (png_ptr == NULL)
  197960. return;
  197961. if (num_chunks == 0)
  197962. {
  197963. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197964. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197965. else
  197966. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197967. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197968. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197969. else
  197970. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197971. return;
  197972. }
  197973. if (chunk_list == NULL)
  197974. return;
  197975. old_num_chunks=png_ptr->num_chunk_list;
  197976. new_list=(png_bytep)png_malloc(png_ptr,
  197977. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197978. if(png_ptr->chunk_list != NULL)
  197979. {
  197980. png_memcpy(new_list, png_ptr->chunk_list,
  197981. (png_size_t)(5*old_num_chunks));
  197982. png_free(png_ptr, png_ptr->chunk_list);
  197983. png_ptr->chunk_list=NULL;
  197984. }
  197985. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197986. (png_size_t)(5*num_chunks));
  197987. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197988. *p=(png_byte)keep;
  197989. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197990. png_ptr->chunk_list=new_list;
  197991. #ifdef PNG_FREE_ME_SUPPORTED
  197992. png_ptr->free_me |= PNG_FREE_LIST;
  197993. #endif
  197994. }
  197995. #endif
  197996. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197997. void PNGAPI
  197998. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197999. png_user_chunk_ptr read_user_chunk_fn)
  198000. {
  198001. png_debug(1, "in png_set_read_user_chunk_fn\n");
  198002. if (png_ptr == NULL)
  198003. return;
  198004. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  198005. png_ptr->user_chunk_ptr = user_chunk_ptr;
  198006. }
  198007. #endif
  198008. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  198009. void PNGAPI
  198010. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  198011. {
  198012. png_debug1(1, "in %s storage function\n", "rows");
  198013. if (png_ptr == NULL || info_ptr == NULL)
  198014. return;
  198015. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  198016. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  198017. info_ptr->row_pointers = row_pointers;
  198018. if(row_pointers)
  198019. info_ptr->valid |= PNG_INFO_IDAT;
  198020. }
  198021. #endif
  198022. #ifdef PNG_WRITE_SUPPORTED
  198023. void PNGAPI
  198024. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  198025. {
  198026. if (png_ptr == NULL)
  198027. return;
  198028. if(png_ptr->zbuf)
  198029. png_free(png_ptr, png_ptr->zbuf);
  198030. png_ptr->zbuf_size = (png_size_t)size;
  198031. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  198032. png_ptr->zstream.next_out = png_ptr->zbuf;
  198033. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198034. }
  198035. #endif
  198036. void PNGAPI
  198037. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  198038. {
  198039. if (png_ptr && info_ptr)
  198040. info_ptr->valid &= ~(mask);
  198041. }
  198042. #ifndef PNG_1_0_X
  198043. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  198044. /* function was added to libpng 1.2.0 and should always exist by default */
  198045. void PNGAPI
  198046. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  198047. {
  198048. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198049. if (png_ptr != NULL)
  198050. png_ptr->asm_flags = 0;
  198051. }
  198052. /* this function was added to libpng 1.2.0 */
  198053. void PNGAPI
  198054. png_set_mmx_thresholds (png_structp png_ptr,
  198055. png_byte,
  198056. png_uint_32)
  198057. {
  198058. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198059. if (png_ptr == NULL)
  198060. return;
  198061. }
  198062. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  198063. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198064. /* this function was added to libpng 1.2.6 */
  198065. void PNGAPI
  198066. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  198067. png_uint_32 user_height_max)
  198068. {
  198069. /* Images with dimensions larger than these limits will be
  198070. * rejected by png_set_IHDR(). To accept any PNG datastream
  198071. * regardless of dimensions, set both limits to 0x7ffffffL.
  198072. */
  198073. if(png_ptr == NULL) return;
  198074. png_ptr->user_width_max = user_width_max;
  198075. png_ptr->user_height_max = user_height_max;
  198076. }
  198077. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  198078. #endif /* ?PNG_1_0_X */
  198079. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198080. /*** End of inlined file: pngset.c ***/
  198081. /*** Start of inlined file: pngtrans.c ***/
  198082. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  198083. *
  198084. * Last changed in libpng 1.2.17 May 15, 2007
  198085. * For conditions of distribution and use, see copyright notice in png.h
  198086. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198087. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198088. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198089. */
  198090. #define PNG_INTERNAL
  198091. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  198092. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198093. /* turn on BGR-to-RGB mapping */
  198094. void PNGAPI
  198095. png_set_bgr(png_structp png_ptr)
  198096. {
  198097. png_debug(1, "in png_set_bgr\n");
  198098. if(png_ptr == NULL) return;
  198099. png_ptr->transformations |= PNG_BGR;
  198100. }
  198101. #endif
  198102. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198103. /* turn on 16 bit byte swapping */
  198104. void PNGAPI
  198105. png_set_swap(png_structp png_ptr)
  198106. {
  198107. png_debug(1, "in png_set_swap\n");
  198108. if(png_ptr == NULL) return;
  198109. if (png_ptr->bit_depth == 16)
  198110. png_ptr->transformations |= PNG_SWAP_BYTES;
  198111. }
  198112. #endif
  198113. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  198114. /* turn on pixel packing */
  198115. void PNGAPI
  198116. png_set_packing(png_structp png_ptr)
  198117. {
  198118. png_debug(1, "in png_set_packing\n");
  198119. if(png_ptr == NULL) return;
  198120. if (png_ptr->bit_depth < 8)
  198121. {
  198122. png_ptr->transformations |= PNG_PACK;
  198123. png_ptr->usr_bit_depth = 8;
  198124. }
  198125. }
  198126. #endif
  198127. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198128. /* turn on packed pixel swapping */
  198129. void PNGAPI
  198130. png_set_packswap(png_structp png_ptr)
  198131. {
  198132. png_debug(1, "in png_set_packswap\n");
  198133. if(png_ptr == NULL) return;
  198134. if (png_ptr->bit_depth < 8)
  198135. png_ptr->transformations |= PNG_PACKSWAP;
  198136. }
  198137. #endif
  198138. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  198139. void PNGAPI
  198140. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  198141. {
  198142. png_debug(1, "in png_set_shift\n");
  198143. if(png_ptr == NULL) return;
  198144. png_ptr->transformations |= PNG_SHIFT;
  198145. png_ptr->shift = *true_bits;
  198146. }
  198147. #endif
  198148. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198149. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198150. int PNGAPI
  198151. png_set_interlace_handling(png_structp png_ptr)
  198152. {
  198153. png_debug(1, "in png_set_interlace handling\n");
  198154. if (png_ptr && png_ptr->interlaced)
  198155. {
  198156. png_ptr->transformations |= PNG_INTERLACE;
  198157. return (7);
  198158. }
  198159. return (1);
  198160. }
  198161. #endif
  198162. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198163. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198164. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198165. * for 48-bit input data, as well as to avoid problems with some compilers
  198166. * that don't like bytes as parameters.
  198167. */
  198168. void PNGAPI
  198169. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198170. {
  198171. png_debug(1, "in png_set_filler\n");
  198172. if(png_ptr == NULL) return;
  198173. png_ptr->transformations |= PNG_FILLER;
  198174. png_ptr->filler = (png_byte)filler;
  198175. if (filler_loc == PNG_FILLER_AFTER)
  198176. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198177. else
  198178. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198179. /* This should probably go in the "do_read_filler" routine.
  198180. * I attempted to do that in libpng-1.0.1a but that caused problems
  198181. * so I restored it in libpng-1.0.2a
  198182. */
  198183. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198184. {
  198185. png_ptr->usr_channels = 4;
  198186. }
  198187. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198188. * a less-than-8-bit grayscale to GA? */
  198189. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198190. {
  198191. png_ptr->usr_channels = 2;
  198192. }
  198193. }
  198194. #if !defined(PNG_1_0_X)
  198195. /* Added to libpng-1.2.7 */
  198196. void PNGAPI
  198197. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198198. {
  198199. png_debug(1, "in png_set_add_alpha\n");
  198200. if(png_ptr == NULL) return;
  198201. png_set_filler(png_ptr, filler, filler_loc);
  198202. png_ptr->transformations |= PNG_ADD_ALPHA;
  198203. }
  198204. #endif
  198205. #endif
  198206. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198207. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198208. void PNGAPI
  198209. png_set_swap_alpha(png_structp png_ptr)
  198210. {
  198211. png_debug(1, "in png_set_swap_alpha\n");
  198212. if(png_ptr == NULL) return;
  198213. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198214. }
  198215. #endif
  198216. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198217. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198218. void PNGAPI
  198219. png_set_invert_alpha(png_structp png_ptr)
  198220. {
  198221. png_debug(1, "in png_set_invert_alpha\n");
  198222. if(png_ptr == NULL) return;
  198223. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198224. }
  198225. #endif
  198226. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198227. void PNGAPI
  198228. png_set_invert_mono(png_structp png_ptr)
  198229. {
  198230. png_debug(1, "in png_set_invert_mono\n");
  198231. if(png_ptr == NULL) return;
  198232. png_ptr->transformations |= PNG_INVERT_MONO;
  198233. }
  198234. /* invert monochrome grayscale data */
  198235. void /* PRIVATE */
  198236. png_do_invert(png_row_infop row_info, png_bytep row)
  198237. {
  198238. png_debug(1, "in png_do_invert\n");
  198239. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198240. * if (row_info->bit_depth == 1 &&
  198241. */
  198242. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198243. if (row == NULL || row_info == NULL)
  198244. return;
  198245. #endif
  198246. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198247. {
  198248. png_bytep rp = row;
  198249. png_uint_32 i;
  198250. png_uint_32 istop = row_info->rowbytes;
  198251. for (i = 0; i < istop; i++)
  198252. {
  198253. *rp = (png_byte)(~(*rp));
  198254. rp++;
  198255. }
  198256. }
  198257. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198258. row_info->bit_depth == 8)
  198259. {
  198260. png_bytep rp = row;
  198261. png_uint_32 i;
  198262. png_uint_32 istop = row_info->rowbytes;
  198263. for (i = 0; i < istop; i+=2)
  198264. {
  198265. *rp = (png_byte)(~(*rp));
  198266. rp+=2;
  198267. }
  198268. }
  198269. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198270. row_info->bit_depth == 16)
  198271. {
  198272. png_bytep rp = row;
  198273. png_uint_32 i;
  198274. png_uint_32 istop = row_info->rowbytes;
  198275. for (i = 0; i < istop; i+=4)
  198276. {
  198277. *rp = (png_byte)(~(*rp));
  198278. *(rp+1) = (png_byte)(~(*(rp+1)));
  198279. rp+=4;
  198280. }
  198281. }
  198282. }
  198283. #endif
  198284. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198285. /* swaps byte order on 16 bit depth images */
  198286. void /* PRIVATE */
  198287. png_do_swap(png_row_infop row_info, png_bytep row)
  198288. {
  198289. png_debug(1, "in png_do_swap\n");
  198290. if (
  198291. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198292. row != NULL && row_info != NULL &&
  198293. #endif
  198294. row_info->bit_depth == 16)
  198295. {
  198296. png_bytep rp = row;
  198297. png_uint_32 i;
  198298. png_uint_32 istop= row_info->width * row_info->channels;
  198299. for (i = 0; i < istop; i++, rp += 2)
  198300. {
  198301. png_byte t = *rp;
  198302. *rp = *(rp + 1);
  198303. *(rp + 1) = t;
  198304. }
  198305. }
  198306. }
  198307. #endif
  198308. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198309. static PNG_CONST png_byte onebppswaptable[256] = {
  198310. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198311. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198312. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198313. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198314. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198315. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198316. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198317. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198318. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198319. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198320. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198321. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198322. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198323. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198324. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198325. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198326. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198327. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198328. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198329. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198330. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198331. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198332. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198333. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198334. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198335. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198336. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198337. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198338. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198339. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198340. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198341. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198342. };
  198343. static PNG_CONST png_byte twobppswaptable[256] = {
  198344. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198345. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198346. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198347. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198348. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198349. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198350. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198351. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198352. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198353. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198354. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198355. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198356. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198357. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198358. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198359. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198360. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198361. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198362. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198363. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198364. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198365. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198366. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198367. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198368. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198369. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198370. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198371. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198372. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198373. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198374. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198375. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198376. };
  198377. static PNG_CONST png_byte fourbppswaptable[256] = {
  198378. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198379. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198380. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198381. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198382. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198383. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198384. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198385. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198386. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198387. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198388. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198389. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198390. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198391. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198392. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198393. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198394. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198395. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198396. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198397. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198398. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198399. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198400. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198401. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198402. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198403. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198404. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198405. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198406. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198407. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198408. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198409. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198410. };
  198411. /* swaps pixel packing order within bytes */
  198412. void /* PRIVATE */
  198413. png_do_packswap(png_row_infop row_info, png_bytep row)
  198414. {
  198415. png_debug(1, "in png_do_packswap\n");
  198416. if (
  198417. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198418. row != NULL && row_info != NULL &&
  198419. #endif
  198420. row_info->bit_depth < 8)
  198421. {
  198422. png_bytep rp, end, table;
  198423. end = row + row_info->rowbytes;
  198424. if (row_info->bit_depth == 1)
  198425. table = (png_bytep)onebppswaptable;
  198426. else if (row_info->bit_depth == 2)
  198427. table = (png_bytep)twobppswaptable;
  198428. else if (row_info->bit_depth == 4)
  198429. table = (png_bytep)fourbppswaptable;
  198430. else
  198431. return;
  198432. for (rp = row; rp < end; rp++)
  198433. *rp = table[*rp];
  198434. }
  198435. }
  198436. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198437. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198438. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198439. /* remove filler or alpha byte(s) */
  198440. void /* PRIVATE */
  198441. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198442. {
  198443. png_debug(1, "in png_do_strip_filler\n");
  198444. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198445. if (row != NULL && row_info != NULL)
  198446. #endif
  198447. {
  198448. png_bytep sp=row;
  198449. png_bytep dp=row;
  198450. png_uint_32 row_width=row_info->width;
  198451. png_uint_32 i;
  198452. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198453. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198454. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198455. row_info->channels == 4)
  198456. {
  198457. if (row_info->bit_depth == 8)
  198458. {
  198459. /* This converts from RGBX or RGBA to RGB */
  198460. if (flags & PNG_FLAG_FILLER_AFTER)
  198461. {
  198462. dp+=3; sp+=4;
  198463. for (i = 1; i < row_width; i++)
  198464. {
  198465. *dp++ = *sp++;
  198466. *dp++ = *sp++;
  198467. *dp++ = *sp++;
  198468. sp++;
  198469. }
  198470. }
  198471. /* This converts from XRGB or ARGB to RGB */
  198472. else
  198473. {
  198474. for (i = 0; i < row_width; i++)
  198475. {
  198476. sp++;
  198477. *dp++ = *sp++;
  198478. *dp++ = *sp++;
  198479. *dp++ = *sp++;
  198480. }
  198481. }
  198482. row_info->pixel_depth = 24;
  198483. row_info->rowbytes = row_width * 3;
  198484. }
  198485. else /* if (row_info->bit_depth == 16) */
  198486. {
  198487. if (flags & PNG_FLAG_FILLER_AFTER)
  198488. {
  198489. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198490. sp += 8; dp += 6;
  198491. for (i = 1; i < row_width; i++)
  198492. {
  198493. /* This could be (although png_memcpy is probably slower):
  198494. png_memcpy(dp, sp, 6);
  198495. sp += 8;
  198496. dp += 6;
  198497. */
  198498. *dp++ = *sp++;
  198499. *dp++ = *sp++;
  198500. *dp++ = *sp++;
  198501. *dp++ = *sp++;
  198502. *dp++ = *sp++;
  198503. *dp++ = *sp++;
  198504. sp += 2;
  198505. }
  198506. }
  198507. else
  198508. {
  198509. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198510. for (i = 0; i < row_width; i++)
  198511. {
  198512. /* This could be (although png_memcpy is probably slower):
  198513. png_memcpy(dp, sp, 6);
  198514. sp += 8;
  198515. dp += 6;
  198516. */
  198517. sp+=2;
  198518. *dp++ = *sp++;
  198519. *dp++ = *sp++;
  198520. *dp++ = *sp++;
  198521. *dp++ = *sp++;
  198522. *dp++ = *sp++;
  198523. *dp++ = *sp++;
  198524. }
  198525. }
  198526. row_info->pixel_depth = 48;
  198527. row_info->rowbytes = row_width * 6;
  198528. }
  198529. row_info->channels = 3;
  198530. }
  198531. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198532. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198533. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198534. row_info->channels == 2)
  198535. {
  198536. if (row_info->bit_depth == 8)
  198537. {
  198538. /* This converts from GX or GA to G */
  198539. if (flags & PNG_FLAG_FILLER_AFTER)
  198540. {
  198541. for (i = 0; i < row_width; i++)
  198542. {
  198543. *dp++ = *sp++;
  198544. sp++;
  198545. }
  198546. }
  198547. /* This converts from XG or AG to G */
  198548. else
  198549. {
  198550. for (i = 0; i < row_width; i++)
  198551. {
  198552. sp++;
  198553. *dp++ = *sp++;
  198554. }
  198555. }
  198556. row_info->pixel_depth = 8;
  198557. row_info->rowbytes = row_width;
  198558. }
  198559. else /* if (row_info->bit_depth == 16) */
  198560. {
  198561. if (flags & PNG_FLAG_FILLER_AFTER)
  198562. {
  198563. /* This converts from GGXX or GGAA to GG */
  198564. sp += 4; dp += 2;
  198565. for (i = 1; i < row_width; i++)
  198566. {
  198567. *dp++ = *sp++;
  198568. *dp++ = *sp++;
  198569. sp += 2;
  198570. }
  198571. }
  198572. else
  198573. {
  198574. /* This converts from XXGG or AAGG to GG */
  198575. for (i = 0; i < row_width; i++)
  198576. {
  198577. sp += 2;
  198578. *dp++ = *sp++;
  198579. *dp++ = *sp++;
  198580. }
  198581. }
  198582. row_info->pixel_depth = 16;
  198583. row_info->rowbytes = row_width * 2;
  198584. }
  198585. row_info->channels = 1;
  198586. }
  198587. if (flags & PNG_FLAG_STRIP_ALPHA)
  198588. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198589. }
  198590. }
  198591. #endif
  198592. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198593. /* swaps red and blue bytes within a pixel */
  198594. void /* PRIVATE */
  198595. png_do_bgr(png_row_infop row_info, png_bytep row)
  198596. {
  198597. png_debug(1, "in png_do_bgr\n");
  198598. if (
  198599. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198600. row != NULL && row_info != NULL &&
  198601. #endif
  198602. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198603. {
  198604. png_uint_32 row_width = row_info->width;
  198605. if (row_info->bit_depth == 8)
  198606. {
  198607. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198608. {
  198609. png_bytep rp;
  198610. png_uint_32 i;
  198611. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198612. {
  198613. png_byte save = *rp;
  198614. *rp = *(rp + 2);
  198615. *(rp + 2) = save;
  198616. }
  198617. }
  198618. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198619. {
  198620. png_bytep rp;
  198621. png_uint_32 i;
  198622. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198623. {
  198624. png_byte save = *rp;
  198625. *rp = *(rp + 2);
  198626. *(rp + 2) = save;
  198627. }
  198628. }
  198629. }
  198630. else if (row_info->bit_depth == 16)
  198631. {
  198632. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198633. {
  198634. png_bytep rp;
  198635. png_uint_32 i;
  198636. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198637. {
  198638. png_byte save = *rp;
  198639. *rp = *(rp + 4);
  198640. *(rp + 4) = save;
  198641. save = *(rp + 1);
  198642. *(rp + 1) = *(rp + 5);
  198643. *(rp + 5) = save;
  198644. }
  198645. }
  198646. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198647. {
  198648. png_bytep rp;
  198649. png_uint_32 i;
  198650. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198651. {
  198652. png_byte save = *rp;
  198653. *rp = *(rp + 4);
  198654. *(rp + 4) = save;
  198655. save = *(rp + 1);
  198656. *(rp + 1) = *(rp + 5);
  198657. *(rp + 5) = save;
  198658. }
  198659. }
  198660. }
  198661. }
  198662. }
  198663. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198664. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198665. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198666. defined(PNG_LEGACY_SUPPORTED)
  198667. void PNGAPI
  198668. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198669. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198670. {
  198671. png_debug(1, "in png_set_user_transform_info\n");
  198672. if(png_ptr == NULL) return;
  198673. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198674. png_ptr->user_transform_ptr = user_transform_ptr;
  198675. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198676. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198677. #else
  198678. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198679. png_warning(png_ptr,
  198680. "This version of libpng does not support user transform info");
  198681. #endif
  198682. }
  198683. #endif
  198684. /* This function returns a pointer to the user_transform_ptr associated with
  198685. * the user transform functions. The application should free any memory
  198686. * associated with this pointer before png_write_destroy and png_read_destroy
  198687. * are called.
  198688. */
  198689. png_voidp PNGAPI
  198690. png_get_user_transform_ptr(png_structp png_ptr)
  198691. {
  198692. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198693. if (png_ptr == NULL) return (NULL);
  198694. return ((png_voidp)png_ptr->user_transform_ptr);
  198695. #else
  198696. return (NULL);
  198697. #endif
  198698. }
  198699. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198700. /*** End of inlined file: pngtrans.c ***/
  198701. /*** Start of inlined file: pngwio.c ***/
  198702. /* pngwio.c - functions for data output
  198703. *
  198704. * Last changed in libpng 1.2.13 November 13, 2006
  198705. * For conditions of distribution and use, see copyright notice in png.h
  198706. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198707. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198708. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198709. *
  198710. * This file provides a location for all output. Users who need
  198711. * special handling are expected to write functions that have the same
  198712. * arguments as these and perform similar functions, but that possibly
  198713. * use different output methods. Note that you shouldn't change these
  198714. * functions, but rather write replacement functions and then change
  198715. * them at run time with png_set_write_fn(...).
  198716. */
  198717. #define PNG_INTERNAL
  198718. #ifdef PNG_WRITE_SUPPORTED
  198719. /* Write the data to whatever output you are using. The default routine
  198720. writes to a file pointer. Note that this routine sometimes gets called
  198721. with very small lengths, so you should implement some kind of simple
  198722. buffering if you are using unbuffered writes. This should never be asked
  198723. to write more than 64K on a 16 bit machine. */
  198724. void /* PRIVATE */
  198725. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198726. {
  198727. if (png_ptr->write_data_fn != NULL )
  198728. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198729. else
  198730. png_error(png_ptr, "Call to NULL write function");
  198731. }
  198732. #if !defined(PNG_NO_STDIO)
  198733. /* This is the function that does the actual writing of data. If you are
  198734. not writing to a standard C stream, you should create a replacement
  198735. write_data function and use it at run time with png_set_write_fn(), rather
  198736. than changing the library. */
  198737. #ifndef USE_FAR_KEYWORD
  198738. void PNGAPI
  198739. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198740. {
  198741. png_uint_32 check;
  198742. if(png_ptr == NULL) return;
  198743. #if defined(_WIN32_WCE)
  198744. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198745. check = 0;
  198746. #else
  198747. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198748. #endif
  198749. if (check != length)
  198750. png_error(png_ptr, "Write Error");
  198751. }
  198752. #else
  198753. /* this is the model-independent version. Since the standard I/O library
  198754. can't handle far buffers in the medium and small models, we have to copy
  198755. the data.
  198756. */
  198757. #define NEAR_BUF_SIZE 1024
  198758. #define MIN(a,b) (a <= b ? a : b)
  198759. void PNGAPI
  198760. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198761. {
  198762. png_uint_32 check;
  198763. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198764. png_FILE_p io_ptr;
  198765. if(png_ptr == NULL) return;
  198766. /* Check if data really is near. If so, use usual code. */
  198767. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198768. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198769. if ((png_bytep)near_data == data)
  198770. {
  198771. #if defined(_WIN32_WCE)
  198772. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198773. check = 0;
  198774. #else
  198775. check = fwrite(near_data, 1, length, io_ptr);
  198776. #endif
  198777. }
  198778. else
  198779. {
  198780. png_byte buf[NEAR_BUF_SIZE];
  198781. png_size_t written, remaining, err;
  198782. check = 0;
  198783. remaining = length;
  198784. do
  198785. {
  198786. written = MIN(NEAR_BUF_SIZE, remaining);
  198787. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198788. #if defined(_WIN32_WCE)
  198789. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198790. err = 0;
  198791. #else
  198792. err = fwrite(buf, 1, written, io_ptr);
  198793. #endif
  198794. if (err != written)
  198795. break;
  198796. else
  198797. check += err;
  198798. data += written;
  198799. remaining -= written;
  198800. }
  198801. while (remaining != 0);
  198802. }
  198803. if (check != length)
  198804. png_error(png_ptr, "Write Error");
  198805. }
  198806. #endif
  198807. #endif
  198808. /* This function is called to output any data pending writing (normally
  198809. to disk). After png_flush is called, there should be no data pending
  198810. writing in any buffers. */
  198811. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198812. void /* PRIVATE */
  198813. png_flush(png_structp png_ptr)
  198814. {
  198815. if (png_ptr->output_flush_fn != NULL)
  198816. (*(png_ptr->output_flush_fn))(png_ptr);
  198817. }
  198818. #if !defined(PNG_NO_STDIO)
  198819. void PNGAPI
  198820. png_default_flush(png_structp png_ptr)
  198821. {
  198822. #if !defined(_WIN32_WCE)
  198823. png_FILE_p io_ptr;
  198824. #endif
  198825. if(png_ptr == NULL) return;
  198826. #if !defined(_WIN32_WCE)
  198827. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198828. if (io_ptr != NULL)
  198829. fflush(io_ptr);
  198830. #endif
  198831. }
  198832. #endif
  198833. #endif
  198834. /* This function allows the application to supply new output functions for
  198835. libpng if standard C streams aren't being used.
  198836. This function takes as its arguments:
  198837. png_ptr - pointer to a png output data structure
  198838. io_ptr - pointer to user supplied structure containing info about
  198839. the output functions. May be NULL.
  198840. write_data_fn - pointer to a new output function that takes as its
  198841. arguments a pointer to a png_struct, a pointer to
  198842. data to be written, and a 32-bit unsigned int that is
  198843. the number of bytes to be written. The new write
  198844. function should call png_error(png_ptr, "Error msg")
  198845. to exit and output any fatal error messages.
  198846. flush_data_fn - pointer to a new flush function that takes as its
  198847. arguments a pointer to a png_struct. After a call to
  198848. the flush function, there should be no data in any buffers
  198849. or pending transmission. If the output method doesn't do
  198850. any buffering of ouput, a function prototype must still be
  198851. supplied although it doesn't have to do anything. If
  198852. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198853. time, output_flush_fn will be ignored, although it must be
  198854. supplied for compatibility. */
  198855. void PNGAPI
  198856. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198857. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198858. {
  198859. if(png_ptr == NULL) return;
  198860. png_ptr->io_ptr = io_ptr;
  198861. #if !defined(PNG_NO_STDIO)
  198862. if (write_data_fn != NULL)
  198863. png_ptr->write_data_fn = write_data_fn;
  198864. else
  198865. png_ptr->write_data_fn = png_default_write_data;
  198866. #else
  198867. png_ptr->write_data_fn = write_data_fn;
  198868. #endif
  198869. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198870. #if !defined(PNG_NO_STDIO)
  198871. if (output_flush_fn != NULL)
  198872. png_ptr->output_flush_fn = output_flush_fn;
  198873. else
  198874. png_ptr->output_flush_fn = png_default_flush;
  198875. #else
  198876. png_ptr->output_flush_fn = output_flush_fn;
  198877. #endif
  198878. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198879. /* It is an error to read while writing a png file */
  198880. if (png_ptr->read_data_fn != NULL)
  198881. {
  198882. png_ptr->read_data_fn = NULL;
  198883. png_warning(png_ptr,
  198884. "Attempted to set both read_data_fn and write_data_fn in");
  198885. png_warning(png_ptr,
  198886. "the same structure. Resetting read_data_fn to NULL.");
  198887. }
  198888. }
  198889. #if defined(USE_FAR_KEYWORD)
  198890. #if defined(_MSC_VER)
  198891. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198892. {
  198893. void *near_ptr;
  198894. void FAR *far_ptr;
  198895. FP_OFF(near_ptr) = FP_OFF(ptr);
  198896. far_ptr = (void FAR *)near_ptr;
  198897. if(check != 0)
  198898. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198899. png_error(png_ptr,"segment lost in conversion");
  198900. return(near_ptr);
  198901. }
  198902. # else
  198903. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198904. {
  198905. void *near_ptr;
  198906. void FAR *far_ptr;
  198907. near_ptr = (void FAR *)ptr;
  198908. far_ptr = (void FAR *)near_ptr;
  198909. if(check != 0)
  198910. if(far_ptr != ptr)
  198911. png_error(png_ptr,"segment lost in conversion");
  198912. return(near_ptr);
  198913. }
  198914. # endif
  198915. # endif
  198916. #endif /* PNG_WRITE_SUPPORTED */
  198917. /*** End of inlined file: pngwio.c ***/
  198918. /*** Start of inlined file: pngwrite.c ***/
  198919. /* pngwrite.c - general routines to write a PNG file
  198920. *
  198921. * Last changed in libpng 1.2.15 January 5, 2007
  198922. * For conditions of distribution and use, see copyright notice in png.h
  198923. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198924. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198925. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198926. */
  198927. /* get internal access to png.h */
  198928. #define PNG_INTERNAL
  198929. #ifdef PNG_WRITE_SUPPORTED
  198930. /* Writes all the PNG information. This is the suggested way to use the
  198931. * library. If you have a new chunk to add, make a function to write it,
  198932. * and put it in the correct location here. If you want the chunk written
  198933. * after the image data, put it in png_write_end(). I strongly encourage
  198934. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198935. * the chunk, as that will keep the code from breaking if you want to just
  198936. * write a plain PNG file. If you have long comments, I suggest writing
  198937. * them in png_write_end(), and compressing them.
  198938. */
  198939. void PNGAPI
  198940. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198941. {
  198942. png_debug(1, "in png_write_info_before_PLTE\n");
  198943. if (png_ptr == NULL || info_ptr == NULL)
  198944. return;
  198945. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198946. {
  198947. png_write_sig(png_ptr); /* write PNG signature */
  198948. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198949. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198950. {
  198951. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198952. png_ptr->mng_features_permitted=0;
  198953. }
  198954. #endif
  198955. /* write IHDR information. */
  198956. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198957. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198958. info_ptr->filter_type,
  198959. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198960. info_ptr->interlace_type);
  198961. #else
  198962. 0);
  198963. #endif
  198964. /* the rest of these check to see if the valid field has the appropriate
  198965. flag set, and if it does, writes the chunk. */
  198966. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198967. if (info_ptr->valid & PNG_INFO_gAMA)
  198968. {
  198969. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198970. png_write_gAMA(png_ptr, info_ptr->gamma);
  198971. #else
  198972. #ifdef PNG_FIXED_POINT_SUPPORTED
  198973. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198974. # endif
  198975. #endif
  198976. }
  198977. #endif
  198978. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198979. if (info_ptr->valid & PNG_INFO_sRGB)
  198980. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198981. #endif
  198982. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198983. if (info_ptr->valid & PNG_INFO_iCCP)
  198984. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198985. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198986. #endif
  198987. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198988. if (info_ptr->valid & PNG_INFO_sBIT)
  198989. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198990. #endif
  198991. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198992. if (info_ptr->valid & PNG_INFO_cHRM)
  198993. {
  198994. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198995. png_write_cHRM(png_ptr,
  198996. info_ptr->x_white, info_ptr->y_white,
  198997. info_ptr->x_red, info_ptr->y_red,
  198998. info_ptr->x_green, info_ptr->y_green,
  198999. info_ptr->x_blue, info_ptr->y_blue);
  199000. #else
  199001. # ifdef PNG_FIXED_POINT_SUPPORTED
  199002. png_write_cHRM_fixed(png_ptr,
  199003. info_ptr->int_x_white, info_ptr->int_y_white,
  199004. info_ptr->int_x_red, info_ptr->int_y_red,
  199005. info_ptr->int_x_green, info_ptr->int_y_green,
  199006. info_ptr->int_x_blue, info_ptr->int_y_blue);
  199007. # endif
  199008. #endif
  199009. }
  199010. #endif
  199011. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199012. if (info_ptr->unknown_chunks_num)
  199013. {
  199014. png_unknown_chunk *up;
  199015. png_debug(5, "writing extra chunks\n");
  199016. for (up = info_ptr->unknown_chunks;
  199017. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199018. up++)
  199019. {
  199020. int keep=png_handle_as_unknown(png_ptr, up->name);
  199021. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199022. up->location && !(up->location & PNG_HAVE_PLTE) &&
  199023. !(up->location & PNG_HAVE_IDAT) &&
  199024. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199025. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199026. {
  199027. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199028. }
  199029. }
  199030. }
  199031. #endif
  199032. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  199033. }
  199034. }
  199035. void PNGAPI
  199036. png_write_info(png_structp png_ptr, png_infop info_ptr)
  199037. {
  199038. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  199039. int i;
  199040. #endif
  199041. png_debug(1, "in png_write_info\n");
  199042. if (png_ptr == NULL || info_ptr == NULL)
  199043. return;
  199044. png_write_info_before_PLTE(png_ptr, info_ptr);
  199045. if (info_ptr->valid & PNG_INFO_PLTE)
  199046. png_write_PLTE(png_ptr, info_ptr->palette,
  199047. (png_uint_32)info_ptr->num_palette);
  199048. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199049. png_error(png_ptr, "Valid palette required for paletted images");
  199050. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  199051. if (info_ptr->valid & PNG_INFO_tRNS)
  199052. {
  199053. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199054. /* invert the alpha channel (in tRNS) */
  199055. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  199056. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199057. {
  199058. int j;
  199059. for (j=0; j<(int)info_ptr->num_trans; j++)
  199060. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  199061. }
  199062. #endif
  199063. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  199064. info_ptr->num_trans, info_ptr->color_type);
  199065. }
  199066. #endif
  199067. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  199068. if (info_ptr->valid & PNG_INFO_bKGD)
  199069. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  199070. #endif
  199071. #if defined(PNG_WRITE_hIST_SUPPORTED)
  199072. if (info_ptr->valid & PNG_INFO_hIST)
  199073. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  199074. #endif
  199075. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  199076. if (info_ptr->valid & PNG_INFO_oFFs)
  199077. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  199078. info_ptr->offset_unit_type);
  199079. #endif
  199080. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  199081. if (info_ptr->valid & PNG_INFO_pCAL)
  199082. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  199083. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  199084. info_ptr->pcal_units, info_ptr->pcal_params);
  199085. #endif
  199086. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199087. if (info_ptr->valid & PNG_INFO_sCAL)
  199088. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199089. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  199090. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  199091. #else
  199092. #ifdef PNG_FIXED_POINT_SUPPORTED
  199093. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  199094. info_ptr->scal_s_width, info_ptr->scal_s_height);
  199095. #else
  199096. png_warning(png_ptr,
  199097. "png_write_sCAL not supported; sCAL chunk not written.");
  199098. #endif
  199099. #endif
  199100. #endif
  199101. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199102. if (info_ptr->valid & PNG_INFO_pHYs)
  199103. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  199104. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  199105. #endif
  199106. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199107. if (info_ptr->valid & PNG_INFO_tIME)
  199108. {
  199109. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199110. png_ptr->mode |= PNG_WROTE_tIME;
  199111. }
  199112. #endif
  199113. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  199114. if (info_ptr->valid & PNG_INFO_sPLT)
  199115. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  199116. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  199117. #endif
  199118. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199119. /* Check to see if we need to write text chunks */
  199120. for (i = 0; i < info_ptr->num_text; i++)
  199121. {
  199122. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  199123. info_ptr->text[i].compression);
  199124. /* an internationalized chunk? */
  199125. if (info_ptr->text[i].compression > 0)
  199126. {
  199127. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199128. /* write international chunk */
  199129. png_write_iTXt(png_ptr,
  199130. info_ptr->text[i].compression,
  199131. info_ptr->text[i].key,
  199132. info_ptr->text[i].lang,
  199133. info_ptr->text[i].lang_key,
  199134. info_ptr->text[i].text);
  199135. #else
  199136. png_warning(png_ptr, "Unable to write international text");
  199137. #endif
  199138. /* Mark this chunk as written */
  199139. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199140. }
  199141. /* If we want a compressed text chunk */
  199142. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  199143. {
  199144. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199145. /* write compressed chunk */
  199146. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199147. info_ptr->text[i].text, 0,
  199148. info_ptr->text[i].compression);
  199149. #else
  199150. png_warning(png_ptr, "Unable to write compressed text");
  199151. #endif
  199152. /* Mark this chunk as written */
  199153. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199154. }
  199155. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199156. {
  199157. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199158. /* write uncompressed chunk */
  199159. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199160. info_ptr->text[i].text,
  199161. 0);
  199162. #else
  199163. png_warning(png_ptr, "Unable to write uncompressed text");
  199164. #endif
  199165. /* Mark this chunk as written */
  199166. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199167. }
  199168. }
  199169. #endif
  199170. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199171. if (info_ptr->unknown_chunks_num)
  199172. {
  199173. png_unknown_chunk *up;
  199174. png_debug(5, "writing extra chunks\n");
  199175. for (up = info_ptr->unknown_chunks;
  199176. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199177. up++)
  199178. {
  199179. int keep=png_handle_as_unknown(png_ptr, up->name);
  199180. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199181. up->location && (up->location & PNG_HAVE_PLTE) &&
  199182. !(up->location & PNG_HAVE_IDAT) &&
  199183. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199184. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199185. {
  199186. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199187. }
  199188. }
  199189. }
  199190. #endif
  199191. }
  199192. /* Writes the end of the PNG file. If you don't want to write comments or
  199193. * time information, you can pass NULL for info. If you already wrote these
  199194. * in png_write_info(), do not write them again here. If you have long
  199195. * comments, I suggest writing them here, and compressing them.
  199196. */
  199197. void PNGAPI
  199198. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199199. {
  199200. png_debug(1, "in png_write_end\n");
  199201. if (png_ptr == NULL)
  199202. return;
  199203. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199204. png_error(png_ptr, "No IDATs written into file");
  199205. /* see if user wants us to write information chunks */
  199206. if (info_ptr != NULL)
  199207. {
  199208. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199209. int i; /* local index variable */
  199210. #endif
  199211. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199212. /* check to see if user has supplied a time chunk */
  199213. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199214. !(png_ptr->mode & PNG_WROTE_tIME))
  199215. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199216. #endif
  199217. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199218. /* loop through comment chunks */
  199219. for (i = 0; i < info_ptr->num_text; i++)
  199220. {
  199221. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199222. info_ptr->text[i].compression);
  199223. /* an internationalized chunk? */
  199224. if (info_ptr->text[i].compression > 0)
  199225. {
  199226. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199227. /* write international chunk */
  199228. png_write_iTXt(png_ptr,
  199229. info_ptr->text[i].compression,
  199230. info_ptr->text[i].key,
  199231. info_ptr->text[i].lang,
  199232. info_ptr->text[i].lang_key,
  199233. info_ptr->text[i].text);
  199234. #else
  199235. png_warning(png_ptr, "Unable to write international text");
  199236. #endif
  199237. /* Mark this chunk as written */
  199238. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199239. }
  199240. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199241. {
  199242. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199243. /* write compressed chunk */
  199244. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199245. info_ptr->text[i].text, 0,
  199246. info_ptr->text[i].compression);
  199247. #else
  199248. png_warning(png_ptr, "Unable to write compressed text");
  199249. #endif
  199250. /* Mark this chunk as written */
  199251. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199252. }
  199253. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199254. {
  199255. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199256. /* write uncompressed chunk */
  199257. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199258. info_ptr->text[i].text, 0);
  199259. #else
  199260. png_warning(png_ptr, "Unable to write uncompressed text");
  199261. #endif
  199262. /* Mark this chunk as written */
  199263. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199264. }
  199265. }
  199266. #endif
  199267. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199268. if (info_ptr->unknown_chunks_num)
  199269. {
  199270. png_unknown_chunk *up;
  199271. png_debug(5, "writing extra chunks\n");
  199272. for (up = info_ptr->unknown_chunks;
  199273. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199274. up++)
  199275. {
  199276. int keep=png_handle_as_unknown(png_ptr, up->name);
  199277. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199278. up->location && (up->location & PNG_AFTER_IDAT) &&
  199279. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199280. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199281. {
  199282. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199283. }
  199284. }
  199285. }
  199286. #endif
  199287. }
  199288. png_ptr->mode |= PNG_AFTER_IDAT;
  199289. /* write end of PNG file */
  199290. png_write_IEND(png_ptr);
  199291. }
  199292. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199293. #if !defined(_WIN32_WCE)
  199294. /* "time.h" functions are not supported on WindowsCE */
  199295. void PNGAPI
  199296. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199297. {
  199298. png_debug(1, "in png_convert_from_struct_tm\n");
  199299. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199300. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199301. ptime->day = (png_byte)ttime->tm_mday;
  199302. ptime->hour = (png_byte)ttime->tm_hour;
  199303. ptime->minute = (png_byte)ttime->tm_min;
  199304. ptime->second = (png_byte)ttime->tm_sec;
  199305. }
  199306. void PNGAPI
  199307. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199308. {
  199309. struct tm *tbuf;
  199310. png_debug(1, "in png_convert_from_time_t\n");
  199311. tbuf = gmtime(&ttime);
  199312. png_convert_from_struct_tm(ptime, tbuf);
  199313. }
  199314. #endif
  199315. #endif
  199316. /* Initialize png_ptr structure, and allocate any memory needed */
  199317. png_structp PNGAPI
  199318. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199319. png_error_ptr error_fn, png_error_ptr warn_fn)
  199320. {
  199321. #ifdef PNG_USER_MEM_SUPPORTED
  199322. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199323. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199324. }
  199325. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199326. png_structp PNGAPI
  199327. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199328. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199329. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199330. {
  199331. #endif /* PNG_USER_MEM_SUPPORTED */
  199332. png_structp png_ptr;
  199333. #ifdef PNG_SETJMP_SUPPORTED
  199334. #ifdef USE_FAR_KEYWORD
  199335. jmp_buf jmpbuf;
  199336. #endif
  199337. #endif
  199338. int i;
  199339. png_debug(1, "in png_create_write_struct\n");
  199340. #ifdef PNG_USER_MEM_SUPPORTED
  199341. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199342. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199343. #else
  199344. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199345. #endif /* PNG_USER_MEM_SUPPORTED */
  199346. if (png_ptr == NULL)
  199347. return (NULL);
  199348. /* added at libpng-1.2.6 */
  199349. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199350. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199351. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199352. #endif
  199353. #ifdef PNG_SETJMP_SUPPORTED
  199354. #ifdef USE_FAR_KEYWORD
  199355. if (setjmp(jmpbuf))
  199356. #else
  199357. if (setjmp(png_ptr->jmpbuf))
  199358. #endif
  199359. {
  199360. png_free(png_ptr, png_ptr->zbuf);
  199361. png_ptr->zbuf=NULL;
  199362. png_destroy_struct(png_ptr);
  199363. return (NULL);
  199364. }
  199365. #ifdef USE_FAR_KEYWORD
  199366. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199367. #endif
  199368. #endif
  199369. #ifdef PNG_USER_MEM_SUPPORTED
  199370. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199371. #endif /* PNG_USER_MEM_SUPPORTED */
  199372. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199373. i=0;
  199374. do
  199375. {
  199376. if(user_png_ver[i] != png_libpng_ver[i])
  199377. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199378. } while (png_libpng_ver[i++]);
  199379. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199380. {
  199381. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199382. * we must recompile any applications that use any older library version.
  199383. * For versions after libpng 1.0, we will be compatible, so we need
  199384. * only check the first digit.
  199385. */
  199386. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199387. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199388. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199389. {
  199390. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199391. char msg[80];
  199392. if (user_png_ver)
  199393. {
  199394. png_snprintf(msg, 80,
  199395. "Application was compiled with png.h from libpng-%.20s",
  199396. user_png_ver);
  199397. png_warning(png_ptr, msg);
  199398. }
  199399. png_snprintf(msg, 80,
  199400. "Application is running with png.c from libpng-%.20s",
  199401. png_libpng_ver);
  199402. png_warning(png_ptr, msg);
  199403. #endif
  199404. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199405. png_ptr->flags=0;
  199406. #endif
  199407. png_error(png_ptr,
  199408. "Incompatible libpng version in application and library");
  199409. }
  199410. }
  199411. /* initialize zbuf - compression buffer */
  199412. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199413. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199414. (png_uint_32)png_ptr->zbuf_size);
  199415. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199416. png_flush_ptr_NULL);
  199417. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199418. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199419. 1, png_doublep_NULL, png_doublep_NULL);
  199420. #endif
  199421. #ifdef PNG_SETJMP_SUPPORTED
  199422. /* Applications that neglect to set up their own setjmp() and then encounter
  199423. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199424. abort instead of returning. */
  199425. #ifdef USE_FAR_KEYWORD
  199426. if (setjmp(jmpbuf))
  199427. PNG_ABORT();
  199428. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199429. #else
  199430. if (setjmp(png_ptr->jmpbuf))
  199431. PNG_ABORT();
  199432. #endif
  199433. #endif
  199434. return (png_ptr);
  199435. }
  199436. /* Initialize png_ptr structure, and allocate any memory needed */
  199437. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199438. /* Deprecated. */
  199439. #undef png_write_init
  199440. void PNGAPI
  199441. png_write_init(png_structp png_ptr)
  199442. {
  199443. /* We only come here via pre-1.0.7-compiled applications */
  199444. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199445. }
  199446. void PNGAPI
  199447. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199448. png_size_t png_struct_size, png_size_t png_info_size)
  199449. {
  199450. /* We only come here via pre-1.0.12-compiled applications */
  199451. if(png_ptr == NULL) return;
  199452. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199453. if(png_sizeof(png_struct) > png_struct_size ||
  199454. png_sizeof(png_info) > png_info_size)
  199455. {
  199456. char msg[80];
  199457. png_ptr->warning_fn=NULL;
  199458. if (user_png_ver)
  199459. {
  199460. png_snprintf(msg, 80,
  199461. "Application was compiled with png.h from libpng-%.20s",
  199462. user_png_ver);
  199463. png_warning(png_ptr, msg);
  199464. }
  199465. png_snprintf(msg, 80,
  199466. "Application is running with png.c from libpng-%.20s",
  199467. png_libpng_ver);
  199468. png_warning(png_ptr, msg);
  199469. }
  199470. #endif
  199471. if(png_sizeof(png_struct) > png_struct_size)
  199472. {
  199473. png_ptr->error_fn=NULL;
  199474. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199475. png_ptr->flags=0;
  199476. #endif
  199477. png_error(png_ptr,
  199478. "The png struct allocated by the application for writing is too small.");
  199479. }
  199480. if(png_sizeof(png_info) > png_info_size)
  199481. {
  199482. png_ptr->error_fn=NULL;
  199483. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199484. png_ptr->flags=0;
  199485. #endif
  199486. png_error(png_ptr,
  199487. "The info struct allocated by the application for writing is too small.");
  199488. }
  199489. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199490. }
  199491. #endif /* PNG_1_0_X || PNG_1_2_X */
  199492. void PNGAPI
  199493. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199494. png_size_t png_struct_size)
  199495. {
  199496. png_structp png_ptr=*ptr_ptr;
  199497. #ifdef PNG_SETJMP_SUPPORTED
  199498. jmp_buf tmp_jmp; /* to save current jump buffer */
  199499. #endif
  199500. int i = 0;
  199501. if (png_ptr == NULL)
  199502. return;
  199503. do
  199504. {
  199505. if (user_png_ver[i] != png_libpng_ver[i])
  199506. {
  199507. #ifdef PNG_LEGACY_SUPPORTED
  199508. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199509. #else
  199510. png_ptr->warning_fn=NULL;
  199511. png_warning(png_ptr,
  199512. "Application uses deprecated png_write_init() and should be recompiled.");
  199513. break;
  199514. #endif
  199515. }
  199516. } while (png_libpng_ver[i++]);
  199517. png_debug(1, "in png_write_init_3\n");
  199518. #ifdef PNG_SETJMP_SUPPORTED
  199519. /* save jump buffer and error functions */
  199520. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199521. #endif
  199522. if (png_sizeof(png_struct) > png_struct_size)
  199523. {
  199524. png_destroy_struct(png_ptr);
  199525. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199526. *ptr_ptr = png_ptr;
  199527. }
  199528. /* reset all variables to 0 */
  199529. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199530. /* added at libpng-1.2.6 */
  199531. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199532. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199533. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199534. #endif
  199535. #ifdef PNG_SETJMP_SUPPORTED
  199536. /* restore jump buffer */
  199537. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199538. #endif
  199539. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199540. png_flush_ptr_NULL);
  199541. /* initialize zbuf - compression buffer */
  199542. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199543. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199544. (png_uint_32)png_ptr->zbuf_size);
  199545. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199546. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199547. 1, png_doublep_NULL, png_doublep_NULL);
  199548. #endif
  199549. }
  199550. /* Write a few rows of image data. If the image is interlaced,
  199551. * either you will have to write the 7 sub images, or, if you
  199552. * have called png_set_interlace_handling(), you will have to
  199553. * "write" the image seven times.
  199554. */
  199555. void PNGAPI
  199556. png_write_rows(png_structp png_ptr, png_bytepp row,
  199557. png_uint_32 num_rows)
  199558. {
  199559. png_uint_32 i; /* row counter */
  199560. png_bytepp rp; /* row pointer */
  199561. png_debug(1, "in png_write_rows\n");
  199562. if (png_ptr == NULL)
  199563. return;
  199564. /* loop through the rows */
  199565. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199566. {
  199567. png_write_row(png_ptr, *rp);
  199568. }
  199569. }
  199570. /* Write the image. You only need to call this function once, even
  199571. * if you are writing an interlaced image.
  199572. */
  199573. void PNGAPI
  199574. png_write_image(png_structp png_ptr, png_bytepp image)
  199575. {
  199576. png_uint_32 i; /* row index */
  199577. int pass, num_pass; /* pass variables */
  199578. png_bytepp rp; /* points to current row */
  199579. if (png_ptr == NULL)
  199580. return;
  199581. png_debug(1, "in png_write_image\n");
  199582. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199583. /* intialize interlace handling. If image is not interlaced,
  199584. this will set pass to 1 */
  199585. num_pass = png_set_interlace_handling(png_ptr);
  199586. #else
  199587. num_pass = 1;
  199588. #endif
  199589. /* loop through passes */
  199590. for (pass = 0; pass < num_pass; pass++)
  199591. {
  199592. /* loop through image */
  199593. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199594. {
  199595. png_write_row(png_ptr, *rp);
  199596. }
  199597. }
  199598. }
  199599. /* called by user to write a row of image data */
  199600. void PNGAPI
  199601. png_write_row(png_structp png_ptr, png_bytep row)
  199602. {
  199603. if (png_ptr == NULL)
  199604. return;
  199605. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199606. png_ptr->row_number, png_ptr->pass);
  199607. /* initialize transformations and other stuff if first time */
  199608. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199609. {
  199610. /* make sure we wrote the header info */
  199611. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199612. png_error(png_ptr,
  199613. "png_write_info was never called before png_write_row.");
  199614. /* check for transforms that have been set but were defined out */
  199615. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199616. if (png_ptr->transformations & PNG_INVERT_MONO)
  199617. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199618. #endif
  199619. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199620. if (png_ptr->transformations & PNG_FILLER)
  199621. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199622. #endif
  199623. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199624. if (png_ptr->transformations & PNG_PACKSWAP)
  199625. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199626. #endif
  199627. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199628. if (png_ptr->transformations & PNG_PACK)
  199629. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199630. #endif
  199631. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199632. if (png_ptr->transformations & PNG_SHIFT)
  199633. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199634. #endif
  199635. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199636. if (png_ptr->transformations & PNG_BGR)
  199637. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199638. #endif
  199639. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199640. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199641. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199642. #endif
  199643. png_write_start_row(png_ptr);
  199644. }
  199645. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199646. /* if interlaced and not interested in row, return */
  199647. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199648. {
  199649. switch (png_ptr->pass)
  199650. {
  199651. case 0:
  199652. if (png_ptr->row_number & 0x07)
  199653. {
  199654. png_write_finish_row(png_ptr);
  199655. return;
  199656. }
  199657. break;
  199658. case 1:
  199659. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199660. {
  199661. png_write_finish_row(png_ptr);
  199662. return;
  199663. }
  199664. break;
  199665. case 2:
  199666. if ((png_ptr->row_number & 0x07) != 4)
  199667. {
  199668. png_write_finish_row(png_ptr);
  199669. return;
  199670. }
  199671. break;
  199672. case 3:
  199673. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199674. {
  199675. png_write_finish_row(png_ptr);
  199676. return;
  199677. }
  199678. break;
  199679. case 4:
  199680. if ((png_ptr->row_number & 0x03) != 2)
  199681. {
  199682. png_write_finish_row(png_ptr);
  199683. return;
  199684. }
  199685. break;
  199686. case 5:
  199687. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199688. {
  199689. png_write_finish_row(png_ptr);
  199690. return;
  199691. }
  199692. break;
  199693. case 6:
  199694. if (!(png_ptr->row_number & 0x01))
  199695. {
  199696. png_write_finish_row(png_ptr);
  199697. return;
  199698. }
  199699. break;
  199700. }
  199701. }
  199702. #endif
  199703. /* set up row info for transformations */
  199704. png_ptr->row_info.color_type = png_ptr->color_type;
  199705. png_ptr->row_info.width = png_ptr->usr_width;
  199706. png_ptr->row_info.channels = png_ptr->usr_channels;
  199707. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199708. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199709. png_ptr->row_info.channels);
  199710. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199711. png_ptr->row_info.width);
  199712. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199713. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199714. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199715. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199716. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199717. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199718. /* Copy user's row into buffer, leaving room for filter byte. */
  199719. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199720. png_ptr->row_info.rowbytes);
  199721. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199722. /* handle interlacing */
  199723. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199724. (png_ptr->transformations & PNG_INTERLACE))
  199725. {
  199726. png_do_write_interlace(&(png_ptr->row_info),
  199727. png_ptr->row_buf + 1, png_ptr->pass);
  199728. /* this should always get caught above, but still ... */
  199729. if (!(png_ptr->row_info.width))
  199730. {
  199731. png_write_finish_row(png_ptr);
  199732. return;
  199733. }
  199734. }
  199735. #endif
  199736. /* handle other transformations */
  199737. if (png_ptr->transformations)
  199738. png_do_write_transformations(png_ptr);
  199739. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199740. /* Write filter_method 64 (intrapixel differencing) only if
  199741. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199742. * 2. Libpng did not write a PNG signature (this filter_method is only
  199743. * used in PNG datastreams that are embedded in MNG datastreams) and
  199744. * 3. The application called png_permit_mng_features with a mask that
  199745. * included PNG_FLAG_MNG_FILTER_64 and
  199746. * 4. The filter_method is 64 and
  199747. * 5. The color_type is RGB or RGBA
  199748. */
  199749. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199750. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199751. {
  199752. /* Intrapixel differencing */
  199753. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199754. }
  199755. #endif
  199756. /* Find a filter if necessary, filter the row and write it out. */
  199757. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199758. if (png_ptr->write_row_fn != NULL)
  199759. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199760. }
  199761. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199762. /* Set the automatic flush interval or 0 to turn flushing off */
  199763. void PNGAPI
  199764. png_set_flush(png_structp png_ptr, int nrows)
  199765. {
  199766. png_debug(1, "in png_set_flush\n");
  199767. if (png_ptr == NULL)
  199768. return;
  199769. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199770. }
  199771. /* flush the current output buffers now */
  199772. void PNGAPI
  199773. png_write_flush(png_structp png_ptr)
  199774. {
  199775. int wrote_IDAT;
  199776. png_debug(1, "in png_write_flush\n");
  199777. if (png_ptr == NULL)
  199778. return;
  199779. /* We have already written out all of the data */
  199780. if (png_ptr->row_number >= png_ptr->num_rows)
  199781. return;
  199782. do
  199783. {
  199784. int ret;
  199785. /* compress the data */
  199786. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199787. wrote_IDAT = 0;
  199788. /* check for compression errors */
  199789. if (ret != Z_OK)
  199790. {
  199791. if (png_ptr->zstream.msg != NULL)
  199792. png_error(png_ptr, png_ptr->zstream.msg);
  199793. else
  199794. png_error(png_ptr, "zlib error");
  199795. }
  199796. if (!(png_ptr->zstream.avail_out))
  199797. {
  199798. /* write the IDAT and reset the zlib output buffer */
  199799. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199800. png_ptr->zbuf_size);
  199801. png_ptr->zstream.next_out = png_ptr->zbuf;
  199802. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199803. wrote_IDAT = 1;
  199804. }
  199805. } while(wrote_IDAT == 1);
  199806. /* If there is any data left to be output, write it into a new IDAT */
  199807. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199808. {
  199809. /* write the IDAT and reset the zlib output buffer */
  199810. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199811. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199812. png_ptr->zstream.next_out = png_ptr->zbuf;
  199813. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199814. }
  199815. png_ptr->flush_rows = 0;
  199816. png_flush(png_ptr);
  199817. }
  199818. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199819. /* free all memory used by the write */
  199820. void PNGAPI
  199821. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199822. {
  199823. png_structp png_ptr = NULL;
  199824. png_infop info_ptr = NULL;
  199825. #ifdef PNG_USER_MEM_SUPPORTED
  199826. png_free_ptr free_fn = NULL;
  199827. png_voidp mem_ptr = NULL;
  199828. #endif
  199829. png_debug(1, "in png_destroy_write_struct\n");
  199830. if (png_ptr_ptr != NULL)
  199831. {
  199832. png_ptr = *png_ptr_ptr;
  199833. #ifdef PNG_USER_MEM_SUPPORTED
  199834. free_fn = png_ptr->free_fn;
  199835. mem_ptr = png_ptr->mem_ptr;
  199836. #endif
  199837. }
  199838. if (info_ptr_ptr != NULL)
  199839. info_ptr = *info_ptr_ptr;
  199840. if (info_ptr != NULL)
  199841. {
  199842. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199843. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199844. if (png_ptr->num_chunk_list)
  199845. {
  199846. png_free(png_ptr, png_ptr->chunk_list);
  199847. png_ptr->chunk_list=NULL;
  199848. png_ptr->num_chunk_list=0;
  199849. }
  199850. #endif
  199851. #ifdef PNG_USER_MEM_SUPPORTED
  199852. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199853. (png_voidp)mem_ptr);
  199854. #else
  199855. png_destroy_struct((png_voidp)info_ptr);
  199856. #endif
  199857. *info_ptr_ptr = NULL;
  199858. }
  199859. if (png_ptr != NULL)
  199860. {
  199861. png_write_destroy(png_ptr);
  199862. #ifdef PNG_USER_MEM_SUPPORTED
  199863. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199864. (png_voidp)mem_ptr);
  199865. #else
  199866. png_destroy_struct((png_voidp)png_ptr);
  199867. #endif
  199868. *png_ptr_ptr = NULL;
  199869. }
  199870. }
  199871. /* Free any memory used in png_ptr struct (old method) */
  199872. void /* PRIVATE */
  199873. png_write_destroy(png_structp png_ptr)
  199874. {
  199875. #ifdef PNG_SETJMP_SUPPORTED
  199876. jmp_buf tmp_jmp; /* save jump buffer */
  199877. #endif
  199878. png_error_ptr error_fn;
  199879. png_error_ptr warning_fn;
  199880. png_voidp error_ptr;
  199881. #ifdef PNG_USER_MEM_SUPPORTED
  199882. png_free_ptr free_fn;
  199883. #endif
  199884. png_debug(1, "in png_write_destroy\n");
  199885. /* free any memory zlib uses */
  199886. deflateEnd(&png_ptr->zstream);
  199887. /* free our memory. png_free checks NULL for us. */
  199888. png_free(png_ptr, png_ptr->zbuf);
  199889. png_free(png_ptr, png_ptr->row_buf);
  199890. png_free(png_ptr, png_ptr->prev_row);
  199891. png_free(png_ptr, png_ptr->sub_row);
  199892. png_free(png_ptr, png_ptr->up_row);
  199893. png_free(png_ptr, png_ptr->avg_row);
  199894. png_free(png_ptr, png_ptr->paeth_row);
  199895. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199896. png_free(png_ptr, png_ptr->time_buffer);
  199897. #endif
  199898. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199899. png_free(png_ptr, png_ptr->prev_filters);
  199900. png_free(png_ptr, png_ptr->filter_weights);
  199901. png_free(png_ptr, png_ptr->inv_filter_weights);
  199902. png_free(png_ptr, png_ptr->filter_costs);
  199903. png_free(png_ptr, png_ptr->inv_filter_costs);
  199904. #endif
  199905. #ifdef PNG_SETJMP_SUPPORTED
  199906. /* reset structure */
  199907. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199908. #endif
  199909. error_fn = png_ptr->error_fn;
  199910. warning_fn = png_ptr->warning_fn;
  199911. error_ptr = png_ptr->error_ptr;
  199912. #ifdef PNG_USER_MEM_SUPPORTED
  199913. free_fn = png_ptr->free_fn;
  199914. #endif
  199915. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199916. png_ptr->error_fn = error_fn;
  199917. png_ptr->warning_fn = warning_fn;
  199918. png_ptr->error_ptr = error_ptr;
  199919. #ifdef PNG_USER_MEM_SUPPORTED
  199920. png_ptr->free_fn = free_fn;
  199921. #endif
  199922. #ifdef PNG_SETJMP_SUPPORTED
  199923. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199924. #endif
  199925. }
  199926. /* Allow the application to select one or more row filters to use. */
  199927. void PNGAPI
  199928. png_set_filter(png_structp png_ptr, int method, int filters)
  199929. {
  199930. png_debug(1, "in png_set_filter\n");
  199931. if (png_ptr == NULL)
  199932. return;
  199933. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199934. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199935. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199936. method = PNG_FILTER_TYPE_BASE;
  199937. #endif
  199938. if (method == PNG_FILTER_TYPE_BASE)
  199939. {
  199940. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199941. {
  199942. #ifndef PNG_NO_WRITE_FILTER
  199943. case 5:
  199944. case 6:
  199945. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199946. #endif /* PNG_NO_WRITE_FILTER */
  199947. case PNG_FILTER_VALUE_NONE:
  199948. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199949. #ifndef PNG_NO_WRITE_FILTER
  199950. case PNG_FILTER_VALUE_SUB:
  199951. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199952. case PNG_FILTER_VALUE_UP:
  199953. png_ptr->do_filter=PNG_FILTER_UP; break;
  199954. case PNG_FILTER_VALUE_AVG:
  199955. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199956. case PNG_FILTER_VALUE_PAETH:
  199957. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199958. default: png_ptr->do_filter = (png_byte)filters; break;
  199959. #else
  199960. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199961. #endif /* PNG_NO_WRITE_FILTER */
  199962. }
  199963. /* If we have allocated the row_buf, this means we have already started
  199964. * with the image and we should have allocated all of the filter buffers
  199965. * that have been selected. If prev_row isn't already allocated, then
  199966. * it is too late to start using the filters that need it, since we
  199967. * will be missing the data in the previous row. If an application
  199968. * wants to start and stop using particular filters during compression,
  199969. * it should start out with all of the filters, and then add and
  199970. * remove them after the start of compression.
  199971. */
  199972. if (png_ptr->row_buf != NULL)
  199973. {
  199974. #ifndef PNG_NO_WRITE_FILTER
  199975. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199976. {
  199977. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199978. (png_ptr->rowbytes + 1));
  199979. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199980. }
  199981. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199982. {
  199983. if (png_ptr->prev_row == NULL)
  199984. {
  199985. png_warning(png_ptr, "Can't add Up filter after starting");
  199986. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199987. }
  199988. else
  199989. {
  199990. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199991. (png_ptr->rowbytes + 1));
  199992. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199993. }
  199994. }
  199995. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199996. {
  199997. if (png_ptr->prev_row == NULL)
  199998. {
  199999. png_warning(png_ptr, "Can't add Average filter after starting");
  200000. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  200001. }
  200002. else
  200003. {
  200004. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  200005. (png_ptr->rowbytes + 1));
  200006. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  200007. }
  200008. }
  200009. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  200010. png_ptr->paeth_row == NULL)
  200011. {
  200012. if (png_ptr->prev_row == NULL)
  200013. {
  200014. png_warning(png_ptr, "Can't add Paeth filter after starting");
  200015. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  200016. }
  200017. else
  200018. {
  200019. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  200020. (png_ptr->rowbytes + 1));
  200021. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  200022. }
  200023. }
  200024. if (png_ptr->do_filter == PNG_NO_FILTERS)
  200025. #endif /* PNG_NO_WRITE_FILTER */
  200026. png_ptr->do_filter = PNG_FILTER_NONE;
  200027. }
  200028. }
  200029. else
  200030. png_error(png_ptr, "Unknown custom filter method");
  200031. }
  200032. /* This allows us to influence the way in which libpng chooses the "best"
  200033. * filter for the current scanline. While the "minimum-sum-of-absolute-
  200034. * differences metric is relatively fast and effective, there is some
  200035. * question as to whether it can be improved upon by trying to keep the
  200036. * filtered data going to zlib more consistent, hopefully resulting in
  200037. * better compression.
  200038. */
  200039. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  200040. void PNGAPI
  200041. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  200042. int num_weights, png_doublep filter_weights,
  200043. png_doublep filter_costs)
  200044. {
  200045. int i;
  200046. png_debug(1, "in png_set_filter_heuristics\n");
  200047. if (png_ptr == NULL)
  200048. return;
  200049. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  200050. {
  200051. png_warning(png_ptr, "Unknown filter heuristic method");
  200052. return;
  200053. }
  200054. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  200055. {
  200056. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  200057. }
  200058. if (num_weights < 0 || filter_weights == NULL ||
  200059. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  200060. {
  200061. num_weights = 0;
  200062. }
  200063. png_ptr->num_prev_filters = (png_byte)num_weights;
  200064. png_ptr->heuristic_method = (png_byte)heuristic_method;
  200065. if (num_weights > 0)
  200066. {
  200067. if (png_ptr->prev_filters == NULL)
  200068. {
  200069. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  200070. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  200071. /* To make sure that the weighting starts out fairly */
  200072. for (i = 0; i < num_weights; i++)
  200073. {
  200074. png_ptr->prev_filters[i] = 255;
  200075. }
  200076. }
  200077. if (png_ptr->filter_weights == NULL)
  200078. {
  200079. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200080. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200081. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200082. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200083. for (i = 0; i < num_weights; i++)
  200084. {
  200085. png_ptr->inv_filter_weights[i] =
  200086. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200087. }
  200088. }
  200089. for (i = 0; i < num_weights; i++)
  200090. {
  200091. if (filter_weights[i] < 0.0)
  200092. {
  200093. png_ptr->inv_filter_weights[i] =
  200094. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200095. }
  200096. else
  200097. {
  200098. png_ptr->inv_filter_weights[i] =
  200099. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  200100. png_ptr->filter_weights[i] =
  200101. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  200102. }
  200103. }
  200104. }
  200105. /* If, in the future, there are other filter methods, this would
  200106. * need to be based on png_ptr->filter.
  200107. */
  200108. if (png_ptr->filter_costs == NULL)
  200109. {
  200110. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200111. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200112. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200113. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200114. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200115. {
  200116. png_ptr->inv_filter_costs[i] =
  200117. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200118. }
  200119. }
  200120. /* Here is where we set the relative costs of the different filters. We
  200121. * should take the desired compression level into account when setting
  200122. * the costs, so that Paeth, for instance, has a high relative cost at low
  200123. * compression levels, while it has a lower relative cost at higher
  200124. * compression settings. The filter types are in order of increasing
  200125. * relative cost, so it would be possible to do this with an algorithm.
  200126. */
  200127. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200128. {
  200129. if (filter_costs == NULL || filter_costs[i] < 0.0)
  200130. {
  200131. png_ptr->inv_filter_costs[i] =
  200132. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200133. }
  200134. else if (filter_costs[i] >= 1.0)
  200135. {
  200136. png_ptr->inv_filter_costs[i] =
  200137. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  200138. png_ptr->filter_costs[i] =
  200139. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  200140. }
  200141. }
  200142. }
  200143. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  200144. void PNGAPI
  200145. png_set_compression_level(png_structp png_ptr, int level)
  200146. {
  200147. png_debug(1, "in png_set_compression_level\n");
  200148. if (png_ptr == NULL)
  200149. return;
  200150. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200151. png_ptr->zlib_level = level;
  200152. }
  200153. void PNGAPI
  200154. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200155. {
  200156. png_debug(1, "in png_set_compression_mem_level\n");
  200157. if (png_ptr == NULL)
  200158. return;
  200159. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200160. png_ptr->zlib_mem_level = mem_level;
  200161. }
  200162. void PNGAPI
  200163. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200164. {
  200165. png_debug(1, "in png_set_compression_strategy\n");
  200166. if (png_ptr == NULL)
  200167. return;
  200168. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200169. png_ptr->zlib_strategy = strategy;
  200170. }
  200171. void PNGAPI
  200172. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200173. {
  200174. if (png_ptr == NULL)
  200175. return;
  200176. if (window_bits > 15)
  200177. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200178. else if (window_bits < 8)
  200179. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200180. #ifndef WBITS_8_OK
  200181. /* avoid libpng bug with 256-byte windows */
  200182. if (window_bits == 8)
  200183. {
  200184. png_warning(png_ptr, "Compression window is being reset to 512");
  200185. window_bits=9;
  200186. }
  200187. #endif
  200188. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200189. png_ptr->zlib_window_bits = window_bits;
  200190. }
  200191. void PNGAPI
  200192. png_set_compression_method(png_structp png_ptr, int method)
  200193. {
  200194. png_debug(1, "in png_set_compression_method\n");
  200195. if (png_ptr == NULL)
  200196. return;
  200197. if (method != 8)
  200198. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200199. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200200. png_ptr->zlib_method = method;
  200201. }
  200202. void PNGAPI
  200203. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200204. {
  200205. if (png_ptr == NULL)
  200206. return;
  200207. png_ptr->write_row_fn = write_row_fn;
  200208. }
  200209. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200210. void PNGAPI
  200211. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200212. write_user_transform_fn)
  200213. {
  200214. png_debug(1, "in png_set_write_user_transform_fn\n");
  200215. if (png_ptr == NULL)
  200216. return;
  200217. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200218. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200219. }
  200220. #endif
  200221. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200222. void PNGAPI
  200223. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200224. int transforms, voidp params)
  200225. {
  200226. if (png_ptr == NULL || info_ptr == NULL)
  200227. return;
  200228. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200229. /* invert the alpha channel from opacity to transparency */
  200230. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200231. png_set_invert_alpha(png_ptr);
  200232. #endif
  200233. /* Write the file header information. */
  200234. png_write_info(png_ptr, info_ptr);
  200235. /* ------ these transformations don't touch the info structure ------- */
  200236. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200237. /* invert monochrome pixels */
  200238. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200239. png_set_invert_mono(png_ptr);
  200240. #endif
  200241. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200242. /* Shift the pixels up to a legal bit depth and fill in
  200243. * as appropriate to correctly scale the image.
  200244. */
  200245. if ((transforms & PNG_TRANSFORM_SHIFT)
  200246. && (info_ptr->valid & PNG_INFO_sBIT))
  200247. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200248. #endif
  200249. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200250. /* pack pixels into bytes */
  200251. if (transforms & PNG_TRANSFORM_PACKING)
  200252. png_set_packing(png_ptr);
  200253. #endif
  200254. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200255. /* swap location of alpha bytes from ARGB to RGBA */
  200256. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200257. png_set_swap_alpha(png_ptr);
  200258. #endif
  200259. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200260. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200261. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200262. */
  200263. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200264. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200265. #endif
  200266. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200267. /* flip BGR pixels to RGB */
  200268. if (transforms & PNG_TRANSFORM_BGR)
  200269. png_set_bgr(png_ptr);
  200270. #endif
  200271. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200272. /* swap bytes of 16-bit files to most significant byte first */
  200273. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200274. png_set_swap(png_ptr);
  200275. #endif
  200276. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200277. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200278. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200279. png_set_packswap(png_ptr);
  200280. #endif
  200281. /* ----------------------- end of transformations ------------------- */
  200282. /* write the bits */
  200283. if (info_ptr->valid & PNG_INFO_IDAT)
  200284. png_write_image(png_ptr, info_ptr->row_pointers);
  200285. /* It is REQUIRED to call this to finish writing the rest of the file */
  200286. png_write_end(png_ptr, info_ptr);
  200287. transforms = transforms; /* quiet compiler warnings */
  200288. params = params;
  200289. }
  200290. #endif
  200291. #endif /* PNG_WRITE_SUPPORTED */
  200292. /*** End of inlined file: pngwrite.c ***/
  200293. /*** Start of inlined file: pngwtran.c ***/
  200294. /* pngwtran.c - transforms the data in a row for PNG writers
  200295. *
  200296. * Last changed in libpng 1.2.9 April 14, 2006
  200297. * For conditions of distribution and use, see copyright notice in png.h
  200298. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200299. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200300. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200301. */
  200302. #define PNG_INTERNAL
  200303. #ifdef PNG_WRITE_SUPPORTED
  200304. /* Transform the data according to the user's wishes. The order of
  200305. * transformations is significant.
  200306. */
  200307. void /* PRIVATE */
  200308. png_do_write_transformations(png_structp png_ptr)
  200309. {
  200310. png_debug(1, "in png_do_write_transformations\n");
  200311. if (png_ptr == NULL)
  200312. return;
  200313. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200314. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200315. if(png_ptr->write_user_transform_fn != NULL)
  200316. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200317. (png_ptr, /* png_ptr */
  200318. &(png_ptr->row_info), /* row_info: */
  200319. /* png_uint_32 width; width of row */
  200320. /* png_uint_32 rowbytes; number of bytes in row */
  200321. /* png_byte color_type; color type of pixels */
  200322. /* png_byte bit_depth; bit depth of samples */
  200323. /* png_byte channels; number of channels (1-4) */
  200324. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200325. png_ptr->row_buf + 1); /* start of pixel data for row */
  200326. #endif
  200327. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200328. if (png_ptr->transformations & PNG_FILLER)
  200329. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200330. png_ptr->flags);
  200331. #endif
  200332. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200333. if (png_ptr->transformations & PNG_PACKSWAP)
  200334. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200335. #endif
  200336. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200337. if (png_ptr->transformations & PNG_PACK)
  200338. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200339. (png_uint_32)png_ptr->bit_depth);
  200340. #endif
  200341. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200342. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200343. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200344. #endif
  200345. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200346. if (png_ptr->transformations & PNG_SHIFT)
  200347. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200348. &(png_ptr->shift));
  200349. #endif
  200350. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200351. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200352. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200353. #endif
  200354. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200355. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200356. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200357. #endif
  200358. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200359. if (png_ptr->transformations & PNG_BGR)
  200360. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200361. #endif
  200362. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200363. if (png_ptr->transformations & PNG_INVERT_MONO)
  200364. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200365. #endif
  200366. }
  200367. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200368. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200369. * row_info bit depth should be 8 (one pixel per byte). The channels
  200370. * should be 1 (this only happens on grayscale and paletted images).
  200371. */
  200372. void /* PRIVATE */
  200373. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200374. {
  200375. png_debug(1, "in png_do_pack\n");
  200376. if (row_info->bit_depth == 8 &&
  200377. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200378. row != NULL && row_info != NULL &&
  200379. #endif
  200380. row_info->channels == 1)
  200381. {
  200382. switch ((int)bit_depth)
  200383. {
  200384. case 1:
  200385. {
  200386. png_bytep sp, dp;
  200387. int mask, v;
  200388. png_uint_32 i;
  200389. png_uint_32 row_width = row_info->width;
  200390. sp = row;
  200391. dp = row;
  200392. mask = 0x80;
  200393. v = 0;
  200394. for (i = 0; i < row_width; i++)
  200395. {
  200396. if (*sp != 0)
  200397. v |= mask;
  200398. sp++;
  200399. if (mask > 1)
  200400. mask >>= 1;
  200401. else
  200402. {
  200403. mask = 0x80;
  200404. *dp = (png_byte)v;
  200405. dp++;
  200406. v = 0;
  200407. }
  200408. }
  200409. if (mask != 0x80)
  200410. *dp = (png_byte)v;
  200411. break;
  200412. }
  200413. case 2:
  200414. {
  200415. png_bytep sp, dp;
  200416. int shift, v;
  200417. png_uint_32 i;
  200418. png_uint_32 row_width = row_info->width;
  200419. sp = row;
  200420. dp = row;
  200421. shift = 6;
  200422. v = 0;
  200423. for (i = 0; i < row_width; i++)
  200424. {
  200425. png_byte value;
  200426. value = (png_byte)(*sp & 0x03);
  200427. v |= (value << shift);
  200428. if (shift == 0)
  200429. {
  200430. shift = 6;
  200431. *dp = (png_byte)v;
  200432. dp++;
  200433. v = 0;
  200434. }
  200435. else
  200436. shift -= 2;
  200437. sp++;
  200438. }
  200439. if (shift != 6)
  200440. *dp = (png_byte)v;
  200441. break;
  200442. }
  200443. case 4:
  200444. {
  200445. png_bytep sp, dp;
  200446. int shift, v;
  200447. png_uint_32 i;
  200448. png_uint_32 row_width = row_info->width;
  200449. sp = row;
  200450. dp = row;
  200451. shift = 4;
  200452. v = 0;
  200453. for (i = 0; i < row_width; i++)
  200454. {
  200455. png_byte value;
  200456. value = (png_byte)(*sp & 0x0f);
  200457. v |= (value << shift);
  200458. if (shift == 0)
  200459. {
  200460. shift = 4;
  200461. *dp = (png_byte)v;
  200462. dp++;
  200463. v = 0;
  200464. }
  200465. else
  200466. shift -= 4;
  200467. sp++;
  200468. }
  200469. if (shift != 4)
  200470. *dp = (png_byte)v;
  200471. break;
  200472. }
  200473. }
  200474. row_info->bit_depth = (png_byte)bit_depth;
  200475. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200476. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200477. row_info->width);
  200478. }
  200479. }
  200480. #endif
  200481. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200482. /* Shift pixel values to take advantage of whole range. Pass the
  200483. * true number of bits in bit_depth. The row should be packed
  200484. * according to row_info->bit_depth. Thus, if you had a row of
  200485. * bit depth 4, but the pixels only had values from 0 to 7, you
  200486. * would pass 3 as bit_depth, and this routine would translate the
  200487. * data to 0 to 15.
  200488. */
  200489. void /* PRIVATE */
  200490. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200491. {
  200492. png_debug(1, "in png_do_shift\n");
  200493. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200494. if (row != NULL && row_info != NULL &&
  200495. #else
  200496. if (
  200497. #endif
  200498. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200499. {
  200500. int shift_start[4], shift_dec[4];
  200501. int channels = 0;
  200502. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200503. {
  200504. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200505. shift_dec[channels] = bit_depth->red;
  200506. channels++;
  200507. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200508. shift_dec[channels] = bit_depth->green;
  200509. channels++;
  200510. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200511. shift_dec[channels] = bit_depth->blue;
  200512. channels++;
  200513. }
  200514. else
  200515. {
  200516. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200517. shift_dec[channels] = bit_depth->gray;
  200518. channels++;
  200519. }
  200520. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200521. {
  200522. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200523. shift_dec[channels] = bit_depth->alpha;
  200524. channels++;
  200525. }
  200526. /* with low row depths, could only be grayscale, so one channel */
  200527. if (row_info->bit_depth < 8)
  200528. {
  200529. png_bytep bp = row;
  200530. png_uint_32 i;
  200531. png_byte mask;
  200532. png_uint_32 row_bytes = row_info->rowbytes;
  200533. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200534. mask = 0x55;
  200535. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200536. mask = 0x11;
  200537. else
  200538. mask = 0xff;
  200539. for (i = 0; i < row_bytes; i++, bp++)
  200540. {
  200541. png_uint_16 v;
  200542. int j;
  200543. v = *bp;
  200544. *bp = 0;
  200545. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200546. {
  200547. if (j > 0)
  200548. *bp |= (png_byte)((v << j) & 0xff);
  200549. else
  200550. *bp |= (png_byte)((v >> (-j)) & mask);
  200551. }
  200552. }
  200553. }
  200554. else if (row_info->bit_depth == 8)
  200555. {
  200556. png_bytep bp = row;
  200557. png_uint_32 i;
  200558. png_uint_32 istop = channels * row_info->width;
  200559. for (i = 0; i < istop; i++, bp++)
  200560. {
  200561. png_uint_16 v;
  200562. int j;
  200563. int c = (int)(i%channels);
  200564. v = *bp;
  200565. *bp = 0;
  200566. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200567. {
  200568. if (j > 0)
  200569. *bp |= (png_byte)((v << j) & 0xff);
  200570. else
  200571. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200572. }
  200573. }
  200574. }
  200575. else
  200576. {
  200577. png_bytep bp;
  200578. png_uint_32 i;
  200579. png_uint_32 istop = channels * row_info->width;
  200580. for (bp = row, i = 0; i < istop; i++)
  200581. {
  200582. int c = (int)(i%channels);
  200583. png_uint_16 value, v;
  200584. int j;
  200585. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200586. value = 0;
  200587. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200588. {
  200589. if (j > 0)
  200590. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200591. else
  200592. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200593. }
  200594. *bp++ = (png_byte)(value >> 8);
  200595. *bp++ = (png_byte)(value & 0xff);
  200596. }
  200597. }
  200598. }
  200599. }
  200600. #endif
  200601. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200602. void /* PRIVATE */
  200603. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200604. {
  200605. png_debug(1, "in png_do_write_swap_alpha\n");
  200606. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200607. if (row != NULL && row_info != NULL)
  200608. #endif
  200609. {
  200610. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200611. {
  200612. /* This converts from ARGB to RGBA */
  200613. if (row_info->bit_depth == 8)
  200614. {
  200615. png_bytep sp, dp;
  200616. png_uint_32 i;
  200617. png_uint_32 row_width = row_info->width;
  200618. for (i = 0, sp = dp = row; i < row_width; i++)
  200619. {
  200620. png_byte save = *(sp++);
  200621. *(dp++) = *(sp++);
  200622. *(dp++) = *(sp++);
  200623. *(dp++) = *(sp++);
  200624. *(dp++) = save;
  200625. }
  200626. }
  200627. /* This converts from AARRGGBB to RRGGBBAA */
  200628. else
  200629. {
  200630. png_bytep sp, dp;
  200631. png_uint_32 i;
  200632. png_uint_32 row_width = row_info->width;
  200633. for (i = 0, sp = dp = row; i < row_width; i++)
  200634. {
  200635. png_byte save[2];
  200636. save[0] = *(sp++);
  200637. save[1] = *(sp++);
  200638. *(dp++) = *(sp++);
  200639. *(dp++) = *(sp++);
  200640. *(dp++) = *(sp++);
  200641. *(dp++) = *(sp++);
  200642. *(dp++) = *(sp++);
  200643. *(dp++) = *(sp++);
  200644. *(dp++) = save[0];
  200645. *(dp++) = save[1];
  200646. }
  200647. }
  200648. }
  200649. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200650. {
  200651. /* This converts from AG to GA */
  200652. if (row_info->bit_depth == 8)
  200653. {
  200654. png_bytep sp, dp;
  200655. png_uint_32 i;
  200656. png_uint_32 row_width = row_info->width;
  200657. for (i = 0, sp = dp = row; i < row_width; i++)
  200658. {
  200659. png_byte save = *(sp++);
  200660. *(dp++) = *(sp++);
  200661. *(dp++) = save;
  200662. }
  200663. }
  200664. /* This converts from AAGG to GGAA */
  200665. else
  200666. {
  200667. png_bytep sp, dp;
  200668. png_uint_32 i;
  200669. png_uint_32 row_width = row_info->width;
  200670. for (i = 0, sp = dp = row; i < row_width; i++)
  200671. {
  200672. png_byte save[2];
  200673. save[0] = *(sp++);
  200674. save[1] = *(sp++);
  200675. *(dp++) = *(sp++);
  200676. *(dp++) = *(sp++);
  200677. *(dp++) = save[0];
  200678. *(dp++) = save[1];
  200679. }
  200680. }
  200681. }
  200682. }
  200683. }
  200684. #endif
  200685. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200686. void /* PRIVATE */
  200687. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200688. {
  200689. png_debug(1, "in png_do_write_invert_alpha\n");
  200690. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200691. if (row != NULL && row_info != NULL)
  200692. #endif
  200693. {
  200694. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200695. {
  200696. /* This inverts the alpha channel in RGBA */
  200697. if (row_info->bit_depth == 8)
  200698. {
  200699. png_bytep sp, dp;
  200700. png_uint_32 i;
  200701. png_uint_32 row_width = row_info->width;
  200702. for (i = 0, sp = dp = row; i < row_width; i++)
  200703. {
  200704. /* does nothing
  200705. *(dp++) = *(sp++);
  200706. *(dp++) = *(sp++);
  200707. *(dp++) = *(sp++);
  200708. */
  200709. sp+=3; dp = sp;
  200710. *(dp++) = (png_byte)(255 - *(sp++));
  200711. }
  200712. }
  200713. /* This inverts the alpha channel in RRGGBBAA */
  200714. else
  200715. {
  200716. png_bytep sp, dp;
  200717. png_uint_32 i;
  200718. png_uint_32 row_width = row_info->width;
  200719. for (i = 0, sp = dp = row; i < row_width; i++)
  200720. {
  200721. /* does nothing
  200722. *(dp++) = *(sp++);
  200723. *(dp++) = *(sp++);
  200724. *(dp++) = *(sp++);
  200725. *(dp++) = *(sp++);
  200726. *(dp++) = *(sp++);
  200727. *(dp++) = *(sp++);
  200728. */
  200729. sp+=6; dp = sp;
  200730. *(dp++) = (png_byte)(255 - *(sp++));
  200731. *(dp++) = (png_byte)(255 - *(sp++));
  200732. }
  200733. }
  200734. }
  200735. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200736. {
  200737. /* This inverts the alpha channel in GA */
  200738. if (row_info->bit_depth == 8)
  200739. {
  200740. png_bytep sp, dp;
  200741. png_uint_32 i;
  200742. png_uint_32 row_width = row_info->width;
  200743. for (i = 0, sp = dp = row; i < row_width; i++)
  200744. {
  200745. *(dp++) = *(sp++);
  200746. *(dp++) = (png_byte)(255 - *(sp++));
  200747. }
  200748. }
  200749. /* This inverts the alpha channel in GGAA */
  200750. else
  200751. {
  200752. png_bytep sp, dp;
  200753. png_uint_32 i;
  200754. png_uint_32 row_width = row_info->width;
  200755. for (i = 0, sp = dp = row; i < row_width; i++)
  200756. {
  200757. /* does nothing
  200758. *(dp++) = *(sp++);
  200759. *(dp++) = *(sp++);
  200760. */
  200761. sp+=2; dp = sp;
  200762. *(dp++) = (png_byte)(255 - *(sp++));
  200763. *(dp++) = (png_byte)(255 - *(sp++));
  200764. }
  200765. }
  200766. }
  200767. }
  200768. }
  200769. #endif
  200770. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200771. /* undoes intrapixel differencing */
  200772. void /* PRIVATE */
  200773. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200774. {
  200775. png_debug(1, "in png_do_write_intrapixel\n");
  200776. if (
  200777. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200778. row != NULL && row_info != NULL &&
  200779. #endif
  200780. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200781. {
  200782. int bytes_per_pixel;
  200783. png_uint_32 row_width = row_info->width;
  200784. if (row_info->bit_depth == 8)
  200785. {
  200786. png_bytep rp;
  200787. png_uint_32 i;
  200788. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200789. bytes_per_pixel = 3;
  200790. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200791. bytes_per_pixel = 4;
  200792. else
  200793. return;
  200794. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200795. {
  200796. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200797. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200798. }
  200799. }
  200800. else if (row_info->bit_depth == 16)
  200801. {
  200802. png_bytep rp;
  200803. png_uint_32 i;
  200804. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200805. bytes_per_pixel = 6;
  200806. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200807. bytes_per_pixel = 8;
  200808. else
  200809. return;
  200810. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200811. {
  200812. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200813. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200814. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200815. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200816. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200817. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200818. *(rp+1) = (png_byte)(red & 0xff);
  200819. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200820. *(rp+5) = (png_byte)(blue & 0xff);
  200821. }
  200822. }
  200823. }
  200824. }
  200825. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200826. #endif /* PNG_WRITE_SUPPORTED */
  200827. /*** End of inlined file: pngwtran.c ***/
  200828. /*** Start of inlined file: pngwutil.c ***/
  200829. /* pngwutil.c - utilities to write a PNG file
  200830. *
  200831. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200832. * For conditions of distribution and use, see copyright notice in png.h
  200833. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200834. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200835. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200836. */
  200837. #define PNG_INTERNAL
  200838. #ifdef PNG_WRITE_SUPPORTED
  200839. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200840. * with unsigned numbers for convenience, although one supported
  200841. * ancillary chunk uses signed (two's complement) numbers.
  200842. */
  200843. void PNGAPI
  200844. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200845. {
  200846. buf[0] = (png_byte)((i >> 24) & 0xff);
  200847. buf[1] = (png_byte)((i >> 16) & 0xff);
  200848. buf[2] = (png_byte)((i >> 8) & 0xff);
  200849. buf[3] = (png_byte)(i & 0xff);
  200850. }
  200851. /* The png_save_int_32 function assumes integers are stored in two's
  200852. * complement format. If this isn't the case, then this routine needs to
  200853. * be modified to write data in two's complement format.
  200854. */
  200855. void PNGAPI
  200856. png_save_int_32(png_bytep buf, png_int_32 i)
  200857. {
  200858. buf[0] = (png_byte)((i >> 24) & 0xff);
  200859. buf[1] = (png_byte)((i >> 16) & 0xff);
  200860. buf[2] = (png_byte)((i >> 8) & 0xff);
  200861. buf[3] = (png_byte)(i & 0xff);
  200862. }
  200863. /* Place a 16-bit number into a buffer in PNG byte order.
  200864. * The parameter is declared unsigned int, not png_uint_16,
  200865. * just to avoid potential problems on pre-ANSI C compilers.
  200866. */
  200867. void PNGAPI
  200868. png_save_uint_16(png_bytep buf, unsigned int i)
  200869. {
  200870. buf[0] = (png_byte)((i >> 8) & 0xff);
  200871. buf[1] = (png_byte)(i & 0xff);
  200872. }
  200873. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200874. * representing the chunk name. The array must be at least 4 bytes in
  200875. * length, and does not need to be null terminated. To be safe, pass the
  200876. * pre-defined chunk names here, and if you need a new one, define it
  200877. * where the others are defined. The length is the length of the data.
  200878. * All the data must be present. If that is not possible, use the
  200879. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200880. * functions instead.
  200881. */
  200882. void PNGAPI
  200883. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200884. png_bytep data, png_size_t length)
  200885. {
  200886. if(png_ptr == NULL) return;
  200887. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200888. png_write_chunk_data(png_ptr, data, length);
  200889. png_write_chunk_end(png_ptr);
  200890. }
  200891. /* Write the start of a PNG chunk. The type is the chunk type.
  200892. * The total_length is the sum of the lengths of all the data you will be
  200893. * passing in png_write_chunk_data().
  200894. */
  200895. void PNGAPI
  200896. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200897. png_uint_32 length)
  200898. {
  200899. png_byte buf[4];
  200900. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200901. if(png_ptr == NULL) return;
  200902. /* write the length */
  200903. png_save_uint_32(buf, length);
  200904. png_write_data(png_ptr, buf, (png_size_t)4);
  200905. /* write the chunk name */
  200906. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200907. /* reset the crc and run it over the chunk name */
  200908. png_reset_crc(png_ptr);
  200909. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200910. }
  200911. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200912. * Note that multiple calls to this function are allowed, and that the
  200913. * sum of the lengths from these calls *must* add up to the total_length
  200914. * given to png_write_chunk_start().
  200915. */
  200916. void PNGAPI
  200917. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200918. {
  200919. /* write the data, and run the CRC over it */
  200920. if(png_ptr == NULL) return;
  200921. if (data != NULL && length > 0)
  200922. {
  200923. png_calculate_crc(png_ptr, data, length);
  200924. png_write_data(png_ptr, data, length);
  200925. }
  200926. }
  200927. /* Finish a chunk started with png_write_chunk_start(). */
  200928. void PNGAPI
  200929. png_write_chunk_end(png_structp png_ptr)
  200930. {
  200931. png_byte buf[4];
  200932. if(png_ptr == NULL) return;
  200933. /* write the crc */
  200934. png_save_uint_32(buf, png_ptr->crc);
  200935. png_write_data(png_ptr, buf, (png_size_t)4);
  200936. }
  200937. /* Simple function to write the signature. If we have already written
  200938. * the magic bytes of the signature, or more likely, the PNG stream is
  200939. * being embedded into another stream and doesn't need its own signature,
  200940. * we should call png_set_sig_bytes() to tell libpng how many of the
  200941. * bytes have already been written.
  200942. */
  200943. void /* PRIVATE */
  200944. png_write_sig(png_structp png_ptr)
  200945. {
  200946. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200947. /* write the rest of the 8 byte signature */
  200948. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200949. (png_size_t)8 - png_ptr->sig_bytes);
  200950. if(png_ptr->sig_bytes < 3)
  200951. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200952. }
  200953. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200954. /*
  200955. * This pair of functions encapsulates the operation of (a) compressing a
  200956. * text string, and (b) issuing it later as a series of chunk data writes.
  200957. * The compression_state structure is shared context for these functions
  200958. * set up by the caller in order to make the whole mess thread-safe.
  200959. */
  200960. typedef struct
  200961. {
  200962. char *input; /* the uncompressed input data */
  200963. int input_len; /* its length */
  200964. int num_output_ptr; /* number of output pointers used */
  200965. int max_output_ptr; /* size of output_ptr */
  200966. png_charpp output_ptr; /* array of pointers to output */
  200967. } compression_state;
  200968. /* compress given text into storage in the png_ptr structure */
  200969. static int /* PRIVATE */
  200970. png_text_compress(png_structp png_ptr,
  200971. png_charp text, png_size_t text_len, int compression,
  200972. compression_state *comp)
  200973. {
  200974. int ret;
  200975. comp->num_output_ptr = 0;
  200976. comp->max_output_ptr = 0;
  200977. comp->output_ptr = NULL;
  200978. comp->input = NULL;
  200979. comp->input_len = 0;
  200980. /* we may just want to pass the text right through */
  200981. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200982. {
  200983. comp->input = text;
  200984. comp->input_len = text_len;
  200985. return((int)text_len);
  200986. }
  200987. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200988. {
  200989. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200990. char msg[50];
  200991. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200992. png_warning(png_ptr, msg);
  200993. #else
  200994. png_warning(png_ptr, "Unknown compression type");
  200995. #endif
  200996. }
  200997. /* We can't write the chunk until we find out how much data we have,
  200998. * which means we need to run the compressor first and save the
  200999. * output. This shouldn't be a problem, as the vast majority of
  201000. * comments should be reasonable, but we will set up an array of
  201001. * malloc'd pointers to be sure.
  201002. *
  201003. * If we knew the application was well behaved, we could simplify this
  201004. * greatly by assuming we can always malloc an output buffer large
  201005. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  201006. * and malloc this directly. The only time this would be a bad idea is
  201007. * if we can't malloc more than 64K and we have 64K of random input
  201008. * data, or if the input string is incredibly large (although this
  201009. * wouldn't cause a failure, just a slowdown due to swapping).
  201010. */
  201011. /* set up the compression buffers */
  201012. png_ptr->zstream.avail_in = (uInt)text_len;
  201013. png_ptr->zstream.next_in = (Bytef *)text;
  201014. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201015. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  201016. /* this is the same compression loop as in png_write_row() */
  201017. do
  201018. {
  201019. /* compress the data */
  201020. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  201021. if (ret != Z_OK)
  201022. {
  201023. /* error */
  201024. if (png_ptr->zstream.msg != NULL)
  201025. png_error(png_ptr, png_ptr->zstream.msg);
  201026. else
  201027. png_error(png_ptr, "zlib error");
  201028. }
  201029. /* check to see if we need more room */
  201030. if (!(png_ptr->zstream.avail_out))
  201031. {
  201032. /* make sure the output array has room */
  201033. if (comp->num_output_ptr >= comp->max_output_ptr)
  201034. {
  201035. int old_max;
  201036. old_max = comp->max_output_ptr;
  201037. comp->max_output_ptr = comp->num_output_ptr + 4;
  201038. if (comp->output_ptr != NULL)
  201039. {
  201040. png_charpp old_ptr;
  201041. old_ptr = comp->output_ptr;
  201042. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201043. (png_uint_32)(comp->max_output_ptr *
  201044. png_sizeof (png_charpp)));
  201045. png_memcpy(comp->output_ptr, old_ptr, old_max
  201046. * png_sizeof (png_charp));
  201047. png_free(png_ptr, old_ptr);
  201048. }
  201049. else
  201050. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201051. (png_uint_32)(comp->max_output_ptr *
  201052. png_sizeof (png_charp)));
  201053. }
  201054. /* save the data */
  201055. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  201056. (png_uint_32)png_ptr->zbuf_size);
  201057. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201058. png_ptr->zbuf_size);
  201059. comp->num_output_ptr++;
  201060. /* and reset the buffer */
  201061. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201062. png_ptr->zstream.next_out = png_ptr->zbuf;
  201063. }
  201064. /* continue until we don't have any more to compress */
  201065. } while (png_ptr->zstream.avail_in);
  201066. /* finish the compression */
  201067. do
  201068. {
  201069. /* tell zlib we are finished */
  201070. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201071. if (ret == Z_OK)
  201072. {
  201073. /* check to see if we need more room */
  201074. if (!(png_ptr->zstream.avail_out))
  201075. {
  201076. /* check to make sure our output array has room */
  201077. if (comp->num_output_ptr >= comp->max_output_ptr)
  201078. {
  201079. int old_max;
  201080. old_max = comp->max_output_ptr;
  201081. comp->max_output_ptr = comp->num_output_ptr + 4;
  201082. if (comp->output_ptr != NULL)
  201083. {
  201084. png_charpp old_ptr;
  201085. old_ptr = comp->output_ptr;
  201086. /* This could be optimized to realloc() */
  201087. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201088. (png_uint_32)(comp->max_output_ptr *
  201089. png_sizeof (png_charpp)));
  201090. png_memcpy(comp->output_ptr, old_ptr,
  201091. old_max * png_sizeof (png_charp));
  201092. png_free(png_ptr, old_ptr);
  201093. }
  201094. else
  201095. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201096. (png_uint_32)(comp->max_output_ptr *
  201097. png_sizeof (png_charp)));
  201098. }
  201099. /* save off the data */
  201100. comp->output_ptr[comp->num_output_ptr] =
  201101. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  201102. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201103. png_ptr->zbuf_size);
  201104. comp->num_output_ptr++;
  201105. /* and reset the buffer pointers */
  201106. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201107. png_ptr->zstream.next_out = png_ptr->zbuf;
  201108. }
  201109. }
  201110. else if (ret != Z_STREAM_END)
  201111. {
  201112. /* we got an error */
  201113. if (png_ptr->zstream.msg != NULL)
  201114. png_error(png_ptr, png_ptr->zstream.msg);
  201115. else
  201116. png_error(png_ptr, "zlib error");
  201117. }
  201118. } while (ret != Z_STREAM_END);
  201119. /* text length is number of buffers plus last buffer */
  201120. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  201121. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201122. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  201123. return((int)text_len);
  201124. }
  201125. /* ship the compressed text out via chunk writes */
  201126. static void /* PRIVATE */
  201127. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  201128. {
  201129. int i;
  201130. /* handle the no-compression case */
  201131. if (comp->input)
  201132. {
  201133. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  201134. (png_size_t)comp->input_len);
  201135. return;
  201136. }
  201137. /* write saved output buffers, if any */
  201138. for (i = 0; i < comp->num_output_ptr; i++)
  201139. {
  201140. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  201141. png_ptr->zbuf_size);
  201142. png_free(png_ptr, comp->output_ptr[i]);
  201143. comp->output_ptr[i]=NULL;
  201144. }
  201145. if (comp->max_output_ptr != 0)
  201146. png_free(png_ptr, comp->output_ptr);
  201147. comp->output_ptr=NULL;
  201148. /* write anything left in zbuf */
  201149. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201150. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201151. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201152. /* reset zlib for another zTXt/iTXt or image data */
  201153. deflateReset(&png_ptr->zstream);
  201154. png_ptr->zstream.data_type = Z_BINARY;
  201155. }
  201156. #endif
  201157. /* Write the IHDR chunk, and update the png_struct with the necessary
  201158. * information. Note that the rest of this code depends upon this
  201159. * information being correct.
  201160. */
  201161. void /* PRIVATE */
  201162. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201163. int bit_depth, int color_type, int compression_type, int filter_type,
  201164. int interlace_type)
  201165. {
  201166. #ifdef PNG_USE_LOCAL_ARRAYS
  201167. PNG_IHDR;
  201168. #endif
  201169. png_byte buf[13]; /* buffer to store the IHDR info */
  201170. png_debug(1, "in png_write_IHDR\n");
  201171. /* Check that we have valid input data from the application info */
  201172. switch (color_type)
  201173. {
  201174. case PNG_COLOR_TYPE_GRAY:
  201175. switch (bit_depth)
  201176. {
  201177. case 1:
  201178. case 2:
  201179. case 4:
  201180. case 8:
  201181. case 16: png_ptr->channels = 1; break;
  201182. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201183. }
  201184. break;
  201185. case PNG_COLOR_TYPE_RGB:
  201186. if (bit_depth != 8 && bit_depth != 16)
  201187. png_error(png_ptr, "Invalid bit depth for RGB image");
  201188. png_ptr->channels = 3;
  201189. break;
  201190. case PNG_COLOR_TYPE_PALETTE:
  201191. switch (bit_depth)
  201192. {
  201193. case 1:
  201194. case 2:
  201195. case 4:
  201196. case 8: png_ptr->channels = 1; break;
  201197. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201198. }
  201199. break;
  201200. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201201. if (bit_depth != 8 && bit_depth != 16)
  201202. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201203. png_ptr->channels = 2;
  201204. break;
  201205. case PNG_COLOR_TYPE_RGB_ALPHA:
  201206. if (bit_depth != 8 && bit_depth != 16)
  201207. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201208. png_ptr->channels = 4;
  201209. break;
  201210. default:
  201211. png_error(png_ptr, "Invalid image color type specified");
  201212. }
  201213. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201214. {
  201215. png_warning(png_ptr, "Invalid compression type specified");
  201216. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201217. }
  201218. /* Write filter_method 64 (intrapixel differencing) only if
  201219. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201220. * 2. Libpng did not write a PNG signature (this filter_method is only
  201221. * used in PNG datastreams that are embedded in MNG datastreams) and
  201222. * 3. The application called png_permit_mng_features with a mask that
  201223. * included PNG_FLAG_MNG_FILTER_64 and
  201224. * 4. The filter_method is 64 and
  201225. * 5. The color_type is RGB or RGBA
  201226. */
  201227. if (
  201228. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201229. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201230. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201231. (color_type == PNG_COLOR_TYPE_RGB ||
  201232. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201233. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201234. #endif
  201235. filter_type != PNG_FILTER_TYPE_BASE)
  201236. {
  201237. png_warning(png_ptr, "Invalid filter type specified");
  201238. filter_type = PNG_FILTER_TYPE_BASE;
  201239. }
  201240. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201241. if (interlace_type != PNG_INTERLACE_NONE &&
  201242. interlace_type != PNG_INTERLACE_ADAM7)
  201243. {
  201244. png_warning(png_ptr, "Invalid interlace type specified");
  201245. interlace_type = PNG_INTERLACE_ADAM7;
  201246. }
  201247. #else
  201248. interlace_type=PNG_INTERLACE_NONE;
  201249. #endif
  201250. /* save off the relevent information */
  201251. png_ptr->bit_depth = (png_byte)bit_depth;
  201252. png_ptr->color_type = (png_byte)color_type;
  201253. png_ptr->interlaced = (png_byte)interlace_type;
  201254. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201255. png_ptr->filter_type = (png_byte)filter_type;
  201256. #endif
  201257. png_ptr->compression_type = (png_byte)compression_type;
  201258. png_ptr->width = width;
  201259. png_ptr->height = height;
  201260. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201261. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201262. /* set the usr info, so any transformations can modify it */
  201263. png_ptr->usr_width = png_ptr->width;
  201264. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201265. png_ptr->usr_channels = png_ptr->channels;
  201266. /* pack the header information into the buffer */
  201267. png_save_uint_32(buf, width);
  201268. png_save_uint_32(buf + 4, height);
  201269. buf[8] = (png_byte)bit_depth;
  201270. buf[9] = (png_byte)color_type;
  201271. buf[10] = (png_byte)compression_type;
  201272. buf[11] = (png_byte)filter_type;
  201273. buf[12] = (png_byte)interlace_type;
  201274. /* write the chunk */
  201275. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201276. /* initialize zlib with PNG info */
  201277. png_ptr->zstream.zalloc = png_zalloc;
  201278. png_ptr->zstream.zfree = png_zfree;
  201279. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201280. if (!(png_ptr->do_filter))
  201281. {
  201282. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201283. png_ptr->bit_depth < 8)
  201284. png_ptr->do_filter = PNG_FILTER_NONE;
  201285. else
  201286. png_ptr->do_filter = PNG_ALL_FILTERS;
  201287. }
  201288. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201289. {
  201290. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201291. png_ptr->zlib_strategy = Z_FILTERED;
  201292. else
  201293. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201294. }
  201295. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201296. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201297. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201298. png_ptr->zlib_mem_level = 8;
  201299. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201300. png_ptr->zlib_window_bits = 15;
  201301. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201302. png_ptr->zlib_method = 8;
  201303. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201304. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201305. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201306. png_error(png_ptr, "zlib failed to initialize compressor");
  201307. png_ptr->zstream.next_out = png_ptr->zbuf;
  201308. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201309. /* libpng is not interested in zstream.data_type */
  201310. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201311. png_ptr->zstream.data_type = Z_BINARY;
  201312. png_ptr->mode = PNG_HAVE_IHDR;
  201313. }
  201314. /* write the palette. We are careful not to trust png_color to be in the
  201315. * correct order for PNG, so people can redefine it to any convenient
  201316. * structure.
  201317. */
  201318. void /* PRIVATE */
  201319. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201320. {
  201321. #ifdef PNG_USE_LOCAL_ARRAYS
  201322. PNG_PLTE;
  201323. #endif
  201324. png_uint_32 i;
  201325. png_colorp pal_ptr;
  201326. png_byte buf[3];
  201327. png_debug(1, "in png_write_PLTE\n");
  201328. if ((
  201329. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201330. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201331. #endif
  201332. num_pal == 0) || num_pal > 256)
  201333. {
  201334. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201335. {
  201336. png_error(png_ptr, "Invalid number of colors in palette");
  201337. }
  201338. else
  201339. {
  201340. png_warning(png_ptr, "Invalid number of colors in palette");
  201341. return;
  201342. }
  201343. }
  201344. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201345. {
  201346. png_warning(png_ptr,
  201347. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201348. return;
  201349. }
  201350. png_ptr->num_palette = (png_uint_16)num_pal;
  201351. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201352. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201353. #ifndef PNG_NO_POINTER_INDEXING
  201354. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201355. {
  201356. buf[0] = pal_ptr->red;
  201357. buf[1] = pal_ptr->green;
  201358. buf[2] = pal_ptr->blue;
  201359. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201360. }
  201361. #else
  201362. /* This is a little slower but some buggy compilers need to do this instead */
  201363. pal_ptr=palette;
  201364. for (i = 0; i < num_pal; i++)
  201365. {
  201366. buf[0] = pal_ptr[i].red;
  201367. buf[1] = pal_ptr[i].green;
  201368. buf[2] = pal_ptr[i].blue;
  201369. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201370. }
  201371. #endif
  201372. png_write_chunk_end(png_ptr);
  201373. png_ptr->mode |= PNG_HAVE_PLTE;
  201374. }
  201375. /* write an IDAT chunk */
  201376. void /* PRIVATE */
  201377. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201378. {
  201379. #ifdef PNG_USE_LOCAL_ARRAYS
  201380. PNG_IDAT;
  201381. #endif
  201382. png_debug(1, "in png_write_IDAT\n");
  201383. /* Optimize the CMF field in the zlib stream. */
  201384. /* This hack of the zlib stream is compliant to the stream specification. */
  201385. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201386. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201387. {
  201388. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201389. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201390. {
  201391. /* Avoid memory underflows and multiplication overflows. */
  201392. /* The conditions below are practically always satisfied;
  201393. however, they still must be checked. */
  201394. if (length >= 2 &&
  201395. png_ptr->height < 16384 && png_ptr->width < 16384)
  201396. {
  201397. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201398. ((png_ptr->width *
  201399. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201400. unsigned int z_cinfo = z_cmf >> 4;
  201401. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201402. while (uncompressed_idat_size <= half_z_window_size &&
  201403. half_z_window_size >= 256)
  201404. {
  201405. z_cinfo--;
  201406. half_z_window_size >>= 1;
  201407. }
  201408. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201409. if (data[0] != (png_byte)z_cmf)
  201410. {
  201411. data[0] = (png_byte)z_cmf;
  201412. data[1] &= 0xe0;
  201413. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201414. }
  201415. }
  201416. }
  201417. else
  201418. png_error(png_ptr,
  201419. "Invalid zlib compression method or flags in IDAT");
  201420. }
  201421. png_write_chunk(png_ptr, png_IDAT, data, length);
  201422. png_ptr->mode |= PNG_HAVE_IDAT;
  201423. }
  201424. /* write an IEND chunk */
  201425. void /* PRIVATE */
  201426. png_write_IEND(png_structp png_ptr)
  201427. {
  201428. #ifdef PNG_USE_LOCAL_ARRAYS
  201429. PNG_IEND;
  201430. #endif
  201431. png_debug(1, "in png_write_IEND\n");
  201432. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201433. (png_size_t)0);
  201434. png_ptr->mode |= PNG_HAVE_IEND;
  201435. }
  201436. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201437. /* write a gAMA chunk */
  201438. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201439. void /* PRIVATE */
  201440. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201441. {
  201442. #ifdef PNG_USE_LOCAL_ARRAYS
  201443. PNG_gAMA;
  201444. #endif
  201445. png_uint_32 igamma;
  201446. png_byte buf[4];
  201447. png_debug(1, "in png_write_gAMA\n");
  201448. /* file_gamma is saved in 1/100,000ths */
  201449. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201450. png_save_uint_32(buf, igamma);
  201451. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201452. }
  201453. #endif
  201454. #ifdef PNG_FIXED_POINT_SUPPORTED
  201455. void /* PRIVATE */
  201456. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201457. {
  201458. #ifdef PNG_USE_LOCAL_ARRAYS
  201459. PNG_gAMA;
  201460. #endif
  201461. png_byte buf[4];
  201462. png_debug(1, "in png_write_gAMA\n");
  201463. /* file_gamma is saved in 1/100,000ths */
  201464. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201465. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201466. }
  201467. #endif
  201468. #endif
  201469. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201470. /* write a sRGB chunk */
  201471. void /* PRIVATE */
  201472. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201473. {
  201474. #ifdef PNG_USE_LOCAL_ARRAYS
  201475. PNG_sRGB;
  201476. #endif
  201477. png_byte buf[1];
  201478. png_debug(1, "in png_write_sRGB\n");
  201479. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201480. png_warning(png_ptr,
  201481. "Invalid sRGB rendering intent specified");
  201482. buf[0]=(png_byte)srgb_intent;
  201483. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201484. }
  201485. #endif
  201486. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201487. /* write an iCCP chunk */
  201488. void /* PRIVATE */
  201489. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201490. png_charp profile, int profile_len)
  201491. {
  201492. #ifdef PNG_USE_LOCAL_ARRAYS
  201493. PNG_iCCP;
  201494. #endif
  201495. png_size_t name_len;
  201496. png_charp new_name;
  201497. compression_state comp;
  201498. int embedded_profile_len = 0;
  201499. png_debug(1, "in png_write_iCCP\n");
  201500. comp.num_output_ptr = 0;
  201501. comp.max_output_ptr = 0;
  201502. comp.output_ptr = NULL;
  201503. comp.input = NULL;
  201504. comp.input_len = 0;
  201505. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201506. &new_name)) == 0)
  201507. {
  201508. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201509. return;
  201510. }
  201511. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201512. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201513. if (profile == NULL)
  201514. profile_len = 0;
  201515. if (profile_len > 3)
  201516. embedded_profile_len =
  201517. ((*( (png_bytep)profile ))<<24) |
  201518. ((*( (png_bytep)profile+1))<<16) |
  201519. ((*( (png_bytep)profile+2))<< 8) |
  201520. ((*( (png_bytep)profile+3)) );
  201521. if (profile_len < embedded_profile_len)
  201522. {
  201523. png_warning(png_ptr,
  201524. "Embedded profile length too large in iCCP chunk");
  201525. return;
  201526. }
  201527. if (profile_len > embedded_profile_len)
  201528. {
  201529. png_warning(png_ptr,
  201530. "Truncating profile to actual length in iCCP chunk");
  201531. profile_len = embedded_profile_len;
  201532. }
  201533. if (profile_len)
  201534. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201535. PNG_COMPRESSION_TYPE_BASE, &comp);
  201536. /* make sure we include the NULL after the name and the compression type */
  201537. png_write_chunk_start(png_ptr, png_iCCP,
  201538. (png_uint_32)name_len+profile_len+2);
  201539. new_name[name_len+1]=0x00;
  201540. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201541. if (profile_len)
  201542. png_write_compressed_data_out(png_ptr, &comp);
  201543. png_write_chunk_end(png_ptr);
  201544. png_free(png_ptr, new_name);
  201545. }
  201546. #endif
  201547. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201548. /* write a sPLT chunk */
  201549. void /* PRIVATE */
  201550. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201551. {
  201552. #ifdef PNG_USE_LOCAL_ARRAYS
  201553. PNG_sPLT;
  201554. #endif
  201555. png_size_t name_len;
  201556. png_charp new_name;
  201557. png_byte entrybuf[10];
  201558. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201559. int palette_size = entry_size * spalette->nentries;
  201560. png_sPLT_entryp ep;
  201561. #ifdef PNG_NO_POINTER_INDEXING
  201562. int i;
  201563. #endif
  201564. png_debug(1, "in png_write_sPLT\n");
  201565. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201566. spalette->name, &new_name))==0)
  201567. {
  201568. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201569. return;
  201570. }
  201571. /* make sure we include the NULL after the name */
  201572. png_write_chunk_start(png_ptr, png_sPLT,
  201573. (png_uint_32)(name_len + 2 + palette_size));
  201574. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201575. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201576. /* loop through each palette entry, writing appropriately */
  201577. #ifndef PNG_NO_POINTER_INDEXING
  201578. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201579. {
  201580. if (spalette->depth == 8)
  201581. {
  201582. entrybuf[0] = (png_byte)ep->red;
  201583. entrybuf[1] = (png_byte)ep->green;
  201584. entrybuf[2] = (png_byte)ep->blue;
  201585. entrybuf[3] = (png_byte)ep->alpha;
  201586. png_save_uint_16(entrybuf + 4, ep->frequency);
  201587. }
  201588. else
  201589. {
  201590. png_save_uint_16(entrybuf + 0, ep->red);
  201591. png_save_uint_16(entrybuf + 2, ep->green);
  201592. png_save_uint_16(entrybuf + 4, ep->blue);
  201593. png_save_uint_16(entrybuf + 6, ep->alpha);
  201594. png_save_uint_16(entrybuf + 8, ep->frequency);
  201595. }
  201596. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201597. }
  201598. #else
  201599. ep=spalette->entries;
  201600. for (i=0; i>spalette->nentries; i++)
  201601. {
  201602. if (spalette->depth == 8)
  201603. {
  201604. entrybuf[0] = (png_byte)ep[i].red;
  201605. entrybuf[1] = (png_byte)ep[i].green;
  201606. entrybuf[2] = (png_byte)ep[i].blue;
  201607. entrybuf[3] = (png_byte)ep[i].alpha;
  201608. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201609. }
  201610. else
  201611. {
  201612. png_save_uint_16(entrybuf + 0, ep[i].red);
  201613. png_save_uint_16(entrybuf + 2, ep[i].green);
  201614. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201615. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201616. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201617. }
  201618. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201619. }
  201620. #endif
  201621. png_write_chunk_end(png_ptr);
  201622. png_free(png_ptr, new_name);
  201623. }
  201624. #endif
  201625. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201626. /* write the sBIT chunk */
  201627. void /* PRIVATE */
  201628. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201629. {
  201630. #ifdef PNG_USE_LOCAL_ARRAYS
  201631. PNG_sBIT;
  201632. #endif
  201633. png_byte buf[4];
  201634. png_size_t size;
  201635. png_debug(1, "in png_write_sBIT\n");
  201636. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201637. if (color_type & PNG_COLOR_MASK_COLOR)
  201638. {
  201639. png_byte maxbits;
  201640. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201641. png_ptr->usr_bit_depth);
  201642. if (sbit->red == 0 || sbit->red > maxbits ||
  201643. sbit->green == 0 || sbit->green > maxbits ||
  201644. sbit->blue == 0 || sbit->blue > maxbits)
  201645. {
  201646. png_warning(png_ptr, "Invalid sBIT depth specified");
  201647. return;
  201648. }
  201649. buf[0] = sbit->red;
  201650. buf[1] = sbit->green;
  201651. buf[2] = sbit->blue;
  201652. size = 3;
  201653. }
  201654. else
  201655. {
  201656. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201657. {
  201658. png_warning(png_ptr, "Invalid sBIT depth specified");
  201659. return;
  201660. }
  201661. buf[0] = sbit->gray;
  201662. size = 1;
  201663. }
  201664. if (color_type & PNG_COLOR_MASK_ALPHA)
  201665. {
  201666. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201667. {
  201668. png_warning(png_ptr, "Invalid sBIT depth specified");
  201669. return;
  201670. }
  201671. buf[size++] = sbit->alpha;
  201672. }
  201673. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201674. }
  201675. #endif
  201676. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201677. /* write the cHRM chunk */
  201678. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201679. void /* PRIVATE */
  201680. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201681. double red_x, double red_y, double green_x, double green_y,
  201682. double blue_x, double blue_y)
  201683. {
  201684. #ifdef PNG_USE_LOCAL_ARRAYS
  201685. PNG_cHRM;
  201686. #endif
  201687. png_byte buf[32];
  201688. png_uint_32 itemp;
  201689. png_debug(1, "in png_write_cHRM\n");
  201690. /* each value is saved in 1/100,000ths */
  201691. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201692. white_x + white_y > 1.0)
  201693. {
  201694. png_warning(png_ptr, "Invalid cHRM white point specified");
  201695. #if !defined(PNG_NO_CONSOLE_IO)
  201696. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201697. #endif
  201698. return;
  201699. }
  201700. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201701. png_save_uint_32(buf, itemp);
  201702. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201703. png_save_uint_32(buf + 4, itemp);
  201704. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201705. {
  201706. png_warning(png_ptr, "Invalid cHRM red point specified");
  201707. return;
  201708. }
  201709. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201710. png_save_uint_32(buf + 8, itemp);
  201711. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201712. png_save_uint_32(buf + 12, itemp);
  201713. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201714. {
  201715. png_warning(png_ptr, "Invalid cHRM green point specified");
  201716. return;
  201717. }
  201718. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201719. png_save_uint_32(buf + 16, itemp);
  201720. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201721. png_save_uint_32(buf + 20, itemp);
  201722. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201723. {
  201724. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201725. return;
  201726. }
  201727. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201728. png_save_uint_32(buf + 24, itemp);
  201729. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201730. png_save_uint_32(buf + 28, itemp);
  201731. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201732. }
  201733. #endif
  201734. #ifdef PNG_FIXED_POINT_SUPPORTED
  201735. void /* PRIVATE */
  201736. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201737. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201738. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201739. png_fixed_point blue_y)
  201740. {
  201741. #ifdef PNG_USE_LOCAL_ARRAYS
  201742. PNG_cHRM;
  201743. #endif
  201744. png_byte buf[32];
  201745. png_debug(1, "in png_write_cHRM\n");
  201746. /* each value is saved in 1/100,000ths */
  201747. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201748. {
  201749. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201750. #if !defined(PNG_NO_CONSOLE_IO)
  201751. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201752. #endif
  201753. return;
  201754. }
  201755. png_save_uint_32(buf, (png_uint_32)white_x);
  201756. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201757. if (red_x + red_y > 100000L)
  201758. {
  201759. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201760. return;
  201761. }
  201762. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201763. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201764. if (green_x + green_y > 100000L)
  201765. {
  201766. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201767. return;
  201768. }
  201769. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201770. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201771. if (blue_x + blue_y > 100000L)
  201772. {
  201773. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201774. return;
  201775. }
  201776. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201777. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201778. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201779. }
  201780. #endif
  201781. #endif
  201782. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201783. /* write the tRNS chunk */
  201784. void /* PRIVATE */
  201785. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201786. int num_trans, int color_type)
  201787. {
  201788. #ifdef PNG_USE_LOCAL_ARRAYS
  201789. PNG_tRNS;
  201790. #endif
  201791. png_byte buf[6];
  201792. png_debug(1, "in png_write_tRNS\n");
  201793. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201794. {
  201795. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201796. {
  201797. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201798. return;
  201799. }
  201800. /* write the chunk out as it is */
  201801. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201802. }
  201803. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201804. {
  201805. /* one 16 bit value */
  201806. if(tran->gray >= (1 << png_ptr->bit_depth))
  201807. {
  201808. png_warning(png_ptr,
  201809. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201810. return;
  201811. }
  201812. png_save_uint_16(buf, tran->gray);
  201813. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201814. }
  201815. else if (color_type == PNG_COLOR_TYPE_RGB)
  201816. {
  201817. /* three 16 bit values */
  201818. png_save_uint_16(buf, tran->red);
  201819. png_save_uint_16(buf + 2, tran->green);
  201820. png_save_uint_16(buf + 4, tran->blue);
  201821. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201822. {
  201823. png_warning(png_ptr,
  201824. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201825. return;
  201826. }
  201827. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201828. }
  201829. else
  201830. {
  201831. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201832. }
  201833. }
  201834. #endif
  201835. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201836. /* write the background chunk */
  201837. void /* PRIVATE */
  201838. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201839. {
  201840. #ifdef PNG_USE_LOCAL_ARRAYS
  201841. PNG_bKGD;
  201842. #endif
  201843. png_byte buf[6];
  201844. png_debug(1, "in png_write_bKGD\n");
  201845. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201846. {
  201847. if (
  201848. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201849. (png_ptr->num_palette ||
  201850. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201851. #endif
  201852. back->index > png_ptr->num_palette)
  201853. {
  201854. png_warning(png_ptr, "Invalid background palette index");
  201855. return;
  201856. }
  201857. buf[0] = back->index;
  201858. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201859. }
  201860. else if (color_type & PNG_COLOR_MASK_COLOR)
  201861. {
  201862. png_save_uint_16(buf, back->red);
  201863. png_save_uint_16(buf + 2, back->green);
  201864. png_save_uint_16(buf + 4, back->blue);
  201865. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201866. {
  201867. png_warning(png_ptr,
  201868. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201869. return;
  201870. }
  201871. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201872. }
  201873. else
  201874. {
  201875. if(back->gray >= (1 << png_ptr->bit_depth))
  201876. {
  201877. png_warning(png_ptr,
  201878. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201879. return;
  201880. }
  201881. png_save_uint_16(buf, back->gray);
  201882. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201883. }
  201884. }
  201885. #endif
  201886. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201887. /* write the histogram */
  201888. void /* PRIVATE */
  201889. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201890. {
  201891. #ifdef PNG_USE_LOCAL_ARRAYS
  201892. PNG_hIST;
  201893. #endif
  201894. int i;
  201895. png_byte buf[3];
  201896. png_debug(1, "in png_write_hIST\n");
  201897. if (num_hist > (int)png_ptr->num_palette)
  201898. {
  201899. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201900. png_ptr->num_palette);
  201901. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201902. return;
  201903. }
  201904. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201905. for (i = 0; i < num_hist; i++)
  201906. {
  201907. png_save_uint_16(buf, hist[i]);
  201908. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201909. }
  201910. png_write_chunk_end(png_ptr);
  201911. }
  201912. #endif
  201913. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201914. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201915. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201916. * and if invalid, correct the keyword rather than discarding the entire
  201917. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201918. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201919. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201920. *
  201921. * The new_key is allocated to hold the corrected keyword and must be freed
  201922. * by the calling routine. This avoids problems with trying to write to
  201923. * static keywords without having to have duplicate copies of the strings.
  201924. */
  201925. png_size_t /* PRIVATE */
  201926. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201927. {
  201928. png_size_t key_len;
  201929. png_charp kp, dp;
  201930. int kflag;
  201931. int kwarn=0;
  201932. png_debug(1, "in png_check_keyword\n");
  201933. *new_key = NULL;
  201934. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201935. {
  201936. png_warning(png_ptr, "zero length keyword");
  201937. return ((png_size_t)0);
  201938. }
  201939. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201940. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201941. if (*new_key == NULL)
  201942. {
  201943. png_warning(png_ptr, "Out of memory while procesing keyword");
  201944. return ((png_size_t)0);
  201945. }
  201946. /* Replace non-printing characters with a blank and print a warning */
  201947. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201948. {
  201949. if ((png_byte)*kp < 0x20 ||
  201950. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201951. {
  201952. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201953. char msg[40];
  201954. png_snprintf(msg, 40,
  201955. "invalid keyword character 0x%02X", (png_byte)*kp);
  201956. png_warning(png_ptr, msg);
  201957. #else
  201958. png_warning(png_ptr, "invalid character in keyword");
  201959. #endif
  201960. *dp = ' ';
  201961. }
  201962. else
  201963. {
  201964. *dp = *kp;
  201965. }
  201966. }
  201967. *dp = '\0';
  201968. /* Remove any trailing white space. */
  201969. kp = *new_key + key_len - 1;
  201970. if (*kp == ' ')
  201971. {
  201972. png_warning(png_ptr, "trailing spaces removed from keyword");
  201973. while (*kp == ' ')
  201974. {
  201975. *(kp--) = '\0';
  201976. key_len--;
  201977. }
  201978. }
  201979. /* Remove any leading white space. */
  201980. kp = *new_key;
  201981. if (*kp == ' ')
  201982. {
  201983. png_warning(png_ptr, "leading spaces removed from keyword");
  201984. while (*kp == ' ')
  201985. {
  201986. kp++;
  201987. key_len--;
  201988. }
  201989. }
  201990. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201991. /* Remove multiple internal spaces. */
  201992. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201993. {
  201994. if (*kp == ' ' && kflag == 0)
  201995. {
  201996. *(dp++) = *kp;
  201997. kflag = 1;
  201998. }
  201999. else if (*kp == ' ')
  202000. {
  202001. key_len--;
  202002. kwarn=1;
  202003. }
  202004. else
  202005. {
  202006. *(dp++) = *kp;
  202007. kflag = 0;
  202008. }
  202009. }
  202010. *dp = '\0';
  202011. if(kwarn)
  202012. png_warning(png_ptr, "extra interior spaces removed from keyword");
  202013. if (key_len == 0)
  202014. {
  202015. png_free(png_ptr, *new_key);
  202016. *new_key=NULL;
  202017. png_warning(png_ptr, "Zero length keyword");
  202018. }
  202019. if (key_len > 79)
  202020. {
  202021. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  202022. new_key[79] = '\0';
  202023. key_len = 79;
  202024. }
  202025. return (key_len);
  202026. }
  202027. #endif
  202028. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  202029. /* write a tEXt chunk */
  202030. void /* PRIVATE */
  202031. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  202032. png_size_t text_len)
  202033. {
  202034. #ifdef PNG_USE_LOCAL_ARRAYS
  202035. PNG_tEXt;
  202036. #endif
  202037. png_size_t key_len;
  202038. png_charp new_key;
  202039. png_debug(1, "in png_write_tEXt\n");
  202040. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202041. {
  202042. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  202043. return;
  202044. }
  202045. if (text == NULL || *text == '\0')
  202046. text_len = 0;
  202047. else
  202048. text_len = png_strlen(text);
  202049. /* make sure we include the 0 after the key */
  202050. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  202051. /*
  202052. * We leave it to the application to meet PNG-1.0 requirements on the
  202053. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202054. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202055. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202056. */
  202057. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202058. if (text_len)
  202059. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  202060. png_write_chunk_end(png_ptr);
  202061. png_free(png_ptr, new_key);
  202062. }
  202063. #endif
  202064. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  202065. /* write a compressed text chunk */
  202066. void /* PRIVATE */
  202067. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  202068. png_size_t text_len, int compression)
  202069. {
  202070. #ifdef PNG_USE_LOCAL_ARRAYS
  202071. PNG_zTXt;
  202072. #endif
  202073. png_size_t key_len;
  202074. char buf[1];
  202075. png_charp new_key;
  202076. compression_state comp;
  202077. png_debug(1, "in png_write_zTXt\n");
  202078. comp.num_output_ptr = 0;
  202079. comp.max_output_ptr = 0;
  202080. comp.output_ptr = NULL;
  202081. comp.input = NULL;
  202082. comp.input_len = 0;
  202083. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202084. {
  202085. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  202086. return;
  202087. }
  202088. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  202089. {
  202090. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  202091. png_free(png_ptr, new_key);
  202092. return;
  202093. }
  202094. text_len = png_strlen(text);
  202095. /* compute the compressed data; do it now for the length */
  202096. text_len = png_text_compress(png_ptr, text, text_len, compression,
  202097. &comp);
  202098. /* write start of chunk */
  202099. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  202100. (key_len+text_len+2));
  202101. /* write key */
  202102. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202103. png_free(png_ptr, new_key);
  202104. buf[0] = (png_byte)compression;
  202105. /* write compression */
  202106. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  202107. /* write the compressed data */
  202108. png_write_compressed_data_out(png_ptr, &comp);
  202109. /* close the chunk */
  202110. png_write_chunk_end(png_ptr);
  202111. }
  202112. #endif
  202113. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  202114. /* write an iTXt chunk */
  202115. void /* PRIVATE */
  202116. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  202117. png_charp lang, png_charp lang_key, png_charp text)
  202118. {
  202119. #ifdef PNG_USE_LOCAL_ARRAYS
  202120. PNG_iTXt;
  202121. #endif
  202122. png_size_t lang_len, key_len, lang_key_len, text_len;
  202123. png_charp new_lang, new_key;
  202124. png_byte cbuf[2];
  202125. compression_state comp;
  202126. png_debug(1, "in png_write_iTXt\n");
  202127. comp.num_output_ptr = 0;
  202128. comp.max_output_ptr = 0;
  202129. comp.output_ptr = NULL;
  202130. comp.input = NULL;
  202131. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202132. {
  202133. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  202134. return;
  202135. }
  202136. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  202137. {
  202138. png_warning(png_ptr, "Empty language field in iTXt chunk");
  202139. new_lang = NULL;
  202140. lang_len = 0;
  202141. }
  202142. if (lang_key == NULL)
  202143. lang_key_len = 0;
  202144. else
  202145. lang_key_len = png_strlen(lang_key);
  202146. if (text == NULL)
  202147. text_len = 0;
  202148. else
  202149. text_len = png_strlen(text);
  202150. /* compute the compressed data; do it now for the length */
  202151. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202152. &comp);
  202153. /* make sure we include the compression flag, the compression byte,
  202154. * and the NULs after the key, lang, and lang_key parts */
  202155. png_write_chunk_start(png_ptr, png_iTXt,
  202156. (png_uint_32)(
  202157. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202158. + key_len
  202159. + lang_len
  202160. + lang_key_len
  202161. + text_len));
  202162. /*
  202163. * We leave it to the application to meet PNG-1.0 requirements on the
  202164. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202165. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202166. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202167. */
  202168. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202169. /* set the compression flag */
  202170. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202171. compression == PNG_TEXT_COMPRESSION_NONE)
  202172. cbuf[0] = 0;
  202173. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202174. cbuf[0] = 1;
  202175. /* set the compression method */
  202176. cbuf[1] = 0;
  202177. png_write_chunk_data(png_ptr, cbuf, 2);
  202178. cbuf[0] = 0;
  202179. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202180. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202181. png_write_compressed_data_out(png_ptr, &comp);
  202182. png_write_chunk_end(png_ptr);
  202183. png_free(png_ptr, new_key);
  202184. if (new_lang)
  202185. png_free(png_ptr, new_lang);
  202186. }
  202187. #endif
  202188. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202189. /* write the oFFs chunk */
  202190. void /* PRIVATE */
  202191. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202192. int unit_type)
  202193. {
  202194. #ifdef PNG_USE_LOCAL_ARRAYS
  202195. PNG_oFFs;
  202196. #endif
  202197. png_byte buf[9];
  202198. png_debug(1, "in png_write_oFFs\n");
  202199. if (unit_type >= PNG_OFFSET_LAST)
  202200. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202201. png_save_int_32(buf, x_offset);
  202202. png_save_int_32(buf + 4, y_offset);
  202203. buf[8] = (png_byte)unit_type;
  202204. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202205. }
  202206. #endif
  202207. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202208. /* write the pCAL chunk (described in the PNG extensions document) */
  202209. void /* PRIVATE */
  202210. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202211. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202212. {
  202213. #ifdef PNG_USE_LOCAL_ARRAYS
  202214. PNG_pCAL;
  202215. #endif
  202216. png_size_t purpose_len, units_len, total_len;
  202217. png_uint_32p params_len;
  202218. png_byte buf[10];
  202219. png_charp new_purpose;
  202220. int i;
  202221. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202222. if (type >= PNG_EQUATION_LAST)
  202223. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202224. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202225. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202226. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202227. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202228. total_len = purpose_len + units_len + 10;
  202229. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202230. *png_sizeof(png_uint_32)));
  202231. /* Find the length of each parameter, making sure we don't count the
  202232. null terminator for the last parameter. */
  202233. for (i = 0; i < nparams; i++)
  202234. {
  202235. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202236. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202237. total_len += (png_size_t)params_len[i];
  202238. }
  202239. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202240. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202241. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202242. png_save_int_32(buf, X0);
  202243. png_save_int_32(buf + 4, X1);
  202244. buf[8] = (png_byte)type;
  202245. buf[9] = (png_byte)nparams;
  202246. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202247. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202248. png_free(png_ptr, new_purpose);
  202249. for (i = 0; i < nparams; i++)
  202250. {
  202251. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202252. (png_size_t)params_len[i]);
  202253. }
  202254. png_free(png_ptr, params_len);
  202255. png_write_chunk_end(png_ptr);
  202256. }
  202257. #endif
  202258. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202259. /* write the sCAL chunk */
  202260. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202261. void /* PRIVATE */
  202262. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202263. {
  202264. #ifdef PNG_USE_LOCAL_ARRAYS
  202265. PNG_sCAL;
  202266. #endif
  202267. char buf[64];
  202268. png_size_t total_len;
  202269. png_debug(1, "in png_write_sCAL\n");
  202270. buf[0] = (char)unit;
  202271. #if defined(_WIN32_WCE)
  202272. /* sprintf() function is not supported on WindowsCE */
  202273. {
  202274. wchar_t wc_buf[32];
  202275. size_t wc_len;
  202276. swprintf(wc_buf, TEXT("%12.12e"), width);
  202277. wc_len = wcslen(wc_buf);
  202278. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202279. total_len = wc_len + 2;
  202280. swprintf(wc_buf, TEXT("%12.12e"), height);
  202281. wc_len = wcslen(wc_buf);
  202282. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202283. NULL, NULL);
  202284. total_len += wc_len;
  202285. }
  202286. #else
  202287. png_snprintf(buf + 1, 63, "%12.12e", width);
  202288. total_len = 1 + png_strlen(buf + 1) + 1;
  202289. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202290. total_len += png_strlen(buf + total_len);
  202291. #endif
  202292. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202293. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202294. }
  202295. #else
  202296. #ifdef PNG_FIXED_POINT_SUPPORTED
  202297. void /* PRIVATE */
  202298. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202299. png_charp height)
  202300. {
  202301. #ifdef PNG_USE_LOCAL_ARRAYS
  202302. PNG_sCAL;
  202303. #endif
  202304. png_byte buf[64];
  202305. png_size_t wlen, hlen, total_len;
  202306. png_debug(1, "in png_write_sCAL_s\n");
  202307. wlen = png_strlen(width);
  202308. hlen = png_strlen(height);
  202309. total_len = wlen + hlen + 2;
  202310. if (total_len > 64)
  202311. {
  202312. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202313. return;
  202314. }
  202315. buf[0] = (png_byte)unit;
  202316. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202317. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202318. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202319. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202320. }
  202321. #endif
  202322. #endif
  202323. #endif
  202324. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202325. /* write the pHYs chunk */
  202326. void /* PRIVATE */
  202327. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202328. png_uint_32 y_pixels_per_unit,
  202329. int unit_type)
  202330. {
  202331. #ifdef PNG_USE_LOCAL_ARRAYS
  202332. PNG_pHYs;
  202333. #endif
  202334. png_byte buf[9];
  202335. png_debug(1, "in png_write_pHYs\n");
  202336. if (unit_type >= PNG_RESOLUTION_LAST)
  202337. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202338. png_save_uint_32(buf, x_pixels_per_unit);
  202339. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202340. buf[8] = (png_byte)unit_type;
  202341. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202342. }
  202343. #endif
  202344. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202345. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202346. * or png_convert_from_time_t(), or fill in the structure yourself.
  202347. */
  202348. void /* PRIVATE */
  202349. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202350. {
  202351. #ifdef PNG_USE_LOCAL_ARRAYS
  202352. PNG_tIME;
  202353. #endif
  202354. png_byte buf[7];
  202355. png_debug(1, "in png_write_tIME\n");
  202356. if (mod_time->month > 12 || mod_time->month < 1 ||
  202357. mod_time->day > 31 || mod_time->day < 1 ||
  202358. mod_time->hour > 23 || mod_time->second > 60)
  202359. {
  202360. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202361. return;
  202362. }
  202363. png_save_uint_16(buf, mod_time->year);
  202364. buf[2] = mod_time->month;
  202365. buf[3] = mod_time->day;
  202366. buf[4] = mod_time->hour;
  202367. buf[5] = mod_time->minute;
  202368. buf[6] = mod_time->second;
  202369. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202370. }
  202371. #endif
  202372. /* initializes the row writing capability of libpng */
  202373. void /* PRIVATE */
  202374. png_write_start_row(png_structp png_ptr)
  202375. {
  202376. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202377. #ifdef PNG_USE_LOCAL_ARRAYS
  202378. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202379. /* start of interlace block */
  202380. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202381. /* offset to next interlace block */
  202382. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202383. /* start of interlace block in the y direction */
  202384. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202385. /* offset to next interlace block in the y direction */
  202386. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202387. #endif
  202388. #endif
  202389. png_size_t buf_size;
  202390. png_debug(1, "in png_write_start_row\n");
  202391. buf_size = (png_size_t)(PNG_ROWBYTES(
  202392. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202393. /* set up row buffer */
  202394. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202395. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202396. #ifndef PNG_NO_WRITE_FILTERING
  202397. /* set up filtering buffer, if using this filter */
  202398. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202399. {
  202400. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202401. (png_ptr->rowbytes + 1));
  202402. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202403. }
  202404. /* We only need to keep the previous row if we are using one of these. */
  202405. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202406. {
  202407. /* set up previous row buffer */
  202408. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202409. png_memset(png_ptr->prev_row, 0, buf_size);
  202410. if (png_ptr->do_filter & PNG_FILTER_UP)
  202411. {
  202412. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202413. (png_ptr->rowbytes + 1));
  202414. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202415. }
  202416. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202417. {
  202418. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202419. (png_ptr->rowbytes + 1));
  202420. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202421. }
  202422. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202423. {
  202424. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202425. (png_ptr->rowbytes + 1));
  202426. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202427. }
  202428. #endif /* PNG_NO_WRITE_FILTERING */
  202429. }
  202430. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202431. /* if interlaced, we need to set up width and height of pass */
  202432. if (png_ptr->interlaced)
  202433. {
  202434. if (!(png_ptr->transformations & PNG_INTERLACE))
  202435. {
  202436. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202437. png_pass_ystart[0]) / png_pass_yinc[0];
  202438. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202439. png_pass_start[0]) / png_pass_inc[0];
  202440. }
  202441. else
  202442. {
  202443. png_ptr->num_rows = png_ptr->height;
  202444. png_ptr->usr_width = png_ptr->width;
  202445. }
  202446. }
  202447. else
  202448. #endif
  202449. {
  202450. png_ptr->num_rows = png_ptr->height;
  202451. png_ptr->usr_width = png_ptr->width;
  202452. }
  202453. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202454. png_ptr->zstream.next_out = png_ptr->zbuf;
  202455. }
  202456. /* Internal use only. Called when finished processing a row of data. */
  202457. void /* PRIVATE */
  202458. png_write_finish_row(png_structp png_ptr)
  202459. {
  202460. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202461. #ifdef PNG_USE_LOCAL_ARRAYS
  202462. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202463. /* start of interlace block */
  202464. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202465. /* offset to next interlace block */
  202466. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202467. /* start of interlace block in the y direction */
  202468. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202469. /* offset to next interlace block in the y direction */
  202470. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202471. #endif
  202472. #endif
  202473. int ret;
  202474. png_debug(1, "in png_write_finish_row\n");
  202475. /* next row */
  202476. png_ptr->row_number++;
  202477. /* see if we are done */
  202478. if (png_ptr->row_number < png_ptr->num_rows)
  202479. return;
  202480. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202481. /* if interlaced, go to next pass */
  202482. if (png_ptr->interlaced)
  202483. {
  202484. png_ptr->row_number = 0;
  202485. if (png_ptr->transformations & PNG_INTERLACE)
  202486. {
  202487. png_ptr->pass++;
  202488. }
  202489. else
  202490. {
  202491. /* loop until we find a non-zero width or height pass */
  202492. do
  202493. {
  202494. png_ptr->pass++;
  202495. if (png_ptr->pass >= 7)
  202496. break;
  202497. png_ptr->usr_width = (png_ptr->width +
  202498. png_pass_inc[png_ptr->pass] - 1 -
  202499. png_pass_start[png_ptr->pass]) /
  202500. png_pass_inc[png_ptr->pass];
  202501. png_ptr->num_rows = (png_ptr->height +
  202502. png_pass_yinc[png_ptr->pass] - 1 -
  202503. png_pass_ystart[png_ptr->pass]) /
  202504. png_pass_yinc[png_ptr->pass];
  202505. if (png_ptr->transformations & PNG_INTERLACE)
  202506. break;
  202507. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202508. }
  202509. /* reset the row above the image for the next pass */
  202510. if (png_ptr->pass < 7)
  202511. {
  202512. if (png_ptr->prev_row != NULL)
  202513. png_memset(png_ptr->prev_row, 0,
  202514. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202515. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202516. return;
  202517. }
  202518. }
  202519. #endif
  202520. /* if we get here, we've just written the last row, so we need
  202521. to flush the compressor */
  202522. do
  202523. {
  202524. /* tell the compressor we are done */
  202525. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202526. /* check for an error */
  202527. if (ret == Z_OK)
  202528. {
  202529. /* check to see if we need more room */
  202530. if (!(png_ptr->zstream.avail_out))
  202531. {
  202532. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202533. png_ptr->zstream.next_out = png_ptr->zbuf;
  202534. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202535. }
  202536. }
  202537. else if (ret != Z_STREAM_END)
  202538. {
  202539. if (png_ptr->zstream.msg != NULL)
  202540. png_error(png_ptr, png_ptr->zstream.msg);
  202541. else
  202542. png_error(png_ptr, "zlib error");
  202543. }
  202544. } while (ret != Z_STREAM_END);
  202545. /* write any extra space */
  202546. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202547. {
  202548. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202549. png_ptr->zstream.avail_out);
  202550. }
  202551. deflateReset(&png_ptr->zstream);
  202552. png_ptr->zstream.data_type = Z_BINARY;
  202553. }
  202554. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202555. /* Pick out the correct pixels for the interlace pass.
  202556. * The basic idea here is to go through the row with a source
  202557. * pointer and a destination pointer (sp and dp), and copy the
  202558. * correct pixels for the pass. As the row gets compacted,
  202559. * sp will always be >= dp, so we should never overwrite anything.
  202560. * See the default: case for the easiest code to understand.
  202561. */
  202562. void /* PRIVATE */
  202563. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202564. {
  202565. #ifdef PNG_USE_LOCAL_ARRAYS
  202566. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202567. /* start of interlace block */
  202568. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202569. /* offset to next interlace block */
  202570. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202571. #endif
  202572. png_debug(1, "in png_do_write_interlace\n");
  202573. /* we don't have to do anything on the last pass (6) */
  202574. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202575. if (row != NULL && row_info != NULL && pass < 6)
  202576. #else
  202577. if (pass < 6)
  202578. #endif
  202579. {
  202580. /* each pixel depth is handled separately */
  202581. switch (row_info->pixel_depth)
  202582. {
  202583. case 1:
  202584. {
  202585. png_bytep sp;
  202586. png_bytep dp;
  202587. int shift;
  202588. int d;
  202589. int value;
  202590. png_uint_32 i;
  202591. png_uint_32 row_width = row_info->width;
  202592. dp = row;
  202593. d = 0;
  202594. shift = 7;
  202595. for (i = png_pass_start[pass]; i < row_width;
  202596. i += png_pass_inc[pass])
  202597. {
  202598. sp = row + (png_size_t)(i >> 3);
  202599. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202600. d |= (value << shift);
  202601. if (shift == 0)
  202602. {
  202603. shift = 7;
  202604. *dp++ = (png_byte)d;
  202605. d = 0;
  202606. }
  202607. else
  202608. shift--;
  202609. }
  202610. if (shift != 7)
  202611. *dp = (png_byte)d;
  202612. break;
  202613. }
  202614. case 2:
  202615. {
  202616. png_bytep sp;
  202617. png_bytep dp;
  202618. int shift;
  202619. int d;
  202620. int value;
  202621. png_uint_32 i;
  202622. png_uint_32 row_width = row_info->width;
  202623. dp = row;
  202624. shift = 6;
  202625. d = 0;
  202626. for (i = png_pass_start[pass]; i < row_width;
  202627. i += png_pass_inc[pass])
  202628. {
  202629. sp = row + (png_size_t)(i >> 2);
  202630. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202631. d |= (value << shift);
  202632. if (shift == 0)
  202633. {
  202634. shift = 6;
  202635. *dp++ = (png_byte)d;
  202636. d = 0;
  202637. }
  202638. else
  202639. shift -= 2;
  202640. }
  202641. if (shift != 6)
  202642. *dp = (png_byte)d;
  202643. break;
  202644. }
  202645. case 4:
  202646. {
  202647. png_bytep sp;
  202648. png_bytep dp;
  202649. int shift;
  202650. int d;
  202651. int value;
  202652. png_uint_32 i;
  202653. png_uint_32 row_width = row_info->width;
  202654. dp = row;
  202655. shift = 4;
  202656. d = 0;
  202657. for (i = png_pass_start[pass]; i < row_width;
  202658. i += png_pass_inc[pass])
  202659. {
  202660. sp = row + (png_size_t)(i >> 1);
  202661. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202662. d |= (value << shift);
  202663. if (shift == 0)
  202664. {
  202665. shift = 4;
  202666. *dp++ = (png_byte)d;
  202667. d = 0;
  202668. }
  202669. else
  202670. shift -= 4;
  202671. }
  202672. if (shift != 4)
  202673. *dp = (png_byte)d;
  202674. break;
  202675. }
  202676. default:
  202677. {
  202678. png_bytep sp;
  202679. png_bytep dp;
  202680. png_uint_32 i;
  202681. png_uint_32 row_width = row_info->width;
  202682. png_size_t pixel_bytes;
  202683. /* start at the beginning */
  202684. dp = row;
  202685. /* find out how many bytes each pixel takes up */
  202686. pixel_bytes = (row_info->pixel_depth >> 3);
  202687. /* loop through the row, only looking at the pixels that
  202688. matter */
  202689. for (i = png_pass_start[pass]; i < row_width;
  202690. i += png_pass_inc[pass])
  202691. {
  202692. /* find out where the original pixel is */
  202693. sp = row + (png_size_t)i * pixel_bytes;
  202694. /* move the pixel */
  202695. if (dp != sp)
  202696. png_memcpy(dp, sp, pixel_bytes);
  202697. /* next pixel */
  202698. dp += pixel_bytes;
  202699. }
  202700. break;
  202701. }
  202702. }
  202703. /* set new row width */
  202704. row_info->width = (row_info->width +
  202705. png_pass_inc[pass] - 1 -
  202706. png_pass_start[pass]) /
  202707. png_pass_inc[pass];
  202708. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202709. row_info->width);
  202710. }
  202711. }
  202712. #endif
  202713. /* This filters the row, chooses which filter to use, if it has not already
  202714. * been specified by the application, and then writes the row out with the
  202715. * chosen filter.
  202716. */
  202717. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202718. #define PNG_HISHIFT 10
  202719. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202720. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202721. void /* PRIVATE */
  202722. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202723. {
  202724. png_bytep best_row;
  202725. #ifndef PNG_NO_WRITE_FILTER
  202726. png_bytep prev_row, row_buf;
  202727. png_uint_32 mins, bpp;
  202728. png_byte filter_to_do = png_ptr->do_filter;
  202729. png_uint_32 row_bytes = row_info->rowbytes;
  202730. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202731. int num_p_filters = (int)png_ptr->num_prev_filters;
  202732. #endif
  202733. png_debug(1, "in png_write_find_filter\n");
  202734. /* find out how many bytes offset each pixel is */
  202735. bpp = (row_info->pixel_depth + 7) >> 3;
  202736. prev_row = png_ptr->prev_row;
  202737. #endif
  202738. best_row = png_ptr->row_buf;
  202739. #ifndef PNG_NO_WRITE_FILTER
  202740. row_buf = best_row;
  202741. mins = PNG_MAXSUM;
  202742. /* The prediction method we use is to find which method provides the
  202743. * smallest value when summing the absolute values of the distances
  202744. * from zero, using anything >= 128 as negative numbers. This is known
  202745. * as the "minimum sum of absolute differences" heuristic. Other
  202746. * heuristics are the "weighted minimum sum of absolute differences"
  202747. * (experimental and can in theory improve compression), and the "zlib
  202748. * predictive" method (not implemented yet), which does test compressions
  202749. * of lines using different filter methods, and then chooses the
  202750. * (series of) filter(s) that give minimum compressed data size (VERY
  202751. * computationally expensive).
  202752. *
  202753. * GRR 980525: consider also
  202754. * (1) minimum sum of absolute differences from running average (i.e.,
  202755. * keep running sum of non-absolute differences & count of bytes)
  202756. * [track dispersion, too? restart average if dispersion too large?]
  202757. * (1b) minimum sum of absolute differences from sliding average, probably
  202758. * with window size <= deflate window (usually 32K)
  202759. * (2) minimum sum of squared differences from zero or running average
  202760. * (i.e., ~ root-mean-square approach)
  202761. */
  202762. /* We don't need to test the 'no filter' case if this is the only filter
  202763. * that has been chosen, as it doesn't actually do anything to the data.
  202764. */
  202765. if ((filter_to_do & PNG_FILTER_NONE) &&
  202766. filter_to_do != PNG_FILTER_NONE)
  202767. {
  202768. png_bytep rp;
  202769. png_uint_32 sum = 0;
  202770. png_uint_32 i;
  202771. int v;
  202772. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202773. {
  202774. v = *rp;
  202775. sum += (v < 128) ? v : 256 - v;
  202776. }
  202777. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202778. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202779. {
  202780. png_uint_32 sumhi, sumlo;
  202781. int j;
  202782. sumlo = sum & PNG_LOMASK;
  202783. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202784. /* Reduce the sum if we match any of the previous rows */
  202785. for (j = 0; j < num_p_filters; j++)
  202786. {
  202787. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202788. {
  202789. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202790. PNG_WEIGHT_SHIFT;
  202791. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202792. PNG_WEIGHT_SHIFT;
  202793. }
  202794. }
  202795. /* Factor in the cost of this filter (this is here for completeness,
  202796. * but it makes no sense to have a "cost" for the NONE filter, as
  202797. * it has the minimum possible computational cost - none).
  202798. */
  202799. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202800. PNG_COST_SHIFT;
  202801. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202802. PNG_COST_SHIFT;
  202803. if (sumhi > PNG_HIMASK)
  202804. sum = PNG_MAXSUM;
  202805. else
  202806. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202807. }
  202808. #endif
  202809. mins = sum;
  202810. }
  202811. /* sub filter */
  202812. if (filter_to_do == PNG_FILTER_SUB)
  202813. /* it's the only filter so no testing is needed */
  202814. {
  202815. png_bytep rp, lp, dp;
  202816. png_uint_32 i;
  202817. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202818. i++, rp++, dp++)
  202819. {
  202820. *dp = *rp;
  202821. }
  202822. for (lp = row_buf + 1; i < row_bytes;
  202823. i++, rp++, lp++, dp++)
  202824. {
  202825. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202826. }
  202827. best_row = png_ptr->sub_row;
  202828. }
  202829. else if (filter_to_do & PNG_FILTER_SUB)
  202830. {
  202831. png_bytep rp, dp, lp;
  202832. png_uint_32 sum = 0, lmins = mins;
  202833. png_uint_32 i;
  202834. int v;
  202835. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202836. /* We temporarily increase the "minimum sum" by the factor we
  202837. * would reduce the sum of this filter, so that we can do the
  202838. * early exit comparison without scaling the sum each time.
  202839. */
  202840. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202841. {
  202842. int j;
  202843. png_uint_32 lmhi, lmlo;
  202844. lmlo = lmins & PNG_LOMASK;
  202845. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202846. for (j = 0; j < num_p_filters; j++)
  202847. {
  202848. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202849. {
  202850. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202851. PNG_WEIGHT_SHIFT;
  202852. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202853. PNG_WEIGHT_SHIFT;
  202854. }
  202855. }
  202856. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202857. PNG_COST_SHIFT;
  202858. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202859. PNG_COST_SHIFT;
  202860. if (lmhi > PNG_HIMASK)
  202861. lmins = PNG_MAXSUM;
  202862. else
  202863. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202864. }
  202865. #endif
  202866. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202867. i++, rp++, dp++)
  202868. {
  202869. v = *dp = *rp;
  202870. sum += (v < 128) ? v : 256 - v;
  202871. }
  202872. for (lp = row_buf + 1; i < row_bytes;
  202873. i++, rp++, lp++, dp++)
  202874. {
  202875. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202876. sum += (v < 128) ? v : 256 - v;
  202877. if (sum > lmins) /* We are already worse, don't continue. */
  202878. break;
  202879. }
  202880. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202881. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202882. {
  202883. int j;
  202884. png_uint_32 sumhi, sumlo;
  202885. sumlo = sum & PNG_LOMASK;
  202886. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202887. for (j = 0; j < num_p_filters; j++)
  202888. {
  202889. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202890. {
  202891. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202892. PNG_WEIGHT_SHIFT;
  202893. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202894. PNG_WEIGHT_SHIFT;
  202895. }
  202896. }
  202897. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202898. PNG_COST_SHIFT;
  202899. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202900. PNG_COST_SHIFT;
  202901. if (sumhi > PNG_HIMASK)
  202902. sum = PNG_MAXSUM;
  202903. else
  202904. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202905. }
  202906. #endif
  202907. if (sum < mins)
  202908. {
  202909. mins = sum;
  202910. best_row = png_ptr->sub_row;
  202911. }
  202912. }
  202913. /* up filter */
  202914. if (filter_to_do == PNG_FILTER_UP)
  202915. {
  202916. png_bytep rp, dp, pp;
  202917. png_uint_32 i;
  202918. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202919. pp = prev_row + 1; i < row_bytes;
  202920. i++, rp++, pp++, dp++)
  202921. {
  202922. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202923. }
  202924. best_row = png_ptr->up_row;
  202925. }
  202926. else if (filter_to_do & PNG_FILTER_UP)
  202927. {
  202928. png_bytep rp, dp, pp;
  202929. png_uint_32 sum = 0, lmins = mins;
  202930. png_uint_32 i;
  202931. int v;
  202932. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202933. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202934. {
  202935. int j;
  202936. png_uint_32 lmhi, lmlo;
  202937. lmlo = lmins & PNG_LOMASK;
  202938. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202939. for (j = 0; j < num_p_filters; j++)
  202940. {
  202941. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202942. {
  202943. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202944. PNG_WEIGHT_SHIFT;
  202945. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202946. PNG_WEIGHT_SHIFT;
  202947. }
  202948. }
  202949. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202950. PNG_COST_SHIFT;
  202951. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202952. PNG_COST_SHIFT;
  202953. if (lmhi > PNG_HIMASK)
  202954. lmins = PNG_MAXSUM;
  202955. else
  202956. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202957. }
  202958. #endif
  202959. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202960. pp = prev_row + 1; i < row_bytes; i++)
  202961. {
  202962. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202963. sum += (v < 128) ? v : 256 - v;
  202964. if (sum > lmins) /* We are already worse, don't continue. */
  202965. break;
  202966. }
  202967. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202968. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202969. {
  202970. int j;
  202971. png_uint_32 sumhi, sumlo;
  202972. sumlo = sum & PNG_LOMASK;
  202973. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202974. for (j = 0; j < num_p_filters; j++)
  202975. {
  202976. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202977. {
  202978. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202979. PNG_WEIGHT_SHIFT;
  202980. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202981. PNG_WEIGHT_SHIFT;
  202982. }
  202983. }
  202984. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202985. PNG_COST_SHIFT;
  202986. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202987. PNG_COST_SHIFT;
  202988. if (sumhi > PNG_HIMASK)
  202989. sum = PNG_MAXSUM;
  202990. else
  202991. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202992. }
  202993. #endif
  202994. if (sum < mins)
  202995. {
  202996. mins = sum;
  202997. best_row = png_ptr->up_row;
  202998. }
  202999. }
  203000. /* avg filter */
  203001. if (filter_to_do == PNG_FILTER_AVG)
  203002. {
  203003. png_bytep rp, dp, pp, lp;
  203004. png_uint_32 i;
  203005. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203006. pp = prev_row + 1; i < bpp; i++)
  203007. {
  203008. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203009. }
  203010. for (lp = row_buf + 1; i < row_bytes; i++)
  203011. {
  203012. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  203013. & 0xff);
  203014. }
  203015. best_row = png_ptr->avg_row;
  203016. }
  203017. else if (filter_to_do & PNG_FILTER_AVG)
  203018. {
  203019. png_bytep rp, dp, pp, lp;
  203020. png_uint_32 sum = 0, lmins = mins;
  203021. png_uint_32 i;
  203022. int v;
  203023. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203024. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203025. {
  203026. int j;
  203027. png_uint_32 lmhi, lmlo;
  203028. lmlo = lmins & PNG_LOMASK;
  203029. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203030. for (j = 0; j < num_p_filters; j++)
  203031. {
  203032. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  203033. {
  203034. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203035. PNG_WEIGHT_SHIFT;
  203036. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203037. PNG_WEIGHT_SHIFT;
  203038. }
  203039. }
  203040. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203041. PNG_COST_SHIFT;
  203042. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203043. PNG_COST_SHIFT;
  203044. if (lmhi > PNG_HIMASK)
  203045. lmins = PNG_MAXSUM;
  203046. else
  203047. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203048. }
  203049. #endif
  203050. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203051. pp = prev_row + 1; i < bpp; i++)
  203052. {
  203053. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203054. sum += (v < 128) ? v : 256 - v;
  203055. }
  203056. for (lp = row_buf + 1; i < row_bytes; i++)
  203057. {
  203058. v = *dp++ =
  203059. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  203060. sum += (v < 128) ? v : 256 - v;
  203061. if (sum > lmins) /* We are already worse, don't continue. */
  203062. break;
  203063. }
  203064. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203065. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203066. {
  203067. int j;
  203068. png_uint_32 sumhi, sumlo;
  203069. sumlo = sum & PNG_LOMASK;
  203070. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203071. for (j = 0; j < num_p_filters; j++)
  203072. {
  203073. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  203074. {
  203075. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203076. PNG_WEIGHT_SHIFT;
  203077. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203078. PNG_WEIGHT_SHIFT;
  203079. }
  203080. }
  203081. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203082. PNG_COST_SHIFT;
  203083. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203084. PNG_COST_SHIFT;
  203085. if (sumhi > PNG_HIMASK)
  203086. sum = PNG_MAXSUM;
  203087. else
  203088. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203089. }
  203090. #endif
  203091. if (sum < mins)
  203092. {
  203093. mins = sum;
  203094. best_row = png_ptr->avg_row;
  203095. }
  203096. }
  203097. /* Paeth filter */
  203098. if (filter_to_do == PNG_FILTER_PAETH)
  203099. {
  203100. png_bytep rp, dp, pp, cp, lp;
  203101. png_uint_32 i;
  203102. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203103. pp = prev_row + 1; i < bpp; i++)
  203104. {
  203105. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203106. }
  203107. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203108. {
  203109. int a, b, c, pa, pb, pc, p;
  203110. b = *pp++;
  203111. c = *cp++;
  203112. a = *lp++;
  203113. p = b - c;
  203114. pc = a - c;
  203115. #ifdef PNG_USE_ABS
  203116. pa = abs(p);
  203117. pb = abs(pc);
  203118. pc = abs(p + pc);
  203119. #else
  203120. pa = p < 0 ? -p : p;
  203121. pb = pc < 0 ? -pc : pc;
  203122. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203123. #endif
  203124. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203125. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203126. }
  203127. best_row = png_ptr->paeth_row;
  203128. }
  203129. else if (filter_to_do & PNG_FILTER_PAETH)
  203130. {
  203131. png_bytep rp, dp, pp, cp, lp;
  203132. png_uint_32 sum = 0, lmins = mins;
  203133. png_uint_32 i;
  203134. int v;
  203135. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203136. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203137. {
  203138. int j;
  203139. png_uint_32 lmhi, lmlo;
  203140. lmlo = lmins & PNG_LOMASK;
  203141. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203142. for (j = 0; j < num_p_filters; j++)
  203143. {
  203144. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203145. {
  203146. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203147. PNG_WEIGHT_SHIFT;
  203148. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203149. PNG_WEIGHT_SHIFT;
  203150. }
  203151. }
  203152. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203153. PNG_COST_SHIFT;
  203154. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203155. PNG_COST_SHIFT;
  203156. if (lmhi > PNG_HIMASK)
  203157. lmins = PNG_MAXSUM;
  203158. else
  203159. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203160. }
  203161. #endif
  203162. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203163. pp = prev_row + 1; i < bpp; i++)
  203164. {
  203165. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203166. sum += (v < 128) ? v : 256 - v;
  203167. }
  203168. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203169. {
  203170. int a, b, c, pa, pb, pc, p;
  203171. b = *pp++;
  203172. c = *cp++;
  203173. a = *lp++;
  203174. #ifndef PNG_SLOW_PAETH
  203175. p = b - c;
  203176. pc = a - c;
  203177. #ifdef PNG_USE_ABS
  203178. pa = abs(p);
  203179. pb = abs(pc);
  203180. pc = abs(p + pc);
  203181. #else
  203182. pa = p < 0 ? -p : p;
  203183. pb = pc < 0 ? -pc : pc;
  203184. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203185. #endif
  203186. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203187. #else /* PNG_SLOW_PAETH */
  203188. p = a + b - c;
  203189. pa = abs(p - a);
  203190. pb = abs(p - b);
  203191. pc = abs(p - c);
  203192. if (pa <= pb && pa <= pc)
  203193. p = a;
  203194. else if (pb <= pc)
  203195. p = b;
  203196. else
  203197. p = c;
  203198. #endif /* PNG_SLOW_PAETH */
  203199. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203200. sum += (v < 128) ? v : 256 - v;
  203201. if (sum > lmins) /* We are already worse, don't continue. */
  203202. break;
  203203. }
  203204. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203205. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203206. {
  203207. int j;
  203208. png_uint_32 sumhi, sumlo;
  203209. sumlo = sum & PNG_LOMASK;
  203210. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203211. for (j = 0; j < num_p_filters; j++)
  203212. {
  203213. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203214. {
  203215. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203216. PNG_WEIGHT_SHIFT;
  203217. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203218. PNG_WEIGHT_SHIFT;
  203219. }
  203220. }
  203221. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203222. PNG_COST_SHIFT;
  203223. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203224. PNG_COST_SHIFT;
  203225. if (sumhi > PNG_HIMASK)
  203226. sum = PNG_MAXSUM;
  203227. else
  203228. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203229. }
  203230. #endif
  203231. if (sum < mins)
  203232. {
  203233. best_row = png_ptr->paeth_row;
  203234. }
  203235. }
  203236. #endif /* PNG_NO_WRITE_FILTER */
  203237. /* Do the actual writing of the filtered row data from the chosen filter. */
  203238. png_write_filtered_row(png_ptr, best_row);
  203239. #ifndef PNG_NO_WRITE_FILTER
  203240. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203241. /* Save the type of filter we picked this time for future calculations */
  203242. if (png_ptr->num_prev_filters > 0)
  203243. {
  203244. int j;
  203245. for (j = 1; j < num_p_filters; j++)
  203246. {
  203247. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203248. }
  203249. png_ptr->prev_filters[j] = best_row[0];
  203250. }
  203251. #endif
  203252. #endif /* PNG_NO_WRITE_FILTER */
  203253. }
  203254. /* Do the actual writing of a previously filtered row. */
  203255. void /* PRIVATE */
  203256. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203257. {
  203258. png_debug(1, "in png_write_filtered_row\n");
  203259. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203260. /* set up the zlib input buffer */
  203261. png_ptr->zstream.next_in = filtered_row;
  203262. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203263. /* repeat until we have compressed all the data */
  203264. do
  203265. {
  203266. int ret; /* return of zlib */
  203267. /* compress the data */
  203268. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203269. /* check for compression errors */
  203270. if (ret != Z_OK)
  203271. {
  203272. if (png_ptr->zstream.msg != NULL)
  203273. png_error(png_ptr, png_ptr->zstream.msg);
  203274. else
  203275. png_error(png_ptr, "zlib error");
  203276. }
  203277. /* see if it is time to write another IDAT */
  203278. if (!(png_ptr->zstream.avail_out))
  203279. {
  203280. /* write the IDAT and reset the zlib output buffer */
  203281. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203282. png_ptr->zstream.next_out = png_ptr->zbuf;
  203283. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203284. }
  203285. /* repeat until all data has been compressed */
  203286. } while (png_ptr->zstream.avail_in);
  203287. /* swap the current and previous rows */
  203288. if (png_ptr->prev_row != NULL)
  203289. {
  203290. png_bytep tptr;
  203291. tptr = png_ptr->prev_row;
  203292. png_ptr->prev_row = png_ptr->row_buf;
  203293. png_ptr->row_buf = tptr;
  203294. }
  203295. /* finish row - updates counters and flushes zlib if last row */
  203296. png_write_finish_row(png_ptr);
  203297. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203298. png_ptr->flush_rows++;
  203299. if (png_ptr->flush_dist > 0 &&
  203300. png_ptr->flush_rows >= png_ptr->flush_dist)
  203301. {
  203302. png_write_flush(png_ptr);
  203303. }
  203304. #endif
  203305. }
  203306. #endif /* PNG_WRITE_SUPPORTED */
  203307. /*** End of inlined file: pngwutil.c ***/
  203308. #else
  203309. extern "C"
  203310. {
  203311. #include <png.h>
  203312. #include <pngconf.h>
  203313. }
  203314. #endif
  203315. }
  203316. #undef max
  203317. #undef min
  203318. #if JUCE_MSVC
  203319. #pragma warning (pop)
  203320. #endif
  203321. BEGIN_JUCE_NAMESPACE
  203322. using ::calloc;
  203323. using ::malloc;
  203324. using ::free;
  203325. namespace PNGHelpers
  203326. {
  203327. using namespace pnglibNamespace;
  203328. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203329. {
  203330. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203331. }
  203332. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203333. {
  203334. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203335. }
  203336. struct PNGErrorStruct {};
  203337. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203338. {
  203339. throw PNGErrorStruct();
  203340. }
  203341. }
  203342. PNGImageFormat::PNGImageFormat() {}
  203343. PNGImageFormat::~PNGImageFormat() {}
  203344. const String PNGImageFormat::getFormatName()
  203345. {
  203346. return "PNG";
  203347. }
  203348. bool PNGImageFormat::canUnderstand (InputStream& in)
  203349. {
  203350. const int bytesNeeded = 4;
  203351. char header [bytesNeeded];
  203352. return in.read (header, bytesNeeded) == bytesNeeded
  203353. && header[1] == 'P'
  203354. && header[2] == 'N'
  203355. && header[3] == 'G';
  203356. }
  203357. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203358. const Image juce_loadWithCoreImage (InputStream& input);
  203359. #endif
  203360. const Image PNGImageFormat::decodeImage (InputStream& in)
  203361. {
  203362. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203363. return juce_loadWithCoreImage (in);
  203364. #else
  203365. using namespace pnglibNamespace;
  203366. Image image;
  203367. png_structp pngReadStruct;
  203368. png_infop pngInfoStruct;
  203369. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203370. if (pngReadStruct != 0)
  203371. {
  203372. try
  203373. {
  203374. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203375. if (pngInfoStruct == 0)
  203376. {
  203377. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203378. return Image::null;
  203379. }
  203380. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203381. // read the header..
  203382. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203383. png_uint_32 width, height;
  203384. int bitDepth, colorType, interlaceType;
  203385. png_read_info (pngReadStruct, pngInfoStruct);
  203386. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203387. &width, &height,
  203388. &bitDepth, &colorType,
  203389. &interlaceType, 0, 0);
  203390. if (bitDepth == 16)
  203391. png_set_strip_16 (pngReadStruct);
  203392. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203393. png_set_expand (pngReadStruct);
  203394. if (bitDepth < 8)
  203395. png_set_expand (pngReadStruct);
  203396. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203397. png_set_expand (pngReadStruct);
  203398. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203399. png_set_gray_to_rgb (pngReadStruct);
  203400. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203401. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203402. || pngInfoStruct->num_trans > 0;
  203403. // Load the image into a temp buffer in the pnglib format..
  203404. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203405. {
  203406. HeapBlock <png_bytep> rows (height);
  203407. for (int y = (int) height; --y >= 0;)
  203408. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203409. try
  203410. {
  203411. png_read_image (pngReadStruct, rows);
  203412. png_read_end (pngReadStruct, pngInfoStruct);
  203413. }
  203414. catch (PNGHelpers::PNGErrorStruct&)
  203415. {}
  203416. }
  203417. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203418. // now convert the data to a juce image format..
  203419. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203420. (int) width, (int) height, hasAlphaChan);
  203421. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203422. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203423. const Image::BitmapData destData (image, Image::BitmapData::writeOnly);
  203424. uint8* srcRow = tempBuffer;
  203425. uint8* destRow = destData.data;
  203426. for (int y = 0; y < (int) height; ++y)
  203427. {
  203428. const uint8* src = srcRow;
  203429. srcRow += (width << 2);
  203430. uint8* dest = destRow;
  203431. destRow += destData.lineStride;
  203432. if (hasAlphaChan)
  203433. {
  203434. for (int i = (int) width; --i >= 0;)
  203435. {
  203436. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203437. ((PixelARGB*) dest)->premultiply();
  203438. dest += destData.pixelStride;
  203439. src += 4;
  203440. }
  203441. }
  203442. else
  203443. {
  203444. for (int i = (int) width; --i >= 0;)
  203445. {
  203446. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203447. dest += destData.pixelStride;
  203448. src += 4;
  203449. }
  203450. }
  203451. }
  203452. }
  203453. catch (PNGHelpers::PNGErrorStruct&)
  203454. {}
  203455. }
  203456. return image;
  203457. #endif
  203458. }
  203459. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203460. {
  203461. using namespace pnglibNamespace;
  203462. const int width = image.getWidth();
  203463. const int height = image.getHeight();
  203464. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203465. if (pngWriteStruct == 0)
  203466. return false;
  203467. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203468. if (pngInfoStruct == 0)
  203469. {
  203470. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203471. return false;
  203472. }
  203473. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203474. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203475. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203476. : PNG_COLOR_TYPE_RGB,
  203477. PNG_INTERLACE_NONE,
  203478. PNG_COMPRESSION_TYPE_BASE,
  203479. PNG_FILTER_TYPE_BASE);
  203480. HeapBlock <uint8> rowData (width * 4);
  203481. png_color_8 sig_bit;
  203482. sig_bit.red = 8;
  203483. sig_bit.green = 8;
  203484. sig_bit.blue = 8;
  203485. sig_bit.alpha = 8;
  203486. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203487. png_write_info (pngWriteStruct, pngInfoStruct);
  203488. png_set_shift (pngWriteStruct, &sig_bit);
  203489. png_set_packing (pngWriteStruct);
  203490. const Image::BitmapData srcData (image, Image::BitmapData::readOnly);
  203491. for (int y = 0; y < height; ++y)
  203492. {
  203493. uint8* dst = rowData;
  203494. const uint8* src = srcData.getLinePointer (y);
  203495. if (image.hasAlphaChannel())
  203496. {
  203497. for (int i = width; --i >= 0;)
  203498. {
  203499. PixelARGB p (*(const PixelARGB*) src);
  203500. p.unpremultiply();
  203501. *dst++ = p.getRed();
  203502. *dst++ = p.getGreen();
  203503. *dst++ = p.getBlue();
  203504. *dst++ = p.getAlpha();
  203505. src += srcData.pixelStride;
  203506. }
  203507. }
  203508. else
  203509. {
  203510. for (int i = width; --i >= 0;)
  203511. {
  203512. *dst++ = ((const PixelRGB*) src)->getRed();
  203513. *dst++ = ((const PixelRGB*) src)->getGreen();
  203514. *dst++ = ((const PixelRGB*) src)->getBlue();
  203515. src += srcData.pixelStride;
  203516. }
  203517. }
  203518. png_bytep rowPtr = rowData;
  203519. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203520. }
  203521. png_write_end (pngWriteStruct, pngInfoStruct);
  203522. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203523. out.flush();
  203524. return true;
  203525. }
  203526. END_JUCE_NAMESPACE
  203527. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203528. #endif
  203529. //==============================================================================
  203530. #if JUCE_BUILD_NATIVE
  203531. // Non-public headers that are needed by more than one platform must be included
  203532. // before the platform-specific sections..
  203533. BEGIN_JUCE_NAMESPACE
  203534. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203535. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203536. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203537. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203538. /**
  203539. Helper class that takes chunks of incoming midi bytes, packages them into
  203540. messages, and dispatches them to a midi callback.
  203541. */
  203542. class MidiDataConcatenator
  203543. {
  203544. public:
  203545. MidiDataConcatenator (const int initialBufferSize)
  203546. : pendingData (initialBufferSize),
  203547. pendingBytes (0), pendingDataTime (0)
  203548. {
  203549. }
  203550. void reset()
  203551. {
  203552. pendingBytes = 0;
  203553. pendingDataTime = 0;
  203554. }
  203555. void pushMidiData (const void* data, int numBytes, double time,
  203556. MidiInput* input, MidiInputCallback& callback)
  203557. {
  203558. const uint8* d = static_cast <const uint8*> (data);
  203559. while (numBytes > 0)
  203560. {
  203561. if (pendingBytes > 0 || d[0] == 0xf0)
  203562. {
  203563. processSysex (d, numBytes, time, input, callback);
  203564. }
  203565. else
  203566. {
  203567. int used = 0;
  203568. const MidiMessage m (d, numBytes, used, 0, time);
  203569. if (used <= 0)
  203570. break; // malformed message..
  203571. callback.handleIncomingMidiMessage (input, m);
  203572. numBytes -= used;
  203573. d += used;
  203574. }
  203575. }
  203576. }
  203577. private:
  203578. void processSysex (const uint8*& d, int& numBytes, double time,
  203579. MidiInput* input, MidiInputCallback& callback)
  203580. {
  203581. if (*d == 0xf0)
  203582. {
  203583. pendingBytes = 0;
  203584. pendingDataTime = time;
  203585. }
  203586. pendingData.ensureSize (pendingBytes + numBytes, false);
  203587. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203588. uint8* dest = totalMessage + pendingBytes;
  203589. do
  203590. {
  203591. if (pendingBytes > 0 && *d >= 0x80)
  203592. {
  203593. if (*d >= 0xfa || *d == 0xf8)
  203594. {
  203595. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203596. ++d;
  203597. --numBytes;
  203598. }
  203599. else
  203600. {
  203601. if (*d == 0xf7)
  203602. {
  203603. *dest++ = *d++;
  203604. pendingBytes++;
  203605. --numBytes;
  203606. }
  203607. break;
  203608. }
  203609. }
  203610. else
  203611. {
  203612. *dest++ = *d++;
  203613. pendingBytes++;
  203614. --numBytes;
  203615. }
  203616. }
  203617. while (numBytes > 0);
  203618. if (pendingBytes > 0)
  203619. {
  203620. if (totalMessage [pendingBytes - 1] == 0xf7)
  203621. {
  203622. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203623. pendingBytes = 0;
  203624. }
  203625. else
  203626. {
  203627. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203628. }
  203629. }
  203630. }
  203631. MemoryBlock pendingData;
  203632. int pendingBytes;
  203633. double pendingDataTime;
  203634. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203635. };
  203636. #endif
  203637. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203638. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203639. END_JUCE_NAMESPACE
  203640. #if JUCE_WINDOWS
  203641. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203642. /*
  203643. This file wraps together all the win32-specific code, so that
  203644. we can include all the native headers just once, and compile all our
  203645. platform-specific stuff in one big lump, keeping it out of the way of
  203646. the rest of the codebase.
  203647. */
  203648. #if JUCE_WINDOWS
  203649. #undef JUCE_BUILD_NATIVE
  203650. #define JUCE_BUILD_NATIVE 1
  203651. BEGIN_JUCE_NAMESPACE
  203652. #define JUCE_INCLUDED_FILE 1
  203653. // Now include the actual code files..
  203654. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203655. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203656. // compiled on its own).
  203657. #if JUCE_INCLUDED_FILE
  203658. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203659. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203660. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203661. #ifndef DOXYGEN
  203662. // use with DynamicLibraryLoader to simplify importing functions
  203663. //
  203664. // functionName: function to import
  203665. // localFunctionName: name you want to use to actually call it (must be different)
  203666. // returnType: the return type
  203667. // object: the DynamicLibraryLoader to use
  203668. // params: list of params (bracketed)
  203669. //
  203670. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203671. typedef returnType (WINAPI *type##localFunctionName) params; \
  203672. type##localFunctionName localFunctionName \
  203673. = (type##localFunctionName)object.findProcAddress (#functionName);
  203674. // loads and unloads a DLL automatically
  203675. class JUCE_API DynamicLibraryLoader
  203676. {
  203677. public:
  203678. DynamicLibraryLoader (const String& name = String::empty);
  203679. ~DynamicLibraryLoader();
  203680. bool load (const String& libraryName);
  203681. void* findProcAddress (const String& functionName);
  203682. private:
  203683. void* libHandle;
  203684. };
  203685. #endif
  203686. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203687. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203688. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203689. : libHandle (0)
  203690. {
  203691. load (name);
  203692. }
  203693. DynamicLibraryLoader::~DynamicLibraryLoader()
  203694. {
  203695. load (String::empty);
  203696. }
  203697. bool DynamicLibraryLoader::load (const String& name)
  203698. {
  203699. FreeLibrary ((HMODULE) libHandle);
  203700. libHandle = name.isNotEmpty() ? LoadLibrary (name.toUTF16()) : 0;
  203701. return libHandle != 0;
  203702. }
  203703. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203704. {
  203705. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toUTF8()); // (void* cast is required for mingw)
  203706. }
  203707. #endif
  203708. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203709. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203710. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203711. // compiled on its own).
  203712. #if JUCE_INCLUDED_FILE
  203713. void Logger::outputDebugString (const String& text)
  203714. {
  203715. OutputDebugString ((text + "\n").toUTF16());
  203716. }
  203717. static int64 hiResTicksPerSecond;
  203718. static double hiResTicksScaleFactor;
  203719. #if JUCE_USE_INTRINSICS
  203720. // CPU info functions using intrinsics...
  203721. #pragma intrinsic (__cpuid)
  203722. #pragma intrinsic (__rdtsc)
  203723. const String SystemStats::getCpuVendor()
  203724. {
  203725. int info [4];
  203726. __cpuid (info, 0);
  203727. char v [12];
  203728. memcpy (v, info + 1, 4);
  203729. memcpy (v + 4, info + 3, 4);
  203730. memcpy (v + 8, info + 2, 4);
  203731. return String (v, 12);
  203732. }
  203733. #else
  203734. // CPU info functions using old fashioned inline asm...
  203735. static void juce_getCpuVendor (char* const v)
  203736. {
  203737. int vendor[4];
  203738. zeromem (vendor, 16);
  203739. #ifdef JUCE_64BIT
  203740. #else
  203741. #ifndef __MINGW32__
  203742. __try
  203743. #endif
  203744. {
  203745. #if JUCE_GCC
  203746. unsigned int dummy = 0;
  203747. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203748. #else
  203749. __asm
  203750. {
  203751. mov eax, 0
  203752. cpuid
  203753. mov [vendor], ebx
  203754. mov [vendor + 4], edx
  203755. mov [vendor + 8], ecx
  203756. }
  203757. #endif
  203758. }
  203759. #ifndef __MINGW32__
  203760. __except (EXCEPTION_EXECUTE_HANDLER)
  203761. {
  203762. *v = 0;
  203763. }
  203764. #endif
  203765. #endif
  203766. memcpy (v, vendor, 16);
  203767. }
  203768. const String SystemStats::getCpuVendor()
  203769. {
  203770. char v [16];
  203771. juce_getCpuVendor (v);
  203772. return String (v, 16);
  203773. }
  203774. #endif
  203775. void SystemStats::initialiseStats()
  203776. {
  203777. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203778. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203779. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203780. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203781. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203782. #else
  203783. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203784. #endif
  203785. {
  203786. SYSTEM_INFO systemInfo;
  203787. GetSystemInfo (&systemInfo);
  203788. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203789. }
  203790. LARGE_INTEGER f;
  203791. QueryPerformanceFrequency (&f);
  203792. hiResTicksPerSecond = f.QuadPart;
  203793. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203794. String s (SystemStats::getJUCEVersion());
  203795. const MMRESULT res = timeBeginPeriod (1);
  203796. (void) res;
  203797. jassert (res == TIMERR_NOERROR);
  203798. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203799. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203800. #endif
  203801. }
  203802. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203803. {
  203804. OSVERSIONINFO info;
  203805. info.dwOSVersionInfoSize = sizeof (info);
  203806. GetVersionEx (&info);
  203807. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203808. {
  203809. switch (info.dwMajorVersion)
  203810. {
  203811. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203812. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203813. default: jassertfalse; break; // !! not a supported OS!
  203814. }
  203815. }
  203816. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203817. {
  203818. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203819. return Win98;
  203820. }
  203821. return UnknownOS;
  203822. }
  203823. const String SystemStats::getOperatingSystemName()
  203824. {
  203825. const char* name = "Unknown OS";
  203826. switch (getOperatingSystemType())
  203827. {
  203828. case Windows7: name = "Windows 7"; break;
  203829. case WinVista: name = "Windows Vista"; break;
  203830. case WinXP: name = "Windows XP"; break;
  203831. case Win2000: name = "Windows 2000"; break;
  203832. case Win98: name = "Windows 98"; break;
  203833. default: jassertfalse; break; // !! new type of OS?
  203834. }
  203835. return name;
  203836. }
  203837. bool SystemStats::isOperatingSystem64Bit()
  203838. {
  203839. #ifdef _WIN64
  203840. return true;
  203841. #else
  203842. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203843. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203844. BOOL isWow64 = FALSE;
  203845. return (fnIsWow64Process != 0)
  203846. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203847. && (isWow64 != FALSE);
  203848. #endif
  203849. }
  203850. int SystemStats::getMemorySizeInMegabytes()
  203851. {
  203852. MEMORYSTATUSEX mem;
  203853. mem.dwLength = sizeof (mem);
  203854. GlobalMemoryStatusEx (&mem);
  203855. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203856. }
  203857. uint32 juce_millisecondsSinceStartup() throw()
  203858. {
  203859. return (uint32) timeGetTime();
  203860. }
  203861. int64 Time::getHighResolutionTicks() throw()
  203862. {
  203863. LARGE_INTEGER ticks;
  203864. QueryPerformanceCounter (&ticks);
  203865. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203866. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203867. // fix for a very obscure PCI hardware bug that can make the counter
  203868. // sometimes jump forwards by a few seconds..
  203869. static int64 hiResTicksOffset = 0;
  203870. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203871. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203872. hiResTicksOffset = newOffset;
  203873. return ticks.QuadPart + hiResTicksOffset;
  203874. }
  203875. double Time::getMillisecondCounterHiRes() throw()
  203876. {
  203877. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203878. }
  203879. int64 Time::getHighResolutionTicksPerSecond() throw()
  203880. {
  203881. return hiResTicksPerSecond;
  203882. }
  203883. static int64 juce_getClockCycleCounter() throw()
  203884. {
  203885. #if JUCE_USE_INTRINSICS
  203886. // MS intrinsics version...
  203887. return __rdtsc();
  203888. #elif JUCE_GCC
  203889. // GNU inline asm version...
  203890. unsigned int hi = 0, lo = 0;
  203891. __asm__ __volatile__ (
  203892. "xor %%eax, %%eax \n\
  203893. xor %%edx, %%edx \n\
  203894. rdtsc \n\
  203895. movl %%eax, %[lo] \n\
  203896. movl %%edx, %[hi]"
  203897. :
  203898. : [hi] "m" (hi),
  203899. [lo] "m" (lo)
  203900. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203901. return (int64) ((((uint64) hi) << 32) | lo);
  203902. #else
  203903. // MSVC inline asm version...
  203904. unsigned int hi = 0, lo = 0;
  203905. __asm
  203906. {
  203907. xor eax, eax
  203908. xor edx, edx
  203909. rdtsc
  203910. mov lo, eax
  203911. mov hi, edx
  203912. }
  203913. return (int64) ((((uint64) hi) << 32) | lo);
  203914. #endif
  203915. }
  203916. int SystemStats::getCpuSpeedInMegaherz()
  203917. {
  203918. const int64 cycles = juce_getClockCycleCounter();
  203919. const uint32 millis = Time::getMillisecondCounter();
  203920. int lastResult = 0;
  203921. for (;;)
  203922. {
  203923. int n = 1000000;
  203924. while (--n > 0) {}
  203925. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203926. const int64 cyclesNow = juce_getClockCycleCounter();
  203927. if (millisElapsed > 80)
  203928. {
  203929. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203930. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203931. return newResult;
  203932. lastResult = newResult;
  203933. }
  203934. }
  203935. }
  203936. bool Time::setSystemTimeToThisTime() const
  203937. {
  203938. SYSTEMTIME st;
  203939. st.wDayOfWeek = 0;
  203940. st.wYear = (WORD) getYear();
  203941. st.wMonth = (WORD) (getMonth() + 1);
  203942. st.wDay = (WORD) getDayOfMonth();
  203943. st.wHour = (WORD) getHours();
  203944. st.wMinute = (WORD) getMinutes();
  203945. st.wSecond = (WORD) getSeconds();
  203946. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203947. // do this twice because of daylight saving conversion problems - the
  203948. // first one sets it up, the second one kicks it in.
  203949. return SetLocalTime (&st) != 0
  203950. && SetLocalTime (&st) != 0;
  203951. }
  203952. int SystemStats::getPageSize()
  203953. {
  203954. SYSTEM_INFO systemInfo;
  203955. GetSystemInfo (&systemInfo);
  203956. return systemInfo.dwPageSize;
  203957. }
  203958. const String SystemStats::getLogonName()
  203959. {
  203960. TCHAR text [256];
  203961. DWORD len = numElementsInArray (text) - 2;
  203962. zerostruct (text);
  203963. GetUserName (text, &len);
  203964. return String (text, len);
  203965. }
  203966. const String SystemStats::getFullUserName()
  203967. {
  203968. return getLogonName();
  203969. }
  203970. #endif
  203971. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203972. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203973. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203974. // compiled on its own).
  203975. #if JUCE_INCLUDED_FILE
  203976. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203977. extern HWND juce_messageWindowHandle;
  203978. #endif
  203979. #if ! JUCE_USE_INTRINSICS
  203980. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203981. // older ones we have to actually call the ops as win32 functions..
  203982. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203983. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203984. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203985. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203986. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203987. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203988. {
  203989. jassertfalse; // This operation isn't available in old MS compiler versions!
  203990. __int64 oldValue = *value;
  203991. if (oldValue == valueToCompare)
  203992. *value = newValue;
  203993. return oldValue;
  203994. }
  203995. #endif
  203996. CriticalSection::CriticalSection() throw()
  203997. {
  203998. // (just to check the MS haven't changed this structure and broken things...)
  203999. #if JUCE_VC7_OR_EARLIER
  204000. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  204001. #else
  204002. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  204003. #endif
  204004. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  204005. }
  204006. CriticalSection::~CriticalSection() throw()
  204007. {
  204008. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  204009. }
  204010. void CriticalSection::enter() const throw()
  204011. {
  204012. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  204013. }
  204014. bool CriticalSection::tryEnter() const throw()
  204015. {
  204016. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  204017. }
  204018. void CriticalSection::exit() const throw()
  204019. {
  204020. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  204021. }
  204022. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  204023. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  204024. {
  204025. }
  204026. WaitableEvent::~WaitableEvent() throw()
  204027. {
  204028. CloseHandle (internal);
  204029. }
  204030. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  204031. {
  204032. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  204033. }
  204034. void WaitableEvent::signal() const throw()
  204035. {
  204036. SetEvent (internal);
  204037. }
  204038. void WaitableEvent::reset() const throw()
  204039. {
  204040. ResetEvent (internal);
  204041. }
  204042. void JUCE_API juce_threadEntryPoint (void*);
  204043. static unsigned int __stdcall threadEntryProc (void* userData)
  204044. {
  204045. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204046. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  204047. GetCurrentThreadId(), TRUE);
  204048. #endif
  204049. juce_threadEntryPoint (userData);
  204050. _endthreadex (0);
  204051. return 0;
  204052. }
  204053. void Thread::launchThread()
  204054. {
  204055. unsigned int newThreadId;
  204056. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  204057. threadId_ = (ThreadID) newThreadId;
  204058. }
  204059. void Thread::closeThreadHandle()
  204060. {
  204061. CloseHandle ((HANDLE) threadHandle_);
  204062. threadId_ = 0;
  204063. threadHandle_ = 0;
  204064. }
  204065. void Thread::killThread()
  204066. {
  204067. if (threadHandle_ != 0)
  204068. {
  204069. #if JUCE_DEBUG
  204070. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  204071. #endif
  204072. TerminateThread (threadHandle_, 0);
  204073. }
  204074. }
  204075. void Thread::setCurrentThreadName (const String& name)
  204076. {
  204077. #if JUCE_DEBUG && JUCE_MSVC
  204078. struct
  204079. {
  204080. DWORD dwType;
  204081. LPCSTR szName;
  204082. DWORD dwThreadID;
  204083. DWORD dwFlags;
  204084. } info;
  204085. info.dwType = 0x1000;
  204086. info.szName = name.toCString();
  204087. info.dwThreadID = GetCurrentThreadId();
  204088. info.dwFlags = 0;
  204089. __try
  204090. {
  204091. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  204092. }
  204093. __except (EXCEPTION_CONTINUE_EXECUTION)
  204094. {}
  204095. #else
  204096. (void) name;
  204097. #endif
  204098. }
  204099. Thread::ThreadID Thread::getCurrentThreadId()
  204100. {
  204101. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  204102. }
  204103. bool Thread::setThreadPriority (void* handle, int priority)
  204104. {
  204105. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  204106. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  204107. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  204108. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  204109. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  204110. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  204111. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  204112. if (handle == 0)
  204113. handle = GetCurrentThread();
  204114. return SetThreadPriority (handle, pri) != FALSE;
  204115. }
  204116. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  204117. {
  204118. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  204119. }
  204120. struct SleepEvent
  204121. {
  204122. SleepEvent()
  204123. : handle (CreateEvent (0, 0, 0,
  204124. #if JUCE_DEBUG
  204125. _T("Juce Sleep Event")))
  204126. #else
  204127. 0))
  204128. #endif
  204129. {
  204130. }
  204131. HANDLE handle;
  204132. };
  204133. static SleepEvent sleepEvent;
  204134. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  204135. {
  204136. if (millisecs >= 10)
  204137. {
  204138. Sleep (millisecs);
  204139. }
  204140. else
  204141. {
  204142. // unlike Sleep() this is guaranteed to return to the current thread after
  204143. // the time expires, so we'll use this for short waits, which are more likely
  204144. // to need to be accurate
  204145. WaitForSingleObject (sleepEvent.handle, millisecs);
  204146. }
  204147. }
  204148. void Thread::yield()
  204149. {
  204150. Sleep (0);
  204151. }
  204152. static int lastProcessPriority = -1;
  204153. // called by WindowDriver because Windows does wierd things to process priority
  204154. // when you swap apps, and this forces an update when the app is brought to the front.
  204155. void juce_repeatLastProcessPriority()
  204156. {
  204157. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  204158. {
  204159. DWORD p;
  204160. switch (lastProcessPriority)
  204161. {
  204162. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  204163. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  204164. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  204165. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  204166. default: jassertfalse; return; // bad priority value
  204167. }
  204168. SetPriorityClass (GetCurrentProcess(), p);
  204169. }
  204170. }
  204171. void Process::setPriority (ProcessPriority prior)
  204172. {
  204173. if (lastProcessPriority != (int) prior)
  204174. {
  204175. lastProcessPriority = (int) prior;
  204176. juce_repeatLastProcessPriority();
  204177. }
  204178. }
  204179. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  204180. {
  204181. return IsDebuggerPresent() != FALSE;
  204182. }
  204183. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204184. {
  204185. return juce_isRunningUnderDebugger();
  204186. }
  204187. void Process::raisePrivilege()
  204188. {
  204189. jassertfalse; // xxx not implemented
  204190. }
  204191. void Process::lowerPrivilege()
  204192. {
  204193. jassertfalse; // xxx not implemented
  204194. }
  204195. void Process::terminate()
  204196. {
  204197. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204198. _CrtDumpMemoryLeaks();
  204199. #endif
  204200. // bullet in the head in case there's a problem shutting down..
  204201. ExitProcess (0);
  204202. }
  204203. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204204. {
  204205. void* result = 0;
  204206. JUCE_TRY
  204207. {
  204208. result = LoadLibrary (name.toUTF16());
  204209. }
  204210. JUCE_CATCH_ALL
  204211. return result;
  204212. }
  204213. void PlatformUtilities::freeDynamicLibrary (void* h)
  204214. {
  204215. JUCE_TRY
  204216. {
  204217. if (h != 0)
  204218. FreeLibrary ((HMODULE) h);
  204219. }
  204220. JUCE_CATCH_ALL
  204221. }
  204222. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204223. {
  204224. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204225. }
  204226. class InterProcessLock::Pimpl
  204227. {
  204228. public:
  204229. Pimpl (const String& name, const int timeOutMillisecs)
  204230. : handle (0), refCount (1)
  204231. {
  204232. handle = CreateMutex (0, TRUE, ("Global\\" + name.replaceCharacter ('\\','/')).toUTF16());
  204233. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204234. {
  204235. if (timeOutMillisecs == 0)
  204236. {
  204237. close();
  204238. return;
  204239. }
  204240. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204241. {
  204242. case WAIT_OBJECT_0:
  204243. case WAIT_ABANDONED:
  204244. break;
  204245. case WAIT_TIMEOUT:
  204246. default:
  204247. close();
  204248. break;
  204249. }
  204250. }
  204251. }
  204252. ~Pimpl()
  204253. {
  204254. close();
  204255. }
  204256. void close()
  204257. {
  204258. if (handle != 0)
  204259. {
  204260. ReleaseMutex (handle);
  204261. CloseHandle (handle);
  204262. handle = 0;
  204263. }
  204264. }
  204265. HANDLE handle;
  204266. int refCount;
  204267. };
  204268. InterProcessLock::InterProcessLock (const String& name_)
  204269. : name (name_)
  204270. {
  204271. }
  204272. InterProcessLock::~InterProcessLock()
  204273. {
  204274. }
  204275. bool InterProcessLock::enter (const int timeOutMillisecs)
  204276. {
  204277. const ScopedLock sl (lock);
  204278. if (pimpl == 0)
  204279. {
  204280. pimpl = new Pimpl (name, timeOutMillisecs);
  204281. if (pimpl->handle == 0)
  204282. pimpl = 0;
  204283. }
  204284. else
  204285. {
  204286. pimpl->refCount++;
  204287. }
  204288. return pimpl != 0;
  204289. }
  204290. void InterProcessLock::exit()
  204291. {
  204292. const ScopedLock sl (lock);
  204293. // Trying to release the lock too many times!
  204294. jassert (pimpl != 0);
  204295. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204296. pimpl = 0;
  204297. }
  204298. #endif
  204299. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204300. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204301. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204302. // compiled on its own).
  204303. #if JUCE_INCLUDED_FILE
  204304. #ifndef CSIDL_MYMUSIC
  204305. #define CSIDL_MYMUSIC 0x000d
  204306. #endif
  204307. #ifndef CSIDL_MYVIDEO
  204308. #define CSIDL_MYVIDEO 0x000e
  204309. #endif
  204310. #ifndef INVALID_FILE_ATTRIBUTES
  204311. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204312. #endif
  204313. namespace WindowsFileHelpers
  204314. {
  204315. int64 fileTimeToTime (const FILETIME* const ft)
  204316. {
  204317. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204318. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204319. }
  204320. void timeToFileTime (const int64 time, FILETIME* const ft)
  204321. {
  204322. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204323. }
  204324. const String getDriveFromPath (String path)
  204325. {
  204326. WCHAR* p = const_cast <WCHAR*> (path.toUTF16().getAddress());
  204327. if (PathStripToRoot (p))
  204328. return String ((const WCHAR*) p);
  204329. return path;
  204330. }
  204331. int64 getDiskSpaceInfo (const String& path, const bool total)
  204332. {
  204333. ULARGE_INTEGER spc, tot, totFree;
  204334. if (GetDiskFreeSpaceEx (getDriveFromPath (path).toUTF16(), &spc, &tot, &totFree))
  204335. return total ? (int64) tot.QuadPart
  204336. : (int64) spc.QuadPart;
  204337. return 0;
  204338. }
  204339. unsigned int getWindowsDriveType (const String& path)
  204340. {
  204341. return GetDriveType (getDriveFromPath (path).toUTF16());
  204342. }
  204343. const File getSpecialFolderPath (int type)
  204344. {
  204345. WCHAR path [MAX_PATH + 256];
  204346. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204347. return File (String (path));
  204348. return File::nonexistent;
  204349. }
  204350. }
  204351. const juce_wchar File::separator = '\\';
  204352. const String File::separatorString ("\\");
  204353. bool File::exists() const
  204354. {
  204355. return fullPath.isNotEmpty()
  204356. && GetFileAttributes (fullPath.toUTF16()) != INVALID_FILE_ATTRIBUTES;
  204357. }
  204358. bool File::existsAsFile() const
  204359. {
  204360. return fullPath.isNotEmpty()
  204361. && (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204362. }
  204363. bool File::isDirectory() const
  204364. {
  204365. const DWORD attr = GetFileAttributes (fullPath.toUTF16());
  204366. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204367. }
  204368. bool File::hasWriteAccess() const
  204369. {
  204370. if (exists())
  204371. return (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_READONLY) == 0;
  204372. // on windows, it seems that even read-only directories can still be written into,
  204373. // so checking the parent directory's permissions would return the wrong result..
  204374. return true;
  204375. }
  204376. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204377. {
  204378. DWORD attr = GetFileAttributes (fullPath.toUTF16());
  204379. if (attr == INVALID_FILE_ATTRIBUTES)
  204380. return false;
  204381. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204382. return true;
  204383. if (shouldBeReadOnly)
  204384. attr |= FILE_ATTRIBUTE_READONLY;
  204385. else
  204386. attr &= ~FILE_ATTRIBUTE_READONLY;
  204387. return SetFileAttributes (fullPath.toUTF16(), attr) != FALSE;
  204388. }
  204389. bool File::isHidden() const
  204390. {
  204391. return (GetFileAttributes (getFullPathName().toUTF16()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204392. }
  204393. bool File::deleteFile() const
  204394. {
  204395. if (! exists())
  204396. return true;
  204397. else if (isDirectory())
  204398. return RemoveDirectory (fullPath.toUTF16()) != 0;
  204399. else
  204400. return DeleteFile (fullPath.toUTF16()) != 0;
  204401. }
  204402. bool File::moveToTrash() const
  204403. {
  204404. if (! exists())
  204405. return true;
  204406. SHFILEOPSTRUCT fos;
  204407. zerostruct (fos);
  204408. // The string we pass in must be double null terminated..
  204409. String doubleNullTermPath (getFullPathName() + " ");
  204410. WCHAR* const p = const_cast <WCHAR*> (doubleNullTermPath.toUTF16().getAddress());
  204411. p [getFullPathName().length()] = 0;
  204412. fos.wFunc = FO_DELETE;
  204413. fos.pFrom = p;
  204414. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204415. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204416. return SHFileOperation (&fos) == 0;
  204417. }
  204418. bool File::copyInternal (const File& dest) const
  204419. {
  204420. return CopyFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16(), false) != 0;
  204421. }
  204422. bool File::moveInternal (const File& dest) const
  204423. {
  204424. return MoveFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16()) != 0;
  204425. }
  204426. void File::createDirectoryInternal (const String& fileName) const
  204427. {
  204428. CreateDirectory (fileName.toUTF16(), 0);
  204429. }
  204430. int64 juce_fileSetPosition (void* handle, int64 pos)
  204431. {
  204432. LARGE_INTEGER li;
  204433. li.QuadPart = pos;
  204434. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204435. return li.QuadPart;
  204436. }
  204437. void FileInputStream::openHandle()
  204438. {
  204439. totalSize = file.getSize();
  204440. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204441. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204442. if (h != INVALID_HANDLE_VALUE)
  204443. fileHandle = (void*) h;
  204444. }
  204445. void FileInputStream::closeHandle()
  204446. {
  204447. CloseHandle ((HANDLE) fileHandle);
  204448. }
  204449. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204450. {
  204451. if (fileHandle != 0)
  204452. {
  204453. DWORD actualNum = 0;
  204454. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204455. return (size_t) actualNum;
  204456. }
  204457. return 0;
  204458. }
  204459. void FileOutputStream::openHandle()
  204460. {
  204461. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204462. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204463. if (h != INVALID_HANDLE_VALUE)
  204464. {
  204465. LARGE_INTEGER li;
  204466. li.QuadPart = 0;
  204467. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204468. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204469. {
  204470. fileHandle = (void*) h;
  204471. currentPosition = li.QuadPart;
  204472. }
  204473. }
  204474. }
  204475. void FileOutputStream::closeHandle()
  204476. {
  204477. CloseHandle ((HANDLE) fileHandle);
  204478. }
  204479. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204480. {
  204481. if (fileHandle != 0)
  204482. {
  204483. DWORD actualNum = 0;
  204484. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204485. return (int) actualNum;
  204486. }
  204487. return 0;
  204488. }
  204489. void FileOutputStream::flushInternal()
  204490. {
  204491. if (fileHandle != 0)
  204492. FlushFileBuffers ((HANDLE) fileHandle);
  204493. }
  204494. int64 File::getSize() const
  204495. {
  204496. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204497. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  204498. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204499. return 0;
  204500. }
  204501. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204502. {
  204503. using namespace WindowsFileHelpers;
  204504. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204505. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  204506. {
  204507. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204508. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204509. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204510. }
  204511. else
  204512. {
  204513. creationTime = accessTime = modificationTime = 0;
  204514. }
  204515. }
  204516. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204517. {
  204518. using namespace WindowsFileHelpers;
  204519. bool ok = false;
  204520. HANDLE h = CreateFile (fullPath.toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204521. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204522. if (h != INVALID_HANDLE_VALUE)
  204523. {
  204524. FILETIME m, a, c;
  204525. timeToFileTime (modificationTime, &m);
  204526. timeToFileTime (accessTime, &a);
  204527. timeToFileTime (creationTime, &c);
  204528. ok = SetFileTime (h,
  204529. creationTime > 0 ? &c : 0,
  204530. accessTime > 0 ? &a : 0,
  204531. modificationTime > 0 ? &m : 0) != 0;
  204532. CloseHandle (h);
  204533. }
  204534. return ok;
  204535. }
  204536. void File::findFileSystemRoots (Array<File>& destArray)
  204537. {
  204538. TCHAR buffer [2048];
  204539. buffer[0] = 0;
  204540. buffer[1] = 0;
  204541. GetLogicalDriveStrings (2048, buffer);
  204542. const TCHAR* n = buffer;
  204543. StringArray roots;
  204544. while (*n != 0)
  204545. {
  204546. roots.add (String (n));
  204547. while (*n++ != 0)
  204548. {}
  204549. }
  204550. roots.sort (true);
  204551. for (int i = 0; i < roots.size(); ++i)
  204552. destArray.add (roots [i]);
  204553. }
  204554. const String File::getVolumeLabel() const
  204555. {
  204556. TCHAR dest[64];
  204557. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  204558. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204559. dest[0] = 0;
  204560. return dest;
  204561. }
  204562. int File::getVolumeSerialNumber() const
  204563. {
  204564. TCHAR dest[64];
  204565. DWORD serialNum;
  204566. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  204567. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204568. return 0;
  204569. return (int) serialNum;
  204570. }
  204571. int64 File::getBytesFreeOnVolume() const
  204572. {
  204573. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204574. }
  204575. int64 File::getVolumeTotalSize() const
  204576. {
  204577. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204578. }
  204579. bool File::isOnCDRomDrive() const
  204580. {
  204581. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204582. }
  204583. bool File::isOnHardDisk() const
  204584. {
  204585. if (fullPath.isEmpty())
  204586. return false;
  204587. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204588. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204589. return n != DRIVE_REMOVABLE;
  204590. else
  204591. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204592. }
  204593. bool File::isOnRemovableDrive() const
  204594. {
  204595. if (fullPath.isEmpty())
  204596. return false;
  204597. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204598. return n == DRIVE_CDROM
  204599. || n == DRIVE_REMOTE
  204600. || n == DRIVE_REMOVABLE
  204601. || n == DRIVE_RAMDISK;
  204602. }
  204603. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204604. {
  204605. int csidlType = 0;
  204606. switch (type)
  204607. {
  204608. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204609. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204610. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204611. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204612. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204613. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204614. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204615. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204616. case tempDirectory:
  204617. {
  204618. WCHAR dest [2048];
  204619. dest[0] = 0;
  204620. GetTempPath (numElementsInArray (dest), dest);
  204621. return File (String (dest));
  204622. }
  204623. case invokedExecutableFile:
  204624. case currentExecutableFile:
  204625. case currentApplicationFile:
  204626. {
  204627. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204628. WCHAR dest [MAX_PATH + 256];
  204629. dest[0] = 0;
  204630. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204631. return File (String (dest));
  204632. }
  204633. case hostApplicationPath:
  204634. {
  204635. WCHAR dest [MAX_PATH + 256];
  204636. dest[0] = 0;
  204637. GetModuleFileName (0, dest, numElementsInArray (dest));
  204638. return File (String (dest));
  204639. }
  204640. default:
  204641. jassertfalse; // unknown type?
  204642. return File::nonexistent;
  204643. }
  204644. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204645. }
  204646. const File File::getCurrentWorkingDirectory()
  204647. {
  204648. WCHAR dest [MAX_PATH + 256];
  204649. dest[0] = 0;
  204650. GetCurrentDirectory (numElementsInArray (dest), dest);
  204651. return File (String (dest));
  204652. }
  204653. bool File::setAsCurrentWorkingDirectory() const
  204654. {
  204655. return SetCurrentDirectory (getFullPathName().toUTF16()) != FALSE;
  204656. }
  204657. const String File::getVersion() const
  204658. {
  204659. String result;
  204660. DWORD handle = 0;
  204661. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName().toUTF16(), &handle);
  204662. HeapBlock<char> buffer;
  204663. buffer.calloc (bufferSize);
  204664. if (GetFileVersionInfo (getFullPathName().toUTF16(), 0, bufferSize, buffer))
  204665. {
  204666. VS_FIXEDFILEINFO* vffi;
  204667. UINT len = 0;
  204668. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204669. {
  204670. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204671. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204672. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204673. << (int) LOWORD (vffi->dwFileVersionLS);
  204674. }
  204675. }
  204676. return result;
  204677. }
  204678. const File File::getLinkedTarget() const
  204679. {
  204680. File result (*this);
  204681. String p (getFullPathName());
  204682. if (! exists())
  204683. p += ".lnk";
  204684. else if (getFileExtension() != ".lnk")
  204685. return result;
  204686. ComSmartPtr <IShellLink> shellLink;
  204687. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204688. {
  204689. ComSmartPtr <IPersistFile> persistFile;
  204690. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204691. {
  204692. if (SUCCEEDED (persistFile->Load (p.toUTF16(), STGM_READ))
  204693. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204694. {
  204695. WIN32_FIND_DATA winFindData;
  204696. WCHAR resolvedPath [MAX_PATH];
  204697. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204698. result = File (resolvedPath);
  204699. }
  204700. }
  204701. }
  204702. return result;
  204703. }
  204704. class DirectoryIterator::NativeIterator::Pimpl
  204705. {
  204706. public:
  204707. Pimpl (const File& directory, const String& wildCard)
  204708. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204709. handle (INVALID_HANDLE_VALUE)
  204710. {
  204711. }
  204712. ~Pimpl()
  204713. {
  204714. if (handle != INVALID_HANDLE_VALUE)
  204715. FindClose (handle);
  204716. }
  204717. bool next (String& filenameFound,
  204718. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204719. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204720. {
  204721. using namespace WindowsFileHelpers;
  204722. WIN32_FIND_DATA findData;
  204723. if (handle == INVALID_HANDLE_VALUE)
  204724. {
  204725. handle = FindFirstFile (directoryWithWildCard.toUTF16(), &findData);
  204726. if (handle == INVALID_HANDLE_VALUE)
  204727. return false;
  204728. }
  204729. else
  204730. {
  204731. if (FindNextFile (handle, &findData) == 0)
  204732. return false;
  204733. }
  204734. filenameFound = findData.cFileName;
  204735. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204736. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204737. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204738. if (modTime != 0) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  204739. if (creationTime != 0) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  204740. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204741. return true;
  204742. }
  204743. private:
  204744. const String directoryWithWildCard;
  204745. HANDLE handle;
  204746. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204747. };
  204748. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204749. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204750. {
  204751. }
  204752. DirectoryIterator::NativeIterator::~NativeIterator()
  204753. {
  204754. }
  204755. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204756. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204757. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204758. {
  204759. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204760. }
  204761. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204762. {
  204763. HINSTANCE hInstance = 0;
  204764. JUCE_TRY
  204765. {
  204766. hInstance = ShellExecute (0, 0, fileName.toUTF16(), parameters.toUTF16(), 0, SW_SHOWDEFAULT);
  204767. }
  204768. JUCE_CATCH_ALL
  204769. return hInstance > (HINSTANCE) 32;
  204770. }
  204771. void File::revealToUser() const
  204772. {
  204773. if (isDirectory())
  204774. startAsProcess();
  204775. else if (getParentDirectory().exists())
  204776. getParentDirectory().startAsProcess();
  204777. }
  204778. class NamedPipeInternal
  204779. {
  204780. public:
  204781. NamedPipeInternal (const String& file, const bool isPipe_)
  204782. : pipeH (0),
  204783. cancelEvent (0),
  204784. connected (false),
  204785. isPipe (isPipe_)
  204786. {
  204787. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204788. pipeH = isPipe ? CreateNamedPipe (file.toUTF16(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204789. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204790. : CreateFile (file.toUTF16(), GENERIC_READ | GENERIC_WRITE, 0, 0,
  204791. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204792. }
  204793. ~NamedPipeInternal()
  204794. {
  204795. disconnectPipe();
  204796. if (pipeH != 0)
  204797. CloseHandle (pipeH);
  204798. CloseHandle (cancelEvent);
  204799. }
  204800. bool connect (const int timeOutMs)
  204801. {
  204802. if (! isPipe)
  204803. return true;
  204804. if (! connected)
  204805. {
  204806. OVERLAPPED over;
  204807. zerostruct (over);
  204808. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204809. if (ConnectNamedPipe (pipeH, &over))
  204810. {
  204811. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204812. }
  204813. else
  204814. {
  204815. const int err = GetLastError();
  204816. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204817. {
  204818. HANDLE handles[] = { over.hEvent, cancelEvent };
  204819. if (WaitForMultipleObjects (2, handles, FALSE,
  204820. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204821. connected = true;
  204822. }
  204823. else if (err == ERROR_PIPE_CONNECTED)
  204824. {
  204825. connected = true;
  204826. }
  204827. }
  204828. CloseHandle (over.hEvent);
  204829. }
  204830. return connected;
  204831. }
  204832. void disconnectPipe()
  204833. {
  204834. if (connected)
  204835. {
  204836. DisconnectNamedPipe (pipeH);
  204837. connected = false;
  204838. }
  204839. }
  204840. HANDLE pipeH;
  204841. HANDLE cancelEvent;
  204842. bool connected, isPipe;
  204843. };
  204844. void NamedPipe::close()
  204845. {
  204846. cancelPendingReads();
  204847. const ScopedLock sl (lock);
  204848. delete static_cast<NamedPipeInternal*> (internal);
  204849. internal = 0;
  204850. }
  204851. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204852. {
  204853. close();
  204854. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204855. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204856. {
  204857. internal = intern.release();
  204858. return true;
  204859. }
  204860. return false;
  204861. }
  204862. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204863. {
  204864. const ScopedLock sl (lock);
  204865. int bytesRead = -1;
  204866. bool waitAgain = true;
  204867. while (waitAgain && internal != 0)
  204868. {
  204869. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204870. waitAgain = false;
  204871. if (! intern->connect (timeOutMilliseconds))
  204872. break;
  204873. if (maxBytesToRead <= 0)
  204874. return 0;
  204875. OVERLAPPED over;
  204876. zerostruct (over);
  204877. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204878. unsigned long numRead;
  204879. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204880. {
  204881. bytesRead = (int) numRead;
  204882. }
  204883. else if (GetLastError() == ERROR_IO_PENDING)
  204884. {
  204885. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204886. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204887. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204888. : INFINITE);
  204889. if (waitResult != WAIT_OBJECT_0)
  204890. {
  204891. // if the operation timed out, let's cancel it...
  204892. CancelIo (intern->pipeH);
  204893. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204894. }
  204895. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204896. {
  204897. bytesRead = (int) numRead;
  204898. }
  204899. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204900. {
  204901. intern->disconnectPipe();
  204902. waitAgain = true;
  204903. }
  204904. }
  204905. else
  204906. {
  204907. waitAgain = internal != 0;
  204908. Sleep (5);
  204909. }
  204910. CloseHandle (over.hEvent);
  204911. }
  204912. return bytesRead;
  204913. }
  204914. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204915. {
  204916. int bytesWritten = -1;
  204917. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204918. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204919. {
  204920. if (numBytesToWrite <= 0)
  204921. return 0;
  204922. OVERLAPPED over;
  204923. zerostruct (over);
  204924. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204925. unsigned long numWritten;
  204926. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204927. {
  204928. bytesWritten = (int) numWritten;
  204929. }
  204930. else if (GetLastError() == ERROR_IO_PENDING)
  204931. {
  204932. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204933. DWORD waitResult;
  204934. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204935. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204936. : INFINITE);
  204937. if (waitResult != WAIT_OBJECT_0)
  204938. {
  204939. CancelIo (intern->pipeH);
  204940. WaitForSingleObject (over.hEvent, INFINITE);
  204941. }
  204942. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204943. {
  204944. bytesWritten = (int) numWritten;
  204945. }
  204946. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204947. {
  204948. intern->disconnectPipe();
  204949. }
  204950. }
  204951. CloseHandle (over.hEvent);
  204952. }
  204953. return bytesWritten;
  204954. }
  204955. void NamedPipe::cancelPendingReads()
  204956. {
  204957. if (internal != 0)
  204958. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204959. }
  204960. #endif
  204961. /*** End of inlined file: juce_win32_Files.cpp ***/
  204962. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204963. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204964. // compiled on its own).
  204965. #if JUCE_INCLUDED_FILE
  204966. #ifndef INTERNET_FLAG_NEED_FILE
  204967. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204968. #endif
  204969. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204970. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204971. #endif
  204972. #ifndef WORKAROUND_TIMEOUT_BUG
  204973. //#define WORKAROUND_TIMEOUT_BUG 1
  204974. #endif
  204975. #if WORKAROUND_TIMEOUT_BUG
  204976. // Required because of a Microsoft bug in setting a timeout
  204977. class InternetConnectThread : public Thread
  204978. {
  204979. public:
  204980. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET sessionHandle_, HINTERNET& connection_, const bool isFtp_)
  204981. : Thread ("Internet"), uc (uc_), sessionHandle (sessionHandle_), connection (connection_), isFtp (isFtp_)
  204982. {
  204983. startThread();
  204984. }
  204985. ~InternetConnectThread()
  204986. {
  204987. stopThread (60000);
  204988. }
  204989. void run()
  204990. {
  204991. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204992. uc.nPort, _T(""), _T(""),
  204993. isFtp ? INTERNET_SERVICE_FTP
  204994. : INTERNET_SERVICE_HTTP,
  204995. 0, 0);
  204996. notify();
  204997. }
  204998. private:
  204999. URL_COMPONENTS& uc;
  205000. HINTERNET sessionHandle;
  205001. HINTERNET& connection;
  205002. const bool isFtp;
  205003. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  205004. };
  205005. #endif
  205006. class WebInputStream : public InputStream
  205007. {
  205008. public:
  205009. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  205010. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  205011. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  205012. : connection (0), request (0),
  205013. address (address_), headers (headers_), postData (postData_), position (0),
  205014. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  205015. {
  205016. createConnection (progressCallback, progressCallbackContext);
  205017. if (responseHeaders != 0 && ! isError())
  205018. {
  205019. DWORD bufferSizeBytes = 4096;
  205020. for (;;)
  205021. {
  205022. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  205023. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  205024. {
  205025. StringArray headersArray;
  205026. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  205027. for (int i = 0; i < headersArray.size(); ++i)
  205028. {
  205029. const String& header = headersArray[i];
  205030. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  205031. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205032. const String previousValue ((*responseHeaders) [key]);
  205033. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205034. }
  205035. break;
  205036. }
  205037. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205038. break;
  205039. }
  205040. }
  205041. }
  205042. ~WebInputStream()
  205043. {
  205044. close();
  205045. }
  205046. bool isError() const { return request == 0; }
  205047. bool isExhausted() { return finished; }
  205048. int64 getPosition() { return position; }
  205049. int64 getTotalLength()
  205050. {
  205051. if (! isError())
  205052. {
  205053. DWORD index = 0, result = 0, size = sizeof (result);
  205054. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  205055. return (int64) result;
  205056. }
  205057. return -1;
  205058. }
  205059. int read (void* buffer, int bytesToRead)
  205060. {
  205061. DWORD bytesRead = 0;
  205062. if (! (finished || isError()))
  205063. {
  205064. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  205065. position += bytesRead;
  205066. if (bytesRead == 0)
  205067. finished = true;
  205068. }
  205069. return (int) bytesRead;
  205070. }
  205071. bool setPosition (int64 wantedPos)
  205072. {
  205073. if (isError())
  205074. return false;
  205075. if (wantedPos != position)
  205076. {
  205077. finished = false;
  205078. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  205079. if (position == wantedPos)
  205080. return true;
  205081. if (wantedPos < position)
  205082. {
  205083. close();
  205084. position = 0;
  205085. createConnection (0, 0);
  205086. }
  205087. skipNextBytes (wantedPos - position);
  205088. }
  205089. return true;
  205090. }
  205091. private:
  205092. HINTERNET connection, request;
  205093. String address, headers;
  205094. MemoryBlock postData;
  205095. int64 position;
  205096. bool finished;
  205097. const bool isPost;
  205098. int timeOutMs;
  205099. void close()
  205100. {
  205101. if (request != 0)
  205102. {
  205103. InternetCloseHandle (request);
  205104. request = 0;
  205105. }
  205106. if (connection != 0)
  205107. {
  205108. InternetCloseHandle (connection);
  205109. connection = 0;
  205110. }
  205111. }
  205112. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  205113. void* progressCallbackContext)
  205114. {
  205115. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  205116. close();
  205117. if (sessionHandle != 0)
  205118. {
  205119. // break up the url..
  205120. TCHAR file[1024], server[1024];
  205121. URL_COMPONENTS uc;
  205122. zerostruct (uc);
  205123. uc.dwStructSize = sizeof (uc);
  205124. uc.dwUrlPathLength = sizeof (file);
  205125. uc.dwHostNameLength = sizeof (server);
  205126. uc.lpszUrlPath = file;
  205127. uc.lpszHostName = server;
  205128. if (InternetCrackUrl (address.toUTF16(), 0, 0, &uc))
  205129. {
  205130. int disable = 1;
  205131. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  205132. if (timeOutMs == 0)
  205133. timeOutMs = 30000;
  205134. else if (timeOutMs < 0)
  205135. timeOutMs = -1;
  205136. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  205137. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  205138. #if WORKAROUND_TIMEOUT_BUG
  205139. connection = 0;
  205140. {
  205141. InternetConnectThread connectThread (uc, sessionHandle, connection, isFtp);
  205142. connectThread.wait (timeOutMs);
  205143. if (connection == 0)
  205144. {
  205145. InternetCloseHandle (sessionHandle);
  205146. sessionHandle = 0;
  205147. }
  205148. }
  205149. #else
  205150. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  205151. _T(""), _T(""),
  205152. isFtp ? INTERNET_SERVICE_FTP
  205153. : INTERNET_SERVICE_HTTP,
  205154. 0, 0);
  205155. #endif
  205156. if (connection != 0)
  205157. {
  205158. if (isFtp)
  205159. {
  205160. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  205161. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  205162. }
  205163. else
  205164. {
  205165. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  205166. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  205167. if (address.startsWithIgnoreCase ("https:"))
  205168. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  205169. // IE7 seems to automatically work out when it's https)
  205170. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  205171. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  205172. if (request != 0)
  205173. {
  205174. INTERNET_BUFFERS buffers;
  205175. zerostruct (buffers);
  205176. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  205177. buffers.lpcszHeader = headers.toUTF16();
  205178. buffers.dwHeadersLength = headers.length();
  205179. buffers.dwBufferTotal = (DWORD) postData.getSize();
  205180. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  205181. {
  205182. int bytesSent = 0;
  205183. for (;;)
  205184. {
  205185. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  205186. DWORD bytesDone = 0;
  205187. if (bytesToDo > 0
  205188. && ! InternetWriteFile (request,
  205189. static_cast <const char*> (postData.getData()) + bytesSent,
  205190. bytesToDo, &bytesDone))
  205191. {
  205192. break;
  205193. }
  205194. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  205195. {
  205196. if (HttpEndRequest (request, 0, 0, 0))
  205197. return;
  205198. break;
  205199. }
  205200. bytesSent += bytesDone;
  205201. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  205202. break;
  205203. }
  205204. }
  205205. }
  205206. close();
  205207. }
  205208. }
  205209. }
  205210. }
  205211. }
  205212. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  205213. };
  205214. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  205215. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  205216. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  205217. {
  205218. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  205219. progressCallback, progressCallbackContext,
  205220. headers, timeOutMs, responseHeaders));
  205221. return wi->isError() ? 0 : wi.release();
  205222. }
  205223. namespace MACAddressHelpers
  205224. {
  205225. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  205226. {
  205227. DynamicLibraryLoader dll ("iphlpapi.dll");
  205228. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205229. if (getAdaptersInfo != 0)
  205230. {
  205231. ULONG len = sizeof (IP_ADAPTER_INFO);
  205232. MemoryBlock mb;
  205233. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205234. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205235. {
  205236. mb.setSize (len);
  205237. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205238. }
  205239. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205240. {
  205241. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  205242. {
  205243. if (adapter->AddressLength >= 6)
  205244. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  205245. }
  205246. }
  205247. }
  205248. }
  205249. void getViaNetBios (Array<MACAddress>& result)
  205250. {
  205251. DynamicLibraryLoader dll ("netapi32.dll");
  205252. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205253. if (NetbiosCall != 0)
  205254. {
  205255. NCB ncb;
  205256. zerostruct (ncb);
  205257. struct ASTAT
  205258. {
  205259. ADAPTER_STATUS adapt;
  205260. NAME_BUFFER NameBuff [30];
  205261. };
  205262. ASTAT astat;
  205263. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205264. LANA_ENUM enums;
  205265. zerostruct (enums);
  205266. ncb.ncb_command = NCBENUM;
  205267. ncb.ncb_buffer = (unsigned char*) &enums;
  205268. ncb.ncb_length = sizeof (LANA_ENUM);
  205269. NetbiosCall (&ncb);
  205270. for (int i = 0; i < enums.length; ++i)
  205271. {
  205272. zerostruct (ncb);
  205273. ncb.ncb_command = NCBRESET;
  205274. ncb.ncb_lana_num = enums.lana[i];
  205275. if (NetbiosCall (&ncb) == 0)
  205276. {
  205277. zerostruct (ncb);
  205278. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205279. ncb.ncb_command = NCBASTAT;
  205280. ncb.ncb_lana_num = enums.lana[i];
  205281. ncb.ncb_buffer = (unsigned char*) &astat;
  205282. ncb.ncb_length = sizeof (ASTAT);
  205283. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  205284. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  205285. }
  205286. }
  205287. }
  205288. }
  205289. }
  205290. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  205291. {
  205292. MACAddressHelpers::getViaGetAdaptersInfo (result);
  205293. MACAddressHelpers::getViaNetBios (result);
  205294. }
  205295. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205296. const String& emailSubject,
  205297. const String& bodyText,
  205298. const StringArray& filesToAttach)
  205299. {
  205300. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205301. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205302. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205303. bool ok = false;
  205304. if (mapiSendMail != 0)
  205305. {
  205306. MapiMessage message;
  205307. zerostruct (message);
  205308. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205309. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205310. MapiRecipDesc recip;
  205311. zerostruct (recip);
  205312. recip.ulRecipClass = MAPI_TO;
  205313. String targetEmailAddress_ (targetEmailAddress);
  205314. if (targetEmailAddress_.isEmpty())
  205315. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205316. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205317. message.nRecipCount = 1;
  205318. message.lpRecips = &recip;
  205319. HeapBlock <MapiFileDesc> files;
  205320. files.calloc (filesToAttach.size());
  205321. message.nFileCount = filesToAttach.size();
  205322. message.lpFiles = files;
  205323. for (int i = 0; i < filesToAttach.size(); ++i)
  205324. {
  205325. files[i].nPosition = (ULONG) -1;
  205326. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205327. }
  205328. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205329. }
  205330. FreeLibrary (h);
  205331. return ok;
  205332. }
  205333. #endif
  205334. /*** End of inlined file: juce_win32_Network.cpp ***/
  205335. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205336. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205337. // compiled on its own).
  205338. #if JUCE_INCLUDED_FILE
  205339. namespace
  205340. {
  205341. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  205342. {
  205343. HKEY rootKey = 0;
  205344. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205345. rootKey = HKEY_CURRENT_USER;
  205346. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205347. rootKey = HKEY_LOCAL_MACHINE;
  205348. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205349. rootKey = HKEY_CLASSES_ROOT;
  205350. if (rootKey != 0)
  205351. {
  205352. name = name.substring (name.indexOfChar ('\\') + 1);
  205353. const int lastSlash = name.lastIndexOfChar ('\\');
  205354. valueName = name.substring (lastSlash + 1);
  205355. name = name.substring (0, lastSlash);
  205356. HKEY key;
  205357. DWORD result;
  205358. if (createForWriting)
  205359. {
  205360. if (RegCreateKeyEx (rootKey, name.toUTF16(), 0, 0, REG_OPTION_NON_VOLATILE,
  205361. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205362. return key;
  205363. }
  205364. else
  205365. {
  205366. if (RegOpenKeyEx (rootKey, name.toUTF16(), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205367. return key;
  205368. }
  205369. }
  205370. return 0;
  205371. }
  205372. }
  205373. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205374. const String& defaultValue)
  205375. {
  205376. String valueName, result (defaultValue);
  205377. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205378. if (k != 0)
  205379. {
  205380. WCHAR buffer [2048];
  205381. unsigned long bufferSize = sizeof (buffer);
  205382. DWORD type = REG_SZ;
  205383. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205384. {
  205385. if (type == REG_SZ)
  205386. result = buffer;
  205387. else if (type == REG_DWORD)
  205388. result = String ((int) *(DWORD*) buffer);
  205389. }
  205390. RegCloseKey (k);
  205391. }
  205392. return result;
  205393. }
  205394. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205395. const String& value)
  205396. {
  205397. String valueName;
  205398. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205399. if (k != 0)
  205400. {
  205401. RegSetValueEx (k, valueName.toUTF16(), 0, REG_SZ,
  205402. (const BYTE*) value.toUTF16().getAddress(),
  205403. CharPointer_UTF16::getBytesRequiredFor (value.getCharPointer()));
  205404. RegCloseKey (k);
  205405. }
  205406. }
  205407. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205408. {
  205409. bool exists = false;
  205410. String valueName;
  205411. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205412. if (k != 0)
  205413. {
  205414. unsigned char buffer [2048];
  205415. unsigned long bufferSize = sizeof (buffer);
  205416. DWORD type = 0;
  205417. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205418. exists = true;
  205419. RegCloseKey (k);
  205420. }
  205421. return exists;
  205422. }
  205423. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205424. {
  205425. String valueName;
  205426. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205427. if (k != 0)
  205428. {
  205429. RegDeleteValue (k, valueName.toUTF16());
  205430. RegCloseKey (k);
  205431. }
  205432. }
  205433. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205434. {
  205435. String valueName;
  205436. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205437. if (k != 0)
  205438. {
  205439. RegDeleteKey (k, valueName.toUTF16());
  205440. RegCloseKey (k);
  205441. }
  205442. }
  205443. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205444. const String& symbolicDescription,
  205445. const String& fullDescription,
  205446. const File& targetExecutable,
  205447. int iconResourceNumber)
  205448. {
  205449. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205450. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205451. if (iconResourceNumber != 0)
  205452. setRegistryValue (key + "\\DefaultIcon\\",
  205453. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205454. setRegistryValue (key + "\\", fullDescription);
  205455. setRegistryValue (key + "\\shell\\open\\command\\",
  205456. targetExecutable.getFullPathName() + " %1");
  205457. }
  205458. bool juce_IsRunningInWine()
  205459. {
  205460. HKEY key;
  205461. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205462. {
  205463. RegCloseKey (key);
  205464. return true;
  205465. }
  205466. return false;
  205467. }
  205468. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205469. {
  205470. String s (::GetCommandLineW());
  205471. StringArray tokens;
  205472. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205473. return tokens.joinIntoString (" ", 1);
  205474. }
  205475. static void* currentModuleHandle = 0;
  205476. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205477. {
  205478. if (currentModuleHandle == 0)
  205479. currentModuleHandle = GetModuleHandle (0);
  205480. return currentModuleHandle;
  205481. }
  205482. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205483. {
  205484. currentModuleHandle = newHandle;
  205485. }
  205486. void PlatformUtilities::fpuReset()
  205487. {
  205488. #if JUCE_MSVC
  205489. _clearfp();
  205490. #endif
  205491. }
  205492. void PlatformUtilities::beep()
  205493. {
  205494. MessageBeep (MB_OK);
  205495. }
  205496. #endif
  205497. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205498. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205499. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205500. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205501. // compiled on its own).
  205502. #if JUCE_INCLUDED_FILE
  205503. static const unsigned int specialId = WM_APP + 0x4400;
  205504. static const unsigned int broadcastId = WM_APP + 0x4403;
  205505. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205506. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205507. HWND juce_messageWindowHandle = 0;
  205508. extern long improbableWindowNumber; // defined in windowing.cpp
  205509. #ifndef WM_APPCOMMAND
  205510. #define WM_APPCOMMAND 0x0319
  205511. #endif
  205512. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205513. const UINT message,
  205514. const WPARAM wParam,
  205515. const LPARAM lParam) throw()
  205516. {
  205517. JUCE_TRY
  205518. {
  205519. if (h == juce_messageWindowHandle)
  205520. {
  205521. if (message == specialCallbackId)
  205522. {
  205523. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205524. return (LRESULT) (*func) ((void*) lParam);
  205525. }
  205526. else if (message == specialId)
  205527. {
  205528. // these are trapped early in the dispatch call, but must also be checked
  205529. // here in case there are windows modal dialog boxes doing their own
  205530. // dispatch loop and not calling our version
  205531. Message* const message = reinterpret_cast <Message*> (lParam);
  205532. MessageManager::getInstance()->deliverMessage (message);
  205533. message->decReferenceCount();
  205534. return 0;
  205535. }
  205536. else if (message == broadcastId)
  205537. {
  205538. const ScopedPointer <String> messageString ((String*) lParam);
  205539. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205540. return 0;
  205541. }
  205542. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205543. {
  205544. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205545. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205546. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205547. return 0;
  205548. }
  205549. }
  205550. }
  205551. JUCE_CATCH_EXCEPTION
  205552. return DefWindowProc (h, message, wParam, lParam);
  205553. }
  205554. static bool isEventBlockedByModalComps (MSG& m)
  205555. {
  205556. if (Component::getNumCurrentlyModalComponents() == 0
  205557. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205558. return false;
  205559. switch (m.message)
  205560. {
  205561. case WM_MOUSEMOVE:
  205562. case WM_NCMOUSEMOVE:
  205563. case 0x020A: /* WM_MOUSEWHEEL */
  205564. case 0x020E: /* WM_MOUSEHWHEEL */
  205565. case WM_KEYUP:
  205566. case WM_SYSKEYUP:
  205567. case WM_CHAR:
  205568. case WM_APPCOMMAND:
  205569. case WM_LBUTTONUP:
  205570. case WM_MBUTTONUP:
  205571. case WM_RBUTTONUP:
  205572. case WM_MOUSEACTIVATE:
  205573. case WM_NCMOUSEHOVER:
  205574. case WM_MOUSEHOVER:
  205575. return true;
  205576. case WM_NCLBUTTONDOWN:
  205577. case WM_NCLBUTTONDBLCLK:
  205578. case WM_NCRBUTTONDOWN:
  205579. case WM_NCRBUTTONDBLCLK:
  205580. case WM_NCMBUTTONDOWN:
  205581. case WM_NCMBUTTONDBLCLK:
  205582. case WM_LBUTTONDOWN:
  205583. case WM_LBUTTONDBLCLK:
  205584. case WM_MBUTTONDOWN:
  205585. case WM_MBUTTONDBLCLK:
  205586. case WM_RBUTTONDOWN:
  205587. case WM_RBUTTONDBLCLK:
  205588. case WM_KEYDOWN:
  205589. case WM_SYSKEYDOWN:
  205590. {
  205591. Component* const modal = Component::getCurrentlyModalComponent (0);
  205592. if (modal != 0)
  205593. modal->inputAttemptWhenModal();
  205594. return true;
  205595. }
  205596. default:
  205597. break;
  205598. }
  205599. return false;
  205600. }
  205601. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205602. {
  205603. MSG m;
  205604. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205605. return false;
  205606. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205607. {
  205608. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205609. {
  205610. Message* const message = reinterpret_cast <Message*> (m.lParam);
  205611. MessageManager::getInstance()->deliverMessage (message);
  205612. message->decReferenceCount();
  205613. }
  205614. else if (m.message == WM_QUIT)
  205615. {
  205616. if (JUCEApplication::getInstance() != 0)
  205617. JUCEApplication::getInstance()->systemRequestedQuit();
  205618. }
  205619. else if (! isEventBlockedByModalComps (m))
  205620. {
  205621. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205622. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205623. {
  205624. // if it's someone else's window being clicked on, and the focus is
  205625. // currently on a juce window, pass the kb focus over..
  205626. HWND currentFocus = GetFocus();
  205627. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205628. SetFocus (m.hwnd);
  205629. }
  205630. TranslateMessage (&m);
  205631. DispatchMessage (&m);
  205632. }
  205633. }
  205634. return true;
  205635. }
  205636. bool juce_postMessageToSystemQueue (Message* message)
  205637. {
  205638. message->incReferenceCount();
  205639. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205640. }
  205641. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205642. void* userData)
  205643. {
  205644. if (MessageManager::getInstance()->isThisTheMessageThread())
  205645. {
  205646. return (*callback) (userData);
  205647. }
  205648. else
  205649. {
  205650. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205651. // deadlock because the message manager is blocked from running, and can't
  205652. // call your function..
  205653. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205654. return (void*) SendMessage (juce_messageWindowHandle,
  205655. specialCallbackId,
  205656. (WPARAM) callback,
  205657. (LPARAM) userData);
  205658. }
  205659. }
  205660. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205661. {
  205662. if (hwnd != juce_messageWindowHandle)
  205663. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205664. return TRUE;
  205665. }
  205666. void MessageManager::broadcastMessage (const String& value)
  205667. {
  205668. Array<void*> windows;
  205669. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205670. const String localCopy (value);
  205671. COPYDATASTRUCT data;
  205672. data.dwData = broadcastId;
  205673. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205674. data.lpData = (void*) localCopy.toUTF16().getAddress();
  205675. for (int i = windows.size(); --i >= 0;)
  205676. {
  205677. HWND hwnd = (HWND) windows.getUnchecked(i);
  205678. TCHAR windowName [64]; // no need to read longer strings than this
  205679. GetWindowText (hwnd, windowName, 64);
  205680. windowName [63] = 0;
  205681. if (String (windowName) == messageWindowName)
  205682. {
  205683. DWORD_PTR result;
  205684. SendMessageTimeout (hwnd, WM_COPYDATA,
  205685. (WPARAM) juce_messageWindowHandle,
  205686. (LPARAM) &data,
  205687. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205688. 8000,
  205689. &result);
  205690. }
  205691. }
  205692. }
  205693. static const String getMessageWindowClassName()
  205694. {
  205695. // this name has to be different for each app/dll instance because otherwise
  205696. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205697. // window class).
  205698. static int number = 0;
  205699. if (number == 0)
  205700. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205701. return "JUCEcs_" + String (number);
  205702. }
  205703. void MessageManager::doPlatformSpecificInitialisation()
  205704. {
  205705. OleInitialize (0);
  205706. const String className (getMessageWindowClassName());
  205707. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205708. WNDCLASSEX wc;
  205709. zerostruct (wc);
  205710. wc.cbSize = sizeof (wc);
  205711. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205712. wc.cbWndExtra = 4;
  205713. wc.hInstance = hmod;
  205714. wc.lpszClassName = className.toUTF16();
  205715. RegisterClassEx (&wc);
  205716. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205717. messageWindowName,
  205718. 0, 0, 0, 0, 0, 0, 0,
  205719. hmod, 0);
  205720. }
  205721. void MessageManager::doPlatformSpecificShutdown()
  205722. {
  205723. DestroyWindow (juce_messageWindowHandle);
  205724. UnregisterClass (getMessageWindowClassName().toUTF16(), 0);
  205725. OleUninitialize();
  205726. }
  205727. #endif
  205728. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205729. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205730. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205731. // compiled on its own).
  205732. #if JUCE_INCLUDED_FILE
  205733. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205734. NEWTEXTMETRICEXW*,
  205735. int type,
  205736. LPARAM lParam)
  205737. {
  205738. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205739. {
  205740. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205741. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205742. }
  205743. return 1;
  205744. }
  205745. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205746. NEWTEXTMETRICEXW*,
  205747. int type,
  205748. LPARAM lParam)
  205749. {
  205750. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205751. {
  205752. LOGFONTW lf;
  205753. zerostruct (lf);
  205754. lf.lfWeight = FW_DONTCARE;
  205755. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205756. lf.lfQuality = DEFAULT_QUALITY;
  205757. lf.lfCharSet = DEFAULT_CHARSET;
  205758. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205759. lf.lfPitchAndFamily = FF_DONTCARE;
  205760. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205761. fontName.copyToUTF16 (lf.lfFaceName, LF_FACESIZE - 1);
  205762. HDC dc = CreateCompatibleDC (0);
  205763. EnumFontFamiliesEx (dc, &lf,
  205764. (FONTENUMPROCW) &wfontEnum2,
  205765. lParam, 0);
  205766. DeleteDC (dc);
  205767. }
  205768. return 1;
  205769. }
  205770. const StringArray Font::findAllTypefaceNames()
  205771. {
  205772. StringArray results;
  205773. HDC dc = CreateCompatibleDC (0);
  205774. {
  205775. LOGFONTW lf;
  205776. zerostruct (lf);
  205777. lf.lfWeight = FW_DONTCARE;
  205778. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205779. lf.lfQuality = DEFAULT_QUALITY;
  205780. lf.lfCharSet = DEFAULT_CHARSET;
  205781. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205782. lf.lfPitchAndFamily = FF_DONTCARE;
  205783. lf.lfFaceName[0] = 0;
  205784. EnumFontFamiliesEx (dc, &lf,
  205785. (FONTENUMPROCW) &wfontEnum1,
  205786. (LPARAM) &results, 0);
  205787. }
  205788. DeleteDC (dc);
  205789. results.sort (true);
  205790. return results;
  205791. }
  205792. extern bool juce_IsRunningInWine();
  205793. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205794. {
  205795. if (juce_IsRunningInWine())
  205796. {
  205797. // If we're running in Wine, then use fonts that might be available on Linux..
  205798. defaultSans = "Bitstream Vera Sans";
  205799. defaultSerif = "Bitstream Vera Serif";
  205800. defaultFixed = "Bitstream Vera Sans Mono";
  205801. }
  205802. else
  205803. {
  205804. defaultSans = "Verdana";
  205805. defaultSerif = "Times";
  205806. defaultFixed = "Lucida Console";
  205807. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205808. }
  205809. }
  205810. class FontDCHolder : private DeletedAtShutdown
  205811. {
  205812. public:
  205813. FontDCHolder()
  205814. : fontH (0), previousFontH (0), dc (0), numKPs (0), size (0),
  205815. bold (false), italic (false)
  205816. {
  205817. }
  205818. ~FontDCHolder()
  205819. {
  205820. deleteDCAndFont();
  205821. clearSingletonInstance();
  205822. }
  205823. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205824. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205825. {
  205826. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205827. {
  205828. fontName = fontName_;
  205829. bold = bold_;
  205830. italic = italic_;
  205831. size = size_;
  205832. deleteDCAndFont();
  205833. dc = CreateCompatibleDC (0);
  205834. SetMapperFlags (dc, 0);
  205835. SetMapMode (dc, MM_TEXT);
  205836. LOGFONTW lfw;
  205837. zerostruct (lfw);
  205838. lfw.lfCharSet = DEFAULT_CHARSET;
  205839. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205840. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205841. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205842. lfw.lfQuality = PROOF_QUALITY;
  205843. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205844. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205845. fontName.copyToUTF16 (lfw.lfFaceName, LF_FACESIZE - 1);
  205846. lfw.lfHeight = size > 0 ? size : -256;
  205847. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205848. if (standardSizedFont != 0)
  205849. {
  205850. if ((previousFontH = SelectObject (dc, standardSizedFont)) != 0)
  205851. {
  205852. fontH = standardSizedFont;
  205853. if (size == 0)
  205854. {
  205855. OUTLINETEXTMETRIC otm;
  205856. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205857. {
  205858. lfw.lfHeight = -(int) otm.otmEMSquare;
  205859. fontH = CreateFontIndirect (&lfw);
  205860. SelectObject (dc, fontH);
  205861. DeleteObject (standardSizedFont);
  205862. }
  205863. }
  205864. }
  205865. }
  205866. }
  205867. return dc;
  205868. }
  205869. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205870. {
  205871. if (kps == 0)
  205872. {
  205873. numKPs = GetKerningPairs (dc, 0, 0);
  205874. kps.calloc (numKPs);
  205875. GetKerningPairs (dc, numKPs, kps);
  205876. }
  205877. numKPs_ = numKPs;
  205878. return kps;
  205879. }
  205880. private:
  205881. HFONT fontH;
  205882. HGDIOBJ previousFontH;
  205883. HDC dc;
  205884. String fontName;
  205885. HeapBlock <KERNINGPAIR> kps;
  205886. int numKPs, size;
  205887. bool bold, italic;
  205888. void deleteDCAndFont()
  205889. {
  205890. if (dc != 0)
  205891. {
  205892. SelectObject (dc, previousFontH); // Replacing the previous font before deleting the DC avoids a warning in BoundsChecker
  205893. DeleteDC (dc);
  205894. dc = 0;
  205895. }
  205896. if (fontH != 0)
  205897. {
  205898. DeleteObject (fontH);
  205899. fontH = 0;
  205900. }
  205901. kps.free();
  205902. }
  205903. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205904. };
  205905. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205906. class WindowsTypeface : public CustomTypeface
  205907. {
  205908. public:
  205909. WindowsTypeface (const Font& font)
  205910. {
  205911. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205912. font.isBold(), font.isItalic(), 0);
  205913. TEXTMETRIC tm;
  205914. tm.tmAscent = tm.tmHeight = 1;
  205915. tm.tmDefaultChar = 0;
  205916. GetTextMetrics (dc, &tm);
  205917. setCharacteristics (font.getTypefaceName(),
  205918. tm.tmAscent / (float) tm.tmHeight,
  205919. font.isBold(), font.isItalic(),
  205920. tm.tmDefaultChar);
  205921. }
  205922. bool loadGlyphIfPossible (juce_wchar character)
  205923. {
  205924. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205925. GLYPHMETRICS gm;
  205926. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205927. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205928. // gets correctly created later on.
  205929. if (! isFallbackFont)
  205930. {
  205931. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205932. WORD index = 0;
  205933. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205934. && index == 0xffff)
  205935. {
  205936. return false;
  205937. }
  205938. }
  205939. Path glyphPath;
  205940. TEXTMETRIC tm;
  205941. if (! GetTextMetrics (dc, &tm))
  205942. {
  205943. addGlyph (character, glyphPath, 0);
  205944. return true;
  205945. }
  205946. const float height = (float) tm.tmHeight;
  205947. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205948. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205949. &gm, 0, 0, &identityMatrix);
  205950. if (bufSize > 0)
  205951. {
  205952. HeapBlock<char> data (bufSize);
  205953. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205954. bufSize, data, &identityMatrix);
  205955. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205956. const float scaleX = 1.0f / height;
  205957. const float scaleY = -1.0f / height;
  205958. while ((char*) pheader < data + bufSize)
  205959. {
  205960. float x = scaleX * pheader->pfxStart.x.value;
  205961. float y = scaleY * pheader->pfxStart.y.value;
  205962. glyphPath.startNewSubPath (x, y);
  205963. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205964. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205965. while ((const char*) curve < curveEnd)
  205966. {
  205967. if (curve->wType == TT_PRIM_LINE)
  205968. {
  205969. for (int i = 0; i < curve->cpfx; ++i)
  205970. {
  205971. x = scaleX * curve->apfx[i].x.value;
  205972. y = scaleY * curve->apfx[i].y.value;
  205973. glyphPath.lineTo (x, y);
  205974. }
  205975. }
  205976. else if (curve->wType == TT_PRIM_QSPLINE)
  205977. {
  205978. for (int i = 0; i < curve->cpfx - 1; ++i)
  205979. {
  205980. const float x2 = scaleX * curve->apfx[i].x.value;
  205981. const float y2 = scaleY * curve->apfx[i].y.value;
  205982. float x3, y3;
  205983. if (i < curve->cpfx - 2)
  205984. {
  205985. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205986. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205987. }
  205988. else
  205989. {
  205990. x3 = scaleX * curve->apfx[i + 1].x.value;
  205991. y3 = scaleY * curve->apfx[i + 1].y.value;
  205992. }
  205993. glyphPath.quadraticTo (x2, y2, x3, y3);
  205994. x = x3;
  205995. y = y3;
  205996. }
  205997. }
  205998. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205999. }
  206000. pheader = (const TTPOLYGONHEADER*) curve;
  206001. glyphPath.closeSubPath();
  206002. }
  206003. }
  206004. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  206005. int numKPs;
  206006. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  206007. for (int i = 0; i < numKPs; ++i)
  206008. {
  206009. if (kps[i].wFirst == character)
  206010. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  206011. kps[i].iKernAmount / height);
  206012. }
  206013. return true;
  206014. }
  206015. private:
  206016. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  206017. };
  206018. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  206019. {
  206020. return new WindowsTypeface (font);
  206021. }
  206022. #endif
  206023. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  206024. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206025. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206026. // compiled on its own).
  206027. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  206028. class SharedD2DFactory : public DeletedAtShutdown
  206029. {
  206030. public:
  206031. SharedD2DFactory()
  206032. {
  206033. jassertfalse; //xxx Direct2D support isn't ready for use yet!
  206034. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, d2dFactory.resetAndGetPointerAddress());
  206035. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) directWriteFactory.resetAndGetPointerAddress());
  206036. if (directWriteFactory != 0)
  206037. directWriteFactory->GetSystemFontCollection (systemFonts.resetAndGetPointerAddress());
  206038. }
  206039. ~SharedD2DFactory()
  206040. {
  206041. clearSingletonInstance();
  206042. }
  206043. juce_DeclareSingleton (SharedD2DFactory, false);
  206044. ComSmartPtr <ID2D1Factory> d2dFactory;
  206045. ComSmartPtr <IDWriteFactory> directWriteFactory;
  206046. ComSmartPtr <IDWriteFontCollection> systemFonts;
  206047. };
  206048. juce_ImplementSingleton (SharedD2DFactory)
  206049. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  206050. {
  206051. public:
  206052. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  206053. : hwnd (hwnd_),
  206054. currentState (0)
  206055. {
  206056. RECT windowRect;
  206057. GetClientRect (hwnd, &windowRect);
  206058. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206059. bounds.setSize (size.width, size.height);
  206060. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  206061. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  206062. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, renderingTarget.resetAndGetPointerAddress());
  206063. // xxx check for error
  206064. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), colourBrush.resetAndGetPointerAddress());
  206065. }
  206066. ~Direct2DLowLevelGraphicsContext()
  206067. {
  206068. states.clear();
  206069. }
  206070. void resized()
  206071. {
  206072. RECT windowRect;
  206073. GetClientRect (hwnd, &windowRect);
  206074. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206075. renderingTarget->Resize (size);
  206076. bounds.setSize (size.width, size.height);
  206077. }
  206078. void clear()
  206079. {
  206080. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  206081. }
  206082. void start()
  206083. {
  206084. renderingTarget->BeginDraw();
  206085. saveState();
  206086. }
  206087. void end()
  206088. {
  206089. states.clear();
  206090. currentState = 0;
  206091. renderingTarget->EndDraw();
  206092. renderingTarget->CheckWindowState();
  206093. }
  206094. bool isVectorDevice() const { return false; }
  206095. void setOrigin (int x, int y)
  206096. {
  206097. currentState->origin.addXY (x, y);
  206098. }
  206099. void addTransform (const AffineTransform& transform)
  206100. {
  206101. //xxx todo
  206102. jassertfalse;
  206103. }
  206104. float getScaleFactor()
  206105. {
  206106. jassertfalse; //xxx
  206107. return 1.0f;
  206108. }
  206109. bool clipToRectangle (const Rectangle<int>& r)
  206110. {
  206111. currentState->clipToRectangle (r);
  206112. return ! isClipEmpty();
  206113. }
  206114. bool clipToRectangleList (const RectangleList& clipRegion)
  206115. {
  206116. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  206117. return ! isClipEmpty();
  206118. }
  206119. void excludeClipRectangle (const Rectangle<int>&)
  206120. {
  206121. //xxx
  206122. }
  206123. void clipToPath (const Path& path, const AffineTransform& transform)
  206124. {
  206125. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  206126. }
  206127. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  206128. {
  206129. currentState->clipToImage (sourceImage,transform);
  206130. }
  206131. bool clipRegionIntersects (const Rectangle<int>& r)
  206132. {
  206133. const Rectangle<int> r2 (r + currentState->origin);
  206134. return currentState->clipRect.intersects (r2);
  206135. }
  206136. const Rectangle<int> getClipBounds() const
  206137. {
  206138. // xxx could this take into account complex clip regions?
  206139. return currentState->clipRect - currentState->origin;
  206140. }
  206141. bool isClipEmpty() const
  206142. {
  206143. return currentState->clipRect.isEmpty();
  206144. }
  206145. void saveState()
  206146. {
  206147. states.add (new SavedState (*this));
  206148. currentState = states.getLast();
  206149. }
  206150. void restoreState()
  206151. {
  206152. jassert (states.size() > 1) //you should never pop the last state!
  206153. states.removeLast (1);
  206154. currentState = states.getLast();
  206155. }
  206156. void beginTransparencyLayer (float opacity)
  206157. {
  206158. jassertfalse; //xxx todo
  206159. }
  206160. void endTransparencyLayer()
  206161. {
  206162. jassertfalse; //xxx todo
  206163. }
  206164. void setFill (const FillType& fillType)
  206165. {
  206166. currentState->setFill (fillType);
  206167. }
  206168. void setOpacity (float newOpacity)
  206169. {
  206170. currentState->setOpacity (newOpacity);
  206171. }
  206172. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  206173. {
  206174. }
  206175. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  206176. {
  206177. currentState->createBrush();
  206178. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  206179. }
  206180. void fillPath (const Path& p, const AffineTransform& transform)
  206181. {
  206182. currentState->createBrush();
  206183. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  206184. if (renderingTarget != 0)
  206185. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  206186. }
  206187. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  206188. {
  206189. const int x = currentState->origin.getX();
  206190. const int y = currentState->origin.getY();
  206191. renderingTarget->SetTransform (transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206192. D2D1_SIZE_U size;
  206193. size.width = image.getWidth();
  206194. size.height = image.getHeight();
  206195. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206196. Image img (image.convertedToFormat (Image::ARGB));
  206197. Image::BitmapData bd (img, Image::BitmapData::readOnly);
  206198. bp.pixelFormat = renderingTarget->GetPixelFormat();
  206199. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206200. {
  206201. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  206202. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, tempBitmap.resetAndGetPointerAddress());
  206203. if (tempBitmap != 0)
  206204. renderingTarget->DrawBitmap (tempBitmap);
  206205. }
  206206. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206207. }
  206208. void drawLine (const Line <float>& line)
  206209. {
  206210. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206211. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  206212. line.getEnd() + currentState->origin.toFloat());
  206213. currentState->createBrush();
  206214. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  206215. D2D1::Point2F (l.getEndX(), l.getEndY()),
  206216. currentState->currentBrush);
  206217. }
  206218. void drawVerticalLine (int x, float top, float bottom)
  206219. {
  206220. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206221. currentState->createBrush();
  206222. x += currentState->origin.getX();
  206223. const int y = currentState->origin.getY();
  206224. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206225. D2D1::Point2F (x, y + bottom),
  206226. currentState->currentBrush);
  206227. }
  206228. void drawHorizontalLine (int y, float left, float right)
  206229. {
  206230. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206231. currentState->createBrush();
  206232. y += currentState->origin.getY();
  206233. const int x = currentState->origin.getX();
  206234. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206235. D2D1::Point2F (x + right, y),
  206236. currentState->currentBrush);
  206237. }
  206238. void setFont (const Font& newFont)
  206239. {
  206240. currentState->setFont (newFont);
  206241. }
  206242. const Font getFont()
  206243. {
  206244. return currentState->font;
  206245. }
  206246. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206247. {
  206248. const float x = currentState->origin.getX();
  206249. const float y = currentState->origin.getY();
  206250. currentState->createBrush();
  206251. currentState->createFont();
  206252. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206253. float hScale = currentState->font.getHorizontalScale();
  206254. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206255. float dpiX = 0, dpiY = 0;
  206256. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206257. UINT32 glyphNum = glyphNumber;
  206258. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206259. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206260. DWRITE_GLYPH_OFFSET offset;
  206261. offset.advanceOffset = 0;
  206262. offset.ascenderOffset = 0;
  206263. float glyphAdvances = 0;
  206264. DWRITE_GLYPH_RUN glyph;
  206265. glyph.fontFace = currentState->currentFontFace;
  206266. glyph.glyphCount = 1;
  206267. glyph.glyphIndices = &glyphNum1;
  206268. glyph.isSideways = FALSE;
  206269. glyph.glyphAdvances = &glyphAdvances;
  206270. glyph.glyphOffsets = &offset;
  206271. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206272. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206273. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206274. }
  206275. class SavedState
  206276. {
  206277. public:
  206278. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206279. : owner (owner_), currentBrush (0),
  206280. fontScaling (1.0f), currentFontFace (0),
  206281. clipsRect (false), shouldClipRect (false),
  206282. clipsRectList (false), shouldClipRectList (false),
  206283. clipsComplex (false), shouldClipComplex (false),
  206284. clipsBitmap (false), shouldClipBitmap (false)
  206285. {
  206286. if (owner.currentState != 0)
  206287. {
  206288. // xxx seems like a very slow way to create one of these, and this is a performance
  206289. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206290. setFill (owner.currentState->fillType);
  206291. currentBrush = owner.currentState->currentBrush;
  206292. origin = owner.currentState->origin;
  206293. clipRect = owner.currentState->clipRect;
  206294. font = owner.currentState->font;
  206295. currentFontFace = owner.currentState->currentFontFace;
  206296. }
  206297. else
  206298. {
  206299. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206300. clipRect.setSize (size.width, size.height);
  206301. setFill (FillType (Colours::black));
  206302. }
  206303. }
  206304. ~SavedState()
  206305. {
  206306. clearClip();
  206307. clearFont();
  206308. clearFill();
  206309. clearPathClip();
  206310. clearImageClip();
  206311. complexClipLayer = 0;
  206312. bitmapMaskLayer = 0;
  206313. }
  206314. void clearClip()
  206315. {
  206316. popClips();
  206317. shouldClipRect = false;
  206318. }
  206319. void clipToRectangle (const Rectangle<int>& r)
  206320. {
  206321. clearClip();
  206322. clipRect = r + origin;
  206323. shouldClipRect = true;
  206324. pushClips();
  206325. }
  206326. void clearPathClip()
  206327. {
  206328. popClips();
  206329. if (shouldClipComplex)
  206330. {
  206331. complexClipGeometry = 0;
  206332. shouldClipComplex = false;
  206333. }
  206334. }
  206335. void clipToPath (ID2D1Geometry* geometry)
  206336. {
  206337. clearPathClip();
  206338. if (complexClipLayer == 0)
  206339. owner.renderingTarget->CreateLayer (complexClipLayer.resetAndGetPointerAddress());
  206340. complexClipGeometry = geometry;
  206341. shouldClipComplex = true;
  206342. pushClips();
  206343. }
  206344. void clearRectListClip()
  206345. {
  206346. popClips();
  206347. if (shouldClipRectList)
  206348. {
  206349. rectListGeometry = 0;
  206350. shouldClipRectList = false;
  206351. }
  206352. }
  206353. void clipToRectList (ID2D1Geometry* geometry)
  206354. {
  206355. clearRectListClip();
  206356. if (rectListLayer == 0)
  206357. owner.renderingTarget->CreateLayer (rectListLayer.resetAndGetPointerAddress());
  206358. rectListGeometry = geometry;
  206359. shouldClipRectList = true;
  206360. pushClips();
  206361. }
  206362. void clearImageClip()
  206363. {
  206364. popClips();
  206365. if (shouldClipBitmap)
  206366. {
  206367. maskBitmap = 0;
  206368. bitmapMaskBrush = 0;
  206369. shouldClipBitmap = false;
  206370. }
  206371. }
  206372. void clipToImage (const Image& image, const AffineTransform& transform)
  206373. {
  206374. clearImageClip();
  206375. if (bitmapMaskLayer == 0)
  206376. owner.renderingTarget->CreateLayer (bitmapMaskLayer.resetAndGetPointerAddress());
  206377. D2D1_BRUSH_PROPERTIES brushProps;
  206378. brushProps.opacity = 1;
  206379. brushProps.transform = transformToMatrix (transform);
  206380. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206381. D2D1_SIZE_U size;
  206382. size.width = image.getWidth();
  206383. size.height = image.getHeight();
  206384. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206385. maskImage = image.convertedToFormat (Image::ARGB);
  206386. Image::BitmapData bd (this->image, Image::BitmapData::readOnly); // xxx should be maskImage?
  206387. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206388. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206389. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, maskBitmap.resetAndGetPointerAddress());
  206390. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, bitmapMaskBrush.resetAndGetPointerAddress());
  206391. imageMaskLayerParams = D2D1::LayerParameters();
  206392. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206393. shouldClipBitmap = true;
  206394. pushClips();
  206395. }
  206396. void popClips()
  206397. {
  206398. if (clipsBitmap)
  206399. {
  206400. owner.renderingTarget->PopLayer();
  206401. clipsBitmap = false;
  206402. }
  206403. if (clipsComplex)
  206404. {
  206405. owner.renderingTarget->PopLayer();
  206406. clipsComplex = false;
  206407. }
  206408. if (clipsRectList)
  206409. {
  206410. owner.renderingTarget->PopLayer();
  206411. clipsRectList = false;
  206412. }
  206413. if (clipsRect)
  206414. {
  206415. owner.renderingTarget->PopAxisAlignedClip();
  206416. clipsRect = false;
  206417. }
  206418. }
  206419. void pushClips()
  206420. {
  206421. if (shouldClipRect && ! clipsRect)
  206422. {
  206423. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206424. clipsRect = true;
  206425. }
  206426. if (shouldClipRectList && ! clipsRectList)
  206427. {
  206428. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206429. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206430. layerParams.geometricMask = rectListGeometry;
  206431. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206432. clipsRectList = true;
  206433. }
  206434. if (shouldClipComplex && ! clipsComplex)
  206435. {
  206436. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206437. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206438. layerParams.geometricMask = complexClipGeometry;
  206439. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206440. clipsComplex = true;
  206441. }
  206442. if (shouldClipBitmap && ! clipsBitmap)
  206443. {
  206444. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206445. clipsBitmap = true;
  206446. }
  206447. }
  206448. void setFill (const FillType& newFillType)
  206449. {
  206450. if (fillType != newFillType)
  206451. {
  206452. fillType = newFillType;
  206453. clearFill();
  206454. }
  206455. }
  206456. void clearFont()
  206457. {
  206458. currentFontFace = localFontFace = 0;
  206459. }
  206460. void setFont (const Font& newFont)
  206461. {
  206462. if (font != newFont)
  206463. {
  206464. font = newFont;
  206465. clearFont();
  206466. }
  206467. }
  206468. void createFont()
  206469. {
  206470. // xxx The font shouldn't be managed by the graphics context.
  206471. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206472. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206473. // WindowsTypeface class.
  206474. if (currentFontFace == 0)
  206475. {
  206476. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206477. fontScaling = systemType->getAscent();
  206478. BOOL fontFound;
  206479. uint32 fontIndex;
  206480. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206481. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206482. if (! fontFound)
  206483. fontIndex = 0;
  206484. ComSmartPtr <IDWriteFontFamily> fontFam;
  206485. fonts->GetFontFamily (fontIndex, fontFam.resetAndGetPointerAddress());
  206486. ComSmartPtr <IDWriteFont> font;
  206487. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206488. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206489. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, font.resetAndGetPointerAddress());
  206490. font->CreateFontFace (localFontFace.resetAndGetPointerAddress());
  206491. currentFontFace = localFontFace;
  206492. }
  206493. }
  206494. void setOpacity (float newOpacity)
  206495. {
  206496. fillType.setOpacity (newOpacity);
  206497. if (currentBrush != 0)
  206498. currentBrush->SetOpacity (newOpacity);
  206499. }
  206500. void clearFill()
  206501. {
  206502. gradientStops = 0;
  206503. linearGradient = 0;
  206504. radialGradient = 0;
  206505. bitmap = 0;
  206506. bitmapBrush = 0;
  206507. currentBrush = 0;
  206508. }
  206509. void createBrush()
  206510. {
  206511. if (currentBrush == 0)
  206512. {
  206513. const int x = origin.getX();
  206514. const int y = origin.getY();
  206515. if (fillType.isColour())
  206516. {
  206517. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206518. owner.colourBrush->SetColor (colour);
  206519. currentBrush = owner.colourBrush;
  206520. }
  206521. else if (fillType.isTiledImage())
  206522. {
  206523. D2D1_BRUSH_PROPERTIES brushProps;
  206524. brushProps.opacity = fillType.getOpacity();
  206525. brushProps.transform = transformToMatrix (fillType.transform);
  206526. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206527. image = fillType.image;
  206528. D2D1_SIZE_U size;
  206529. size.width = image.getWidth();
  206530. size.height = image.getHeight();
  206531. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206532. this->image = image.convertedToFormat (Image::ARGB);
  206533. Image::BitmapData bd (this->image, Image::BitmapData::readOnly);
  206534. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206535. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206536. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, bitmap.resetAndGetPointerAddress());
  206537. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, bitmapBrush.resetAndGetPointerAddress());
  206538. currentBrush = bitmapBrush;
  206539. }
  206540. else if (fillType.isGradient())
  206541. {
  206542. gradientStops = 0;
  206543. D2D1_BRUSH_PROPERTIES brushProps;
  206544. brushProps.opacity = fillType.getOpacity();
  206545. brushProps.transform = transformToMatrix (fillType.transform);
  206546. const int numColors = fillType.gradient->getNumColours();
  206547. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206548. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206549. {
  206550. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206551. stops[i].position = fillType.gradient->getColourPosition(i);
  206552. }
  206553. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, gradientStops.resetAndGetPointerAddress());
  206554. if (fillType.gradient->isRadial)
  206555. {
  206556. radialGradient = 0;
  206557. const Point<float>& p1 = fillType.gradient->point1;
  206558. const Point<float>& p2 = fillType.gradient->point2;
  206559. float r = p1.getDistanceFrom (p2);
  206560. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206561. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206562. D2D1::Point2F (0, 0),
  206563. r, r);
  206564. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, radialGradient.resetAndGetPointerAddress());
  206565. currentBrush = radialGradient;
  206566. }
  206567. else
  206568. {
  206569. linearGradient = 0;
  206570. const Point<float>& p1 = fillType.gradient->point1;
  206571. const Point<float>& p2 = fillType.gradient->point2;
  206572. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206573. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206574. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206575. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, linearGradient.resetAndGetPointerAddress());
  206576. currentBrush = linearGradient;
  206577. }
  206578. }
  206579. }
  206580. }
  206581. //xxx most of these members should probably be private...
  206582. Direct2DLowLevelGraphicsContext& owner;
  206583. Point<int> origin;
  206584. Font font;
  206585. float fontScaling;
  206586. IDWriteFontFace* currentFontFace;
  206587. ComSmartPtr <IDWriteFontFace> localFontFace;
  206588. FillType fillType;
  206589. Image image;
  206590. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206591. Rectangle<int> clipRect;
  206592. bool clipsRect, shouldClipRect;
  206593. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206594. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206595. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206596. bool clipsComplex, shouldClipComplex;
  206597. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206598. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206599. ComSmartPtr <ID2D1Layer> rectListLayer;
  206600. bool clipsRectList, shouldClipRectList;
  206601. Image maskImage;
  206602. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206603. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206604. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206605. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206606. bool clipsBitmap, shouldClipBitmap;
  206607. ID2D1Brush* currentBrush;
  206608. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206609. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206610. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206611. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206612. private:
  206613. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206614. };
  206615. private:
  206616. HWND hwnd;
  206617. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206618. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206619. Rectangle<int> bounds;
  206620. SavedState* currentState;
  206621. OwnedArray<SavedState> states;
  206622. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206623. {
  206624. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206625. }
  206626. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206627. {
  206628. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206629. }
  206630. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206631. {
  206632. transform.transformPoint (x, y);
  206633. return D2D1::Point2F (x, y);
  206634. }
  206635. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206636. {
  206637. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206638. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206639. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206640. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206641. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206642. }
  206643. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206644. {
  206645. ID2D1PathGeometry* p = 0;
  206646. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206647. ComSmartPtr <ID2D1GeometrySink> sink;
  206648. HRESULT hr = p->Open (sink.resetAndGetPointerAddress()); // xxx handle error
  206649. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206650. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206651. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206652. hr = sink->Close();
  206653. return p;
  206654. }
  206655. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206656. {
  206657. Path::Iterator it (path);
  206658. while (it.next())
  206659. {
  206660. switch (it.elementType)
  206661. {
  206662. case Path::Iterator::cubicTo:
  206663. {
  206664. D2D1_BEZIER_SEGMENT seg;
  206665. transform.transformPoint (it.x1, it.y1);
  206666. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206667. transform.transformPoint (it.x2, it.y2);
  206668. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206669. transform.transformPoint(it.x3, it.y3);
  206670. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206671. sink->AddBezier (seg);
  206672. break;
  206673. }
  206674. case Path::Iterator::lineTo:
  206675. {
  206676. transform.transformPoint (it.x1, it.y1);
  206677. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206678. break;
  206679. }
  206680. case Path::Iterator::quadraticTo:
  206681. {
  206682. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206683. transform.transformPoint (it.x1, it.y1);
  206684. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206685. transform.transformPoint (it.x2, it.y2);
  206686. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206687. sink->AddQuadraticBezier (seg);
  206688. break;
  206689. }
  206690. case Path::Iterator::closePath:
  206691. {
  206692. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206693. break;
  206694. }
  206695. case Path::Iterator::startNewSubPath:
  206696. {
  206697. transform.transformPoint (it.x1, it.y1);
  206698. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206699. break;
  206700. }
  206701. }
  206702. }
  206703. }
  206704. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206705. {
  206706. ID2D1PathGeometry* p = 0;
  206707. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206708. ComSmartPtr <ID2D1GeometrySink> sink;
  206709. HRESULT hr = p->Open (sink.resetAndGetPointerAddress());
  206710. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206711. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206712. hr = sink->Close();
  206713. return p;
  206714. }
  206715. static const D2D1::Matrix3x2F transformToMatrix (const AffineTransform& transform)
  206716. {
  206717. D2D1::Matrix3x2F matrix;
  206718. matrix._11 = transform.mat00;
  206719. matrix._12 = transform.mat10;
  206720. matrix._21 = transform.mat01;
  206721. matrix._22 = transform.mat11;
  206722. matrix._31 = transform.mat02;
  206723. matrix._32 = transform.mat12;
  206724. return matrix;
  206725. }
  206726. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206727. };
  206728. #endif
  206729. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206730. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206731. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206732. // compiled on its own).
  206733. #if JUCE_INCLUDED_FILE
  206734. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206735. // these are in the windows SDK, but need to be repeated here for GCC..
  206736. #ifndef GET_APPCOMMAND_LPARAM
  206737. #define FAPPCOMMAND_MASK 0xF000
  206738. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206739. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206740. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206741. #define APPCOMMAND_MEDIA_STOP 13
  206742. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206743. #define WM_APPCOMMAND 0x0319
  206744. #endif
  206745. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206746. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206747. extern bool juce_IsRunningInWine();
  206748. #ifndef ULW_ALPHA
  206749. #define ULW_ALPHA 0x00000002
  206750. #endif
  206751. #ifndef AC_SRC_ALPHA
  206752. #define AC_SRC_ALPHA 0x01
  206753. #endif
  206754. static bool shouldDeactivateTitleBar = true;
  206755. #define WM_TRAYNOTIFY WM_USER + 100
  206756. using ::abs;
  206757. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206758. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206759. bool Desktop::canUseSemiTransparentWindows() throw()
  206760. {
  206761. if (updateLayeredWindow == 0)
  206762. {
  206763. if (! juce_IsRunningInWine())
  206764. {
  206765. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206766. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206767. }
  206768. }
  206769. return updateLayeredWindow != 0;
  206770. }
  206771. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206772. {
  206773. return upright;
  206774. }
  206775. const int extendedKeyModifier = 0x10000;
  206776. const int KeyPress::spaceKey = VK_SPACE;
  206777. const int KeyPress::returnKey = VK_RETURN;
  206778. const int KeyPress::escapeKey = VK_ESCAPE;
  206779. const int KeyPress::backspaceKey = VK_BACK;
  206780. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206781. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206782. const int KeyPress::tabKey = VK_TAB;
  206783. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206784. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206785. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206786. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206787. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206788. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206789. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206790. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206791. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206792. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206793. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206794. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206795. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206796. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206797. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206798. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206799. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206800. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206801. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206802. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206803. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206804. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206805. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206806. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206807. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206808. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206809. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206810. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206811. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206812. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206813. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206814. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206815. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206816. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206817. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206818. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206819. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206820. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206821. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206822. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206823. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206824. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206825. const int KeyPress::playKey = 0x30000;
  206826. const int KeyPress::stopKey = 0x30001;
  206827. const int KeyPress::fastForwardKey = 0x30002;
  206828. const int KeyPress::rewindKey = 0x30003;
  206829. class WindowsBitmapImage : public Image::SharedImage
  206830. {
  206831. public:
  206832. WindowsBitmapImage (const Image::PixelFormat format_,
  206833. const int w, const int h, const bool clearImage)
  206834. : Image::SharedImage (format_, w, h)
  206835. {
  206836. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206837. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206838. lineStride = -((w * pixelStride + 3) & ~3);
  206839. zerostruct (bitmapInfo);
  206840. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206841. bitmapInfo.bV4Width = w;
  206842. bitmapInfo.bV4Height = h;
  206843. bitmapInfo.bV4Planes = 1;
  206844. bitmapInfo.bV4CSType = 1;
  206845. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206846. if (format_ == Image::ARGB)
  206847. {
  206848. bitmapInfo.bV4AlphaMask = 0xff000000;
  206849. bitmapInfo.bV4RedMask = 0xff0000;
  206850. bitmapInfo.bV4GreenMask = 0xff00;
  206851. bitmapInfo.bV4BlueMask = 0xff;
  206852. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206853. }
  206854. else
  206855. {
  206856. bitmapInfo.bV4V4Compression = BI_RGB;
  206857. }
  206858. HDC dc = GetDC (0);
  206859. hdc = CreateCompatibleDC (dc);
  206860. ReleaseDC (0, dc);
  206861. SetMapMode (hdc, MM_TEXT);
  206862. hBitmap = CreateDIBSection (hdc, (BITMAPINFO*) &(bitmapInfo), DIB_RGB_COLORS,
  206863. (void**) &bitmapData, 0, 0);
  206864. previousBitmap = SelectObject (hdc, hBitmap);
  206865. if (format_ == Image::ARGB && clearImage)
  206866. zeromem (bitmapData, abs (h * lineStride));
  206867. imageData = bitmapData - (lineStride * (h - 1));
  206868. }
  206869. ~WindowsBitmapImage()
  206870. {
  206871. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  206872. DeleteDC (hdc);
  206873. DeleteObject (hBitmap);
  206874. }
  206875. Image::ImageType getType() const { return Image::NativeImage; }
  206876. LowLevelGraphicsContext* createLowLevelContext()
  206877. {
  206878. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206879. }
  206880. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  206881. {
  206882. bitmap.data = imageData + x * pixelStride + y * lineStride;
  206883. bitmap.pixelFormat = format;
  206884. bitmap.lineStride = lineStride;
  206885. bitmap.pixelStride = pixelStride;
  206886. }
  206887. Image::SharedImage* clone()
  206888. {
  206889. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206890. for (int i = 0; i < height; ++i)
  206891. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206892. return im;
  206893. }
  206894. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206895. const int x, const int y,
  206896. const RectangleList& maskedRegion,
  206897. const uint8 updateLayeredWindowAlpha) throw()
  206898. {
  206899. static HDRAWDIB hdd = 0;
  206900. static bool needToCreateDrawDib = true;
  206901. if (needToCreateDrawDib)
  206902. {
  206903. needToCreateDrawDib = false;
  206904. HDC dc = GetDC (0);
  206905. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206906. ReleaseDC (0, dc);
  206907. // only open if we're not palettised
  206908. if (n > 8)
  206909. hdd = DrawDibOpen();
  206910. }
  206911. SetMapMode (dc, MM_TEXT);
  206912. if (transparent)
  206913. {
  206914. POINT p, pos;
  206915. SIZE size;
  206916. RECT windowBounds;
  206917. GetWindowRect (hwnd, &windowBounds);
  206918. p.x = -x;
  206919. p.y = -y;
  206920. pos.x = windowBounds.left;
  206921. pos.y = windowBounds.top;
  206922. size.cx = windowBounds.right - windowBounds.left;
  206923. size.cy = windowBounds.bottom - windowBounds.top;
  206924. BLENDFUNCTION bf;
  206925. bf.AlphaFormat = AC_SRC_ALPHA;
  206926. bf.BlendFlags = 0;
  206927. bf.BlendOp = AC_SRC_OVER;
  206928. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206929. if (! maskedRegion.isEmpty())
  206930. {
  206931. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206932. {
  206933. const Rectangle<int>& r = *i.getRectangle();
  206934. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206935. }
  206936. }
  206937. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206938. }
  206939. else
  206940. {
  206941. int savedDC = 0;
  206942. if (! maskedRegion.isEmpty())
  206943. {
  206944. savedDC = SaveDC (dc);
  206945. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206946. {
  206947. const Rectangle<int>& r = *i.getRectangle();
  206948. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206949. }
  206950. }
  206951. if (hdd == 0)
  206952. {
  206953. StretchDIBits (dc,
  206954. x, y, width, height,
  206955. 0, 0, width, height,
  206956. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206957. DIB_RGB_COLORS, SRCCOPY);
  206958. }
  206959. else
  206960. {
  206961. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206962. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206963. 0, 0, width, height, 0);
  206964. }
  206965. if (! maskedRegion.isEmpty())
  206966. RestoreDC (dc, savedDC);
  206967. }
  206968. }
  206969. HBITMAP hBitmap;
  206970. HGDIOBJ previousBitmap;
  206971. BITMAPV4HEADER bitmapInfo;
  206972. HDC hdc;
  206973. uint8* bitmapData;
  206974. int pixelStride, lineStride;
  206975. uint8* imageData;
  206976. private:
  206977. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206978. };
  206979. namespace IconConverters
  206980. {
  206981. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206982. {
  206983. Image im;
  206984. if (bitmap != 0)
  206985. {
  206986. BITMAP bm;
  206987. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206988. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206989. {
  206990. HDC tempDC = GetDC (0);
  206991. HDC dc = CreateCompatibleDC (tempDC);
  206992. ReleaseDC (0, tempDC);
  206993. SelectObject (dc, bitmap);
  206994. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206995. Image::BitmapData imageData (im, Image::BitmapData::writeOnly);
  206996. for (int y = bm.bmHeight; --y >= 0;)
  206997. {
  206998. for (int x = bm.bmWidth; --x >= 0;)
  206999. {
  207000. COLORREF col = GetPixel (dc, x, y);
  207001. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  207002. (uint8) GetGValue (col),
  207003. (uint8) GetBValue (col)));
  207004. }
  207005. }
  207006. DeleteDC (dc);
  207007. }
  207008. }
  207009. return im;
  207010. }
  207011. const Image createImageFromHICON (HICON icon)
  207012. {
  207013. ICONINFO info;
  207014. if (GetIconInfo (icon, &info))
  207015. {
  207016. Image mask (createImageFromHBITMAP (info.hbmMask));
  207017. Image image (createImageFromHBITMAP (info.hbmColor));
  207018. if (mask.isValid() && image.isValid())
  207019. {
  207020. for (int y = image.getHeight(); --y >= 0;)
  207021. {
  207022. for (int x = image.getWidth(); --x >= 0;)
  207023. {
  207024. const float brightness = mask.getPixelAt (x, y).getBrightness();
  207025. if (brightness > 0.0f)
  207026. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  207027. }
  207028. }
  207029. return image;
  207030. }
  207031. }
  207032. return Image::null;
  207033. }
  207034. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  207035. {
  207036. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  207037. Image bitmap (nativeBitmap);
  207038. {
  207039. Graphics g (bitmap);
  207040. g.drawImageAt (image, 0, 0);
  207041. }
  207042. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  207043. ICONINFO info;
  207044. info.fIcon = isIcon;
  207045. info.xHotspot = hotspotX;
  207046. info.yHotspot = hotspotY;
  207047. info.hbmMask = mask;
  207048. info.hbmColor = nativeBitmap->hBitmap;
  207049. HICON hi = CreateIconIndirect (&info);
  207050. DeleteObject (mask);
  207051. return hi;
  207052. }
  207053. }
  207054. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  207055. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  207056. {
  207057. SHORT k = (SHORT) keyCode;
  207058. if ((keyCode & extendedKeyModifier) == 0
  207059. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  207060. k += (SHORT) 'A' - (SHORT) 'a';
  207061. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  207062. (SHORT) '+', VK_OEM_PLUS,
  207063. (SHORT) '-', VK_OEM_MINUS,
  207064. (SHORT) '.', VK_OEM_PERIOD,
  207065. (SHORT) ';', VK_OEM_1,
  207066. (SHORT) ':', VK_OEM_1,
  207067. (SHORT) '/', VK_OEM_2,
  207068. (SHORT) '?', VK_OEM_2,
  207069. (SHORT) '[', VK_OEM_4,
  207070. (SHORT) ']', VK_OEM_6 };
  207071. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  207072. if (k == translatedValues [i])
  207073. k = translatedValues [i + 1];
  207074. return (GetKeyState (k) & 0x8000) != 0;
  207075. }
  207076. class Win32ComponentPeer : public ComponentPeer
  207077. {
  207078. public:
  207079. enum RenderingEngineType
  207080. {
  207081. softwareRenderingEngine = 0,
  207082. direct2DRenderingEngine
  207083. };
  207084. Win32ComponentPeer (Component* const component,
  207085. const int windowStyleFlags,
  207086. HWND parentToAddTo_)
  207087. : ComponentPeer (component, windowStyleFlags),
  207088. dontRepaint (false),
  207089. #if JUCE_DIRECT2D
  207090. currentRenderingEngine (direct2DRenderingEngine),
  207091. #else
  207092. currentRenderingEngine (softwareRenderingEngine),
  207093. #endif
  207094. fullScreen (false),
  207095. isDragging (false),
  207096. isMouseOver (false),
  207097. hasCreatedCaret (false),
  207098. constrainerIsResizing (false),
  207099. currentWindowIcon (0),
  207100. dropTarget (0),
  207101. parentToAddTo (parentToAddTo_),
  207102. updateLayeredWindowAlpha (255)
  207103. {
  207104. callFunctionIfNotLocked (&createWindowCallback, this);
  207105. setTitle (component->getName());
  207106. if ((windowStyleFlags & windowHasDropShadow) != 0
  207107. && Desktop::canUseSemiTransparentWindows())
  207108. {
  207109. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  207110. if (shadower != 0)
  207111. shadower->setOwner (component);
  207112. }
  207113. }
  207114. ~Win32ComponentPeer()
  207115. {
  207116. setTaskBarIcon (Image());
  207117. shadower = 0;
  207118. // do this before the next bit to avoid messages arriving for this window
  207119. // before it's destroyed
  207120. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  207121. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  207122. if (currentWindowIcon != 0)
  207123. DestroyIcon (currentWindowIcon);
  207124. if (dropTarget != 0)
  207125. {
  207126. dropTarget->Release();
  207127. dropTarget = 0;
  207128. }
  207129. #if JUCE_DIRECT2D
  207130. direct2DContext = 0;
  207131. #endif
  207132. }
  207133. void* getNativeHandle() const
  207134. {
  207135. return hwnd;
  207136. }
  207137. void setVisible (bool shouldBeVisible)
  207138. {
  207139. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207140. if (shouldBeVisible)
  207141. InvalidateRect (hwnd, 0, 0);
  207142. else
  207143. lastPaintTime = 0;
  207144. }
  207145. void setTitle (const String& title)
  207146. {
  207147. SetWindowText (hwnd, title.toUTF16());
  207148. }
  207149. void setPosition (int x, int y)
  207150. {
  207151. offsetWithinParent (x, y);
  207152. SetWindowPos (hwnd, 0,
  207153. x - windowBorder.getLeft(),
  207154. y - windowBorder.getTop(),
  207155. 0, 0,
  207156. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207157. }
  207158. void repaintNowIfTransparent()
  207159. {
  207160. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  207161. handlePaintMessage();
  207162. }
  207163. void updateBorderSize()
  207164. {
  207165. WINDOWINFO info;
  207166. info.cbSize = sizeof (info);
  207167. if (GetWindowInfo (hwnd, &info))
  207168. {
  207169. windowBorder = BorderSize<int> (info.rcClient.top - info.rcWindow.top,
  207170. info.rcClient.left - info.rcWindow.left,
  207171. info.rcWindow.bottom - info.rcClient.bottom,
  207172. info.rcWindow.right - info.rcClient.right);
  207173. }
  207174. #if JUCE_DIRECT2D
  207175. if (direct2DContext != 0)
  207176. direct2DContext->resized();
  207177. #endif
  207178. }
  207179. void setSize (int w, int h)
  207180. {
  207181. SetWindowPos (hwnd, 0, 0, 0,
  207182. w + windowBorder.getLeftAndRight(),
  207183. h + windowBorder.getTopAndBottom(),
  207184. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207185. updateBorderSize();
  207186. repaintNowIfTransparent();
  207187. }
  207188. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  207189. {
  207190. fullScreen = isNowFullScreen;
  207191. offsetWithinParent (x, y);
  207192. SetWindowPos (hwnd, 0,
  207193. x - windowBorder.getLeft(),
  207194. y - windowBorder.getTop(),
  207195. w + windowBorder.getLeftAndRight(),
  207196. h + windowBorder.getTopAndBottom(),
  207197. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207198. updateBorderSize();
  207199. repaintNowIfTransparent();
  207200. }
  207201. const Rectangle<int> getBounds() const
  207202. {
  207203. RECT r;
  207204. GetWindowRect (hwnd, &r);
  207205. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  207206. HWND parentH = GetParent (hwnd);
  207207. if (parentH != 0)
  207208. {
  207209. GetWindowRect (parentH, &r);
  207210. bounds.translate (-r.left, -r.top);
  207211. }
  207212. return windowBorder.subtractedFrom (bounds);
  207213. }
  207214. const Point<int> getScreenPosition() const
  207215. {
  207216. RECT r;
  207217. GetWindowRect (hwnd, &r);
  207218. return Point<int> (r.left + windowBorder.getLeft(),
  207219. r.top + windowBorder.getTop());
  207220. }
  207221. const Point<int> localToGlobal (const Point<int>& relativePosition)
  207222. {
  207223. return relativePosition + getScreenPosition();
  207224. }
  207225. const Point<int> globalToLocal (const Point<int>& screenPosition)
  207226. {
  207227. return screenPosition - getScreenPosition();
  207228. }
  207229. void setAlpha (float newAlpha)
  207230. {
  207231. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  207232. if (component->isOpaque())
  207233. {
  207234. if (newAlpha < 1.0f)
  207235. {
  207236. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  207237. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  207238. }
  207239. else
  207240. {
  207241. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  207242. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  207243. }
  207244. }
  207245. else
  207246. {
  207247. updateLayeredWindowAlpha = intAlpha;
  207248. component->repaint();
  207249. }
  207250. }
  207251. void setMinimised (bool shouldBeMinimised)
  207252. {
  207253. if (shouldBeMinimised != isMinimised())
  207254. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207255. }
  207256. bool isMinimised() const
  207257. {
  207258. WINDOWPLACEMENT wp;
  207259. wp.length = sizeof (WINDOWPLACEMENT);
  207260. GetWindowPlacement (hwnd, &wp);
  207261. return wp.showCmd == SW_SHOWMINIMIZED;
  207262. }
  207263. void setFullScreen (bool shouldBeFullScreen)
  207264. {
  207265. setMinimised (false);
  207266. if (fullScreen != shouldBeFullScreen)
  207267. {
  207268. fullScreen = shouldBeFullScreen;
  207269. const WeakReference<Component> deletionChecker (component);
  207270. if (! fullScreen)
  207271. {
  207272. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207273. if (hasTitleBar())
  207274. ShowWindow (hwnd, SW_SHOWNORMAL);
  207275. if (! boundsCopy.isEmpty())
  207276. {
  207277. setBounds (boundsCopy.getX(),
  207278. boundsCopy.getY(),
  207279. boundsCopy.getWidth(),
  207280. boundsCopy.getHeight(),
  207281. false);
  207282. }
  207283. }
  207284. else
  207285. {
  207286. if (hasTitleBar())
  207287. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207288. else
  207289. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207290. }
  207291. if (deletionChecker != 0)
  207292. handleMovedOrResized();
  207293. }
  207294. }
  207295. bool isFullScreen() const
  207296. {
  207297. if (! hasTitleBar())
  207298. return fullScreen;
  207299. WINDOWPLACEMENT wp;
  207300. wp.length = sizeof (wp);
  207301. GetWindowPlacement (hwnd, &wp);
  207302. return wp.showCmd == SW_SHOWMAXIMIZED;
  207303. }
  207304. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207305. {
  207306. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  207307. && isPositiveAndBelow (position.getY(), component->getHeight())))
  207308. return false;
  207309. RECT r;
  207310. GetWindowRect (hwnd, &r);
  207311. POINT p;
  207312. p.x = position.getX() + r.left + windowBorder.getLeft();
  207313. p.y = position.getY() + r.top + windowBorder.getTop();
  207314. HWND w = WindowFromPoint (p);
  207315. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207316. }
  207317. const BorderSize<int> getFrameSize() const
  207318. {
  207319. return windowBorder;
  207320. }
  207321. bool setAlwaysOnTop (bool alwaysOnTop)
  207322. {
  207323. const bool oldDeactivate = shouldDeactivateTitleBar;
  207324. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207325. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207326. 0, 0, 0, 0,
  207327. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207328. shouldDeactivateTitleBar = oldDeactivate;
  207329. if (shadower != 0)
  207330. shadower->componentBroughtToFront (*component);
  207331. return true;
  207332. }
  207333. void toFront (bool makeActive)
  207334. {
  207335. setMinimised (false);
  207336. const bool oldDeactivate = shouldDeactivateTitleBar;
  207337. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207338. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207339. shouldDeactivateTitleBar = oldDeactivate;
  207340. if (! makeActive)
  207341. {
  207342. // in this case a broughttofront call won't have occured, so do it now..
  207343. handleBroughtToFront();
  207344. }
  207345. }
  207346. void toBehind (ComponentPeer* other)
  207347. {
  207348. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207349. jassert (otherPeer != 0); // wrong type of window?
  207350. if (otherPeer != 0)
  207351. {
  207352. setMinimised (false);
  207353. // must be careful not to try to put a topmost window behind a normal one, or win32
  207354. // promotes the normal one to be topmost!
  207355. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207356. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207357. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207358. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207359. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207360. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207361. }
  207362. }
  207363. bool isFocused() const
  207364. {
  207365. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207366. }
  207367. void grabFocus()
  207368. {
  207369. const bool oldDeactivate = shouldDeactivateTitleBar;
  207370. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207371. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207372. shouldDeactivateTitleBar = oldDeactivate;
  207373. }
  207374. void textInputRequired (const Point<int>&)
  207375. {
  207376. if (! hasCreatedCaret)
  207377. {
  207378. hasCreatedCaret = true;
  207379. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207380. }
  207381. ShowCaret (hwnd);
  207382. SetCaretPos (0, 0);
  207383. }
  207384. void repaint (const Rectangle<int>& area)
  207385. {
  207386. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207387. InvalidateRect (hwnd, &r, FALSE);
  207388. }
  207389. void performAnyPendingRepaintsNow()
  207390. {
  207391. MSG m;
  207392. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207393. DispatchMessage (&m);
  207394. }
  207395. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207396. {
  207397. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207398. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207399. return 0;
  207400. }
  207401. void setTaskBarIcon (const Image& image)
  207402. {
  207403. if (image.isValid())
  207404. {
  207405. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  207406. if (taskBarIcon == 0)
  207407. {
  207408. taskBarIcon = new NOTIFYICONDATA();
  207409. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  207410. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207411. taskBarIcon->hWnd = (HWND) hwnd;
  207412. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207413. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207414. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207415. taskBarIcon->hIcon = hicon;
  207416. taskBarIcon->szTip[0] = 0;
  207417. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207418. }
  207419. else
  207420. {
  207421. HICON oldIcon = taskBarIcon->hIcon;
  207422. taskBarIcon->hIcon = hicon;
  207423. taskBarIcon->uFlags = NIF_ICON;
  207424. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207425. DestroyIcon (oldIcon);
  207426. }
  207427. }
  207428. else if (taskBarIcon != 0)
  207429. {
  207430. taskBarIcon->uFlags = 0;
  207431. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207432. DestroyIcon (taskBarIcon->hIcon);
  207433. taskBarIcon = 0;
  207434. }
  207435. }
  207436. void setTaskBarIconToolTip (const String& toolTip) const
  207437. {
  207438. if (taskBarIcon != 0)
  207439. {
  207440. taskBarIcon->uFlags = NIF_TIP;
  207441. toolTip.copyToUTF16 (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207442. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207443. }
  207444. }
  207445. void handleTaskBarEvent (const LPARAM lParam)
  207446. {
  207447. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207448. {
  207449. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207450. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207451. {
  207452. Component* const current = Component::getCurrentlyModalComponent();
  207453. if (current != 0)
  207454. current->inputAttemptWhenModal();
  207455. }
  207456. }
  207457. else
  207458. {
  207459. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207460. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207461. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207462. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207463. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207464. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207465. eventMods = eventMods.withoutMouseButtons();
  207466. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207467. Point<int>(), eventMods, component, component, Time (getMouseEventTime()),
  207468. Point<int>(), Time (getMouseEventTime()), 1, false);
  207469. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207470. {
  207471. SetFocus (hwnd);
  207472. SetForegroundWindow (hwnd);
  207473. component->mouseDown (e);
  207474. }
  207475. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207476. {
  207477. component->mouseUp (e);
  207478. }
  207479. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207480. {
  207481. component->mouseDoubleClick (e);
  207482. }
  207483. else if (lParam == WM_MOUSEMOVE)
  207484. {
  207485. component->mouseMove (e);
  207486. }
  207487. }
  207488. }
  207489. bool isInside (HWND h) const
  207490. {
  207491. return GetAncestor (hwnd, GA_ROOT) == h;
  207492. }
  207493. static void updateKeyModifiers() throw()
  207494. {
  207495. int keyMods = 0;
  207496. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207497. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207498. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207499. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207500. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207501. }
  207502. static void updateModifiersFromWParam (const WPARAM wParam)
  207503. {
  207504. int mouseMods = 0;
  207505. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207506. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207507. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207508. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207509. updateKeyModifiers();
  207510. }
  207511. static int64 getMouseEventTime()
  207512. {
  207513. static int64 eventTimeOffset = 0;
  207514. static DWORD lastMessageTime = 0;
  207515. const DWORD thisMessageTime = GetMessageTime();
  207516. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207517. {
  207518. lastMessageTime = thisMessageTime;
  207519. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207520. }
  207521. return eventTimeOffset + thisMessageTime;
  207522. }
  207523. bool dontRepaint;
  207524. static ModifierKeys currentModifiers;
  207525. static ModifierKeys modifiersAtLastCallback;
  207526. private:
  207527. HWND hwnd, parentToAddTo;
  207528. ScopedPointer<DropShadower> shadower;
  207529. RenderingEngineType currentRenderingEngine;
  207530. #if JUCE_DIRECT2D
  207531. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207532. #endif
  207533. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  207534. BorderSize<int> windowBorder;
  207535. HICON currentWindowIcon;
  207536. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207537. IDropTarget* dropTarget;
  207538. uint8 updateLayeredWindowAlpha;
  207539. class TemporaryImage : public Timer
  207540. {
  207541. public:
  207542. TemporaryImage() {}
  207543. ~TemporaryImage() {}
  207544. const Image& getImage (const bool transparent, const int w, const int h)
  207545. {
  207546. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207547. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207548. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207549. startTimer (3000);
  207550. return image;
  207551. }
  207552. void timerCallback()
  207553. {
  207554. stopTimer();
  207555. image = Image::null;
  207556. }
  207557. private:
  207558. Image image;
  207559. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207560. };
  207561. TemporaryImage offscreenImageGenerator;
  207562. class WindowClassHolder : public DeletedAtShutdown
  207563. {
  207564. public:
  207565. WindowClassHolder()
  207566. : windowClassName ("JUCE_")
  207567. {
  207568. // this name has to be different for each app/dll instance because otherwise
  207569. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207570. // window class).
  207571. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207572. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207573. TCHAR moduleFile [1024];
  207574. moduleFile[0] = 0;
  207575. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207576. WORD iconNum = 0;
  207577. WNDCLASSEX wcex;
  207578. wcex.cbSize = sizeof (wcex);
  207579. wcex.style = CS_OWNDC;
  207580. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207581. wcex.lpszClassName = windowClassName.toUTF16();
  207582. wcex.cbClsExtra = 0;
  207583. wcex.cbWndExtra = 32;
  207584. wcex.hInstance = moduleHandle;
  207585. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207586. iconNum = 1;
  207587. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207588. wcex.hCursor = 0;
  207589. wcex.hbrBackground = 0;
  207590. wcex.lpszMenuName = 0;
  207591. RegisterClassEx (&wcex);
  207592. }
  207593. ~WindowClassHolder()
  207594. {
  207595. if (ComponentPeer::getNumPeers() == 0)
  207596. UnregisterClass (windowClassName.toUTF16(), (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207597. clearSingletonInstance();
  207598. }
  207599. String windowClassName;
  207600. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207601. };
  207602. static void* createWindowCallback (void* userData)
  207603. {
  207604. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207605. return 0;
  207606. }
  207607. void createWindow()
  207608. {
  207609. DWORD exstyle = WS_EX_ACCEPTFILES;
  207610. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207611. if (hasTitleBar())
  207612. {
  207613. type |= WS_OVERLAPPED;
  207614. if ((styleFlags & windowHasCloseButton) != 0)
  207615. {
  207616. type |= WS_SYSMENU;
  207617. }
  207618. else
  207619. {
  207620. // annoyingly, windows won't let you have a min/max button without a close button
  207621. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207622. }
  207623. if ((styleFlags & windowIsResizable) != 0)
  207624. type |= WS_THICKFRAME;
  207625. }
  207626. else if (parentToAddTo != 0)
  207627. {
  207628. type |= WS_CHILD;
  207629. }
  207630. else
  207631. {
  207632. type |= WS_POPUP | WS_SYSMENU;
  207633. }
  207634. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207635. exstyle |= WS_EX_TOOLWINDOW;
  207636. else
  207637. exstyle |= WS_EX_APPWINDOW;
  207638. if ((styleFlags & windowHasMinimiseButton) != 0)
  207639. type |= WS_MINIMIZEBOX;
  207640. if ((styleFlags & windowHasMaximiseButton) != 0)
  207641. type |= WS_MAXIMIZEBOX;
  207642. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207643. exstyle |= WS_EX_TRANSPARENT;
  207644. if ((styleFlags & windowIsSemiTransparent) != 0
  207645. && Desktop::canUseSemiTransparentWindows())
  207646. exstyle |= WS_EX_LAYERED;
  207647. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName.toUTF16(), L"", type, 0, 0, 0, 0,
  207648. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207649. #if JUCE_DIRECT2D
  207650. updateDirect2DContext();
  207651. #endif
  207652. if (hwnd != 0)
  207653. {
  207654. SetWindowLongPtr (hwnd, 0, 0);
  207655. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207656. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207657. if (dropTarget == 0)
  207658. dropTarget = new JuceDropTarget (this);
  207659. RegisterDragDrop (hwnd, dropTarget);
  207660. updateBorderSize();
  207661. // Calling this function here is (for some reason) necessary to make Windows
  207662. // correctly enable the menu items that we specify in the wm_initmenu message.
  207663. GetSystemMenu (hwnd, false);
  207664. const float alpha = component->getAlpha();
  207665. if (alpha < 1.0f)
  207666. setAlpha (alpha);
  207667. }
  207668. else
  207669. {
  207670. jassertfalse;
  207671. }
  207672. }
  207673. static void* destroyWindowCallback (void* handle)
  207674. {
  207675. RevokeDragDrop ((HWND) handle);
  207676. DestroyWindow ((HWND) handle);
  207677. return 0;
  207678. }
  207679. static void* toFrontCallback1 (void* h)
  207680. {
  207681. SetForegroundWindow ((HWND) h);
  207682. return 0;
  207683. }
  207684. static void* toFrontCallback2 (void* h)
  207685. {
  207686. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207687. return 0;
  207688. }
  207689. static void* setFocusCallback (void* h)
  207690. {
  207691. SetFocus ((HWND) h);
  207692. return 0;
  207693. }
  207694. static void* getFocusCallback (void*)
  207695. {
  207696. return GetFocus();
  207697. }
  207698. void offsetWithinParent (int& x, int& y) const
  207699. {
  207700. if (isUsingUpdateLayeredWindow())
  207701. {
  207702. HWND parentHwnd = GetParent (hwnd);
  207703. if (parentHwnd != 0)
  207704. {
  207705. RECT parentRect;
  207706. GetWindowRect (parentHwnd, &parentRect);
  207707. x += parentRect.left;
  207708. y += parentRect.top;
  207709. }
  207710. }
  207711. }
  207712. bool isUsingUpdateLayeredWindow() const
  207713. {
  207714. return ! component->isOpaque();
  207715. }
  207716. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207717. void setIcon (const Image& newIcon)
  207718. {
  207719. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207720. if (hicon != 0)
  207721. {
  207722. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207723. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207724. if (currentWindowIcon != 0)
  207725. DestroyIcon (currentWindowIcon);
  207726. currentWindowIcon = hicon;
  207727. }
  207728. }
  207729. void handlePaintMessage()
  207730. {
  207731. #if JUCE_DIRECT2D
  207732. if (direct2DContext != 0)
  207733. {
  207734. RECT r;
  207735. if (GetUpdateRect (hwnd, &r, false))
  207736. {
  207737. direct2DContext->start();
  207738. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207739. handlePaint (*direct2DContext);
  207740. direct2DContext->end();
  207741. }
  207742. }
  207743. else
  207744. #endif
  207745. {
  207746. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207747. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207748. PAINTSTRUCT paintStruct;
  207749. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207750. // message and become re-entrant, but that's OK
  207751. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207752. // corrupt the image it's using to paint into, so do a check here.
  207753. static bool reentrant = false;
  207754. if (reentrant)
  207755. {
  207756. DeleteObject (rgn);
  207757. EndPaint (hwnd, &paintStruct);
  207758. return;
  207759. }
  207760. const ScopedValueSetter<bool> setter (reentrant, true, false);
  207761. // this is the rectangle to update..
  207762. int x = paintStruct.rcPaint.left;
  207763. int y = paintStruct.rcPaint.top;
  207764. int w = paintStruct.rcPaint.right - x;
  207765. int h = paintStruct.rcPaint.bottom - y;
  207766. const bool transparent = isUsingUpdateLayeredWindow();
  207767. if (transparent)
  207768. {
  207769. // it's not possible to have a transparent window with a title bar at the moment!
  207770. jassert (! hasTitleBar());
  207771. RECT r;
  207772. GetWindowRect (hwnd, &r);
  207773. x = y = 0;
  207774. w = r.right - r.left;
  207775. h = r.bottom - r.top;
  207776. }
  207777. if (w > 0 && h > 0)
  207778. {
  207779. clearMaskedRegion();
  207780. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207781. RectangleList contextClip;
  207782. const Rectangle<int> clipBounds (0, 0, w, h);
  207783. bool needToPaintAll = true;
  207784. if (regionType == COMPLEXREGION && ! transparent)
  207785. {
  207786. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207787. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207788. DeleteObject (clipRgn);
  207789. char rgnData [8192];
  207790. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207791. if (res > 0 && res <= sizeof (rgnData))
  207792. {
  207793. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207794. if (hdr->iType == RDH_RECTANGLES
  207795. && hdr->rcBound.right - hdr->rcBound.left >= w
  207796. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207797. {
  207798. needToPaintAll = false;
  207799. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207800. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207801. while (--num >= 0)
  207802. {
  207803. if (rects->right <= x + w && rects->bottom <= y + h)
  207804. {
  207805. const int cx = jmax (x, (int) rects->left);
  207806. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207807. .getIntersection (clipBounds));
  207808. }
  207809. else
  207810. {
  207811. needToPaintAll = true;
  207812. break;
  207813. }
  207814. ++rects;
  207815. }
  207816. }
  207817. }
  207818. }
  207819. if (needToPaintAll)
  207820. {
  207821. contextClip.clear();
  207822. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207823. }
  207824. if (transparent)
  207825. {
  207826. RectangleList::Iterator i (contextClip);
  207827. while (i.next())
  207828. offscreenImage.clear (*i.getRectangle());
  207829. }
  207830. // if the component's not opaque, this won't draw properly unless the platform can support this
  207831. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207832. updateCurrentModifiers();
  207833. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207834. handlePaint (context);
  207835. if (! dontRepaint)
  207836. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207837. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207838. }
  207839. DeleteObject (rgn);
  207840. EndPaint (hwnd, &paintStruct);
  207841. }
  207842. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207843. _fpreset(); // because some graphics cards can unmask FP exceptions
  207844. #endif
  207845. lastPaintTime = Time::getMillisecondCounter();
  207846. }
  207847. void doMouseEvent (const Point<int>& position)
  207848. {
  207849. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207850. }
  207851. const StringArray getAvailableRenderingEngines()
  207852. {
  207853. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207854. #if JUCE_DIRECT2D
  207855. // xxx is this correct? Seems to enable it on Vista too??
  207856. OSVERSIONINFO info;
  207857. zerostruct (info);
  207858. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207859. GetVersionEx (&info);
  207860. if (info.dwMajorVersion >= 6)
  207861. s.add ("Direct2D");
  207862. #endif
  207863. return s;
  207864. }
  207865. int getCurrentRenderingEngine() throw()
  207866. {
  207867. return currentRenderingEngine;
  207868. }
  207869. #if JUCE_DIRECT2D
  207870. void updateDirect2DContext()
  207871. {
  207872. if (currentRenderingEngine != direct2DRenderingEngine)
  207873. direct2DContext = 0;
  207874. else if (direct2DContext == 0)
  207875. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207876. }
  207877. #endif
  207878. void setCurrentRenderingEngine (int index)
  207879. {
  207880. (void) index;
  207881. #if JUCE_DIRECT2D
  207882. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207883. updateDirect2DContext();
  207884. repaint (component->getLocalBounds());
  207885. #endif
  207886. }
  207887. void doMouseMove (const Point<int>& position)
  207888. {
  207889. if (! isMouseOver)
  207890. {
  207891. isMouseOver = true;
  207892. updateKeyModifiers();
  207893. TRACKMOUSEEVENT tme;
  207894. tme.cbSize = sizeof (tme);
  207895. tme.dwFlags = TME_LEAVE;
  207896. tme.hwndTrack = hwnd;
  207897. tme.dwHoverTime = 0;
  207898. if (! TrackMouseEvent (&tme))
  207899. jassertfalse;
  207900. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207901. }
  207902. else if (! isDragging)
  207903. {
  207904. if (! contains (position, false))
  207905. return;
  207906. }
  207907. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207908. static uint32 lastMouseTime = 0;
  207909. const uint32 now = Time::getMillisecondCounter();
  207910. const int maxMouseMovesPerSecond = 60;
  207911. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207912. {
  207913. lastMouseTime = now;
  207914. doMouseEvent (position);
  207915. }
  207916. }
  207917. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207918. {
  207919. if (GetCapture() != hwnd)
  207920. SetCapture (hwnd);
  207921. doMouseMove (position);
  207922. updateModifiersFromWParam (wParam);
  207923. isDragging = true;
  207924. doMouseEvent (position);
  207925. }
  207926. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207927. {
  207928. updateModifiersFromWParam (wParam);
  207929. isDragging = false;
  207930. // release the mouse capture if the user has released all buttons
  207931. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207932. ReleaseCapture();
  207933. doMouseEvent (position);
  207934. }
  207935. void doCaptureChanged()
  207936. {
  207937. if (constrainerIsResizing)
  207938. {
  207939. if (constrainer != 0)
  207940. constrainer->resizeEnd();
  207941. constrainerIsResizing = false;
  207942. }
  207943. if (isDragging)
  207944. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207945. }
  207946. void doMouseExit()
  207947. {
  207948. isMouseOver = false;
  207949. doMouseEvent (getCurrentMousePos());
  207950. }
  207951. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207952. {
  207953. updateKeyModifiers();
  207954. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207955. handleMouseWheel (0, position, getMouseEventTime(),
  207956. isVertical ? 0.0f : amount,
  207957. isVertical ? amount : 0.0f);
  207958. }
  207959. void sendModifierKeyChangeIfNeeded()
  207960. {
  207961. if (modifiersAtLastCallback != currentModifiers)
  207962. {
  207963. modifiersAtLastCallback = currentModifiers;
  207964. handleModifierKeysChange();
  207965. }
  207966. }
  207967. bool doKeyUp (const WPARAM key)
  207968. {
  207969. updateKeyModifiers();
  207970. switch (key)
  207971. {
  207972. case VK_SHIFT:
  207973. case VK_CONTROL:
  207974. case VK_MENU:
  207975. case VK_CAPITAL:
  207976. case VK_LWIN:
  207977. case VK_RWIN:
  207978. case VK_APPS:
  207979. case VK_NUMLOCK:
  207980. case VK_SCROLL:
  207981. case VK_LSHIFT:
  207982. case VK_RSHIFT:
  207983. case VK_LCONTROL:
  207984. case VK_LMENU:
  207985. case VK_RCONTROL:
  207986. case VK_RMENU:
  207987. sendModifierKeyChangeIfNeeded();
  207988. }
  207989. return handleKeyUpOrDown (false)
  207990. || Component::getCurrentlyModalComponent() != 0;
  207991. }
  207992. bool doKeyDown (const WPARAM key)
  207993. {
  207994. updateKeyModifiers();
  207995. bool used = false;
  207996. switch (key)
  207997. {
  207998. case VK_SHIFT:
  207999. case VK_LSHIFT:
  208000. case VK_RSHIFT:
  208001. case VK_CONTROL:
  208002. case VK_LCONTROL:
  208003. case VK_RCONTROL:
  208004. case VK_MENU:
  208005. case VK_LMENU:
  208006. case VK_RMENU:
  208007. case VK_LWIN:
  208008. case VK_RWIN:
  208009. case VK_CAPITAL:
  208010. case VK_NUMLOCK:
  208011. case VK_SCROLL:
  208012. case VK_APPS:
  208013. sendModifierKeyChangeIfNeeded();
  208014. break;
  208015. case VK_LEFT:
  208016. case VK_RIGHT:
  208017. case VK_UP:
  208018. case VK_DOWN:
  208019. case VK_PRIOR:
  208020. case VK_NEXT:
  208021. case VK_HOME:
  208022. case VK_END:
  208023. case VK_DELETE:
  208024. case VK_INSERT:
  208025. case VK_F1:
  208026. case VK_F2:
  208027. case VK_F3:
  208028. case VK_F4:
  208029. case VK_F5:
  208030. case VK_F6:
  208031. case VK_F7:
  208032. case VK_F8:
  208033. case VK_F9:
  208034. case VK_F10:
  208035. case VK_F11:
  208036. case VK_F12:
  208037. case VK_F13:
  208038. case VK_F14:
  208039. case VK_F15:
  208040. case VK_F16:
  208041. used = handleKeyUpOrDown (true);
  208042. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  208043. break;
  208044. case VK_ADD:
  208045. case VK_SUBTRACT:
  208046. case VK_MULTIPLY:
  208047. case VK_DIVIDE:
  208048. case VK_SEPARATOR:
  208049. case VK_DECIMAL:
  208050. used = handleKeyUpOrDown (true);
  208051. break;
  208052. default:
  208053. used = handleKeyUpOrDown (true);
  208054. {
  208055. MSG msg;
  208056. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  208057. {
  208058. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  208059. // manually generate the key-press event that matches this key-down.
  208060. const UINT keyChar = MapVirtualKey (key, 2);
  208061. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  208062. }
  208063. }
  208064. break;
  208065. }
  208066. if (Component::getCurrentlyModalComponent() != 0)
  208067. used = true;
  208068. return used;
  208069. }
  208070. bool doKeyChar (int key, const LPARAM flags)
  208071. {
  208072. updateKeyModifiers();
  208073. juce_wchar textChar = (juce_wchar) key;
  208074. const int virtualScanCode = (flags >> 16) & 0xff;
  208075. if (key >= '0' && key <= '9')
  208076. {
  208077. switch (virtualScanCode) // check for a numeric keypad scan-code
  208078. {
  208079. case 0x52:
  208080. case 0x4f:
  208081. case 0x50:
  208082. case 0x51:
  208083. case 0x4b:
  208084. case 0x4c:
  208085. case 0x4d:
  208086. case 0x47:
  208087. case 0x48:
  208088. case 0x49:
  208089. key = (key - '0') + KeyPress::numberPad0;
  208090. break;
  208091. default:
  208092. break;
  208093. }
  208094. }
  208095. else
  208096. {
  208097. // convert the scan code to an unmodified character code..
  208098. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  208099. UINT keyChar = MapVirtualKey (virtualKey, 2);
  208100. keyChar = LOWORD (keyChar);
  208101. if (keyChar != 0)
  208102. key = (int) keyChar;
  208103. // avoid sending junk text characters for some control-key combinations
  208104. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  208105. textChar = 0;
  208106. }
  208107. return handleKeyPress (key, textChar);
  208108. }
  208109. bool doAppCommand (const LPARAM lParam)
  208110. {
  208111. int key = 0;
  208112. switch (GET_APPCOMMAND_LPARAM (lParam))
  208113. {
  208114. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  208115. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  208116. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  208117. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  208118. default: break;
  208119. }
  208120. if (key != 0)
  208121. {
  208122. updateKeyModifiers();
  208123. if (hwnd == GetActiveWindow())
  208124. {
  208125. handleKeyPress (key, 0);
  208126. return true;
  208127. }
  208128. }
  208129. return false;
  208130. }
  208131. bool isConstrainedNativeWindow() const
  208132. {
  208133. return constrainer != 0
  208134. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable);
  208135. }
  208136. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  208137. {
  208138. if (isConstrainedNativeWindow())
  208139. {
  208140. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  208141. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  208142. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208143. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  208144. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  208145. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  208146. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  208147. r->left = pos.getX();
  208148. r->top = pos.getY();
  208149. r->right = pos.getRight();
  208150. r->bottom = pos.getBottom();
  208151. }
  208152. return TRUE;
  208153. }
  208154. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  208155. {
  208156. if (isConstrainedNativeWindow())
  208157. {
  208158. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  208159. && ! Component::isMouseButtonDownAnywhere())
  208160. {
  208161. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  208162. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  208163. constrainer->checkBounds (pos, current,
  208164. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208165. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  208166. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  208167. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  208168. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  208169. wp->x = pos.getX();
  208170. wp->y = pos.getY();
  208171. wp->cx = pos.getWidth();
  208172. wp->cy = pos.getHeight();
  208173. }
  208174. }
  208175. return 0;
  208176. }
  208177. void handleAppActivation (const WPARAM wParam)
  208178. {
  208179. modifiersAtLastCallback = -1;
  208180. updateKeyModifiers();
  208181. if (isMinimised())
  208182. {
  208183. component->repaint();
  208184. handleMovedOrResized();
  208185. if (! ComponentPeer::isValidPeer (this))
  208186. return;
  208187. }
  208188. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  208189. {
  208190. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  208191. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208192. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208193. }
  208194. else
  208195. {
  208196. handleBroughtToFront();
  208197. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208198. Component::getCurrentlyModalComponent()->toFront (true);
  208199. }
  208200. }
  208201. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  208202. {
  208203. public:
  208204. JuceDropTarget (Win32ComponentPeer* const owner_)
  208205. : owner (owner_)
  208206. {
  208207. }
  208208. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208209. {
  208210. updateFileList (pDataObject);
  208211. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208212. *pdwEffect = DROPEFFECT_COPY;
  208213. return S_OK;
  208214. }
  208215. HRESULT __stdcall DragLeave()
  208216. {
  208217. owner->handleFileDragExit (files);
  208218. return S_OK;
  208219. }
  208220. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208221. {
  208222. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208223. *pdwEffect = DROPEFFECT_COPY;
  208224. return S_OK;
  208225. }
  208226. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208227. {
  208228. updateFileList (pDataObject);
  208229. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208230. *pdwEffect = DROPEFFECT_COPY;
  208231. return S_OK;
  208232. }
  208233. private:
  208234. Win32ComponentPeer* const owner;
  208235. StringArray files;
  208236. void updateFileList (IDataObject* const pDataObject)
  208237. {
  208238. files.clear();
  208239. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208240. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208241. if (pDataObject->GetData (&format, &medium) == S_OK)
  208242. {
  208243. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  208244. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  208245. unsigned int i = 0;
  208246. if (pDropFiles->fWide)
  208247. {
  208248. const WCHAR* const fname = (WCHAR*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  208249. for (;;)
  208250. {
  208251. unsigned int len = 0;
  208252. while (i + len < totalLen && fname [i + len] != 0)
  208253. ++len;
  208254. if (len == 0)
  208255. break;
  208256. files.add (String (fname + i, len));
  208257. i += len + 1;
  208258. }
  208259. }
  208260. else
  208261. {
  208262. const char* const fname = (const char*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  208263. for (;;)
  208264. {
  208265. unsigned int len = 0;
  208266. while (i + len < totalLen && fname [i + len] != 0)
  208267. ++len;
  208268. if (len == 0)
  208269. break;
  208270. files.add (String (fname + i, len));
  208271. i += len + 1;
  208272. }
  208273. }
  208274. GlobalUnlock (medium.hGlobal);
  208275. }
  208276. }
  208277. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  208278. };
  208279. void doSettingChange()
  208280. {
  208281. Desktop::getInstance().refreshMonitorSizes();
  208282. if (fullScreen && ! isMinimised())
  208283. {
  208284. const Rectangle<int> r (component->getParentMonitorArea());
  208285. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  208286. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  208287. }
  208288. }
  208289. public:
  208290. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208291. {
  208292. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  208293. if (peer != 0)
  208294. {
  208295. jassert (isValidPeer (peer));
  208296. return peer->peerWindowProc (h, message, wParam, lParam);
  208297. }
  208298. return DefWindowProcW (h, message, wParam, lParam);
  208299. }
  208300. private:
  208301. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  208302. {
  208303. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  208304. return callback (userData);
  208305. else
  208306. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  208307. }
  208308. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208309. {
  208310. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208311. }
  208312. const Point<int> getCurrentMousePos() throw()
  208313. {
  208314. RECT wr;
  208315. GetWindowRect (hwnd, &wr);
  208316. const DWORD mp = GetMessagePos();
  208317. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208318. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208319. }
  208320. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208321. {
  208322. switch (message)
  208323. {
  208324. case WM_NCHITTEST:
  208325. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208326. return HTTRANSPARENT;
  208327. else if (! hasTitleBar())
  208328. return HTCLIENT;
  208329. break;
  208330. case WM_PAINT:
  208331. handlePaintMessage();
  208332. return 0;
  208333. case WM_NCPAINT:
  208334. if (hasTitleBar())
  208335. break;
  208336. else if (wParam != 1)
  208337. handlePaintMessage();
  208338. return 0;
  208339. case WM_ERASEBKGND:
  208340. case WM_NCCALCSIZE:
  208341. if (hasTitleBar())
  208342. break;
  208343. return 1;
  208344. case WM_MOUSEMOVE:
  208345. doMouseMove (getPointFromLParam (lParam));
  208346. return 0;
  208347. case WM_MOUSELEAVE:
  208348. doMouseExit();
  208349. return 0;
  208350. case WM_LBUTTONDOWN:
  208351. case WM_MBUTTONDOWN:
  208352. case WM_RBUTTONDOWN:
  208353. doMouseDown (getPointFromLParam (lParam), wParam);
  208354. return 0;
  208355. case WM_LBUTTONUP:
  208356. case WM_MBUTTONUP:
  208357. case WM_RBUTTONUP:
  208358. doMouseUp (getPointFromLParam (lParam), wParam);
  208359. return 0;
  208360. case WM_CAPTURECHANGED:
  208361. doCaptureChanged();
  208362. return 0;
  208363. case WM_NCMOUSEMOVE:
  208364. if (hasTitleBar())
  208365. break;
  208366. return 0;
  208367. case 0x020A: /* WM_MOUSEWHEEL */
  208368. case 0x020E: /* WM_MOUSEHWHEEL */
  208369. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  208370. return 0;
  208371. case WM_SIZING:
  208372. return handleSizeConstraining ((RECT*) lParam, wParam);
  208373. case WM_WINDOWPOSCHANGING:
  208374. return handlePositionChanging ((WINDOWPOS*) lParam);
  208375. case WM_WINDOWPOSCHANGED:
  208376. {
  208377. const Point<int> pos (getCurrentMousePos());
  208378. if (contains (pos, false))
  208379. doMouseEvent (pos);
  208380. }
  208381. handleMovedOrResized();
  208382. if (dontRepaint)
  208383. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208384. return 0;
  208385. case WM_KEYDOWN:
  208386. case WM_SYSKEYDOWN:
  208387. if (doKeyDown (wParam))
  208388. return 0;
  208389. break;
  208390. case WM_KEYUP:
  208391. case WM_SYSKEYUP:
  208392. if (doKeyUp (wParam))
  208393. return 0;
  208394. break;
  208395. case WM_CHAR:
  208396. if (doKeyChar ((int) wParam, lParam))
  208397. return 0;
  208398. break;
  208399. case WM_APPCOMMAND:
  208400. if (doAppCommand (lParam))
  208401. return TRUE;
  208402. break;
  208403. case WM_SETFOCUS:
  208404. updateKeyModifiers();
  208405. handleFocusGain();
  208406. break;
  208407. case WM_KILLFOCUS:
  208408. if (hasCreatedCaret)
  208409. {
  208410. hasCreatedCaret = false;
  208411. DestroyCaret();
  208412. }
  208413. handleFocusLoss();
  208414. break;
  208415. case WM_ACTIVATEAPP:
  208416. // Windows does weird things to process priority when you swap apps,
  208417. // so this forces an update when the app is brought to the front
  208418. if (wParam != FALSE)
  208419. juce_repeatLastProcessPriority();
  208420. else
  208421. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208422. juce_CheckCurrentlyFocusedTopLevelWindow();
  208423. modifiersAtLastCallback = -1;
  208424. return 0;
  208425. case WM_ACTIVATE:
  208426. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208427. {
  208428. handleAppActivation (wParam);
  208429. return 0;
  208430. }
  208431. break;
  208432. case WM_NCACTIVATE:
  208433. // while a temporary window is being shown, prevent Windows from deactivating the
  208434. // title bars of our main windows.
  208435. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208436. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208437. break;
  208438. case WM_MOUSEACTIVATE:
  208439. if (! component->getMouseClickGrabsKeyboardFocus())
  208440. return MA_NOACTIVATE;
  208441. break;
  208442. case WM_SHOWWINDOW:
  208443. if (wParam != 0)
  208444. handleBroughtToFront();
  208445. break;
  208446. case WM_CLOSE:
  208447. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208448. handleUserClosingWindow();
  208449. return 0;
  208450. case WM_QUERYENDSESSION:
  208451. if (JUCEApplication::getInstance() != 0)
  208452. {
  208453. JUCEApplication::getInstance()->systemRequestedQuit();
  208454. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208455. }
  208456. return TRUE;
  208457. case WM_TRAYNOTIFY:
  208458. handleTaskBarEvent (lParam);
  208459. break;
  208460. case WM_SYNCPAINT:
  208461. return 0;
  208462. case WM_DISPLAYCHANGE:
  208463. InvalidateRect (h, 0, 0);
  208464. // intentional fall-through...
  208465. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208466. doSettingChange();
  208467. break;
  208468. case WM_INITMENU:
  208469. if (! hasTitleBar())
  208470. {
  208471. if (isFullScreen())
  208472. {
  208473. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208474. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208475. }
  208476. else if (! isMinimised())
  208477. {
  208478. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208479. }
  208480. }
  208481. break;
  208482. case WM_SYSCOMMAND:
  208483. switch (wParam & 0xfff0)
  208484. {
  208485. case SC_CLOSE:
  208486. if (sendInputAttemptWhenModalMessage())
  208487. return 0;
  208488. if (hasTitleBar())
  208489. {
  208490. PostMessage (h, WM_CLOSE, 0, 0);
  208491. return 0;
  208492. }
  208493. break;
  208494. case SC_KEYMENU:
  208495. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  208496. // situations that can arise if a modal loop is started from an alt-key keypress).
  208497. if (hasTitleBar() && h == GetCapture())
  208498. ReleaseCapture();
  208499. break;
  208500. case SC_MAXIMIZE:
  208501. if (! sendInputAttemptWhenModalMessage())
  208502. setFullScreen (true);
  208503. return 0;
  208504. case SC_MINIMIZE:
  208505. if (sendInputAttemptWhenModalMessage())
  208506. return 0;
  208507. if (! hasTitleBar())
  208508. {
  208509. setMinimised (true);
  208510. return 0;
  208511. }
  208512. break;
  208513. case SC_RESTORE:
  208514. if (sendInputAttemptWhenModalMessage())
  208515. return 0;
  208516. if (hasTitleBar())
  208517. {
  208518. if (isFullScreen())
  208519. {
  208520. setFullScreen (false);
  208521. return 0;
  208522. }
  208523. }
  208524. else
  208525. {
  208526. if (isMinimised())
  208527. setMinimised (false);
  208528. else if (isFullScreen())
  208529. setFullScreen (false);
  208530. return 0;
  208531. }
  208532. break;
  208533. }
  208534. break;
  208535. case WM_NCLBUTTONDOWN:
  208536. if (! sendInputAttemptWhenModalMessage())
  208537. {
  208538. switch (wParam)
  208539. {
  208540. case HTBOTTOM:
  208541. case HTBOTTOMLEFT:
  208542. case HTBOTTOMRIGHT:
  208543. case HTGROWBOX:
  208544. case HTLEFT:
  208545. case HTRIGHT:
  208546. case HTTOP:
  208547. case HTTOPLEFT:
  208548. case HTTOPRIGHT:
  208549. if (isConstrainedNativeWindow())
  208550. {
  208551. constrainerIsResizing = true;
  208552. constrainer->resizeStart();
  208553. }
  208554. break;
  208555. default:
  208556. break;
  208557. };
  208558. }
  208559. break;
  208560. case WM_NCRBUTTONDOWN:
  208561. case WM_NCMBUTTONDOWN:
  208562. sendInputAttemptWhenModalMessage();
  208563. break;
  208564. //case WM_IME_STARTCOMPOSITION;
  208565. // return 0;
  208566. case WM_GETDLGCODE:
  208567. return DLGC_WANTALLKEYS;
  208568. default:
  208569. if (taskBarIcon != 0)
  208570. {
  208571. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208572. if (message == taskbarCreatedMessage)
  208573. {
  208574. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208575. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208576. }
  208577. }
  208578. break;
  208579. }
  208580. return DefWindowProcW (h, message, wParam, lParam);
  208581. }
  208582. bool sendInputAttemptWhenModalMessage()
  208583. {
  208584. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208585. {
  208586. Component* const current = Component::getCurrentlyModalComponent();
  208587. if (current != 0)
  208588. current->inputAttemptWhenModal();
  208589. return true;
  208590. }
  208591. return false;
  208592. }
  208593. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208594. };
  208595. ModifierKeys Win32ComponentPeer::currentModifiers;
  208596. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208597. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208598. {
  208599. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208600. }
  208601. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208602. void ModifierKeys::updateCurrentModifiers() throw()
  208603. {
  208604. currentModifiers = Win32ComponentPeer::currentModifiers;
  208605. }
  208606. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208607. {
  208608. Win32ComponentPeer::updateKeyModifiers();
  208609. int mouseMods = 0;
  208610. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208611. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208612. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208613. Win32ComponentPeer::currentModifiers
  208614. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208615. return Win32ComponentPeer::currentModifiers;
  208616. }
  208617. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208618. {
  208619. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208620. if (wp != 0)
  208621. wp->setTaskBarIcon (newImage);
  208622. }
  208623. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208624. {
  208625. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208626. if (wp != 0)
  208627. wp->setTaskBarIconToolTip (tooltip);
  208628. }
  208629. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208630. {
  208631. DWORD val = GetWindowLong (h, styleType);
  208632. if (bitIsSet)
  208633. val |= feature;
  208634. else
  208635. val &= ~feature;
  208636. SetWindowLongPtr (h, styleType, val);
  208637. SetWindowPos (h, 0, 0, 0, 0, 0,
  208638. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208639. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208640. }
  208641. bool Process::isForegroundProcess()
  208642. {
  208643. HWND fg = GetForegroundWindow();
  208644. if (fg == 0)
  208645. return true;
  208646. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208647. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208648. // have to see if any of our windows are children of the foreground window
  208649. fg = GetAncestor (fg, GA_ROOT);
  208650. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208651. {
  208652. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208653. if (wp != 0 && wp->isInside (fg))
  208654. return true;
  208655. }
  208656. return false;
  208657. }
  208658. bool AlertWindow::showNativeDialogBox (const String& title,
  208659. const String& bodyText,
  208660. bool isOkCancel)
  208661. {
  208662. return MessageBox (0, bodyText.toUTF16(), title.toUTF16(),
  208663. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208664. : MB_OK)) == IDOK;
  208665. }
  208666. void Desktop::createMouseInputSources()
  208667. {
  208668. mouseSources.add (new MouseInputSource (0, true));
  208669. }
  208670. const Point<int> MouseInputSource::getCurrentMousePosition()
  208671. {
  208672. POINT mousePos;
  208673. GetCursorPos (&mousePos);
  208674. return Point<int> (mousePos.x, mousePos.y);
  208675. }
  208676. void Desktop::setMousePosition (const Point<int>& newPosition)
  208677. {
  208678. SetCursorPos (newPosition.getX(), newPosition.getY());
  208679. }
  208680. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208681. {
  208682. return createSoftwareImage (format, width, height, clearImage);
  208683. }
  208684. class ScreenSaverDefeater : public Timer,
  208685. public DeletedAtShutdown
  208686. {
  208687. public:
  208688. ScreenSaverDefeater()
  208689. {
  208690. startTimer (10000);
  208691. timerCallback();
  208692. }
  208693. ~ScreenSaverDefeater() {}
  208694. void timerCallback()
  208695. {
  208696. if (Process::isForegroundProcess())
  208697. {
  208698. // simulate a shift key getting pressed..
  208699. INPUT input[2];
  208700. input[0].type = INPUT_KEYBOARD;
  208701. input[0].ki.wVk = VK_SHIFT;
  208702. input[0].ki.dwFlags = 0;
  208703. input[0].ki.dwExtraInfo = 0;
  208704. input[1].type = INPUT_KEYBOARD;
  208705. input[1].ki.wVk = VK_SHIFT;
  208706. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208707. input[1].ki.dwExtraInfo = 0;
  208708. SendInput (2, input, sizeof (INPUT));
  208709. }
  208710. }
  208711. };
  208712. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208713. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208714. {
  208715. if (isEnabled)
  208716. deleteAndZero (screenSaverDefeater);
  208717. else if (screenSaverDefeater == 0)
  208718. screenSaverDefeater = new ScreenSaverDefeater();
  208719. }
  208720. bool Desktop::isScreenSaverEnabled()
  208721. {
  208722. return screenSaverDefeater == 0;
  208723. }
  208724. /* (The code below is the "correct" way to disable the screen saver, but it
  208725. completely fails on winXP when the saver is password-protected...)
  208726. static bool juce_screenSaverEnabled = true;
  208727. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208728. {
  208729. juce_screenSaverEnabled = isEnabled;
  208730. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208731. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208732. }
  208733. bool Desktop::isScreenSaverEnabled() throw()
  208734. {
  208735. return juce_screenSaverEnabled;
  208736. }
  208737. */
  208738. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208739. {
  208740. if (enableOrDisable)
  208741. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208742. }
  208743. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208744. {
  208745. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208746. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208747. return TRUE;
  208748. }
  208749. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208750. {
  208751. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208752. // make sure the first in the list is the main monitor
  208753. for (int i = 1; i < monitorCoords.size(); ++i)
  208754. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208755. monitorCoords.swap (i, 0);
  208756. if (monitorCoords.size() == 0)
  208757. {
  208758. RECT r;
  208759. GetWindowRect (GetDesktopWindow(), &r);
  208760. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208761. }
  208762. if (clipToWorkArea)
  208763. {
  208764. // clip the main monitor to the active non-taskbar area
  208765. RECT r;
  208766. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208767. Rectangle<int>& screen = monitorCoords.getReference (0);
  208768. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208769. jmax (screen.getY(), (int) r.top));
  208770. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208771. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208772. }
  208773. }
  208774. const Image juce_createIconForFile (const File& file)
  208775. {
  208776. Image image;
  208777. WORD iconNum = 0;
  208778. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208779. const_cast <WCHAR*> (file.getFullPathName().toUTF16().getAddress()), &iconNum);
  208780. if (icon != 0)
  208781. {
  208782. image = IconConverters::createImageFromHICON (icon);
  208783. DestroyIcon (icon);
  208784. }
  208785. return image;
  208786. }
  208787. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208788. {
  208789. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208790. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208791. Image im (image);
  208792. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208793. {
  208794. im = im.rescaled (maxW, maxH);
  208795. hotspotX = (hotspotX * maxW) / image.getWidth();
  208796. hotspotY = (hotspotY * maxH) / image.getHeight();
  208797. }
  208798. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208799. }
  208800. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208801. {
  208802. if (cursorHandle != 0 && ! isStandard)
  208803. DestroyCursor ((HCURSOR) cursorHandle);
  208804. }
  208805. enum
  208806. {
  208807. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208808. };
  208809. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208810. {
  208811. LPCTSTR cursorName = IDC_ARROW;
  208812. switch (type)
  208813. {
  208814. case NormalCursor: break;
  208815. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208816. case WaitCursor: cursorName = IDC_WAIT; break;
  208817. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208818. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208819. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208820. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208821. case LeftRightResizeCursor:
  208822. case LeftEdgeResizeCursor:
  208823. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208824. case UpDownResizeCursor:
  208825. case TopEdgeResizeCursor:
  208826. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208827. case TopLeftCornerResizeCursor:
  208828. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208829. case TopRightCornerResizeCursor:
  208830. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208831. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208832. case DraggingHandCursor:
  208833. {
  208834. static void* dragHandCursor = 0;
  208835. if (dragHandCursor == 0)
  208836. {
  208837. static const unsigned char dragHandData[] =
  208838. { 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,
  208839. 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,
  208840. 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 };
  208841. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208842. }
  208843. return dragHandCursor;
  208844. }
  208845. default:
  208846. jassertfalse; break;
  208847. }
  208848. HCURSOR cursorH = LoadCursor (0, cursorName);
  208849. if (cursorH == 0)
  208850. cursorH = LoadCursor (0, IDC_ARROW);
  208851. return cursorH;
  208852. }
  208853. void MouseCursor::showInWindow (ComponentPeer*) const
  208854. {
  208855. HCURSOR c = (HCURSOR) getHandle();
  208856. if (c == 0)
  208857. c = LoadCursor (0, IDC_ARROW);
  208858. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208859. c = 0;
  208860. SetCursor (c);
  208861. }
  208862. void MouseCursor::showInAllWindows() const
  208863. {
  208864. showInWindow (0);
  208865. }
  208866. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208867. {
  208868. public:
  208869. JuceDropSource() {}
  208870. ~JuceDropSource() {}
  208871. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208872. {
  208873. if (escapePressed)
  208874. return DRAGDROP_S_CANCEL;
  208875. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208876. return DRAGDROP_S_DROP;
  208877. return S_OK;
  208878. }
  208879. HRESULT __stdcall GiveFeedback (DWORD)
  208880. {
  208881. return DRAGDROP_S_USEDEFAULTCURSORS;
  208882. }
  208883. };
  208884. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208885. {
  208886. public:
  208887. JuceEnumFormatEtc (const FORMATETC* const format_)
  208888. : format (format_),
  208889. index (0)
  208890. {
  208891. }
  208892. ~JuceEnumFormatEtc() {}
  208893. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208894. {
  208895. if (result == 0)
  208896. return E_POINTER;
  208897. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208898. newOne->index = index;
  208899. *result = newOne;
  208900. return S_OK;
  208901. }
  208902. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208903. {
  208904. if (pceltFetched != 0)
  208905. *pceltFetched = 0;
  208906. else if (celt != 1)
  208907. return S_FALSE;
  208908. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208909. {
  208910. copyFormatEtc (lpFormatEtc [0], *format);
  208911. ++index;
  208912. if (pceltFetched != 0)
  208913. *pceltFetched = 1;
  208914. return S_OK;
  208915. }
  208916. return S_FALSE;
  208917. }
  208918. HRESULT __stdcall Skip (ULONG celt)
  208919. {
  208920. if (index + (int) celt >= 1)
  208921. return S_FALSE;
  208922. index += celt;
  208923. return S_OK;
  208924. }
  208925. HRESULT __stdcall Reset()
  208926. {
  208927. index = 0;
  208928. return S_OK;
  208929. }
  208930. private:
  208931. const FORMATETC* const format;
  208932. int index;
  208933. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208934. {
  208935. dest = source;
  208936. if (source.ptd != 0)
  208937. {
  208938. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208939. *(dest.ptd) = *(source.ptd);
  208940. }
  208941. }
  208942. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208943. };
  208944. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208945. {
  208946. public:
  208947. JuceDataObject (JuceDropSource* const dropSource_,
  208948. const FORMATETC* const format_,
  208949. const STGMEDIUM* const medium_)
  208950. : dropSource (dropSource_),
  208951. format (format_),
  208952. medium (medium_)
  208953. {
  208954. }
  208955. ~JuceDataObject()
  208956. {
  208957. jassert (refCount == 0);
  208958. }
  208959. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208960. {
  208961. if ((pFormatEtc->tymed & format->tymed) != 0
  208962. && pFormatEtc->cfFormat == format->cfFormat
  208963. && pFormatEtc->dwAspect == format->dwAspect)
  208964. {
  208965. pMedium->tymed = format->tymed;
  208966. pMedium->pUnkForRelease = 0;
  208967. if (format->tymed == TYMED_HGLOBAL)
  208968. {
  208969. const SIZE_T len = GlobalSize (medium->hGlobal);
  208970. void* const src = GlobalLock (medium->hGlobal);
  208971. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208972. memcpy (dst, src, len);
  208973. GlobalUnlock (medium->hGlobal);
  208974. pMedium->hGlobal = dst;
  208975. return S_OK;
  208976. }
  208977. }
  208978. return DV_E_FORMATETC;
  208979. }
  208980. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208981. {
  208982. if (f == 0)
  208983. return E_INVALIDARG;
  208984. if (f->tymed == format->tymed
  208985. && f->cfFormat == format->cfFormat
  208986. && f->dwAspect == format->dwAspect)
  208987. return S_OK;
  208988. return DV_E_FORMATETC;
  208989. }
  208990. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208991. {
  208992. pFormatEtcOut->ptd = 0;
  208993. return E_NOTIMPL;
  208994. }
  208995. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208996. {
  208997. if (result == 0)
  208998. return E_POINTER;
  208999. if (direction == DATADIR_GET)
  209000. {
  209001. *result = new JuceEnumFormatEtc (format);
  209002. return S_OK;
  209003. }
  209004. *result = 0;
  209005. return E_NOTIMPL;
  209006. }
  209007. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  209008. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  209009. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  209010. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  209011. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  209012. private:
  209013. JuceDropSource* const dropSource;
  209014. const FORMATETC* const format;
  209015. const STGMEDIUM* const medium;
  209016. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  209017. };
  209018. static HDROP createHDrop (const StringArray& fileNames)
  209019. {
  209020. int totalBytes = 0;
  209021. for (int i = fileNames.size(); --i >= 0;)
  209022. totalBytes += CharPointer_UTF16::getBytesRequiredFor (fileNames[i].getCharPointer()) + sizeof (WCHAR);
  209023. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (DROPFILES) + totalBytes + 4);
  209024. if (hDrop != 0)
  209025. {
  209026. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  209027. pDropFiles->pFiles = sizeof (DROPFILES);
  209028. pDropFiles->fWide = true;
  209029. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  209030. for (int i = 0; i < fileNames.size(); ++i)
  209031. {
  209032. const int bytesWritten = fileNames[i].copyToUTF16 (fname, 2048);
  209033. fname = reinterpret_cast<WCHAR*> (addBytesToPointer (fname, bytesWritten));
  209034. }
  209035. *fname = 0;
  209036. GlobalUnlock (hDrop);
  209037. }
  209038. return hDrop;
  209039. }
  209040. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  209041. {
  209042. JuceDropSource* const source = new JuceDropSource();
  209043. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  209044. DWORD effect;
  209045. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  209046. data->Release();
  209047. source->Release();
  209048. return res == DRAGDROP_S_DROP;
  209049. }
  209050. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  209051. {
  209052. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  209053. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  209054. medium.hGlobal = createHDrop (files);
  209055. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  209056. : DROPEFFECT_COPY);
  209057. }
  209058. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  209059. {
  209060. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  209061. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  209062. const int numBytes = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer());
  209063. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, numBytes + 2);
  209064. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  209065. text.copyToUTF16 (data, numBytes);
  209066. format.cfFormat = CF_UNICODETEXT;
  209067. GlobalUnlock (medium.hGlobal);
  209068. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  209069. }
  209070. #endif
  209071. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  209072. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  209073. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209074. // compiled on its own).
  209075. #if JUCE_INCLUDED_FILE
  209076. namespace FileChooserHelpers
  209077. {
  209078. static bool areThereAnyAlwaysOnTopWindows()
  209079. {
  209080. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  209081. {
  209082. Component* c = Desktop::getInstance().getComponent (i);
  209083. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  209084. return true;
  209085. }
  209086. return false;
  209087. }
  209088. struct FileChooserCallbackInfo
  209089. {
  209090. String initialPath;
  209091. String returnedString; // need this to get non-existent pathnames from the directory chooser
  209092. ScopedPointer<Component> customComponent;
  209093. };
  209094. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  209095. {
  209096. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  209097. if (msg == BFFM_INITIALIZED)
  209098. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) info->initialPath.toUTF16().getAddress());
  209099. else if (msg == BFFM_VALIDATEFAILEDW)
  209100. info->returnedString = (LPCWSTR) lParam;
  209101. else if (msg == BFFM_VALIDATEFAILEDA)
  209102. info->returnedString = (const char*) lParam;
  209103. return 0;
  209104. }
  209105. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  209106. {
  209107. if (uiMsg == WM_INITDIALOG)
  209108. {
  209109. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  209110. HWND dialogH = GetParent (hdlg);
  209111. jassert (dialogH != 0);
  209112. if (dialogH == 0)
  209113. dialogH = hdlg;
  209114. RECT r, cr;
  209115. GetWindowRect (dialogH, &r);
  209116. GetClientRect (dialogH, &cr);
  209117. SetWindowPos (dialogH, 0,
  209118. r.left, r.top,
  209119. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  209120. jmax (150, (int) (r.bottom - r.top)),
  209121. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  209122. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  209123. customComp->addToDesktop (0, dialogH);
  209124. }
  209125. else if (uiMsg == WM_NOTIFY)
  209126. {
  209127. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  209128. if (ofn->hdr.code == CDN_SELCHANGE)
  209129. {
  209130. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  209131. FilePreviewComponent* comp = dynamic_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  209132. if (comp != 0)
  209133. {
  209134. WCHAR path [MAX_PATH * 2];
  209135. zerostruct (path);
  209136. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  209137. comp->selectedFileChanged (File (path));
  209138. }
  209139. }
  209140. }
  209141. return 0;
  209142. }
  209143. class CustomComponentHolder : public Component
  209144. {
  209145. public:
  209146. CustomComponentHolder (Component* customComp)
  209147. {
  209148. setVisible (true);
  209149. setOpaque (true);
  209150. addAndMakeVisible (customComp);
  209151. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  209152. }
  209153. void paint (Graphics& g)
  209154. {
  209155. g.fillAll (Colours::lightgrey);
  209156. }
  209157. void resized()
  209158. {
  209159. Component* const c = getChildComponent(0);
  209160. if (c != 0)
  209161. c->setBounds (getLocalBounds());
  209162. }
  209163. private:
  209164. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  209165. };
  209166. }
  209167. void FileChooser::showPlatformDialog (Array<File>& results, const String& title_, const File& currentFileOrDirectory,
  209168. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  209169. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  209170. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  209171. {
  209172. using namespace FileChooserHelpers;
  209173. const String title (title_);
  209174. HeapBlock<WCHAR> files;
  209175. const int charsAvailableForResult = 32768;
  209176. files.calloc (charsAvailableForResult + 1);
  209177. int filenameOffset = 0;
  209178. FileChooserCallbackInfo info;
  209179. // use a modal window as the parent for this dialog box
  209180. // to block input from other app windows
  209181. Component parentWindow (String::empty);
  209182. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  209183. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  209184. mainMon.getY() + mainMon.getHeight() / 4,
  209185. 0, 0);
  209186. parentWindow.setOpaque (true);
  209187. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  209188. parentWindow.addToDesktop (0);
  209189. if (extraInfoComponent == 0)
  209190. parentWindow.enterModalState();
  209191. if (currentFileOrDirectory.isDirectory())
  209192. {
  209193. info.initialPath = currentFileOrDirectory.getFullPathName();
  209194. }
  209195. else
  209196. {
  209197. currentFileOrDirectory.getFileName().copyToUTF16 (files, charsAvailableForResult * sizeof (WCHAR));
  209198. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  209199. }
  209200. if (selectsDirectory)
  209201. {
  209202. BROWSEINFO bi;
  209203. zerostruct (bi);
  209204. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209205. bi.pszDisplayName = files;
  209206. bi.lpszTitle = title.toUTF16();
  209207. bi.lParam = (LPARAM) &info;
  209208. bi.lpfn = browseCallbackProc;
  209209. #ifdef BIF_USENEWUI
  209210. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  209211. #else
  209212. bi.ulFlags = 0x50;
  209213. #endif
  209214. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  209215. if (! SHGetPathFromIDListW (list, files))
  209216. {
  209217. files[0] = 0;
  209218. info.returnedString = String::empty;
  209219. }
  209220. LPMALLOC al;
  209221. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  209222. al->Free (list);
  209223. if (info.returnedString.isNotEmpty())
  209224. {
  209225. results.add (File (String (files)).getSiblingFile (info.returnedString));
  209226. return;
  209227. }
  209228. }
  209229. else
  209230. {
  209231. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209232. if (warnAboutOverwritingExistingFiles)
  209233. flags |= OFN_OVERWRITEPROMPT;
  209234. if (selectMultipleFiles)
  209235. flags |= OFN_ALLOWMULTISELECT;
  209236. if (extraInfoComponent != 0)
  209237. {
  209238. flags |= OFN_ENABLEHOOK;
  209239. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  209240. info.customComponent->enterModalState();
  209241. }
  209242. const int filterSpaceNumChars = 2048;
  209243. HeapBlock<WCHAR> filters;
  209244. filters.calloc (filterSpaceNumChars);
  209245. const int bytesWritten = filter.copyToUTF16 (filters.getData(), filterSpaceNumChars * sizeof (WCHAR));
  209246. filter.copyToUTF16 (filters + (bytesWritten / sizeof (WCHAR)) + 1,
  209247. (filterSpaceNumChars - 1) * sizeof (WCHAR) - bytesWritten);
  209248. OPENFILENAMEW of;
  209249. zerostruct (of);
  209250. String localPath (info.initialPath);
  209251. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209252. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209253. #else
  209254. of.lStructSize = sizeof (of);
  209255. #endif
  209256. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209257. of.lpstrFilter = filters.getData();
  209258. of.nFilterIndex = 1;
  209259. of.lpstrFile = files;
  209260. of.nMaxFile = charsAvailableForResult;
  209261. of.lpstrInitialDir = localPath.toUTF16();
  209262. of.lpstrTitle = title.toUTF16();
  209263. of.Flags = flags;
  209264. of.lCustData = (LPARAM) &info;
  209265. if (extraInfoComponent != 0)
  209266. of.lpfnHook = &openCallback;
  209267. if (! (isSaveDialogue ? GetSaveFileName (&of)
  209268. : GetOpenFileName (&of)))
  209269. return;
  209270. filenameOffset = of.nFileOffset;
  209271. }
  209272. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  209273. {
  209274. const WCHAR* filename = files + filenameOffset;
  209275. while (*filename != 0)
  209276. {
  209277. results.add (File (String (files) + "\\" + String (filename)));
  209278. filename += wcslen (filename) + 1;
  209279. }
  209280. }
  209281. else if (files[0] != 0)
  209282. {
  209283. results.add (File (String (files)));
  209284. }
  209285. }
  209286. #endif
  209287. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209288. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209289. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209290. // compiled on its own).
  209291. #if JUCE_INCLUDED_FILE
  209292. void SystemClipboard::copyTextToClipboard (const String& text)
  209293. {
  209294. if (OpenClipboard (0) != 0)
  209295. {
  209296. if (EmptyClipboard() != 0)
  209297. {
  209298. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  209299. if (bytesNeeded > 0)
  209300. {
  209301. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR));
  209302. if (bufH != 0)
  209303. {
  209304. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209305. text.copyToUTF16 (data, bytesNeeded);
  209306. GlobalUnlock (bufH);
  209307. SetClipboardData (CF_UNICODETEXT, bufH);
  209308. }
  209309. }
  209310. }
  209311. CloseClipboard();
  209312. }
  209313. }
  209314. const String SystemClipboard::getTextFromClipboard()
  209315. {
  209316. String result;
  209317. if (OpenClipboard (0) != 0)
  209318. {
  209319. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209320. if (bufH != 0)
  209321. {
  209322. const WCHAR* const data = (const WCHAR*) GlobalLock (bufH);
  209323. if (data != 0)
  209324. {
  209325. result = String (data, (int) (GlobalSize (bufH) / sizeof (WCHAR)));
  209326. GlobalUnlock (bufH);
  209327. }
  209328. }
  209329. CloseClipboard();
  209330. }
  209331. return result;
  209332. }
  209333. #endif
  209334. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209335. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209336. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209337. // compiled on its own).
  209338. #if JUCE_INCLUDED_FILE
  209339. namespace ActiveXHelpers
  209340. {
  209341. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209342. {
  209343. public:
  209344. JuceIStorage() {}
  209345. ~JuceIStorage() {}
  209346. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209347. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209348. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209349. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209350. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209351. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209352. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209353. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209354. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209355. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209356. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209357. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209358. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209359. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209360. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209361. };
  209362. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209363. {
  209364. HWND window;
  209365. public:
  209366. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209367. ~JuceOleInPlaceFrame() {}
  209368. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209369. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209370. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209371. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209372. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209373. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209374. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209375. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209376. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209377. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209378. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209379. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209380. };
  209381. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209382. {
  209383. HWND window;
  209384. JuceOleInPlaceFrame* frame;
  209385. public:
  209386. JuceIOleInPlaceSite (HWND window_)
  209387. : window (window_),
  209388. frame (new JuceOleInPlaceFrame (window))
  209389. {}
  209390. ~JuceIOleInPlaceSite()
  209391. {
  209392. frame->Release();
  209393. }
  209394. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209395. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209396. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209397. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209398. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209399. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209400. {
  209401. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209402. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209403. */
  209404. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209405. if (lplpDoc != 0) *lplpDoc = 0;
  209406. lpFrameInfo->fMDIApp = FALSE;
  209407. lpFrameInfo->hwndFrame = window;
  209408. lpFrameInfo->haccel = 0;
  209409. lpFrameInfo->cAccelEntries = 0;
  209410. return S_OK;
  209411. }
  209412. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209413. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209414. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209415. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209416. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209417. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209418. };
  209419. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209420. {
  209421. JuceIOleInPlaceSite* inplaceSite;
  209422. public:
  209423. JuceIOleClientSite (HWND window)
  209424. : inplaceSite (new JuceIOleInPlaceSite (window))
  209425. {}
  209426. ~JuceIOleClientSite()
  209427. {
  209428. inplaceSite->Release();
  209429. }
  209430. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209431. {
  209432. if (type == IID_IOleInPlaceSite)
  209433. {
  209434. inplaceSite->AddRef();
  209435. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209436. return S_OK;
  209437. }
  209438. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209439. }
  209440. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209441. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209442. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209443. HRESULT __stdcall ShowObject() { return S_OK; }
  209444. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209445. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209446. };
  209447. static Array<ActiveXControlComponent*> activeXComps;
  209448. static HWND getHWND (const ActiveXControlComponent* const component)
  209449. {
  209450. HWND hwnd = 0;
  209451. const IID iid = IID_IOleWindow;
  209452. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209453. if (window != 0)
  209454. {
  209455. window->GetWindow (&hwnd);
  209456. window->Release();
  209457. }
  209458. return hwnd;
  209459. }
  209460. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209461. {
  209462. RECT activeXRect, peerRect;
  209463. GetWindowRect (hwnd, &activeXRect);
  209464. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209465. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209466. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209467. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209468. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209469. switch (message)
  209470. {
  209471. case WM_MOUSEMOVE:
  209472. case WM_LBUTTONDOWN:
  209473. case WM_MBUTTONDOWN:
  209474. case WM_RBUTTONDOWN:
  209475. case WM_LBUTTONUP:
  209476. case WM_MBUTTONUP:
  209477. case WM_RBUTTONUP:
  209478. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209479. break;
  209480. default:
  209481. break;
  209482. }
  209483. }
  209484. }
  209485. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209486. {
  209487. public:
  209488. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209489. : ComponentMovementWatcher (&owner_),
  209490. owner (owner_),
  209491. controlHWND (0),
  209492. storage (new ActiveXHelpers::JuceIStorage()),
  209493. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209494. control (0)
  209495. {
  209496. }
  209497. ~Pimpl()
  209498. {
  209499. if (control != 0)
  209500. {
  209501. control->Close (OLECLOSE_NOSAVE);
  209502. control->Release();
  209503. }
  209504. clientSite->Release();
  209505. storage->Release();
  209506. }
  209507. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209508. {
  209509. Component* const topComp = owner.getTopLevelComponent();
  209510. if (topComp->getPeer() != 0)
  209511. {
  209512. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  209513. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209514. }
  209515. }
  209516. void componentPeerChanged()
  209517. {
  209518. componentMovedOrResized (true, true);
  209519. }
  209520. void componentVisibilityChanged()
  209521. {
  209522. owner.setControlVisible (owner.isShowing());
  209523. componentPeerChanged();
  209524. }
  209525. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209526. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209527. {
  209528. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209529. {
  209530. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209531. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209532. {
  209533. switch (message)
  209534. {
  209535. case WM_MOUSEMOVE:
  209536. case WM_LBUTTONDOWN:
  209537. case WM_MBUTTONDOWN:
  209538. case WM_RBUTTONDOWN:
  209539. case WM_LBUTTONUP:
  209540. case WM_MBUTTONUP:
  209541. case WM_RBUTTONUP:
  209542. case WM_LBUTTONDBLCLK:
  209543. case WM_MBUTTONDBLCLK:
  209544. case WM_RBUTTONDBLCLK:
  209545. if (ax->isShowing())
  209546. {
  209547. ComponentPeer* const peer = ax->getPeer();
  209548. if (peer != 0)
  209549. {
  209550. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209551. if (! ax->areMouseEventsAllowed())
  209552. return 0;
  209553. }
  209554. }
  209555. break;
  209556. default:
  209557. break;
  209558. }
  209559. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209560. }
  209561. }
  209562. return DefWindowProc (hwnd, message, wParam, lParam);
  209563. }
  209564. private:
  209565. ActiveXControlComponent& owner;
  209566. public:
  209567. HWND controlHWND;
  209568. IStorage* storage;
  209569. IOleClientSite* clientSite;
  209570. IOleObject* control;
  209571. };
  209572. ActiveXControlComponent::ActiveXControlComponent()
  209573. : originalWndProc (0),
  209574. mouseEventsAllowed (true)
  209575. {
  209576. ActiveXHelpers::activeXComps.add (this);
  209577. }
  209578. ActiveXControlComponent::~ActiveXControlComponent()
  209579. {
  209580. deleteControl();
  209581. ActiveXHelpers::activeXComps.removeValue (this);
  209582. }
  209583. void ActiveXControlComponent::paint (Graphics& g)
  209584. {
  209585. if (control == 0)
  209586. g.fillAll (Colours::lightgrey);
  209587. }
  209588. bool ActiveXControlComponent::createControl (const void* controlIID)
  209589. {
  209590. deleteControl();
  209591. ComponentPeer* const peer = getPeer();
  209592. // the component must have already been added to a real window when you call this!
  209593. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209594. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209595. {
  209596. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209597. HWND hwnd = (HWND) peer->getNativeHandle();
  209598. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209599. HRESULT hr;
  209600. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209601. newControl->clientSite, newControl->storage,
  209602. (void**) &(newControl->control))) == S_OK)
  209603. {
  209604. newControl->control->SetHostNames (L"Juce", 0);
  209605. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209606. {
  209607. RECT rect;
  209608. rect.left = pos.getX();
  209609. rect.top = pos.getY();
  209610. rect.right = pos.getX() + getWidth();
  209611. rect.bottom = pos.getY() + getHeight();
  209612. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209613. {
  209614. control = newControl;
  209615. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209616. control->controlHWND = ActiveXHelpers::getHWND (this);
  209617. if (control->controlHWND != 0)
  209618. {
  209619. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209620. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209621. }
  209622. return true;
  209623. }
  209624. }
  209625. }
  209626. }
  209627. return false;
  209628. }
  209629. void ActiveXControlComponent::deleteControl()
  209630. {
  209631. control = 0;
  209632. originalWndProc = 0;
  209633. }
  209634. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209635. {
  209636. void* result = 0;
  209637. if (control != 0 && control->control != 0
  209638. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209639. return result;
  209640. return 0;
  209641. }
  209642. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209643. {
  209644. if (control->controlHWND != 0)
  209645. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209646. }
  209647. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209648. {
  209649. if (control->controlHWND != 0)
  209650. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209651. }
  209652. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209653. {
  209654. mouseEventsAllowed = eventsCanReachControl;
  209655. }
  209656. #endif
  209657. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209658. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209659. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209660. // compiled on its own).
  209661. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209662. using namespace QTOLibrary;
  209663. using namespace QTOControlLib;
  209664. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209665. static bool isQTAvailable = false;
  209666. class QuickTimeMovieComponent::Pimpl
  209667. {
  209668. public:
  209669. Pimpl() : dataHandle (0)
  209670. {
  209671. }
  209672. ~Pimpl()
  209673. {
  209674. clearHandle();
  209675. }
  209676. void clearHandle()
  209677. {
  209678. if (dataHandle != 0)
  209679. {
  209680. DisposeHandle (dataHandle);
  209681. dataHandle = 0;
  209682. }
  209683. }
  209684. IQTControlPtr qtControl;
  209685. IQTMoviePtr qtMovie;
  209686. Handle dataHandle;
  209687. };
  209688. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209689. : movieLoaded (false),
  209690. controllerVisible (true)
  209691. {
  209692. pimpl = new Pimpl();
  209693. setMouseEventsAllowed (false);
  209694. }
  209695. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209696. {
  209697. closeMovie();
  209698. pimpl->qtControl = 0;
  209699. deleteControl();
  209700. pimpl = 0;
  209701. }
  209702. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209703. {
  209704. if (! isQTAvailable)
  209705. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209706. return isQTAvailable;
  209707. }
  209708. void QuickTimeMovieComponent::createControlIfNeeded()
  209709. {
  209710. if (isShowing() && ! isControlCreated())
  209711. {
  209712. const IID qtIID = __uuidof (QTControl);
  209713. if (createControl (&qtIID))
  209714. {
  209715. const IID qtInterfaceIID = __uuidof (IQTControl);
  209716. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209717. if (pimpl->qtControl != 0)
  209718. {
  209719. pimpl->qtControl->Release(); // it has one ref too many at this point
  209720. pimpl->qtControl->QuickTimeInitialize();
  209721. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209722. if (movieFile != File::nonexistent)
  209723. loadMovie (movieFile, controllerVisible);
  209724. }
  209725. }
  209726. }
  209727. }
  209728. bool QuickTimeMovieComponent::isControlCreated() const
  209729. {
  209730. return isControlOpen();
  209731. }
  209732. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209733. const bool isControllerVisible)
  209734. {
  209735. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209736. movieFile = File::nonexistent;
  209737. movieLoaded = false;
  209738. pimpl->qtMovie = 0;
  209739. controllerVisible = isControllerVisible;
  209740. createControlIfNeeded();
  209741. if (isControlCreated())
  209742. {
  209743. if (pimpl->qtControl != 0)
  209744. {
  209745. pimpl->qtControl->Put_MovieHandle (0);
  209746. pimpl->clearHandle();
  209747. Movie movie;
  209748. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209749. {
  209750. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209751. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209752. if (pimpl->qtMovie != 0)
  209753. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209754. : qtMovieControllerTypeNone);
  209755. }
  209756. if (movie == 0)
  209757. pimpl->clearHandle();
  209758. }
  209759. movieLoaded = (pimpl->qtMovie != 0);
  209760. }
  209761. else
  209762. {
  209763. // You're trying to open a movie when the control hasn't yet been created, probably because
  209764. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209765. jassertfalse;
  209766. }
  209767. return movieLoaded;
  209768. }
  209769. void QuickTimeMovieComponent::closeMovie()
  209770. {
  209771. stop();
  209772. movieFile = File::nonexistent;
  209773. movieLoaded = false;
  209774. pimpl->qtMovie = 0;
  209775. if (pimpl->qtControl != 0)
  209776. pimpl->qtControl->Put_MovieHandle (0);
  209777. pimpl->clearHandle();
  209778. }
  209779. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209780. {
  209781. return movieFile;
  209782. }
  209783. bool QuickTimeMovieComponent::isMovieOpen() const
  209784. {
  209785. return movieLoaded;
  209786. }
  209787. double QuickTimeMovieComponent::getMovieDuration() const
  209788. {
  209789. if (pimpl->qtMovie != 0)
  209790. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209791. return 0.0;
  209792. }
  209793. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209794. {
  209795. if (pimpl->qtMovie != 0)
  209796. {
  209797. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209798. width = r.right - r.left;
  209799. height = r.bottom - r.top;
  209800. }
  209801. else
  209802. {
  209803. width = height = 0;
  209804. }
  209805. }
  209806. void QuickTimeMovieComponent::play()
  209807. {
  209808. if (pimpl->qtMovie != 0)
  209809. pimpl->qtMovie->Play();
  209810. }
  209811. void QuickTimeMovieComponent::stop()
  209812. {
  209813. if (pimpl->qtMovie != 0)
  209814. pimpl->qtMovie->Stop();
  209815. }
  209816. bool QuickTimeMovieComponent::isPlaying() const
  209817. {
  209818. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209819. }
  209820. void QuickTimeMovieComponent::setPosition (const double seconds)
  209821. {
  209822. if (pimpl->qtMovie != 0)
  209823. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209824. }
  209825. double QuickTimeMovieComponent::getPosition() const
  209826. {
  209827. if (pimpl->qtMovie != 0)
  209828. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209829. return 0.0;
  209830. }
  209831. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209832. {
  209833. if (pimpl->qtMovie != 0)
  209834. pimpl->qtMovie->PutRate (newSpeed);
  209835. }
  209836. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209837. {
  209838. if (pimpl->qtMovie != 0)
  209839. {
  209840. pimpl->qtMovie->PutAudioVolume (newVolume);
  209841. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209842. }
  209843. }
  209844. float QuickTimeMovieComponent::getMovieVolume() const
  209845. {
  209846. if (pimpl->qtMovie != 0)
  209847. return pimpl->qtMovie->GetAudioVolume();
  209848. return 0.0f;
  209849. }
  209850. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209851. {
  209852. if (pimpl->qtMovie != 0)
  209853. pimpl->qtMovie->PutLoop (shouldLoop);
  209854. }
  209855. bool QuickTimeMovieComponent::isLooping() const
  209856. {
  209857. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209858. }
  209859. bool QuickTimeMovieComponent::isControllerVisible() const
  209860. {
  209861. return controllerVisible;
  209862. }
  209863. void QuickTimeMovieComponent::parentHierarchyChanged()
  209864. {
  209865. createControlIfNeeded();
  209866. QTCompBaseClass::parentHierarchyChanged();
  209867. }
  209868. void QuickTimeMovieComponent::visibilityChanged()
  209869. {
  209870. createControlIfNeeded();
  209871. QTCompBaseClass::visibilityChanged();
  209872. }
  209873. void QuickTimeMovieComponent::paint (Graphics& g)
  209874. {
  209875. if (! isControlCreated())
  209876. g.fillAll (Colours::black);
  209877. }
  209878. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209879. {
  209880. Handle dataRef = 0;
  209881. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209882. if (err == noErr)
  209883. {
  209884. Str255 suffix;
  209885. strncpy ((char*) suffix, fileName, 128);
  209886. StringPtr name = suffix;
  209887. err = PtrAndHand (name, dataRef, name[0] + 1);
  209888. if (err == noErr)
  209889. {
  209890. long atoms[3];
  209891. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209892. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209893. atoms[2] = EndianU32_NtoB (MovieFileType);
  209894. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209895. if (err == noErr)
  209896. return dataRef;
  209897. }
  209898. DisposeHandle (dataRef);
  209899. }
  209900. return 0;
  209901. }
  209902. static CFStringRef juceStringToCFString (const String& s)
  209903. {
  209904. return CFStringCreateWithCString (kCFAllocatorDefault, s.toUTF8(), kCFStringEncodingUTF8);
  209905. }
  209906. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209907. {
  209908. Boolean trueBool = true;
  209909. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209910. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209911. props[prop].propValueSize = sizeof (trueBool);
  209912. props[prop].propValueAddress = &trueBool;
  209913. ++prop;
  209914. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209915. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209916. props[prop].propValueSize = sizeof (trueBool);
  209917. props[prop].propValueAddress = &trueBool;
  209918. ++prop;
  209919. Boolean isActive = true;
  209920. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209921. props[prop].propID = kQTNewMoviePropertyID_Active;
  209922. props[prop].propValueSize = sizeof (isActive);
  209923. props[prop].propValueAddress = &isActive;
  209924. ++prop;
  209925. MacSetPort (0);
  209926. jassert (prop <= 5);
  209927. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209928. return err == noErr;
  209929. }
  209930. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209931. {
  209932. if (input == 0)
  209933. return false;
  209934. dataHandle = 0;
  209935. bool ok = false;
  209936. QTNewMoviePropertyElement props[5];
  209937. zeromem (props, sizeof (props));
  209938. int prop = 0;
  209939. DataReferenceRecord dr;
  209940. props[prop].propClass = kQTPropertyClass_DataLocation;
  209941. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209942. props[prop].propValueSize = sizeof (dr);
  209943. props[prop].propValueAddress = &dr;
  209944. ++prop;
  209945. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209946. if (fin != 0)
  209947. {
  209948. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209949. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209950. &dr.dataRef, &dr.dataRefType);
  209951. ok = openMovie (props, prop, movie);
  209952. DisposeHandle (dr.dataRef);
  209953. CFRelease (filePath);
  209954. }
  209955. else
  209956. {
  209957. // sanity-check because this currently needs to load the whole stream into memory..
  209958. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209959. dataHandle = NewHandle ((Size) input->getTotalLength());
  209960. HLock (dataHandle);
  209961. // read the entire stream into memory - this is a pain, but can't get it to work
  209962. // properly using a custom callback to supply the data.
  209963. input->read (*dataHandle, (int) input->getTotalLength());
  209964. HUnlock (dataHandle);
  209965. // different types to get QT to try. (We should really be a bit smarter here by
  209966. // working out in advance which one the stream contains, rather than just trying
  209967. // each one)
  209968. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209969. "\04.avi", "\04.m4a" };
  209970. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209971. {
  209972. /* // this fails for some bizarre reason - it can be bodged to work with
  209973. // movies, but can't seem to do it for other file types..
  209974. QTNewMovieUserProcRecord procInfo;
  209975. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209976. procInfo.getMovieUserProcRefcon = this;
  209977. procInfo.defaultDataRef.dataRef = dataRef;
  209978. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209979. props[prop].propClass = kQTPropertyClass_DataLocation;
  209980. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209981. props[prop].propValueSize = sizeof (procInfo);
  209982. props[prop].propValueAddress = (void*) &procInfo;
  209983. ++prop; */
  209984. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209985. dr.dataRefType = HandleDataHandlerSubType;
  209986. ok = openMovie (props, prop, movie);
  209987. DisposeHandle (dr.dataRef);
  209988. }
  209989. }
  209990. return ok;
  209991. }
  209992. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209993. const bool isControllerVisible)
  209994. {
  209995. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209996. movieFile = movieFile_;
  209997. return ok;
  209998. }
  209999. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  210000. const bool isControllerVisible)
  210001. {
  210002. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  210003. }
  210004. void QuickTimeMovieComponent::goToStart()
  210005. {
  210006. setPosition (0.0);
  210007. }
  210008. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  210009. const RectanglePlacement& placement)
  210010. {
  210011. int normalWidth, normalHeight;
  210012. getMovieNormalSize (normalWidth, normalHeight);
  210013. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  210014. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  210015. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  210016. else
  210017. setBounds (spaceToFitWithin);
  210018. }
  210019. #endif
  210020. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  210021. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210022. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210023. // compiled on its own).
  210024. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  210025. class WebBrowserComponentInternal : public ActiveXControlComponent
  210026. {
  210027. public:
  210028. WebBrowserComponentInternal()
  210029. : browser (0),
  210030. connectionPoint (0),
  210031. adviseCookie (0)
  210032. {
  210033. }
  210034. ~WebBrowserComponentInternal()
  210035. {
  210036. if (connectionPoint != 0)
  210037. connectionPoint->Unadvise (adviseCookie);
  210038. if (browser != 0)
  210039. browser->Release();
  210040. }
  210041. void createBrowser()
  210042. {
  210043. createControl (&CLSID_WebBrowser);
  210044. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  210045. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  210046. if (connectionPointContainer != 0)
  210047. {
  210048. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  210049. &connectionPoint);
  210050. if (connectionPoint != 0)
  210051. {
  210052. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  210053. jassert (owner != 0);
  210054. EventHandler* handler = new EventHandler (*owner);
  210055. connectionPoint->Advise (handler, &adviseCookie);
  210056. handler->Release();
  210057. }
  210058. }
  210059. }
  210060. void goToURL (const String& url,
  210061. const StringArray* headers,
  210062. const MemoryBlock* postData)
  210063. {
  210064. if (browser != 0)
  210065. {
  210066. LPSAFEARRAY sa = 0;
  210067. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  210068. VariantInit (&flags);
  210069. VariantInit (&frame);
  210070. VariantInit (&postDataVar);
  210071. VariantInit (&headersVar);
  210072. if (headers != 0)
  210073. {
  210074. V_VT (&headersVar) = VT_BSTR;
  210075. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n").toUTF16().getAddress());
  210076. }
  210077. if (postData != 0 && postData->getSize() > 0)
  210078. {
  210079. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  210080. if (sa != 0)
  210081. {
  210082. void* data = 0;
  210083. SafeArrayAccessData (sa, &data);
  210084. jassert (data != 0);
  210085. if (data != 0)
  210086. {
  210087. postData->copyTo (data, 0, postData->getSize());
  210088. SafeArrayUnaccessData (sa);
  210089. VARIANT postDataVar2;
  210090. VariantInit (&postDataVar2);
  210091. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  210092. V_ARRAY (&postDataVar2) = sa;
  210093. postDataVar = postDataVar2;
  210094. }
  210095. }
  210096. }
  210097. browser->Navigate ((BSTR) (const OLECHAR*) url.toUTF16().getAddress(),
  210098. &flags, &frame,
  210099. &postDataVar, &headersVar);
  210100. if (sa != 0)
  210101. SafeArrayDestroy (sa);
  210102. VariantClear (&flags);
  210103. VariantClear (&frame);
  210104. VariantClear (&postDataVar);
  210105. VariantClear (&headersVar);
  210106. }
  210107. }
  210108. IWebBrowser2* browser;
  210109. private:
  210110. IConnectionPoint* connectionPoint;
  210111. DWORD adviseCookie;
  210112. class EventHandler : public ComBaseClassHelper <IDispatch>,
  210113. public ComponentMovementWatcher
  210114. {
  210115. public:
  210116. EventHandler (WebBrowserComponent& owner_)
  210117. : ComponentMovementWatcher (&owner_),
  210118. owner (owner_)
  210119. {
  210120. }
  210121. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  210122. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  210123. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  210124. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  210125. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  210126. {
  210127. if (dispIdMember == DISPID_BEFORENAVIGATE2)
  210128. {
  210129. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  210130. String url;
  210131. if ((vurl->vt & VT_BYREF) != 0)
  210132. url = *vurl->pbstrVal;
  210133. else
  210134. url = vurl->bstrVal;
  210135. *pDispParams->rgvarg->pboolVal
  210136. = owner.pageAboutToLoad (url) ? VARIANT_FALSE
  210137. : VARIANT_TRUE;
  210138. return S_OK;
  210139. }
  210140. return E_NOTIMPL;
  210141. }
  210142. void componentMovedOrResized (bool, bool ) {}
  210143. void componentPeerChanged() {}
  210144. void componentVisibilityChanged() { owner.visibilityChanged(); }
  210145. private:
  210146. WebBrowserComponent& owner;
  210147. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  210148. };
  210149. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  210150. };
  210151. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  210152. : browser (0),
  210153. blankPageShown (false),
  210154. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  210155. {
  210156. setOpaque (true);
  210157. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  210158. }
  210159. WebBrowserComponent::~WebBrowserComponent()
  210160. {
  210161. delete browser;
  210162. }
  210163. void WebBrowserComponent::goToURL (const String& url,
  210164. const StringArray* headers,
  210165. const MemoryBlock* postData)
  210166. {
  210167. lastURL = url;
  210168. lastHeaders.clear();
  210169. if (headers != 0)
  210170. lastHeaders = *headers;
  210171. lastPostData.setSize (0);
  210172. if (postData != 0)
  210173. lastPostData = *postData;
  210174. blankPageShown = false;
  210175. browser->goToURL (url, headers, postData);
  210176. }
  210177. void WebBrowserComponent::stop()
  210178. {
  210179. if (browser->browser != 0)
  210180. browser->browser->Stop();
  210181. }
  210182. void WebBrowserComponent::goBack()
  210183. {
  210184. lastURL = String::empty;
  210185. blankPageShown = false;
  210186. if (browser->browser != 0)
  210187. browser->browser->GoBack();
  210188. }
  210189. void WebBrowserComponent::goForward()
  210190. {
  210191. lastURL = String::empty;
  210192. if (browser->browser != 0)
  210193. browser->browser->GoForward();
  210194. }
  210195. void WebBrowserComponent::refresh()
  210196. {
  210197. if (browser->browser != 0)
  210198. browser->browser->Refresh();
  210199. }
  210200. void WebBrowserComponent::paint (Graphics& g)
  210201. {
  210202. if (browser->browser == 0)
  210203. g.fillAll (Colours::white);
  210204. }
  210205. void WebBrowserComponent::checkWindowAssociation()
  210206. {
  210207. if (isShowing())
  210208. {
  210209. if (browser->browser == 0 && getPeer() != 0)
  210210. {
  210211. browser->createBrowser();
  210212. reloadLastURL();
  210213. }
  210214. else
  210215. {
  210216. if (blankPageShown)
  210217. goBack();
  210218. }
  210219. }
  210220. else
  210221. {
  210222. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  210223. {
  210224. // when the component becomes invisible, some stuff like flash
  210225. // carries on playing audio, so we need to force it onto a blank
  210226. // page to avoid this..
  210227. blankPageShown = true;
  210228. browser->goToURL ("about:blank", 0, 0);
  210229. }
  210230. }
  210231. }
  210232. void WebBrowserComponent::reloadLastURL()
  210233. {
  210234. if (lastURL.isNotEmpty())
  210235. {
  210236. goToURL (lastURL, &lastHeaders, &lastPostData);
  210237. lastURL = String::empty;
  210238. }
  210239. }
  210240. void WebBrowserComponent::parentHierarchyChanged()
  210241. {
  210242. checkWindowAssociation();
  210243. }
  210244. void WebBrowserComponent::resized()
  210245. {
  210246. browser->setSize (getWidth(), getHeight());
  210247. }
  210248. void WebBrowserComponent::visibilityChanged()
  210249. {
  210250. checkWindowAssociation();
  210251. }
  210252. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210253. {
  210254. return true;
  210255. }
  210256. #endif
  210257. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210258. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210259. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210260. // compiled on its own).
  210261. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210262. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210263. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210264. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210265. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210266. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210267. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210268. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210269. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210270. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210271. #define WGL_ACCELERATION_ARB 0x2003
  210272. #define WGL_SWAP_METHOD_ARB 0x2007
  210273. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210274. #define WGL_PIXEL_TYPE_ARB 0x2013
  210275. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210276. #define WGL_COLOR_BITS_ARB 0x2014
  210277. #define WGL_RED_BITS_ARB 0x2015
  210278. #define WGL_GREEN_BITS_ARB 0x2017
  210279. #define WGL_BLUE_BITS_ARB 0x2019
  210280. #define WGL_ALPHA_BITS_ARB 0x201B
  210281. #define WGL_DEPTH_BITS_ARB 0x2022
  210282. #define WGL_STENCIL_BITS_ARB 0x2023
  210283. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210284. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210285. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210286. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210287. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210288. #define WGL_STEREO_ARB 0x2012
  210289. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210290. #define WGL_SAMPLES_ARB 0x2042
  210291. #define WGL_TYPE_RGBA_ARB 0x202B
  210292. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210293. {
  210294. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210295. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210296. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210297. else
  210298. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210299. }
  210300. class WindowedGLContext : public OpenGLContext
  210301. {
  210302. public:
  210303. WindowedGLContext (Component* const component_,
  210304. HGLRC contextToShareWith,
  210305. const OpenGLPixelFormat& pixelFormat)
  210306. : renderContext (0),
  210307. component (component_),
  210308. dc (0)
  210309. {
  210310. jassert (component != 0);
  210311. createNativeWindow();
  210312. // Use a default pixel format that should be supported everywhere
  210313. PIXELFORMATDESCRIPTOR pfd;
  210314. zerostruct (pfd);
  210315. pfd.nSize = sizeof (pfd);
  210316. pfd.nVersion = 1;
  210317. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210318. pfd.iPixelType = PFD_TYPE_RGBA;
  210319. pfd.cColorBits = 24;
  210320. pfd.cDepthBits = 16;
  210321. const int format = ChoosePixelFormat (dc, &pfd);
  210322. if (format != 0)
  210323. SetPixelFormat (dc, format, &pfd);
  210324. renderContext = wglCreateContext (dc);
  210325. makeActive();
  210326. setPixelFormat (pixelFormat);
  210327. if (contextToShareWith != 0 && renderContext != 0)
  210328. wglShareLists (contextToShareWith, renderContext);
  210329. }
  210330. ~WindowedGLContext()
  210331. {
  210332. deleteContext();
  210333. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210334. nativeWindow = 0;
  210335. }
  210336. void deleteContext()
  210337. {
  210338. makeInactive();
  210339. if (renderContext != 0)
  210340. {
  210341. wglDeleteContext (renderContext);
  210342. renderContext = 0;
  210343. }
  210344. }
  210345. bool makeActive() const throw()
  210346. {
  210347. jassert (renderContext != 0);
  210348. return wglMakeCurrent (dc, renderContext) != 0;
  210349. }
  210350. bool makeInactive() const throw()
  210351. {
  210352. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210353. }
  210354. bool isActive() const throw()
  210355. {
  210356. return wglGetCurrentContext() == renderContext;
  210357. }
  210358. const OpenGLPixelFormat getPixelFormat() const
  210359. {
  210360. OpenGLPixelFormat pf;
  210361. makeActive();
  210362. StringArray availableExtensions;
  210363. getWglExtensions (dc, availableExtensions);
  210364. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210365. return pf;
  210366. }
  210367. void* getRawContext() const throw()
  210368. {
  210369. return renderContext;
  210370. }
  210371. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210372. {
  210373. makeActive();
  210374. PIXELFORMATDESCRIPTOR pfd;
  210375. zerostruct (pfd);
  210376. pfd.nSize = sizeof (pfd);
  210377. pfd.nVersion = 1;
  210378. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210379. pfd.iPixelType = PFD_TYPE_RGBA;
  210380. pfd.iLayerType = PFD_MAIN_PLANE;
  210381. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210382. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210383. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210384. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210385. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210386. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210387. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210388. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210389. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210390. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210391. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210392. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210393. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210394. int format = 0;
  210395. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210396. StringArray availableExtensions;
  210397. getWglExtensions (dc, availableExtensions);
  210398. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210399. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210400. {
  210401. int attributes[64];
  210402. int n = 0;
  210403. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210404. attributes[n++] = GL_TRUE;
  210405. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210406. attributes[n++] = GL_TRUE;
  210407. attributes[n++] = WGL_ACCELERATION_ARB;
  210408. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210409. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210410. attributes[n++] = GL_TRUE;
  210411. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210412. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210413. attributes[n++] = WGL_COLOR_BITS_ARB;
  210414. attributes[n++] = pfd.cColorBits;
  210415. attributes[n++] = WGL_RED_BITS_ARB;
  210416. attributes[n++] = pixelFormat.redBits;
  210417. attributes[n++] = WGL_GREEN_BITS_ARB;
  210418. attributes[n++] = pixelFormat.greenBits;
  210419. attributes[n++] = WGL_BLUE_BITS_ARB;
  210420. attributes[n++] = pixelFormat.blueBits;
  210421. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210422. attributes[n++] = pixelFormat.alphaBits;
  210423. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210424. attributes[n++] = pixelFormat.depthBufferBits;
  210425. if (pixelFormat.stencilBufferBits > 0)
  210426. {
  210427. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210428. attributes[n++] = pixelFormat.stencilBufferBits;
  210429. }
  210430. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210431. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210432. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210433. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210434. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210435. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210436. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210437. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210438. if (availableExtensions.contains ("WGL_ARB_multisample")
  210439. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210440. {
  210441. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210442. attributes[n++] = 1;
  210443. attributes[n++] = WGL_SAMPLES_ARB;
  210444. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210445. }
  210446. attributes[n++] = 0;
  210447. UINT formatsCount;
  210448. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210449. (void) ok;
  210450. jassert (ok);
  210451. }
  210452. else
  210453. {
  210454. format = ChoosePixelFormat (dc, &pfd);
  210455. }
  210456. if (format != 0)
  210457. {
  210458. makeInactive();
  210459. // win32 can't change the pixel format of a window, so need to delete the
  210460. // old one and create a new one..
  210461. jassert (nativeWindow != 0);
  210462. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210463. nativeWindow = 0;
  210464. createNativeWindow();
  210465. if (SetPixelFormat (dc, format, &pfd))
  210466. {
  210467. wglDeleteContext (renderContext);
  210468. renderContext = wglCreateContext (dc);
  210469. jassert (renderContext != 0);
  210470. return renderContext != 0;
  210471. }
  210472. }
  210473. return false;
  210474. }
  210475. void updateWindowPosition (int x, int y, int w, int h, int)
  210476. {
  210477. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210478. x, y, w, h,
  210479. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210480. }
  210481. void repaint()
  210482. {
  210483. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210484. }
  210485. void swapBuffers()
  210486. {
  210487. SwapBuffers (dc);
  210488. }
  210489. bool setSwapInterval (int numFramesPerSwap)
  210490. {
  210491. makeActive();
  210492. StringArray availableExtensions;
  210493. getWglExtensions (dc, availableExtensions);
  210494. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210495. return availableExtensions.contains ("WGL_EXT_swap_control")
  210496. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210497. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210498. }
  210499. int getSwapInterval() const
  210500. {
  210501. makeActive();
  210502. StringArray availableExtensions;
  210503. getWglExtensions (dc, availableExtensions);
  210504. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210505. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210506. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210507. return wglGetSwapIntervalEXT();
  210508. return 0;
  210509. }
  210510. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210511. {
  210512. jassert (isActive());
  210513. StringArray availableExtensions;
  210514. getWglExtensions (dc, availableExtensions);
  210515. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210516. int numTypes = 0;
  210517. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210518. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210519. {
  210520. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210521. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210522. jassertfalse;
  210523. }
  210524. else
  210525. {
  210526. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210527. }
  210528. OpenGLPixelFormat pf;
  210529. for (int i = 0; i < numTypes; ++i)
  210530. {
  210531. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210532. {
  210533. bool alreadyListed = false;
  210534. for (int j = results.size(); --j >= 0;)
  210535. if (pf == *results.getUnchecked(j))
  210536. alreadyListed = true;
  210537. if (! alreadyListed)
  210538. results.add (new OpenGLPixelFormat (pf));
  210539. }
  210540. }
  210541. }
  210542. void* getNativeWindowHandle() const
  210543. {
  210544. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210545. }
  210546. HGLRC renderContext;
  210547. private:
  210548. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210549. Component* const component;
  210550. HDC dc;
  210551. void createNativeWindow()
  210552. {
  210553. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210554. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210555. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210556. nativeWindow->dontRepaint = true;
  210557. nativeWindow->setVisible (true);
  210558. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210559. }
  210560. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210561. OpenGLPixelFormat& result,
  210562. const StringArray& availableExtensions) const throw()
  210563. {
  210564. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210565. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210566. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210567. {
  210568. int attributes[32];
  210569. int numAttributes = 0;
  210570. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210571. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210572. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210573. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210574. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210575. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210576. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210577. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210578. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210579. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210580. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210581. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210582. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210583. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210584. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210585. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210586. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210587. int values[32];
  210588. zeromem (values, sizeof (values));
  210589. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210590. {
  210591. int n = 0;
  210592. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210593. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210594. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210595. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210596. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210597. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210598. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210599. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210600. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210601. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210602. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210603. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210604. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210605. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210606. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210607. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210608. return isValidFormat;
  210609. }
  210610. else
  210611. {
  210612. jassertfalse;
  210613. }
  210614. }
  210615. else
  210616. {
  210617. PIXELFORMATDESCRIPTOR pfd;
  210618. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210619. {
  210620. result.redBits = pfd.cRedBits;
  210621. result.greenBits = pfd.cGreenBits;
  210622. result.blueBits = pfd.cBlueBits;
  210623. result.alphaBits = pfd.cAlphaBits;
  210624. result.depthBufferBits = pfd.cDepthBits;
  210625. result.stencilBufferBits = pfd.cStencilBits;
  210626. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210627. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210628. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210629. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210630. result.fullSceneAntiAliasingNumSamples = 0;
  210631. return true;
  210632. }
  210633. else
  210634. {
  210635. jassertfalse;
  210636. }
  210637. }
  210638. return false;
  210639. }
  210640. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210641. };
  210642. OpenGLContext* OpenGLComponent::createContext()
  210643. {
  210644. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210645. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210646. preferredPixelFormat));
  210647. return (c->renderContext != 0) ? c.release() : 0;
  210648. }
  210649. void* OpenGLComponent::getNativeWindowHandle() const
  210650. {
  210651. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210652. }
  210653. void juce_glViewport (const int w, const int h)
  210654. {
  210655. glViewport (0, 0, w, h);
  210656. }
  210657. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210658. OwnedArray <OpenGLPixelFormat>& results)
  210659. {
  210660. Component tempComp;
  210661. {
  210662. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210663. wc.makeActive();
  210664. wc.findAlternativeOpenGLPixelFormats (results);
  210665. }
  210666. }
  210667. #endif
  210668. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210669. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210670. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210671. // compiled on its own).
  210672. #if JUCE_INCLUDED_FILE
  210673. #if JUCE_USE_CDREADER
  210674. namespace CDReaderHelpers
  210675. {
  210676. #define FILE_ANY_ACCESS 0
  210677. #ifndef FILE_READ_ACCESS
  210678. #define FILE_READ_ACCESS 1
  210679. #endif
  210680. #ifndef FILE_WRITE_ACCESS
  210681. #define FILE_WRITE_ACCESS 2
  210682. #endif
  210683. #define METHOD_BUFFERED 0
  210684. #define IOCTL_SCSI_BASE 4
  210685. #define SCSI_IOCTL_DATA_OUT 0
  210686. #define SCSI_IOCTL_DATA_IN 1
  210687. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210688. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210689. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210690. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210691. #define SENSE_LEN 14
  210692. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210693. #define SRB_DIR_IN 0x08
  210694. #define SRB_DIR_OUT 0x10
  210695. #define SRB_EVENT_NOTIFY 0x40
  210696. #define SC_HA_INQUIRY 0x00
  210697. #define SC_GET_DEV_TYPE 0x01
  210698. #define SC_EXEC_SCSI_CMD 0x02
  210699. #define SS_PENDING 0x00
  210700. #define SS_COMP 0x01
  210701. #define SS_ERR 0x04
  210702. enum
  210703. {
  210704. READTYPE_ANY = 0,
  210705. READTYPE_ATAPI1 = 1,
  210706. READTYPE_ATAPI2 = 2,
  210707. READTYPE_READ6 = 3,
  210708. READTYPE_READ10 = 4,
  210709. READTYPE_READ_D8 = 5,
  210710. READTYPE_READ_D4 = 6,
  210711. READTYPE_READ_D4_1 = 7,
  210712. READTYPE_READ10_2 = 8
  210713. };
  210714. struct SCSI_PASS_THROUGH
  210715. {
  210716. USHORT Length;
  210717. UCHAR ScsiStatus;
  210718. UCHAR PathId;
  210719. UCHAR TargetId;
  210720. UCHAR Lun;
  210721. UCHAR CdbLength;
  210722. UCHAR SenseInfoLength;
  210723. UCHAR DataIn;
  210724. ULONG DataTransferLength;
  210725. ULONG TimeOutValue;
  210726. ULONG DataBufferOffset;
  210727. ULONG SenseInfoOffset;
  210728. UCHAR Cdb[16];
  210729. };
  210730. struct SCSI_PASS_THROUGH_DIRECT
  210731. {
  210732. USHORT Length;
  210733. UCHAR ScsiStatus;
  210734. UCHAR PathId;
  210735. UCHAR TargetId;
  210736. UCHAR Lun;
  210737. UCHAR CdbLength;
  210738. UCHAR SenseInfoLength;
  210739. UCHAR DataIn;
  210740. ULONG DataTransferLength;
  210741. ULONG TimeOutValue;
  210742. PVOID DataBuffer;
  210743. ULONG SenseInfoOffset;
  210744. UCHAR Cdb[16];
  210745. };
  210746. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210747. {
  210748. SCSI_PASS_THROUGH_DIRECT spt;
  210749. ULONG Filler;
  210750. UCHAR ucSenseBuf[32];
  210751. };
  210752. struct SCSI_ADDRESS
  210753. {
  210754. ULONG Length;
  210755. UCHAR PortNumber;
  210756. UCHAR PathId;
  210757. UCHAR TargetId;
  210758. UCHAR Lun;
  210759. };
  210760. #pragma pack(1)
  210761. struct SRB_GDEVBlock
  210762. {
  210763. BYTE SRB_Cmd;
  210764. BYTE SRB_Status;
  210765. BYTE SRB_HaID;
  210766. BYTE SRB_Flags;
  210767. DWORD SRB_Hdr_Rsvd;
  210768. BYTE SRB_Target;
  210769. BYTE SRB_Lun;
  210770. BYTE SRB_DeviceType;
  210771. BYTE SRB_Rsvd1;
  210772. BYTE pad[68];
  210773. };
  210774. struct SRB_ExecSCSICmd
  210775. {
  210776. BYTE SRB_Cmd;
  210777. BYTE SRB_Status;
  210778. BYTE SRB_HaID;
  210779. BYTE SRB_Flags;
  210780. DWORD SRB_Hdr_Rsvd;
  210781. BYTE SRB_Target;
  210782. BYTE SRB_Lun;
  210783. WORD SRB_Rsvd1;
  210784. DWORD SRB_BufLen;
  210785. BYTE *SRB_BufPointer;
  210786. BYTE SRB_SenseLen;
  210787. BYTE SRB_CDBLen;
  210788. BYTE SRB_HaStat;
  210789. BYTE SRB_TargStat;
  210790. VOID *SRB_PostProc;
  210791. BYTE SRB_Rsvd2[20];
  210792. BYTE CDBByte[16];
  210793. BYTE SenseArea[SENSE_LEN + 2];
  210794. };
  210795. struct SRB
  210796. {
  210797. BYTE SRB_Cmd;
  210798. BYTE SRB_Status;
  210799. BYTE SRB_HaId;
  210800. BYTE SRB_Flags;
  210801. DWORD SRB_Hdr_Rsvd;
  210802. };
  210803. struct TOCTRACK
  210804. {
  210805. BYTE rsvd;
  210806. BYTE ADR;
  210807. BYTE trackNumber;
  210808. BYTE rsvd2;
  210809. BYTE addr[4];
  210810. };
  210811. struct TOC
  210812. {
  210813. WORD tocLen;
  210814. BYTE firstTrack;
  210815. BYTE lastTrack;
  210816. TOCTRACK tracks[100];
  210817. };
  210818. #pragma pack()
  210819. struct CDDeviceDescription
  210820. {
  210821. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210822. {
  210823. }
  210824. void createDescription (const char* data)
  210825. {
  210826. description << String (data + 8, 8).trim() // vendor
  210827. << ' ' << String (data + 16, 16).trim() // product id
  210828. << ' ' << String (data + 32, 4).trim(); // rev
  210829. }
  210830. String description;
  210831. BYTE ha, tgt, lun;
  210832. char scsiDriveLetter; // will be 0 if not using scsi
  210833. };
  210834. class CDReadBuffer
  210835. {
  210836. public:
  210837. CDReadBuffer (const int numberOfFrames)
  210838. : startFrame (0), numFrames (0), dataStartOffset (0),
  210839. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210840. buffer (bufferSize), wantsIndex (false)
  210841. {
  210842. }
  210843. bool isZero() const throw()
  210844. {
  210845. for (int i = 0; i < dataLength; ++i)
  210846. if (buffer [dataStartOffset + i] != 0)
  210847. return false;
  210848. return true;
  210849. }
  210850. int startFrame, numFrames, dataStartOffset;
  210851. int dataLength, bufferSize, index;
  210852. HeapBlock<BYTE> buffer;
  210853. bool wantsIndex;
  210854. };
  210855. class CDDeviceHandle;
  210856. class CDController
  210857. {
  210858. public:
  210859. CDController() : initialised (false) {}
  210860. virtual ~CDController() {}
  210861. virtual bool read (CDReadBuffer&) = 0;
  210862. virtual void shutDown() {}
  210863. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210864. int getLastIndex();
  210865. public:
  210866. CDDeviceHandle* deviceInfo;
  210867. int framesToCheck, framesOverlap;
  210868. bool initialised;
  210869. void prepare (SRB_ExecSCSICmd& s);
  210870. void perform (SRB_ExecSCSICmd& s);
  210871. void setPaused (bool paused);
  210872. };
  210873. class CDDeviceHandle
  210874. {
  210875. public:
  210876. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210877. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210878. {
  210879. }
  210880. ~CDDeviceHandle()
  210881. {
  210882. if (controller != 0)
  210883. {
  210884. controller->shutDown();
  210885. controller = 0;
  210886. }
  210887. if (scsiHandle != 0)
  210888. CloseHandle (scsiHandle);
  210889. }
  210890. bool readTOC (TOC* lpToc);
  210891. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210892. void openDrawer (bool shouldBeOpen);
  210893. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210894. CDDeviceDescription info;
  210895. HANDLE scsiHandle;
  210896. BYTE readType;
  210897. private:
  210898. ScopedPointer<CDController> controller;
  210899. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210900. };
  210901. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210902. {
  210903. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210904. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210905. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210906. if (h == INVALID_HANDLE_VALUE)
  210907. {
  210908. flags ^= GENERIC_WRITE;
  210909. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210910. }
  210911. return h;
  210912. }
  210913. void findCDDevices (Array<CDDeviceDescription>& list)
  210914. {
  210915. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210916. {
  210917. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210918. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210919. {
  210920. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210921. if (h != INVALID_HANDLE_VALUE)
  210922. {
  210923. char buffer[100];
  210924. zeromem (buffer, sizeof (buffer));
  210925. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210926. zerostruct (p);
  210927. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210928. p.spt.CdbLength = 6;
  210929. p.spt.SenseInfoLength = 24;
  210930. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210931. p.spt.DataTransferLength = sizeof (buffer);
  210932. p.spt.TimeOutValue = 2;
  210933. p.spt.DataBuffer = buffer;
  210934. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210935. p.spt.Cdb[0] = 0x12;
  210936. p.spt.Cdb[4] = 100;
  210937. DWORD bytesReturned = 0;
  210938. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210939. &p, sizeof (p), &p, sizeof (p),
  210940. &bytesReturned, 0) != 0)
  210941. {
  210942. CDDeviceDescription dev;
  210943. dev.scsiDriveLetter = driveLetter;
  210944. dev.createDescription (buffer);
  210945. SCSI_ADDRESS scsiAddr;
  210946. zerostruct (scsiAddr);
  210947. scsiAddr.Length = sizeof (scsiAddr);
  210948. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210949. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210950. &bytesReturned, 0) != 0)
  210951. {
  210952. dev.ha = scsiAddr.PortNumber;
  210953. dev.tgt = scsiAddr.TargetId;
  210954. dev.lun = scsiAddr.Lun;
  210955. list.add (dev);
  210956. }
  210957. }
  210958. CloseHandle (h);
  210959. }
  210960. }
  210961. }
  210962. }
  210963. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210964. HANDLE& deviceHandle, const bool retryOnFailure)
  210965. {
  210966. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210967. zerostruct (s);
  210968. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210969. s.spt.CdbLength = srb->SRB_CDBLen;
  210970. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210971. ? SCSI_IOCTL_DATA_IN
  210972. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210973. ? SCSI_IOCTL_DATA_OUT
  210974. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210975. s.spt.DataTransferLength = srb->SRB_BufLen;
  210976. s.spt.TimeOutValue = 5;
  210977. s.spt.DataBuffer = srb->SRB_BufPointer;
  210978. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210979. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210980. srb->SRB_Status = SS_ERR;
  210981. srb->SRB_TargStat = 0x0004;
  210982. DWORD bytesReturned = 0;
  210983. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210984. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210985. {
  210986. srb->SRB_Status = SS_COMP;
  210987. }
  210988. else if (retryOnFailure)
  210989. {
  210990. const DWORD error = GetLastError();
  210991. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210992. {
  210993. if (error != ERROR_INVALID_HANDLE)
  210994. CloseHandle (deviceHandle);
  210995. deviceHandle = createSCSIDeviceHandle (driveLetter);
  210996. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210997. }
  210998. }
  210999. return srb->SRB_Status;
  211000. }
  211001. // Controller types..
  211002. class ControllerType1 : public CDController
  211003. {
  211004. public:
  211005. ControllerType1() {}
  211006. bool read (CDReadBuffer& rb)
  211007. {
  211008. if (rb.numFrames * 2352 > rb.bufferSize)
  211009. return false;
  211010. SRB_ExecSCSICmd s;
  211011. prepare (s);
  211012. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211013. s.SRB_BufLen = rb.bufferSize;
  211014. s.SRB_BufPointer = rb.buffer;
  211015. s.SRB_CDBLen = 12;
  211016. s.CDBByte[0] = 0xBE;
  211017. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211018. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211019. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211020. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211021. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  211022. perform (s);
  211023. if (s.SRB_Status != SS_COMP)
  211024. return false;
  211025. rb.dataLength = rb.numFrames * 2352;
  211026. rb.dataStartOffset = 0;
  211027. return true;
  211028. }
  211029. };
  211030. class ControllerType2 : public CDController
  211031. {
  211032. public:
  211033. ControllerType2() {}
  211034. void shutDown()
  211035. {
  211036. if (initialised)
  211037. {
  211038. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211039. SRB_ExecSCSICmd s;
  211040. prepare (s);
  211041. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211042. s.SRB_BufLen = 0x0C;
  211043. s.SRB_BufPointer = bufPointer;
  211044. s.SRB_CDBLen = 6;
  211045. s.CDBByte[0] = 0x15;
  211046. s.CDBByte[4] = 0x0C;
  211047. perform (s);
  211048. }
  211049. }
  211050. bool init()
  211051. {
  211052. SRB_ExecSCSICmd s;
  211053. s.SRB_Status = SS_ERR;
  211054. if (deviceInfo->readType == READTYPE_READ10_2)
  211055. {
  211056. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211057. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211058. for (int i = 0; i < 2; ++i)
  211059. {
  211060. prepare (s);
  211061. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211062. s.SRB_BufLen = 0x14;
  211063. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211064. s.SRB_CDBLen = 6;
  211065. s.CDBByte[0] = 0x15;
  211066. s.CDBByte[1] = 0x10;
  211067. s.CDBByte[4] = 0x14;
  211068. perform (s);
  211069. if (s.SRB_Status != SS_COMP)
  211070. return false;
  211071. }
  211072. }
  211073. else
  211074. {
  211075. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211076. prepare (s);
  211077. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211078. s.SRB_BufLen = 0x0C;
  211079. s.SRB_BufPointer = bufPointer;
  211080. s.SRB_CDBLen = 6;
  211081. s.CDBByte[0] = 0x15;
  211082. s.CDBByte[4] = 0x0C;
  211083. perform (s);
  211084. }
  211085. return s.SRB_Status == SS_COMP;
  211086. }
  211087. bool read (CDReadBuffer& rb)
  211088. {
  211089. if (rb.numFrames * 2352 > rb.bufferSize)
  211090. return false;
  211091. if (! initialised)
  211092. {
  211093. initialised = init();
  211094. if (! initialised)
  211095. return false;
  211096. }
  211097. SRB_ExecSCSICmd s;
  211098. prepare (s);
  211099. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211100. s.SRB_BufLen = rb.bufferSize;
  211101. s.SRB_BufPointer = rb.buffer;
  211102. s.SRB_CDBLen = 10;
  211103. s.CDBByte[0] = 0x28;
  211104. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  211105. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211106. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211107. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211108. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211109. perform (s);
  211110. if (s.SRB_Status != SS_COMP)
  211111. return false;
  211112. rb.dataLength = rb.numFrames * 2352;
  211113. rb.dataStartOffset = 0;
  211114. return true;
  211115. }
  211116. };
  211117. class ControllerType3 : public CDController
  211118. {
  211119. public:
  211120. ControllerType3() {}
  211121. bool read (CDReadBuffer& rb)
  211122. {
  211123. if (rb.numFrames * 2352 > rb.bufferSize)
  211124. return false;
  211125. if (! initialised)
  211126. {
  211127. setPaused (false);
  211128. initialised = true;
  211129. }
  211130. SRB_ExecSCSICmd s;
  211131. prepare (s);
  211132. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211133. s.SRB_BufLen = rb.numFrames * 2352;
  211134. s.SRB_BufPointer = rb.buffer;
  211135. s.SRB_CDBLen = 12;
  211136. s.CDBByte[0] = 0xD8;
  211137. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211138. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211139. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211140. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  211141. perform (s);
  211142. if (s.SRB_Status != SS_COMP)
  211143. return false;
  211144. rb.dataLength = rb.numFrames * 2352;
  211145. rb.dataStartOffset = 0;
  211146. return true;
  211147. }
  211148. };
  211149. class ControllerType4 : public CDController
  211150. {
  211151. public:
  211152. ControllerType4() {}
  211153. bool selectD4Mode()
  211154. {
  211155. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211156. SRB_ExecSCSICmd s;
  211157. prepare (s);
  211158. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211159. s.SRB_CDBLen = 6;
  211160. s.SRB_BufLen = 12;
  211161. s.SRB_BufPointer = bufPointer;
  211162. s.CDBByte[0] = 0x15;
  211163. s.CDBByte[1] = 0x10;
  211164. s.CDBByte[4] = 0x08;
  211165. perform (s);
  211166. return s.SRB_Status == SS_COMP;
  211167. }
  211168. bool read (CDReadBuffer& rb)
  211169. {
  211170. if (rb.numFrames * 2352 > rb.bufferSize)
  211171. return false;
  211172. if (! initialised)
  211173. {
  211174. setPaused (true);
  211175. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211176. selectD4Mode();
  211177. initialised = true;
  211178. }
  211179. SRB_ExecSCSICmd s;
  211180. prepare (s);
  211181. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211182. s.SRB_BufLen = rb.bufferSize;
  211183. s.SRB_BufPointer = rb.buffer;
  211184. s.SRB_CDBLen = 10;
  211185. s.CDBByte[0] = 0xD4;
  211186. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211187. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211188. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211189. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211190. perform (s);
  211191. if (s.SRB_Status != SS_COMP)
  211192. return false;
  211193. rb.dataLength = rb.numFrames * 2352;
  211194. rb.dataStartOffset = 0;
  211195. return true;
  211196. }
  211197. };
  211198. void CDController::prepare (SRB_ExecSCSICmd& s)
  211199. {
  211200. zerostruct (s);
  211201. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211202. s.SRB_HaID = deviceInfo->info.ha;
  211203. s.SRB_Target = deviceInfo->info.tgt;
  211204. s.SRB_Lun = deviceInfo->info.lun;
  211205. s.SRB_SenseLen = SENSE_LEN;
  211206. }
  211207. void CDController::perform (SRB_ExecSCSICmd& s)
  211208. {
  211209. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211210. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  211211. }
  211212. void CDController::setPaused (bool paused)
  211213. {
  211214. SRB_ExecSCSICmd s;
  211215. prepare (s);
  211216. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211217. s.SRB_CDBLen = 10;
  211218. s.CDBByte[0] = 0x4B;
  211219. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211220. perform (s);
  211221. }
  211222. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  211223. {
  211224. if (overlapBuffer != 0)
  211225. {
  211226. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211227. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211228. if (doJitter
  211229. && overlapBuffer->startFrame > 0
  211230. && overlapBuffer->numFrames > 0
  211231. && overlapBuffer->dataLength > 0)
  211232. {
  211233. const int numFrames = rb.numFrames;
  211234. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  211235. {
  211236. rb.startFrame -= framesOverlap;
  211237. if (framesToCheck < framesOverlap
  211238. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  211239. rb.numFrames += framesOverlap;
  211240. }
  211241. else
  211242. {
  211243. overlapBuffer->dataLength = 0;
  211244. overlapBuffer->startFrame = 0;
  211245. overlapBuffer->numFrames = 0;
  211246. }
  211247. }
  211248. if (! read (rb))
  211249. return false;
  211250. if (doJitter)
  211251. {
  211252. const int checkLen = framesToCheck * 2352;
  211253. const int maxToCheck = rb.dataLength - checkLen;
  211254. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211255. return true;
  211256. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211257. bool found = false;
  211258. for (int i = 0; i < maxToCheck; ++i)
  211259. {
  211260. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  211261. {
  211262. i += checkLen;
  211263. rb.dataStartOffset = i;
  211264. rb.dataLength -= i;
  211265. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  211266. found = true;
  211267. break;
  211268. }
  211269. }
  211270. rb.numFrames = rb.dataLength / 2352;
  211271. rb.dataLength = 2352 * rb.numFrames;
  211272. if (! found)
  211273. return false;
  211274. }
  211275. if (canDoJitter)
  211276. {
  211277. memcpy (overlapBuffer->buffer,
  211278. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  211279. 2352 * framesToCheck);
  211280. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  211281. overlapBuffer->numFrames = framesToCheck;
  211282. overlapBuffer->dataLength = 2352 * framesToCheck;
  211283. overlapBuffer->dataStartOffset = 0;
  211284. }
  211285. else
  211286. {
  211287. overlapBuffer->startFrame = 0;
  211288. overlapBuffer->numFrames = 0;
  211289. overlapBuffer->dataLength = 0;
  211290. }
  211291. return true;
  211292. }
  211293. return read (rb);
  211294. }
  211295. int CDController::getLastIndex()
  211296. {
  211297. char qdata[100];
  211298. SRB_ExecSCSICmd s;
  211299. prepare (s);
  211300. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211301. s.SRB_BufLen = sizeof (qdata);
  211302. s.SRB_BufPointer = (BYTE*) qdata;
  211303. s.SRB_CDBLen = 12;
  211304. s.CDBByte[0] = 0x42;
  211305. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  211306. s.CDBByte[2] = 64;
  211307. s.CDBByte[3] = 1; // get current position
  211308. s.CDBByte[7] = 0;
  211309. s.CDBByte[8] = (BYTE) sizeof (qdata);
  211310. perform (s);
  211311. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  211312. }
  211313. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211314. {
  211315. SRB_ExecSCSICmd s;
  211316. zerostruct (s);
  211317. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211318. s.SRB_HaID = info.ha;
  211319. s.SRB_Target = info.tgt;
  211320. s.SRB_Lun = info.lun;
  211321. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211322. s.SRB_BufLen = 0x324;
  211323. s.SRB_BufPointer = (BYTE*) lpToc;
  211324. s.SRB_SenseLen = 0x0E;
  211325. s.SRB_CDBLen = 0x0A;
  211326. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211327. s.CDBByte[0] = 0x43;
  211328. s.CDBByte[1] = 0x00;
  211329. s.CDBByte[7] = 0x03;
  211330. s.CDBByte[8] = 0x24;
  211331. performScsiCommand (s.SRB_PostProc, s);
  211332. return (s.SRB_Status == SS_COMP);
  211333. }
  211334. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  211335. {
  211336. ResetEvent (event);
  211337. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  211338. if (status == SS_PENDING)
  211339. WaitForSingleObject (event, 4000);
  211340. CloseHandle (event);
  211341. }
  211342. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  211343. {
  211344. if (controller == 0)
  211345. {
  211346. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211347. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211348. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211349. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211350. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211351. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211352. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211353. }
  211354. buffer.index = 0;
  211355. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  211356. {
  211357. if (buffer.wantsIndex)
  211358. buffer.index = controller->getLastIndex();
  211359. return true;
  211360. }
  211361. return false;
  211362. }
  211363. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211364. {
  211365. if (shouldBeOpen)
  211366. {
  211367. if (controller != 0)
  211368. {
  211369. controller->shutDown();
  211370. controller = 0;
  211371. }
  211372. if (scsiHandle != 0)
  211373. {
  211374. CloseHandle (scsiHandle);
  211375. scsiHandle = 0;
  211376. }
  211377. }
  211378. SRB_ExecSCSICmd s;
  211379. zerostruct (s);
  211380. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211381. s.SRB_HaID = info.ha;
  211382. s.SRB_Target = info.tgt;
  211383. s.SRB_Lun = info.lun;
  211384. s.SRB_SenseLen = SENSE_LEN;
  211385. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211386. s.SRB_BufLen = 0;
  211387. s.SRB_BufPointer = 0;
  211388. s.SRB_CDBLen = 12;
  211389. s.CDBByte[0] = 0x1b;
  211390. s.CDBByte[1] = (BYTE) (info.lun << 5);
  211391. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  211392. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211393. performScsiCommand (s.SRB_PostProc, s);
  211394. }
  211395. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  211396. {
  211397. controller = newController;
  211398. readType = (BYTE) type;
  211399. controller->deviceInfo = this;
  211400. controller->framesToCheck = 1;
  211401. controller->framesOverlap = 3;
  211402. bool passed = false;
  211403. memset (rb.buffer, 0xcd, rb.bufferSize);
  211404. if (controller->read (rb))
  211405. {
  211406. passed = true;
  211407. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  211408. int wrong = 0;
  211409. for (int i = rb.dataLength / 4; --i >= 0;)
  211410. {
  211411. if (*p++ == (int) 0xcdcdcdcd)
  211412. {
  211413. if (++wrong == 4)
  211414. {
  211415. passed = false;
  211416. break;
  211417. }
  211418. }
  211419. else
  211420. {
  211421. wrong = 0;
  211422. }
  211423. }
  211424. }
  211425. if (! passed)
  211426. {
  211427. controller->shutDown();
  211428. controller = 0;
  211429. }
  211430. return passed;
  211431. }
  211432. struct CDDeviceWrapper
  211433. {
  211434. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  211435. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  211436. {
  211437. // xxx jitter never seemed to actually be enabled (??)
  211438. }
  211439. CDDeviceHandle deviceHandle;
  211440. CDReadBuffer overlapBuffer;
  211441. bool jitter;
  211442. };
  211443. int getAddressOfTrack (const TOCTRACK& t) throw()
  211444. {
  211445. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  211446. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  211447. }
  211448. const int samplesPerFrame = 44100 / 75;
  211449. const int bytesPerFrame = samplesPerFrame * 4;
  211450. const int framesPerIndexRead = 4;
  211451. }
  211452. const StringArray AudioCDReader::getAvailableCDNames()
  211453. {
  211454. using namespace CDReaderHelpers;
  211455. StringArray results;
  211456. Array<CDDeviceDescription> list;
  211457. findCDDevices (list);
  211458. for (int i = 0; i < list.size(); ++i)
  211459. {
  211460. String s;
  211461. if (list[i].scsiDriveLetter > 0)
  211462. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211463. s << list[i].description;
  211464. results.add (s);
  211465. }
  211466. return results;
  211467. }
  211468. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211469. {
  211470. using namespace CDReaderHelpers;
  211471. Array<CDDeviceDescription> list;
  211472. findCDDevices (list);
  211473. if (isPositiveAndBelow (deviceIndex, list.size()))
  211474. {
  211475. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  211476. if (h != INVALID_HANDLE_VALUE)
  211477. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  211478. }
  211479. return 0;
  211480. }
  211481. AudioCDReader::AudioCDReader (void* handle_)
  211482. : AudioFormatReader (0, "CD Audio"),
  211483. handle (handle_),
  211484. indexingEnabled (false),
  211485. lastIndex (0),
  211486. firstFrameInBuffer (0),
  211487. samplesInBuffer (0)
  211488. {
  211489. using namespace CDReaderHelpers;
  211490. jassert (handle_ != 0);
  211491. refreshTrackLengths();
  211492. sampleRate = 44100.0;
  211493. bitsPerSample = 16;
  211494. numChannels = 2;
  211495. usesFloatingPointData = false;
  211496. buffer.setSize (4 * bytesPerFrame, true);
  211497. }
  211498. AudioCDReader::~AudioCDReader()
  211499. {
  211500. using namespace CDReaderHelpers;
  211501. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211502. delete device;
  211503. }
  211504. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211505. int64 startSampleInFile, int numSamples)
  211506. {
  211507. using namespace CDReaderHelpers;
  211508. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211509. bool ok = true;
  211510. while (numSamples > 0)
  211511. {
  211512. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211513. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211514. if (startSampleInFile >= bufferStartSample
  211515. && startSampleInFile < bufferEndSample)
  211516. {
  211517. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211518. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211519. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211520. const short* src = (const short*) buffer.getData();
  211521. src += 2 * (startSampleInFile - bufferStartSample);
  211522. for (int i = 0; i < toDo; ++i)
  211523. {
  211524. l[i] = src [i << 1] << 16;
  211525. if (r != 0)
  211526. r[i] = src [(i << 1) + 1] << 16;
  211527. }
  211528. startOffsetInDestBuffer += toDo;
  211529. startSampleInFile += toDo;
  211530. numSamples -= toDo;
  211531. }
  211532. else
  211533. {
  211534. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211535. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211536. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211537. {
  211538. device->overlapBuffer.dataLength = 0;
  211539. device->overlapBuffer.startFrame = 0;
  211540. device->overlapBuffer.numFrames = 0;
  211541. device->jitter = false;
  211542. }
  211543. firstFrameInBuffer = frameNeeded;
  211544. lastIndex = 0;
  211545. CDReadBuffer readBuffer (framesInBuffer + 4);
  211546. readBuffer.wantsIndex = indexingEnabled;
  211547. int i;
  211548. for (i = 5; --i >= 0;)
  211549. {
  211550. readBuffer.startFrame = frameNeeded;
  211551. readBuffer.numFrames = framesInBuffer;
  211552. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  211553. break;
  211554. else
  211555. device->overlapBuffer.dataLength = 0;
  211556. }
  211557. if (i >= 0)
  211558. {
  211559. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  211560. samplesInBuffer = readBuffer.dataLength >> 2;
  211561. lastIndex = readBuffer.index;
  211562. }
  211563. else
  211564. {
  211565. int* l = destSamples[0] + startOffsetInDestBuffer;
  211566. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211567. while (--numSamples >= 0)
  211568. {
  211569. *l++ = 0;
  211570. if (r != 0)
  211571. *r++ = 0;
  211572. }
  211573. // sometimes the read fails for just the very last couple of blocks, so
  211574. // we'll ignore and errors in the last half-second of the disk..
  211575. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211576. break;
  211577. }
  211578. }
  211579. }
  211580. return ok;
  211581. }
  211582. bool AudioCDReader::isCDStillPresent() const
  211583. {
  211584. using namespace CDReaderHelpers;
  211585. TOC toc;
  211586. zerostruct (toc);
  211587. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  211588. }
  211589. void AudioCDReader::refreshTrackLengths()
  211590. {
  211591. using namespace CDReaderHelpers;
  211592. trackStartSamples.clear();
  211593. zeromem (audioTracks, sizeof (audioTracks));
  211594. TOC toc;
  211595. zerostruct (toc);
  211596. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211597. {
  211598. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211599. for (int i = 0; i <= numTracks; ++i)
  211600. {
  211601. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211602. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211603. }
  211604. }
  211605. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211606. }
  211607. bool AudioCDReader::isTrackAudio (int trackNum) const
  211608. {
  211609. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211610. }
  211611. void AudioCDReader::enableIndexScanning (bool b)
  211612. {
  211613. indexingEnabled = b;
  211614. }
  211615. int AudioCDReader::getLastIndex() const
  211616. {
  211617. return lastIndex;
  211618. }
  211619. int AudioCDReader::getIndexAt (int samplePos)
  211620. {
  211621. using namespace CDReaderHelpers;
  211622. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211623. const int frameNeeded = samplePos / samplesPerFrame;
  211624. device->overlapBuffer.dataLength = 0;
  211625. device->overlapBuffer.startFrame = 0;
  211626. device->overlapBuffer.numFrames = 0;
  211627. device->jitter = false;
  211628. firstFrameInBuffer = 0;
  211629. lastIndex = 0;
  211630. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211631. readBuffer.wantsIndex = true;
  211632. int i;
  211633. for (i = 5; --i >= 0;)
  211634. {
  211635. readBuffer.startFrame = frameNeeded;
  211636. readBuffer.numFrames = framesPerIndexRead;
  211637. if (device->deviceHandle.readAudio (readBuffer))
  211638. break;
  211639. }
  211640. if (i >= 0)
  211641. return readBuffer.index;
  211642. return -1;
  211643. }
  211644. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211645. {
  211646. using namespace CDReaderHelpers;
  211647. Array <int> indexes;
  211648. const int trackStart = getPositionOfTrackStart (trackNumber);
  211649. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211650. bool needToScan = true;
  211651. if (trackEnd - trackStart > 20 * 44100)
  211652. {
  211653. // check the end of the track for indexes before scanning the whole thing
  211654. needToScan = false;
  211655. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211656. bool seenAnIndex = false;
  211657. while (pos <= trackEnd - samplesPerFrame)
  211658. {
  211659. const int index = getIndexAt (pos);
  211660. if (index == 0)
  211661. {
  211662. // lead-out, so skip back a bit if we've not found any indexes yet..
  211663. if (seenAnIndex)
  211664. break;
  211665. pos -= 44100 * 5;
  211666. if (pos < trackStart)
  211667. break;
  211668. }
  211669. else
  211670. {
  211671. if (index > 0)
  211672. seenAnIndex = true;
  211673. if (index > 1)
  211674. {
  211675. needToScan = true;
  211676. break;
  211677. }
  211678. pos += samplesPerFrame * framesPerIndexRead;
  211679. }
  211680. }
  211681. }
  211682. if (needToScan)
  211683. {
  211684. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211685. int pos = trackStart;
  211686. int last = -1;
  211687. while (pos < trackEnd - samplesPerFrame * 10)
  211688. {
  211689. const int frameNeeded = pos / samplesPerFrame;
  211690. device->overlapBuffer.dataLength = 0;
  211691. device->overlapBuffer.startFrame = 0;
  211692. device->overlapBuffer.numFrames = 0;
  211693. device->jitter = false;
  211694. firstFrameInBuffer = 0;
  211695. CDReadBuffer readBuffer (4);
  211696. readBuffer.wantsIndex = true;
  211697. int i;
  211698. for (i = 5; --i >= 0;)
  211699. {
  211700. readBuffer.startFrame = frameNeeded;
  211701. readBuffer.numFrames = framesPerIndexRead;
  211702. if (device->deviceHandle.readAudio (readBuffer))
  211703. break;
  211704. }
  211705. if (i < 0)
  211706. break;
  211707. if (readBuffer.index > last && readBuffer.index > 1)
  211708. {
  211709. last = readBuffer.index;
  211710. indexes.add (pos);
  211711. }
  211712. pos += samplesPerFrame * framesPerIndexRead;
  211713. }
  211714. indexes.removeValue (trackStart);
  211715. }
  211716. return indexes;
  211717. }
  211718. void AudioCDReader::ejectDisk()
  211719. {
  211720. using namespace CDReaderHelpers;
  211721. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211722. }
  211723. #endif
  211724. #if JUCE_USE_CDBURNER
  211725. namespace CDBurnerHelpers
  211726. {
  211727. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211728. {
  211729. CoInitialize (0);
  211730. IDiscMaster* dm;
  211731. IDiscRecorder* result = 0;
  211732. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211733. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211734. IID_IDiscMaster,
  211735. (void**) &dm)))
  211736. {
  211737. if (SUCCEEDED (dm->Open()))
  211738. {
  211739. IEnumDiscRecorders* drEnum = 0;
  211740. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211741. {
  211742. IDiscRecorder* dr = 0;
  211743. DWORD dummy;
  211744. int index = 0;
  211745. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211746. {
  211747. if (indexToOpen == index)
  211748. {
  211749. result = dr;
  211750. break;
  211751. }
  211752. else if (list != 0)
  211753. {
  211754. BSTR path;
  211755. if (SUCCEEDED (dr->GetPath (&path)))
  211756. list->add ((const WCHAR*) path);
  211757. }
  211758. ++index;
  211759. dr->Release();
  211760. }
  211761. drEnum->Release();
  211762. }
  211763. if (master == 0)
  211764. dm->Close();
  211765. }
  211766. if (master != 0)
  211767. *master = dm;
  211768. else
  211769. dm->Release();
  211770. }
  211771. return result;
  211772. }
  211773. }
  211774. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211775. public Timer
  211776. {
  211777. public:
  211778. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211779. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211780. listener (0), progress (0), shouldCancel (false)
  211781. {
  211782. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211783. jassert (SUCCEEDED (hr));
  211784. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211785. //jassert (SUCCEEDED (hr));
  211786. lastState = getDiskState();
  211787. startTimer (2000);
  211788. }
  211789. ~Pimpl() {}
  211790. void releaseObjects()
  211791. {
  211792. discRecorder->Close();
  211793. if (redbook != 0)
  211794. redbook->Release();
  211795. discRecorder->Release();
  211796. discMaster->Release();
  211797. Release();
  211798. }
  211799. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211800. {
  211801. if (listener != 0 && ! shouldCancel)
  211802. shouldCancel = listener->audioCDBurnProgress (progress);
  211803. *pbCancel = shouldCancel;
  211804. return S_OK;
  211805. }
  211806. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211807. {
  211808. progress = nCompleted / (float) nTotal;
  211809. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211810. return E_NOTIMPL;
  211811. }
  211812. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211813. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211814. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211815. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211816. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211817. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211818. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211819. class ScopedDiscOpener
  211820. {
  211821. public:
  211822. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211823. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211824. private:
  211825. Pimpl& pimpl;
  211826. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211827. };
  211828. DiskState getDiskState()
  211829. {
  211830. const ScopedDiscOpener opener (*this);
  211831. long type, flags;
  211832. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211833. if (FAILED (hr))
  211834. return unknown;
  211835. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211836. return writableDiskPresent;
  211837. if (type == 0)
  211838. return noDisc;
  211839. else
  211840. return readOnlyDiskPresent;
  211841. }
  211842. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211843. {
  211844. ComSmartPtr<IPropertyStorage> prop;
  211845. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211846. return defaultReturn;
  211847. PROPSPEC iPropSpec;
  211848. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211849. iPropSpec.lpwstr = name;
  211850. PROPVARIANT iPropVariant;
  211851. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211852. ? defaultReturn : (int) iPropVariant.lVal;
  211853. }
  211854. bool setIntProperty (const LPOLESTR name, const int value) const
  211855. {
  211856. ComSmartPtr<IPropertyStorage> prop;
  211857. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211858. return false;
  211859. PROPSPEC iPropSpec;
  211860. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211861. iPropSpec.lpwstr = name;
  211862. PROPVARIANT iPropVariant;
  211863. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211864. return false;
  211865. iPropVariant.lVal = (long) value;
  211866. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211867. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211868. }
  211869. void timerCallback()
  211870. {
  211871. const DiskState state = getDiskState();
  211872. if (state != lastState)
  211873. {
  211874. lastState = state;
  211875. owner.sendChangeMessage();
  211876. }
  211877. }
  211878. AudioCDBurner& owner;
  211879. DiskState lastState;
  211880. IDiscMaster* discMaster;
  211881. IDiscRecorder* discRecorder;
  211882. IRedbookDiscMaster* redbook;
  211883. AudioCDBurner::BurnProgressListener* listener;
  211884. float progress;
  211885. bool shouldCancel;
  211886. };
  211887. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211888. {
  211889. IDiscMaster* discMaster = 0;
  211890. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211891. if (discRecorder != 0)
  211892. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211893. }
  211894. AudioCDBurner::~AudioCDBurner()
  211895. {
  211896. if (pimpl != 0)
  211897. pimpl.release()->releaseObjects();
  211898. }
  211899. const StringArray AudioCDBurner::findAvailableDevices()
  211900. {
  211901. StringArray devs;
  211902. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211903. return devs;
  211904. }
  211905. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211906. {
  211907. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211908. if (b->pimpl == 0)
  211909. b = 0;
  211910. return b.release();
  211911. }
  211912. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211913. {
  211914. return pimpl->getDiskState();
  211915. }
  211916. bool AudioCDBurner::isDiskPresent() const
  211917. {
  211918. return getDiskState() == writableDiskPresent;
  211919. }
  211920. bool AudioCDBurner::openTray()
  211921. {
  211922. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211923. return SUCCEEDED (pimpl->discRecorder->Eject());
  211924. }
  211925. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211926. {
  211927. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211928. DiskState oldState = getDiskState();
  211929. DiskState newState = oldState;
  211930. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211931. {
  211932. newState = getDiskState();
  211933. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211934. }
  211935. return newState;
  211936. }
  211937. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211938. {
  211939. Array<int> results;
  211940. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211941. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211942. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211943. if (speeds[i] <= maxSpeed)
  211944. results.add (speeds[i]);
  211945. results.addIfNotAlreadyThere (maxSpeed);
  211946. return results;
  211947. }
  211948. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211949. {
  211950. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211951. return false;
  211952. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211953. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211954. }
  211955. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211956. {
  211957. long blocksFree = 0;
  211958. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211959. return blocksFree;
  211960. }
  211961. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211962. bool performFakeBurnForTesting, int writeSpeed)
  211963. {
  211964. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211965. pimpl->listener = listener;
  211966. pimpl->progress = 0;
  211967. pimpl->shouldCancel = false;
  211968. UINT_PTR cookie;
  211969. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211970. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211971. ejectDiscAfterwards);
  211972. String error;
  211973. if (hr != S_OK)
  211974. {
  211975. const char* e = "Couldn't open or write to the CD device";
  211976. if (hr == IMAPI_E_USERABORT)
  211977. e = "User cancelled the write operation";
  211978. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211979. e = "No Disk present";
  211980. error = e;
  211981. }
  211982. pimpl->discMaster->ProgressUnadvise (cookie);
  211983. pimpl->listener = 0;
  211984. return error;
  211985. }
  211986. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211987. {
  211988. if (audioSource == 0)
  211989. return false;
  211990. ScopedPointer<AudioSource> source (audioSource);
  211991. long bytesPerBlock;
  211992. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211993. const int samplesPerBlock = bytesPerBlock / 4;
  211994. bool ok = true;
  211995. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  211996. HeapBlock <byte> buffer (bytesPerBlock);
  211997. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  211998. int samplesDone = 0;
  211999. source->prepareToPlay (samplesPerBlock, 44100.0);
  212000. while (ok)
  212001. {
  212002. {
  212003. AudioSourceChannelInfo info;
  212004. info.buffer = &sourceBuffer;
  212005. info.numSamples = samplesPerBlock;
  212006. info.startSample = 0;
  212007. sourceBuffer.clear();
  212008. source->getNextAudioBlock (info);
  212009. }
  212010. zeromem (buffer, bytesPerBlock);
  212011. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212012. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212013. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212014. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212015. CDSampleFormat left (buffer, 2);
  212016. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212017. CDSampleFormat right (buffer + 2, 2);
  212018. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212019. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212020. if (FAILED (hr))
  212021. ok = false;
  212022. samplesDone += samplesPerBlock;
  212023. if (samplesDone >= numSamples)
  212024. break;
  212025. }
  212026. hr = pimpl->redbook->CloseAudioTrack();
  212027. return ok && hr == S_OK;
  212028. }
  212029. #endif
  212030. #endif
  212031. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212032. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212033. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212034. // compiled on its own).
  212035. #if JUCE_INCLUDED_FILE
  212036. class MidiInCollector
  212037. {
  212038. public:
  212039. MidiInCollector (MidiInput* const input_,
  212040. MidiInputCallback& callback_)
  212041. : deviceHandle (0),
  212042. input (input_),
  212043. callback (callback_),
  212044. concatenator (4096),
  212045. isStarted (false),
  212046. startTime (0)
  212047. {
  212048. }
  212049. ~MidiInCollector()
  212050. {
  212051. stop();
  212052. if (deviceHandle != 0)
  212053. {
  212054. int count = 5;
  212055. while (--count >= 0)
  212056. {
  212057. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212058. break;
  212059. Sleep (20);
  212060. }
  212061. }
  212062. }
  212063. void handleMessage (const uint32 message, const uint32 timeStamp)
  212064. {
  212065. if ((message & 0xff) >= 0x80 && isStarted)
  212066. {
  212067. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212068. writeFinishedBlocks();
  212069. }
  212070. }
  212071. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212072. {
  212073. if (isStarted)
  212074. {
  212075. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212076. writeFinishedBlocks();
  212077. }
  212078. }
  212079. void start()
  212080. {
  212081. jassert (deviceHandle != 0);
  212082. if (deviceHandle != 0 && ! isStarted)
  212083. {
  212084. activeMidiCollectors.addIfNotAlreadyThere (this);
  212085. for (int i = 0; i < (int) numHeaders; ++i)
  212086. headers[i].write (deviceHandle);
  212087. startTime = Time::getMillisecondCounter();
  212088. MMRESULT res = midiInStart (deviceHandle);
  212089. if (res == MMSYSERR_NOERROR)
  212090. {
  212091. concatenator.reset();
  212092. isStarted = true;
  212093. }
  212094. else
  212095. {
  212096. unprepareAllHeaders();
  212097. }
  212098. }
  212099. }
  212100. void stop()
  212101. {
  212102. if (isStarted)
  212103. {
  212104. isStarted = false;
  212105. midiInReset (deviceHandle);
  212106. midiInStop (deviceHandle);
  212107. activeMidiCollectors.removeValue (this);
  212108. unprepareAllHeaders();
  212109. concatenator.reset();
  212110. }
  212111. }
  212112. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212113. {
  212114. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212115. if (activeMidiCollectors.contains (collector))
  212116. {
  212117. if (uMsg == MIM_DATA)
  212118. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212119. else if (uMsg == MIM_LONGDATA)
  212120. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212121. }
  212122. }
  212123. HMIDIIN deviceHandle;
  212124. private:
  212125. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212126. MidiInput* input;
  212127. MidiInputCallback& callback;
  212128. MidiDataConcatenator concatenator;
  212129. bool volatile isStarted;
  212130. uint32 startTime;
  212131. class MidiHeader
  212132. {
  212133. public:
  212134. MidiHeader()
  212135. {
  212136. zerostruct (hdr);
  212137. hdr.lpData = data;
  212138. hdr.dwBufferLength = numElementsInArray (data);
  212139. }
  212140. void write (HMIDIIN deviceHandle)
  212141. {
  212142. hdr.dwBytesRecorded = 0;
  212143. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212144. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212145. }
  212146. void writeIfFinished (HMIDIIN deviceHandle)
  212147. {
  212148. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212149. {
  212150. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212151. (void) res;
  212152. write (deviceHandle);
  212153. }
  212154. }
  212155. void unprepare (HMIDIIN deviceHandle)
  212156. {
  212157. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212158. {
  212159. int c = 10;
  212160. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212161. Thread::sleep (20);
  212162. jassert (c >= 0);
  212163. }
  212164. }
  212165. private:
  212166. MIDIHDR hdr;
  212167. char data [256];
  212168. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  212169. };
  212170. enum { numHeaders = 32 };
  212171. MidiHeader headers [numHeaders];
  212172. void writeFinishedBlocks()
  212173. {
  212174. for (int i = 0; i < (int) numHeaders; ++i)
  212175. headers[i].writeIfFinished (deviceHandle);
  212176. }
  212177. void unprepareAllHeaders()
  212178. {
  212179. for (int i = 0; i < (int) numHeaders; ++i)
  212180. headers[i].unprepare (deviceHandle);
  212181. }
  212182. double convertTimeStamp (uint32 timeStamp)
  212183. {
  212184. timeStamp += startTime;
  212185. const uint32 now = Time::getMillisecondCounter();
  212186. if (timeStamp > now)
  212187. {
  212188. if (timeStamp > now + 2)
  212189. --startTime;
  212190. timeStamp = now;
  212191. }
  212192. return timeStamp * 0.001;
  212193. }
  212194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  212195. };
  212196. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212197. const StringArray MidiInput::getDevices()
  212198. {
  212199. StringArray s;
  212200. const int num = midiInGetNumDevs();
  212201. for (int i = 0; i < num; ++i)
  212202. {
  212203. MIDIINCAPS mc;
  212204. zerostruct (mc);
  212205. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212206. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212207. }
  212208. return s;
  212209. }
  212210. int MidiInput::getDefaultDeviceIndex()
  212211. {
  212212. return 0;
  212213. }
  212214. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212215. {
  212216. if (callback == 0)
  212217. return 0;
  212218. UINT deviceId = MIDI_MAPPER;
  212219. int n = 0;
  212220. String name;
  212221. const int num = midiInGetNumDevs();
  212222. for (int i = 0; i < num; ++i)
  212223. {
  212224. MIDIINCAPS mc;
  212225. zerostruct (mc);
  212226. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212227. {
  212228. if (index == n)
  212229. {
  212230. deviceId = i;
  212231. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212232. break;
  212233. }
  212234. ++n;
  212235. }
  212236. }
  212237. ScopedPointer <MidiInput> in (new MidiInput (name));
  212238. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212239. HMIDIIN h;
  212240. HRESULT err = midiInOpen (&h, deviceId,
  212241. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212242. (DWORD_PTR) (MidiInCollector*) collector,
  212243. CALLBACK_FUNCTION);
  212244. if (err == MMSYSERR_NOERROR)
  212245. {
  212246. collector->deviceHandle = h;
  212247. in->internal = collector.release();
  212248. return in.release();
  212249. }
  212250. return 0;
  212251. }
  212252. MidiInput::MidiInput (const String& name_)
  212253. : name (name_),
  212254. internal (0)
  212255. {
  212256. }
  212257. MidiInput::~MidiInput()
  212258. {
  212259. delete static_cast <MidiInCollector*> (internal);
  212260. }
  212261. void MidiInput::start()
  212262. {
  212263. static_cast <MidiInCollector*> (internal)->start();
  212264. }
  212265. void MidiInput::stop()
  212266. {
  212267. static_cast <MidiInCollector*> (internal)->stop();
  212268. }
  212269. struct MidiOutHandle
  212270. {
  212271. int refCount;
  212272. UINT deviceId;
  212273. HMIDIOUT handle;
  212274. static Array<MidiOutHandle*> activeHandles;
  212275. private:
  212276. JUCE_LEAK_DETECTOR (MidiOutHandle);
  212277. };
  212278. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212279. const StringArray MidiOutput::getDevices()
  212280. {
  212281. StringArray s;
  212282. const int num = midiOutGetNumDevs();
  212283. for (int i = 0; i < num; ++i)
  212284. {
  212285. MIDIOUTCAPS mc;
  212286. zerostruct (mc);
  212287. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212288. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212289. }
  212290. return s;
  212291. }
  212292. int MidiOutput::getDefaultDeviceIndex()
  212293. {
  212294. const int num = midiOutGetNumDevs();
  212295. int n = 0;
  212296. for (int i = 0; i < num; ++i)
  212297. {
  212298. MIDIOUTCAPS mc;
  212299. zerostruct (mc);
  212300. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212301. {
  212302. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212303. return n;
  212304. ++n;
  212305. }
  212306. }
  212307. return 0;
  212308. }
  212309. MidiOutput* MidiOutput::openDevice (int index)
  212310. {
  212311. UINT deviceId = MIDI_MAPPER;
  212312. const int num = midiOutGetNumDevs();
  212313. int i, n = 0;
  212314. for (i = 0; i < num; ++i)
  212315. {
  212316. MIDIOUTCAPS mc;
  212317. zerostruct (mc);
  212318. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212319. {
  212320. // use the microsoft sw synth as a default - best not to allow deviceId
  212321. // to be MIDI_MAPPER, or else device sharing breaks
  212322. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212323. deviceId = i;
  212324. if (index == n)
  212325. {
  212326. deviceId = i;
  212327. break;
  212328. }
  212329. ++n;
  212330. }
  212331. }
  212332. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212333. {
  212334. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212335. if (han != 0 && han->deviceId == deviceId)
  212336. {
  212337. han->refCount++;
  212338. MidiOutput* const out = new MidiOutput();
  212339. out->internal = han;
  212340. return out;
  212341. }
  212342. }
  212343. for (i = 4; --i >= 0;)
  212344. {
  212345. HMIDIOUT h = 0;
  212346. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212347. if (res == MMSYSERR_NOERROR)
  212348. {
  212349. MidiOutHandle* const han = new MidiOutHandle();
  212350. han->deviceId = deviceId;
  212351. han->refCount = 1;
  212352. han->handle = h;
  212353. MidiOutHandle::activeHandles.add (han);
  212354. MidiOutput* const out = new MidiOutput();
  212355. out->internal = han;
  212356. return out;
  212357. }
  212358. else if (res == MMSYSERR_ALLOCATED)
  212359. {
  212360. Sleep (100);
  212361. }
  212362. else
  212363. {
  212364. break;
  212365. }
  212366. }
  212367. return 0;
  212368. }
  212369. MidiOutput::~MidiOutput()
  212370. {
  212371. stopBackgroundThread();
  212372. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212373. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212374. {
  212375. midiOutClose (h->handle);
  212376. MidiOutHandle::activeHandles.removeValue (h);
  212377. delete h;
  212378. }
  212379. }
  212380. void MidiOutput::reset()
  212381. {
  212382. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212383. midiOutReset (h->handle);
  212384. }
  212385. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212386. {
  212387. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212388. DWORD n;
  212389. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212390. {
  212391. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212392. rightVol = nn[0] / (float) 0xffff;
  212393. leftVol = nn[1] / (float) 0xffff;
  212394. return true;
  212395. }
  212396. else
  212397. {
  212398. rightVol = leftVol = 1.0f;
  212399. return false;
  212400. }
  212401. }
  212402. void MidiOutput::setVolume (float leftVol, float rightVol)
  212403. {
  212404. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212405. DWORD n;
  212406. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212407. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212408. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212409. midiOutSetVolume (handle->handle, n);
  212410. }
  212411. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212412. {
  212413. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212414. if (message.getRawDataSize() > 3
  212415. || message.isSysEx())
  212416. {
  212417. MIDIHDR h;
  212418. zerostruct (h);
  212419. h.lpData = (char*) message.getRawData();
  212420. h.dwBufferLength = message.getRawDataSize();
  212421. h.dwBytesRecorded = message.getRawDataSize();
  212422. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212423. {
  212424. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212425. if (res == MMSYSERR_NOERROR)
  212426. {
  212427. while ((h.dwFlags & MHDR_DONE) == 0)
  212428. Sleep (1);
  212429. int count = 500; // 1 sec timeout
  212430. while (--count >= 0)
  212431. {
  212432. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212433. if (res == MIDIERR_STILLPLAYING)
  212434. Sleep (2);
  212435. else
  212436. break;
  212437. }
  212438. }
  212439. }
  212440. }
  212441. else
  212442. {
  212443. midiOutShortMsg (handle->handle,
  212444. *(unsigned int*) message.getRawData());
  212445. }
  212446. }
  212447. #endif
  212448. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212449. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212450. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212451. // compiled on its own).
  212452. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212453. #undef WINDOWS
  212454. // #define ASIO_DEBUGGING 1
  212455. #undef log
  212456. #if ASIO_DEBUGGING
  212457. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212458. #else
  212459. #define log(a) {}
  212460. #endif
  212461. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212462. to be pretty random about whether or not they do this. If you hit an error using these functions
  212463. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212464. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212465. */
  212466. #define JUCE_ASIOCALLBACK __cdecl
  212467. namespace ASIODebugging
  212468. {
  212469. #if ASIO_DEBUGGING
  212470. static void log (const String& context, long error)
  212471. {
  212472. String err ("unknown error");
  212473. if (error == ASE_NotPresent) err = "Not Present";
  212474. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212475. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212476. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212477. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212478. else if (error == ASE_NoClock) err = "No Clock";
  212479. else if (error == ASE_NoMemory) err = "Out of memory";
  212480. log ("!!error: " + context + " - " + err);
  212481. }
  212482. #define logError(a, b) ASIODebugging::log ((a), (b))
  212483. #else
  212484. #define logError(a, b) {}
  212485. #endif
  212486. }
  212487. class ASIOAudioIODevice;
  212488. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212489. static const int maxASIOChannels = 160;
  212490. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212491. private Timer
  212492. {
  212493. public:
  212494. Component ourWindow;
  212495. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212496. const String& optionalDllForDirectLoading_)
  212497. : AudioIODevice (name_, "ASIO"),
  212498. asioObject (0),
  212499. classId (classId_),
  212500. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212501. currentBitDepth (16),
  212502. currentSampleRate (0),
  212503. isOpen_ (false),
  212504. isStarted (false),
  212505. postOutput (true),
  212506. insideControlPanelModalLoop (false),
  212507. shouldUsePreferredSize (false)
  212508. {
  212509. name = name_;
  212510. ourWindow.addToDesktop (0);
  212511. windowHandle = ourWindow.getWindowHandle();
  212512. jassert (currentASIODev [slotNumber] == 0);
  212513. currentASIODev [slotNumber] = this;
  212514. openDevice();
  212515. }
  212516. ~ASIOAudioIODevice()
  212517. {
  212518. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212519. if (currentASIODev[i] == this)
  212520. currentASIODev[i] = 0;
  212521. close();
  212522. log ("ASIO - exiting");
  212523. removeCurrentDriver();
  212524. }
  212525. void updateSampleRates()
  212526. {
  212527. // find a list of sample rates..
  212528. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212529. sampleRates.clear();
  212530. if (asioObject != 0)
  212531. {
  212532. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212533. {
  212534. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212535. if (err == 0)
  212536. {
  212537. sampleRates.add ((int) possibleSampleRates[index]);
  212538. log ("rate: " + String ((int) possibleSampleRates[index]));
  212539. }
  212540. else if (err != ASE_NoClock)
  212541. {
  212542. logError ("CanSampleRate", err);
  212543. }
  212544. }
  212545. if (sampleRates.size() == 0)
  212546. {
  212547. double cr = 0;
  212548. const long err = asioObject->getSampleRate (&cr);
  212549. log ("No sample rates supported - current rate: " + String ((int) cr));
  212550. if (err == 0)
  212551. sampleRates.add ((int) cr);
  212552. }
  212553. }
  212554. }
  212555. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212556. const StringArray getInputChannelNames() { return inputChannelNames; }
  212557. int getNumSampleRates() { return sampleRates.size(); }
  212558. double getSampleRate (int index) { return sampleRates [index]; }
  212559. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212560. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212561. int getDefaultBufferSize() { return preferredSize; }
  212562. const String open (const BigInteger& inputChannels,
  212563. const BigInteger& outputChannels,
  212564. double sr,
  212565. int bufferSizeSamples)
  212566. {
  212567. close();
  212568. currentCallback = 0;
  212569. if (bufferSizeSamples <= 0)
  212570. shouldUsePreferredSize = true;
  212571. if (asioObject == 0 || ! isASIOOpen)
  212572. {
  212573. log ("Warning: device not open");
  212574. const String err (openDevice());
  212575. if (asioObject == 0 || ! isASIOOpen)
  212576. return err;
  212577. }
  212578. isStarted = false;
  212579. bufferIndex = -1;
  212580. long err = 0;
  212581. long newPreferredSize = 0;
  212582. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212583. minSize = 0;
  212584. maxSize = 0;
  212585. newPreferredSize = 0;
  212586. granularity = 0;
  212587. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212588. {
  212589. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212590. shouldUsePreferredSize = true;
  212591. preferredSize = newPreferredSize;
  212592. }
  212593. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212594. // dynamic changes to the buffer size...
  212595. shouldUsePreferredSize = shouldUsePreferredSize
  212596. || getName().containsIgnoreCase ("Digidesign");
  212597. if (shouldUsePreferredSize)
  212598. {
  212599. log ("Using preferred size for buffer..");
  212600. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212601. {
  212602. bufferSizeSamples = preferredSize;
  212603. }
  212604. else
  212605. {
  212606. bufferSizeSamples = 1024;
  212607. logError ("GetBufferSize1", err);
  212608. }
  212609. shouldUsePreferredSize = false;
  212610. }
  212611. int sampleRate = roundDoubleToInt (sr);
  212612. currentSampleRate = sampleRate;
  212613. currentBlockSizeSamples = bufferSizeSamples;
  212614. currentChansOut.clear();
  212615. currentChansIn.clear();
  212616. zeromem (inBuffers, sizeof (inBuffers));
  212617. zeromem (outBuffers, sizeof (outBuffers));
  212618. updateSampleRates();
  212619. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212620. sampleRate = sampleRates[0];
  212621. jassert (sampleRate != 0);
  212622. if (sampleRate == 0)
  212623. sampleRate = 44100;
  212624. long numSources = 32;
  212625. ASIOClockSource clocks[32];
  212626. zeromem (clocks, sizeof (clocks));
  212627. asioObject->getClockSources (clocks, &numSources);
  212628. bool isSourceSet = false;
  212629. // careful not to remove this loop because it does more than just logging!
  212630. int i;
  212631. for (i = 0; i < numSources; ++i)
  212632. {
  212633. String s ("clock: ");
  212634. s += clocks[i].name;
  212635. if (clocks[i].isCurrentSource)
  212636. {
  212637. isSourceSet = true;
  212638. s << " (cur)";
  212639. }
  212640. log (s);
  212641. }
  212642. if (numSources > 1 && ! isSourceSet)
  212643. {
  212644. log ("setting clock source");
  212645. asioObject->setClockSource (clocks[0].index);
  212646. Thread::sleep (20);
  212647. }
  212648. else
  212649. {
  212650. if (numSources == 0)
  212651. {
  212652. log ("ASIO - no clock sources!");
  212653. }
  212654. }
  212655. double cr = 0;
  212656. err = asioObject->getSampleRate (&cr);
  212657. if (err == 0)
  212658. {
  212659. currentSampleRate = cr;
  212660. }
  212661. else
  212662. {
  212663. logError ("GetSampleRate", err);
  212664. currentSampleRate = 0;
  212665. }
  212666. error = String::empty;
  212667. needToReset = false;
  212668. isReSync = false;
  212669. err = 0;
  212670. bool buffersCreated = false;
  212671. if (currentSampleRate != sampleRate)
  212672. {
  212673. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212674. err = asioObject->setSampleRate (sampleRate);
  212675. if (err == ASE_NoClock && numSources > 0)
  212676. {
  212677. log ("trying to set a clock source..");
  212678. Thread::sleep (10);
  212679. err = asioObject->setClockSource (clocks[0].index);
  212680. if (err != 0)
  212681. {
  212682. logError ("SetClock", err);
  212683. }
  212684. Thread::sleep (10);
  212685. err = asioObject->setSampleRate (sampleRate);
  212686. }
  212687. }
  212688. if (err == 0)
  212689. {
  212690. currentSampleRate = sampleRate;
  212691. if (needToReset)
  212692. {
  212693. if (isReSync)
  212694. {
  212695. log ("Resync request");
  212696. }
  212697. log ("! Resetting ASIO after sample rate change");
  212698. removeCurrentDriver();
  212699. loadDriver();
  212700. const String error (initDriver());
  212701. if (error.isNotEmpty())
  212702. {
  212703. log ("ASIOInit: " + error);
  212704. }
  212705. needToReset = false;
  212706. isReSync = false;
  212707. }
  212708. numActiveInputChans = 0;
  212709. numActiveOutputChans = 0;
  212710. ASIOBufferInfo* info = bufferInfos;
  212711. int i;
  212712. for (i = 0; i < totalNumInputChans; ++i)
  212713. {
  212714. if (inputChannels[i])
  212715. {
  212716. currentChansIn.setBit (i);
  212717. info->isInput = 1;
  212718. info->channelNum = i;
  212719. info->buffers[0] = info->buffers[1] = 0;
  212720. ++info;
  212721. ++numActiveInputChans;
  212722. }
  212723. }
  212724. for (i = 0; i < totalNumOutputChans; ++i)
  212725. {
  212726. if (outputChannels[i])
  212727. {
  212728. currentChansOut.setBit (i);
  212729. info->isInput = 0;
  212730. info->channelNum = i;
  212731. info->buffers[0] = info->buffers[1] = 0;
  212732. ++info;
  212733. ++numActiveOutputChans;
  212734. }
  212735. }
  212736. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212737. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212738. if (currentASIODev[0] == this)
  212739. {
  212740. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212741. callbacks.asioMessage = &asioMessagesCallback0;
  212742. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212743. }
  212744. else if (currentASIODev[1] == this)
  212745. {
  212746. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212747. callbacks.asioMessage = &asioMessagesCallback1;
  212748. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212749. }
  212750. else if (currentASIODev[2] == this)
  212751. {
  212752. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212753. callbacks.asioMessage = &asioMessagesCallback2;
  212754. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212755. }
  212756. else
  212757. {
  212758. jassertfalse;
  212759. }
  212760. log ("disposing buffers");
  212761. err = asioObject->disposeBuffers();
  212762. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212763. err = asioObject->createBuffers (bufferInfos,
  212764. totalBuffers,
  212765. currentBlockSizeSamples,
  212766. &callbacks);
  212767. if (err != 0)
  212768. {
  212769. currentBlockSizeSamples = preferredSize;
  212770. logError ("create buffers 2", err);
  212771. asioObject->disposeBuffers();
  212772. err = asioObject->createBuffers (bufferInfos,
  212773. totalBuffers,
  212774. currentBlockSizeSamples,
  212775. &callbacks);
  212776. }
  212777. if (err == 0)
  212778. {
  212779. buffersCreated = true;
  212780. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212781. int n = 0;
  212782. Array <int> types;
  212783. currentBitDepth = 16;
  212784. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212785. {
  212786. if (inputChannels[i])
  212787. {
  212788. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212789. ASIOChannelInfo channelInfo;
  212790. zerostruct (channelInfo);
  212791. channelInfo.channel = i;
  212792. channelInfo.isInput = 1;
  212793. asioObject->getChannelInfo (&channelInfo);
  212794. types.addIfNotAlreadyThere (channelInfo.type);
  212795. typeToFormatParameters (channelInfo.type,
  212796. inputChannelBitDepths[n],
  212797. inputChannelBytesPerSample[n],
  212798. inputChannelIsFloat[n],
  212799. inputChannelLittleEndian[n]);
  212800. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212801. ++n;
  212802. }
  212803. }
  212804. jassert (numActiveInputChans == n);
  212805. n = 0;
  212806. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212807. {
  212808. if (outputChannels[i])
  212809. {
  212810. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212811. ASIOChannelInfo channelInfo;
  212812. zerostruct (channelInfo);
  212813. channelInfo.channel = i;
  212814. channelInfo.isInput = 0;
  212815. asioObject->getChannelInfo (&channelInfo);
  212816. types.addIfNotAlreadyThere (channelInfo.type);
  212817. typeToFormatParameters (channelInfo.type,
  212818. outputChannelBitDepths[n],
  212819. outputChannelBytesPerSample[n],
  212820. outputChannelIsFloat[n],
  212821. outputChannelLittleEndian[n]);
  212822. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212823. ++n;
  212824. }
  212825. }
  212826. jassert (numActiveOutputChans == n);
  212827. for (i = types.size(); --i >= 0;)
  212828. {
  212829. log ("channel format: " + String (types[i]));
  212830. }
  212831. jassert (n <= totalBuffers);
  212832. for (i = 0; i < numActiveOutputChans; ++i)
  212833. {
  212834. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212835. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212836. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212837. {
  212838. log ("!! Null buffers");
  212839. }
  212840. else
  212841. {
  212842. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212843. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212844. }
  212845. }
  212846. inputLatency = outputLatency = 0;
  212847. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212848. {
  212849. log ("ASIO - no latencies");
  212850. }
  212851. else
  212852. {
  212853. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212854. }
  212855. isOpen_ = true;
  212856. log ("starting ASIO");
  212857. calledback = false;
  212858. err = asioObject->start();
  212859. if (err != 0)
  212860. {
  212861. isOpen_ = false;
  212862. log ("ASIO - stop on failure");
  212863. Thread::sleep (10);
  212864. asioObject->stop();
  212865. error = "Can't start device";
  212866. Thread::sleep (10);
  212867. }
  212868. else
  212869. {
  212870. int count = 300;
  212871. while (--count > 0 && ! calledback)
  212872. Thread::sleep (10);
  212873. isStarted = true;
  212874. if (! calledback)
  212875. {
  212876. error = "Device didn't start correctly";
  212877. log ("ASIO didn't callback - stopping..");
  212878. asioObject->stop();
  212879. }
  212880. }
  212881. }
  212882. else
  212883. {
  212884. error = "Can't create i/o buffers";
  212885. }
  212886. }
  212887. else
  212888. {
  212889. error = "Can't set sample rate: ";
  212890. error << sampleRate;
  212891. }
  212892. if (error.isNotEmpty())
  212893. {
  212894. logError (error, err);
  212895. if (asioObject != 0 && buffersCreated)
  212896. asioObject->disposeBuffers();
  212897. Thread::sleep (20);
  212898. isStarted = false;
  212899. isOpen_ = false;
  212900. const String errorCopy (error);
  212901. close(); // (this resets the error string)
  212902. error = errorCopy;
  212903. }
  212904. needToReset = false;
  212905. isReSync = false;
  212906. return error;
  212907. }
  212908. void close()
  212909. {
  212910. error = String::empty;
  212911. stopTimer();
  212912. stop();
  212913. if (isASIOOpen && isOpen_)
  212914. {
  212915. const ScopedLock sl (callbackLock);
  212916. isOpen_ = false;
  212917. isStarted = false;
  212918. needToReset = false;
  212919. isReSync = false;
  212920. log ("ASIO - stopping");
  212921. if (asioObject != 0)
  212922. {
  212923. Thread::sleep (20);
  212924. asioObject->stop();
  212925. Thread::sleep (10);
  212926. asioObject->disposeBuffers();
  212927. }
  212928. Thread::sleep (10);
  212929. }
  212930. }
  212931. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212932. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212933. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212934. double getCurrentSampleRate() { return currentSampleRate; }
  212935. int getCurrentBitDepth() { return currentBitDepth; }
  212936. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212937. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212938. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212939. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212940. void start (AudioIODeviceCallback* callback)
  212941. {
  212942. if (callback != 0)
  212943. {
  212944. callback->audioDeviceAboutToStart (this);
  212945. const ScopedLock sl (callbackLock);
  212946. currentCallback = callback;
  212947. }
  212948. }
  212949. void stop()
  212950. {
  212951. AudioIODeviceCallback* const lastCallback = currentCallback;
  212952. {
  212953. const ScopedLock sl (callbackLock);
  212954. currentCallback = 0;
  212955. }
  212956. if (lastCallback != 0)
  212957. lastCallback->audioDeviceStopped();
  212958. }
  212959. const String getLastError() { return error; }
  212960. bool hasControlPanel() const { return true; }
  212961. bool showControlPanel()
  212962. {
  212963. log ("ASIO - showing control panel");
  212964. Component modalWindow (String::empty);
  212965. modalWindow.setOpaque (true);
  212966. modalWindow.addToDesktop (0);
  212967. modalWindow.enterModalState();
  212968. bool done = false;
  212969. JUCE_TRY
  212970. {
  212971. // are there are devices that need to be closed before showing their control panel?
  212972. // close();
  212973. insideControlPanelModalLoop = true;
  212974. const uint32 started = Time::getMillisecondCounter();
  212975. if (asioObject != 0)
  212976. {
  212977. asioObject->controlPanel();
  212978. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212979. log ("spent: " + String (spent));
  212980. if (spent > 300)
  212981. {
  212982. shouldUsePreferredSize = true;
  212983. done = true;
  212984. }
  212985. }
  212986. }
  212987. JUCE_CATCH_ALL
  212988. insideControlPanelModalLoop = false;
  212989. return done;
  212990. }
  212991. void resetRequest() throw()
  212992. {
  212993. needToReset = true;
  212994. }
  212995. void resyncRequest() throw()
  212996. {
  212997. needToReset = true;
  212998. isReSync = true;
  212999. }
  213000. void timerCallback()
  213001. {
  213002. if (! insideControlPanelModalLoop)
  213003. {
  213004. stopTimer();
  213005. // used to cause a reset
  213006. log ("! ASIO restart request!");
  213007. if (isOpen_)
  213008. {
  213009. AudioIODeviceCallback* const oldCallback = currentCallback;
  213010. close();
  213011. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213012. currentSampleRate, currentBlockSizeSamples);
  213013. if (oldCallback != 0)
  213014. start (oldCallback);
  213015. }
  213016. }
  213017. else
  213018. {
  213019. startTimer (100);
  213020. }
  213021. }
  213022. private:
  213023. IASIO* volatile asioObject;
  213024. ASIOCallbacks callbacks;
  213025. void* windowHandle;
  213026. CLSID classId;
  213027. const String optionalDllForDirectLoading;
  213028. String error;
  213029. long totalNumInputChans, totalNumOutputChans;
  213030. StringArray inputChannelNames, outputChannelNames;
  213031. Array<int> sampleRates, bufferSizes;
  213032. long inputLatency, outputLatency;
  213033. long minSize, maxSize, preferredSize, granularity;
  213034. int volatile currentBlockSizeSamples;
  213035. int volatile currentBitDepth;
  213036. double volatile currentSampleRate;
  213037. BigInteger currentChansOut, currentChansIn;
  213038. AudioIODeviceCallback* volatile currentCallback;
  213039. CriticalSection callbackLock;
  213040. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213041. float* inBuffers [maxASIOChannels];
  213042. float* outBuffers [maxASIOChannels];
  213043. int inputChannelBitDepths [maxASIOChannels];
  213044. int outputChannelBitDepths [maxASIOChannels];
  213045. int inputChannelBytesPerSample [maxASIOChannels];
  213046. int outputChannelBytesPerSample [maxASIOChannels];
  213047. bool inputChannelIsFloat [maxASIOChannels];
  213048. bool outputChannelIsFloat [maxASIOChannels];
  213049. bool inputChannelLittleEndian [maxASIOChannels];
  213050. bool outputChannelLittleEndian [maxASIOChannels];
  213051. WaitableEvent event1;
  213052. HeapBlock <float> tempBuffer;
  213053. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213054. bool isOpen_, isStarted;
  213055. bool volatile isASIOOpen;
  213056. bool volatile calledback;
  213057. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213058. bool volatile insideControlPanelModalLoop;
  213059. bool volatile shouldUsePreferredSize;
  213060. void removeCurrentDriver()
  213061. {
  213062. if (asioObject != 0)
  213063. {
  213064. asioObject->Release();
  213065. asioObject = 0;
  213066. }
  213067. }
  213068. bool loadDriver()
  213069. {
  213070. removeCurrentDriver();
  213071. JUCE_TRY
  213072. {
  213073. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213074. classId, (void**) &asioObject) == S_OK)
  213075. {
  213076. return true;
  213077. }
  213078. // If a class isn't registered but we have a path for it, we can fallback to
  213079. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213080. if (optionalDllForDirectLoading.isNotEmpty())
  213081. {
  213082. HMODULE h = LoadLibrary (optionalDllForDirectLoading.toUTF16());
  213083. if (h != 0)
  213084. {
  213085. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213086. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213087. if (dllGetClassObject != 0)
  213088. {
  213089. IClassFactory* classFactory = 0;
  213090. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213091. if (classFactory != 0)
  213092. {
  213093. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213094. classFactory->Release();
  213095. }
  213096. return asioObject != 0;
  213097. }
  213098. }
  213099. }
  213100. }
  213101. JUCE_CATCH_ALL
  213102. asioObject = 0;
  213103. return false;
  213104. }
  213105. const String initDriver()
  213106. {
  213107. if (asioObject != 0)
  213108. {
  213109. char buffer [256];
  213110. zeromem (buffer, sizeof (buffer));
  213111. if (! asioObject->init (windowHandle))
  213112. {
  213113. asioObject->getErrorMessage (buffer);
  213114. return String (buffer, sizeof (buffer) - 1);
  213115. }
  213116. // just in case any daft drivers expect this to be called..
  213117. asioObject->getDriverName (buffer);
  213118. return String::empty;
  213119. }
  213120. return "No Driver";
  213121. }
  213122. const String openDevice()
  213123. {
  213124. // use this in case the driver starts opening dialog boxes..
  213125. Component modalWindow (String::empty);
  213126. modalWindow.setOpaque (true);
  213127. modalWindow.addToDesktop (0);
  213128. modalWindow.enterModalState();
  213129. // open the device and get its info..
  213130. log ("opening ASIO device: " + getName());
  213131. needToReset = false;
  213132. isReSync = false;
  213133. outputChannelNames.clear();
  213134. inputChannelNames.clear();
  213135. bufferSizes.clear();
  213136. sampleRates.clear();
  213137. isASIOOpen = false;
  213138. isOpen_ = false;
  213139. totalNumInputChans = 0;
  213140. totalNumOutputChans = 0;
  213141. numActiveInputChans = 0;
  213142. numActiveOutputChans = 0;
  213143. currentCallback = 0;
  213144. error = String::empty;
  213145. if (getName().isEmpty())
  213146. return error;
  213147. long err = 0;
  213148. if (loadDriver())
  213149. {
  213150. if ((error = initDriver()).isEmpty())
  213151. {
  213152. numActiveInputChans = 0;
  213153. numActiveOutputChans = 0;
  213154. totalNumInputChans = 0;
  213155. totalNumOutputChans = 0;
  213156. if (asioObject != 0
  213157. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213158. {
  213159. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213160. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213161. {
  213162. // find a list of buffer sizes..
  213163. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213164. if (granularity >= 0)
  213165. {
  213166. granularity = jmax (1, (int) granularity);
  213167. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213168. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213169. }
  213170. else if (granularity < 0)
  213171. {
  213172. for (int i = 0; i < 18; ++i)
  213173. {
  213174. const int s = (1 << i);
  213175. if (s >= minSize && s <= maxSize)
  213176. bufferSizes.add (s);
  213177. }
  213178. }
  213179. if (! bufferSizes.contains (preferredSize))
  213180. bufferSizes.insert (0, preferredSize);
  213181. double currentRate = 0;
  213182. asioObject->getSampleRate (&currentRate);
  213183. if (currentRate <= 0.0 || currentRate > 192001.0)
  213184. {
  213185. log ("setting sample rate");
  213186. err = asioObject->setSampleRate (44100.0);
  213187. if (err != 0)
  213188. {
  213189. logError ("setting sample rate", err);
  213190. }
  213191. asioObject->getSampleRate (&currentRate);
  213192. }
  213193. currentSampleRate = currentRate;
  213194. postOutput = (asioObject->outputReady() == 0);
  213195. if (postOutput)
  213196. {
  213197. log ("ASIO outputReady = ok");
  213198. }
  213199. updateSampleRates();
  213200. // ..because cubase does it at this point
  213201. inputLatency = outputLatency = 0;
  213202. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213203. {
  213204. log ("ASIO - no latencies");
  213205. }
  213206. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213207. // create some dummy buffers now.. because cubase does..
  213208. numActiveInputChans = 0;
  213209. numActiveOutputChans = 0;
  213210. ASIOBufferInfo* info = bufferInfos;
  213211. int i, numChans = 0;
  213212. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213213. {
  213214. info->isInput = 1;
  213215. info->channelNum = i;
  213216. info->buffers[0] = info->buffers[1] = 0;
  213217. ++info;
  213218. ++numChans;
  213219. }
  213220. const int outputBufferIndex = numChans;
  213221. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213222. {
  213223. info->isInput = 0;
  213224. info->channelNum = i;
  213225. info->buffers[0] = info->buffers[1] = 0;
  213226. ++info;
  213227. ++numChans;
  213228. }
  213229. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213230. if (currentASIODev[0] == this)
  213231. {
  213232. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213233. callbacks.asioMessage = &asioMessagesCallback0;
  213234. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213235. }
  213236. else if (currentASIODev[1] == this)
  213237. {
  213238. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213239. callbacks.asioMessage = &asioMessagesCallback1;
  213240. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213241. }
  213242. else if (currentASIODev[2] == this)
  213243. {
  213244. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213245. callbacks.asioMessage = &asioMessagesCallback2;
  213246. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213247. }
  213248. else
  213249. {
  213250. jassertfalse;
  213251. }
  213252. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213253. if (preferredSize > 0)
  213254. {
  213255. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213256. if (err != 0)
  213257. {
  213258. logError ("dummy buffers", err);
  213259. }
  213260. }
  213261. long newInps = 0, newOuts = 0;
  213262. asioObject->getChannels (&newInps, &newOuts);
  213263. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213264. {
  213265. totalNumInputChans = newInps;
  213266. totalNumOutputChans = newOuts;
  213267. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213268. }
  213269. updateSampleRates();
  213270. ASIOChannelInfo channelInfo;
  213271. channelInfo.type = 0;
  213272. for (i = 0; i < totalNumInputChans; ++i)
  213273. {
  213274. zerostruct (channelInfo);
  213275. channelInfo.channel = i;
  213276. channelInfo.isInput = 1;
  213277. asioObject->getChannelInfo (&channelInfo);
  213278. inputChannelNames.add (String (channelInfo.name));
  213279. }
  213280. for (i = 0; i < totalNumOutputChans; ++i)
  213281. {
  213282. zerostruct (channelInfo);
  213283. channelInfo.channel = i;
  213284. channelInfo.isInput = 0;
  213285. asioObject->getChannelInfo (&channelInfo);
  213286. outputChannelNames.add (String (channelInfo.name));
  213287. typeToFormatParameters (channelInfo.type,
  213288. outputChannelBitDepths[i],
  213289. outputChannelBytesPerSample[i],
  213290. outputChannelIsFloat[i],
  213291. outputChannelLittleEndian[i]);
  213292. if (i < 2)
  213293. {
  213294. // clear the channels that are used with the dummy stuff
  213295. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213296. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213297. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213298. }
  213299. }
  213300. outputChannelNames.trim();
  213301. inputChannelNames.trim();
  213302. outputChannelNames.appendNumbersToDuplicates (false, true);
  213303. inputChannelNames.appendNumbersToDuplicates (false, true);
  213304. // start and stop because cubase does it..
  213305. asioObject->getLatencies (&inputLatency, &outputLatency);
  213306. if ((err = asioObject->start()) != 0)
  213307. {
  213308. // ignore an error here, as it might start later after setting other stuff up
  213309. logError ("ASIO start", err);
  213310. }
  213311. Thread::sleep (100);
  213312. asioObject->stop();
  213313. }
  213314. else
  213315. {
  213316. error = "Can't detect buffer sizes";
  213317. }
  213318. }
  213319. else
  213320. {
  213321. error = "Can't detect asio channels";
  213322. }
  213323. }
  213324. }
  213325. else
  213326. {
  213327. error = "No such device";
  213328. }
  213329. if (error.isNotEmpty())
  213330. {
  213331. logError (error, err);
  213332. if (asioObject != 0)
  213333. asioObject->disposeBuffers();
  213334. removeCurrentDriver();
  213335. isASIOOpen = false;
  213336. }
  213337. else
  213338. {
  213339. isASIOOpen = true;
  213340. log ("ASIO device open");
  213341. }
  213342. isOpen_ = false;
  213343. needToReset = false;
  213344. isReSync = false;
  213345. return error;
  213346. }
  213347. void JUCE_ASIOCALLBACK callback (const long index)
  213348. {
  213349. if (isStarted)
  213350. {
  213351. bufferIndex = index;
  213352. processBuffer();
  213353. }
  213354. else
  213355. {
  213356. if (postOutput && (asioObject != 0))
  213357. asioObject->outputReady();
  213358. }
  213359. calledback = true;
  213360. }
  213361. void processBuffer()
  213362. {
  213363. const ASIOBufferInfo* const infos = bufferInfos;
  213364. const int bi = bufferIndex;
  213365. const ScopedLock sl (callbackLock);
  213366. if (needToReset)
  213367. {
  213368. needToReset = false;
  213369. if (isReSync)
  213370. {
  213371. log ("! ASIO resync");
  213372. isReSync = false;
  213373. }
  213374. else
  213375. {
  213376. startTimer (20);
  213377. }
  213378. }
  213379. if (bi >= 0)
  213380. {
  213381. const int samps = currentBlockSizeSamples;
  213382. if (currentCallback != 0)
  213383. {
  213384. int i;
  213385. for (i = 0; i < numActiveInputChans; ++i)
  213386. {
  213387. float* const dst = inBuffers[i];
  213388. jassert (dst != 0);
  213389. const char* const src = (const char*) (infos[i].buffers[bi]);
  213390. if (inputChannelIsFloat[i])
  213391. {
  213392. memcpy (dst, src, samps * sizeof (float));
  213393. }
  213394. else
  213395. {
  213396. jassert (dst == tempBuffer + (samps * i));
  213397. switch (inputChannelBitDepths[i])
  213398. {
  213399. case 16:
  213400. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213401. samps, inputChannelLittleEndian[i]);
  213402. break;
  213403. case 24:
  213404. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213405. samps, inputChannelLittleEndian[i]);
  213406. break;
  213407. case 32:
  213408. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213409. samps, inputChannelLittleEndian[i]);
  213410. break;
  213411. case 64:
  213412. jassertfalse;
  213413. break;
  213414. }
  213415. }
  213416. }
  213417. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213418. outBuffers, numActiveOutputChans, samps);
  213419. for (i = 0; i < numActiveOutputChans; ++i)
  213420. {
  213421. float* const src = outBuffers[i];
  213422. jassert (src != 0);
  213423. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213424. if (outputChannelIsFloat[i])
  213425. {
  213426. memcpy (dst, src, samps * sizeof (float));
  213427. }
  213428. else
  213429. {
  213430. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213431. switch (outputChannelBitDepths[i])
  213432. {
  213433. case 16:
  213434. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213435. samps, outputChannelLittleEndian[i]);
  213436. break;
  213437. case 24:
  213438. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213439. samps, outputChannelLittleEndian[i]);
  213440. break;
  213441. case 32:
  213442. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213443. samps, outputChannelLittleEndian[i]);
  213444. break;
  213445. case 64:
  213446. jassertfalse;
  213447. break;
  213448. }
  213449. }
  213450. }
  213451. }
  213452. else
  213453. {
  213454. for (int i = 0; i < numActiveOutputChans; ++i)
  213455. {
  213456. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213457. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213458. }
  213459. }
  213460. }
  213461. if (postOutput)
  213462. asioObject->outputReady();
  213463. }
  213464. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213465. {
  213466. if (currentASIODev[0] != 0)
  213467. currentASIODev[0]->callback (index);
  213468. return 0;
  213469. }
  213470. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213471. {
  213472. if (currentASIODev[1] != 0)
  213473. currentASIODev[1]->callback (index);
  213474. return 0;
  213475. }
  213476. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213477. {
  213478. if (currentASIODev[2] != 0)
  213479. currentASIODev[2]->callback (index);
  213480. return 0;
  213481. }
  213482. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213483. {
  213484. if (currentASIODev[0] != 0)
  213485. currentASIODev[0]->callback (index);
  213486. }
  213487. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213488. {
  213489. if (currentASIODev[1] != 0)
  213490. currentASIODev[1]->callback (index);
  213491. }
  213492. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213493. {
  213494. if (currentASIODev[2] != 0)
  213495. currentASIODev[2]->callback (index);
  213496. }
  213497. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213498. {
  213499. return asioMessagesCallback (selector, value, 0);
  213500. }
  213501. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213502. {
  213503. return asioMessagesCallback (selector, value, 1);
  213504. }
  213505. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213506. {
  213507. return asioMessagesCallback (selector, value, 2);
  213508. }
  213509. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213510. {
  213511. switch (selector)
  213512. {
  213513. case kAsioSelectorSupported:
  213514. if (value == kAsioResetRequest
  213515. || value == kAsioEngineVersion
  213516. || value == kAsioResyncRequest
  213517. || value == kAsioLatenciesChanged
  213518. || value == kAsioSupportsInputMonitor)
  213519. return 1;
  213520. break;
  213521. case kAsioBufferSizeChange:
  213522. break;
  213523. case kAsioResetRequest:
  213524. if (currentASIODev[deviceIndex] != 0)
  213525. currentASIODev[deviceIndex]->resetRequest();
  213526. return 1;
  213527. case kAsioResyncRequest:
  213528. if (currentASIODev[deviceIndex] != 0)
  213529. currentASIODev[deviceIndex]->resyncRequest();
  213530. return 1;
  213531. case kAsioLatenciesChanged:
  213532. return 1;
  213533. case kAsioEngineVersion:
  213534. return 2;
  213535. case kAsioSupportsTimeInfo:
  213536. case kAsioSupportsTimeCode:
  213537. return 0;
  213538. }
  213539. return 0;
  213540. }
  213541. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213542. {
  213543. }
  213544. static void convertInt16ToFloat (const char* src,
  213545. float* dest,
  213546. const int srcStrideBytes,
  213547. int numSamples,
  213548. const bool littleEndian) throw()
  213549. {
  213550. const double g = 1.0 / 32768.0;
  213551. if (littleEndian)
  213552. {
  213553. while (--numSamples >= 0)
  213554. {
  213555. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213556. src += srcStrideBytes;
  213557. }
  213558. }
  213559. else
  213560. {
  213561. while (--numSamples >= 0)
  213562. {
  213563. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213564. src += srcStrideBytes;
  213565. }
  213566. }
  213567. }
  213568. static void convertFloatToInt16 (const float* src,
  213569. char* dest,
  213570. const int dstStrideBytes,
  213571. int numSamples,
  213572. const bool littleEndian) throw()
  213573. {
  213574. const double maxVal = (double) 0x7fff;
  213575. if (littleEndian)
  213576. {
  213577. while (--numSamples >= 0)
  213578. {
  213579. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213580. dest += dstStrideBytes;
  213581. }
  213582. }
  213583. else
  213584. {
  213585. while (--numSamples >= 0)
  213586. {
  213587. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213588. dest += dstStrideBytes;
  213589. }
  213590. }
  213591. }
  213592. static void convertInt24ToFloat (const char* src,
  213593. float* dest,
  213594. const int srcStrideBytes,
  213595. int numSamples,
  213596. const bool littleEndian) throw()
  213597. {
  213598. const double g = 1.0 / 0x7fffff;
  213599. if (littleEndian)
  213600. {
  213601. while (--numSamples >= 0)
  213602. {
  213603. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213604. src += srcStrideBytes;
  213605. }
  213606. }
  213607. else
  213608. {
  213609. while (--numSamples >= 0)
  213610. {
  213611. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213612. src += srcStrideBytes;
  213613. }
  213614. }
  213615. }
  213616. static void convertFloatToInt24 (const float* src,
  213617. char* dest,
  213618. const int dstStrideBytes,
  213619. int numSamples,
  213620. const bool littleEndian) throw()
  213621. {
  213622. const double maxVal = (double) 0x7fffff;
  213623. if (littleEndian)
  213624. {
  213625. while (--numSamples >= 0)
  213626. {
  213627. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213628. dest += dstStrideBytes;
  213629. }
  213630. }
  213631. else
  213632. {
  213633. while (--numSamples >= 0)
  213634. {
  213635. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213636. dest += dstStrideBytes;
  213637. }
  213638. }
  213639. }
  213640. static void convertInt32ToFloat (const char* src,
  213641. float* dest,
  213642. const int srcStrideBytes,
  213643. int numSamples,
  213644. const bool littleEndian) throw()
  213645. {
  213646. const double g = 1.0 / 0x7fffffff;
  213647. if (littleEndian)
  213648. {
  213649. while (--numSamples >= 0)
  213650. {
  213651. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213652. src += srcStrideBytes;
  213653. }
  213654. }
  213655. else
  213656. {
  213657. while (--numSamples >= 0)
  213658. {
  213659. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213660. src += srcStrideBytes;
  213661. }
  213662. }
  213663. }
  213664. static void convertFloatToInt32 (const float* src,
  213665. char* dest,
  213666. const int dstStrideBytes,
  213667. int numSamples,
  213668. const bool littleEndian) throw()
  213669. {
  213670. const double maxVal = (double) 0x7fffffff;
  213671. if (littleEndian)
  213672. {
  213673. while (--numSamples >= 0)
  213674. {
  213675. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213676. dest += dstStrideBytes;
  213677. }
  213678. }
  213679. else
  213680. {
  213681. while (--numSamples >= 0)
  213682. {
  213683. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213684. dest += dstStrideBytes;
  213685. }
  213686. }
  213687. }
  213688. static void typeToFormatParameters (const long type,
  213689. int& bitDepth,
  213690. int& byteStride,
  213691. bool& formatIsFloat,
  213692. bool& littleEndian) throw()
  213693. {
  213694. bitDepth = 0;
  213695. littleEndian = false;
  213696. formatIsFloat = false;
  213697. switch (type)
  213698. {
  213699. case ASIOSTInt16MSB:
  213700. case ASIOSTInt16LSB:
  213701. case ASIOSTInt32MSB16:
  213702. case ASIOSTInt32LSB16:
  213703. bitDepth = 16; break;
  213704. case ASIOSTFloat32MSB:
  213705. case ASIOSTFloat32LSB:
  213706. formatIsFloat = true;
  213707. bitDepth = 32; break;
  213708. case ASIOSTInt32MSB:
  213709. case ASIOSTInt32LSB:
  213710. bitDepth = 32; break;
  213711. case ASIOSTInt24MSB:
  213712. case ASIOSTInt24LSB:
  213713. case ASIOSTInt32MSB24:
  213714. case ASIOSTInt32LSB24:
  213715. case ASIOSTInt32MSB18:
  213716. case ASIOSTInt32MSB20:
  213717. case ASIOSTInt32LSB18:
  213718. case ASIOSTInt32LSB20:
  213719. bitDepth = 24; break;
  213720. case ASIOSTFloat64MSB:
  213721. case ASIOSTFloat64LSB:
  213722. default:
  213723. bitDepth = 64;
  213724. break;
  213725. }
  213726. switch (type)
  213727. {
  213728. case ASIOSTInt16MSB:
  213729. case ASIOSTInt32MSB16:
  213730. case ASIOSTFloat32MSB:
  213731. case ASIOSTFloat64MSB:
  213732. case ASIOSTInt32MSB:
  213733. case ASIOSTInt32MSB18:
  213734. case ASIOSTInt32MSB20:
  213735. case ASIOSTInt32MSB24:
  213736. case ASIOSTInt24MSB:
  213737. littleEndian = false; break;
  213738. case ASIOSTInt16LSB:
  213739. case ASIOSTInt32LSB16:
  213740. case ASIOSTFloat32LSB:
  213741. case ASIOSTFloat64LSB:
  213742. case ASIOSTInt32LSB:
  213743. case ASIOSTInt32LSB18:
  213744. case ASIOSTInt32LSB20:
  213745. case ASIOSTInt32LSB24:
  213746. case ASIOSTInt24LSB:
  213747. littleEndian = true; break;
  213748. default:
  213749. break;
  213750. }
  213751. switch (type)
  213752. {
  213753. case ASIOSTInt16LSB:
  213754. case ASIOSTInt16MSB:
  213755. byteStride = 2; break;
  213756. case ASIOSTInt24LSB:
  213757. case ASIOSTInt24MSB:
  213758. byteStride = 3; break;
  213759. case ASIOSTInt32MSB16:
  213760. case ASIOSTInt32LSB16:
  213761. case ASIOSTInt32MSB:
  213762. case ASIOSTInt32MSB18:
  213763. case ASIOSTInt32MSB20:
  213764. case ASIOSTInt32MSB24:
  213765. case ASIOSTInt32LSB:
  213766. case ASIOSTInt32LSB18:
  213767. case ASIOSTInt32LSB20:
  213768. case ASIOSTInt32LSB24:
  213769. case ASIOSTFloat32LSB:
  213770. case ASIOSTFloat32MSB:
  213771. byteStride = 4; break;
  213772. case ASIOSTFloat64MSB:
  213773. case ASIOSTFloat64LSB:
  213774. byteStride = 8; break;
  213775. default:
  213776. break;
  213777. }
  213778. }
  213779. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213780. };
  213781. class ASIOAudioIODeviceType : public AudioIODeviceType
  213782. {
  213783. public:
  213784. ASIOAudioIODeviceType()
  213785. : AudioIODeviceType ("ASIO"),
  213786. hasScanned (false)
  213787. {
  213788. CoInitialize (0);
  213789. }
  213790. ~ASIOAudioIODeviceType()
  213791. {
  213792. }
  213793. void scanForDevices()
  213794. {
  213795. hasScanned = true;
  213796. deviceNames.clear();
  213797. classIds.clear();
  213798. HKEY hk = 0;
  213799. int index = 0;
  213800. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213801. {
  213802. for (;;)
  213803. {
  213804. char name [256];
  213805. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213806. {
  213807. addDriverInfo (name, hk);
  213808. }
  213809. else
  213810. {
  213811. break;
  213812. }
  213813. }
  213814. RegCloseKey (hk);
  213815. }
  213816. }
  213817. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213818. {
  213819. jassert (hasScanned); // need to call scanForDevices() before doing this
  213820. return deviceNames;
  213821. }
  213822. int getDefaultDeviceIndex (bool) const
  213823. {
  213824. jassert (hasScanned); // need to call scanForDevices() before doing this
  213825. for (int i = deviceNames.size(); --i >= 0;)
  213826. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213827. return i; // asio4all is a safe choice for a default..
  213828. #if JUCE_DEBUG
  213829. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213830. return 1; // (the digi m-box driver crashes the app when you run
  213831. // it in the debugger, which can be a bit annoying)
  213832. #endif
  213833. return 0;
  213834. }
  213835. static int findFreeSlot()
  213836. {
  213837. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213838. if (currentASIODev[i] == 0)
  213839. return i;
  213840. jassertfalse; // unfortunately you can only have a finite number
  213841. // of ASIO devices open at the same time..
  213842. return -1;
  213843. }
  213844. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213845. {
  213846. jassert (hasScanned); // need to call scanForDevices() before doing this
  213847. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213848. }
  213849. bool hasSeparateInputsAndOutputs() const { return false; }
  213850. AudioIODevice* createDevice (const String& outputDeviceName,
  213851. const String& inputDeviceName)
  213852. {
  213853. // ASIO can't open two different devices for input and output - they must be the same one.
  213854. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213855. jassert (hasScanned); // need to call scanForDevices() before doing this
  213856. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213857. : inputDeviceName);
  213858. if (index >= 0)
  213859. {
  213860. const int freeSlot = findFreeSlot();
  213861. if (freeSlot >= 0)
  213862. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213863. }
  213864. return 0;
  213865. }
  213866. private:
  213867. StringArray deviceNames;
  213868. OwnedArray <CLSID> classIds;
  213869. bool hasScanned;
  213870. static bool checkClassIsOk (const String& classId)
  213871. {
  213872. HKEY hk = 0;
  213873. bool ok = false;
  213874. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213875. {
  213876. int index = 0;
  213877. for (;;)
  213878. {
  213879. WCHAR buf [512];
  213880. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213881. {
  213882. if (classId.equalsIgnoreCase (buf))
  213883. {
  213884. HKEY subKey, pathKey;
  213885. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213886. {
  213887. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213888. {
  213889. WCHAR pathName [1024];
  213890. DWORD dtype = REG_SZ;
  213891. DWORD dsize = sizeof (pathName);
  213892. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213893. ok = File (pathName).exists();
  213894. RegCloseKey (pathKey);
  213895. }
  213896. RegCloseKey (subKey);
  213897. }
  213898. break;
  213899. }
  213900. }
  213901. else
  213902. {
  213903. break;
  213904. }
  213905. }
  213906. RegCloseKey (hk);
  213907. }
  213908. return ok;
  213909. }
  213910. void addDriverInfo (const String& keyName, HKEY hk)
  213911. {
  213912. HKEY subKey;
  213913. if (RegOpenKeyEx (hk, keyName.toUTF16(), 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213914. {
  213915. WCHAR buf [256];
  213916. zerostruct (buf);
  213917. DWORD dtype = REG_SZ;
  213918. DWORD dsize = sizeof (buf);
  213919. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213920. {
  213921. if (dsize > 0 && checkClassIsOk (buf))
  213922. {
  213923. CLSID classId;
  213924. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213925. {
  213926. dtype = REG_SZ;
  213927. dsize = sizeof (buf);
  213928. String deviceName;
  213929. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213930. deviceName = buf;
  213931. else
  213932. deviceName = keyName;
  213933. log ("found " + deviceName);
  213934. deviceNames.add (deviceName);
  213935. classIds.add (new CLSID (classId));
  213936. }
  213937. }
  213938. RegCloseKey (subKey);
  213939. }
  213940. }
  213941. }
  213942. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213943. };
  213944. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO()
  213945. {
  213946. return new ASIOAudioIODeviceType();
  213947. }
  213948. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213949. void* guid,
  213950. const String& optionalDllForDirectLoading)
  213951. {
  213952. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213953. if (freeSlot < 0)
  213954. return 0;
  213955. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213956. }
  213957. #undef logError
  213958. #undef log
  213959. #endif
  213960. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213961. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213962. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213963. // compiled on its own).
  213964. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213965. END_JUCE_NAMESPACE
  213966. extern "C"
  213967. {
  213968. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213969. typedef struct typeDSBUFFERDESC
  213970. {
  213971. DWORD dwSize;
  213972. DWORD dwFlags;
  213973. DWORD dwBufferBytes;
  213974. DWORD dwReserved;
  213975. LPWAVEFORMATEX lpwfxFormat;
  213976. GUID guid3DAlgorithm;
  213977. } DSBUFFERDESC;
  213978. struct IDirectSoundBuffer;
  213979. #undef INTERFACE
  213980. #define INTERFACE IDirectSound
  213981. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213982. {
  213983. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213984. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213985. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213986. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213987. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213988. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213989. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213990. STDMETHOD(Compact) (THIS) PURE;
  213991. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213992. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213993. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213994. };
  213995. #undef INTERFACE
  213996. #define INTERFACE IDirectSoundBuffer
  213997. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213998. {
  213999. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214000. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214001. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214002. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214003. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214004. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214005. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214006. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214007. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214008. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214009. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214010. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214011. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214012. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214013. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214014. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214015. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214016. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214017. STDMETHOD(Stop) (THIS) PURE;
  214018. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214019. STDMETHOD(Restore) (THIS) PURE;
  214020. };
  214021. typedef struct typeDSCBUFFERDESC
  214022. {
  214023. DWORD dwSize;
  214024. DWORD dwFlags;
  214025. DWORD dwBufferBytes;
  214026. DWORD dwReserved;
  214027. LPWAVEFORMATEX lpwfxFormat;
  214028. } DSCBUFFERDESC;
  214029. struct IDirectSoundCaptureBuffer;
  214030. #undef INTERFACE
  214031. #define INTERFACE IDirectSoundCapture
  214032. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214033. {
  214034. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214035. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214036. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214037. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214038. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214039. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214040. };
  214041. #undef INTERFACE
  214042. #define INTERFACE IDirectSoundCaptureBuffer
  214043. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214044. {
  214045. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214046. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214047. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214048. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214049. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214050. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214051. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214052. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214053. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214054. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214055. STDMETHOD(Stop) (THIS) PURE;
  214056. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214057. };
  214058. };
  214059. BEGIN_JUCE_NAMESPACE
  214060. namespace
  214061. {
  214062. const String getDSErrorMessage (HRESULT hr)
  214063. {
  214064. const char* result = 0;
  214065. switch (hr)
  214066. {
  214067. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214068. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214069. case E_INVALIDARG: result = "Invalid parameter"; break;
  214070. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214071. case E_FAIL: result = "Generic error"; break;
  214072. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214073. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214074. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214075. case E_NOTIMPL: result = "Unsupported function"; break;
  214076. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214077. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214078. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214079. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214080. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214081. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214082. case E_NOINTERFACE: result = "No interface"; break;
  214083. case S_OK: result = "No error"; break;
  214084. default: return "Unknown error: " + String ((int) hr);
  214085. }
  214086. return result;
  214087. }
  214088. #define DS_DEBUGGING 1
  214089. #ifdef DS_DEBUGGING
  214090. #define CATCH JUCE_CATCH_EXCEPTION
  214091. #undef log
  214092. #define log(a) Logger::writeToLog(a);
  214093. #undef logError
  214094. #define logError(a) logDSError(a, __LINE__);
  214095. static void logDSError (HRESULT hr, int lineNum)
  214096. {
  214097. if (hr != S_OK)
  214098. {
  214099. String error ("DS error at line ");
  214100. error << lineNum << " - " << getDSErrorMessage (hr);
  214101. log (error);
  214102. }
  214103. }
  214104. #else
  214105. #define CATCH JUCE_CATCH_ALL
  214106. #define log(a)
  214107. #define logError(a)
  214108. #endif
  214109. #define DSOUND_FUNCTION(functionName, params) \
  214110. typedef HRESULT (WINAPI *type##functionName) params; \
  214111. static type##functionName ds##functionName = 0;
  214112. #define DSOUND_FUNCTION_LOAD(functionName) \
  214113. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214114. jassert (ds##functionName != 0);
  214115. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214116. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214117. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214118. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214119. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214120. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214121. void initialiseDSoundFunctions()
  214122. {
  214123. if (dsDirectSoundCreate == 0)
  214124. {
  214125. HMODULE h = LoadLibraryA ("dsound.dll");
  214126. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214127. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214128. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214129. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214130. }
  214131. }
  214132. }
  214133. class DSoundInternalOutChannel
  214134. {
  214135. public:
  214136. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  214137. int bufferSize, float* left, float* right)
  214138. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  214139. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  214140. pDirectSound (0), pOutputBuffer (0)
  214141. {
  214142. }
  214143. ~DSoundInternalOutChannel()
  214144. {
  214145. close();
  214146. }
  214147. void close()
  214148. {
  214149. HRESULT hr;
  214150. if (pOutputBuffer != 0)
  214151. {
  214152. log ("closing dsound out: " + name);
  214153. hr = pOutputBuffer->Stop();
  214154. logError (hr);
  214155. hr = pOutputBuffer->Release();
  214156. pOutputBuffer = 0;
  214157. logError (hr);
  214158. }
  214159. if (pDirectSound != 0)
  214160. {
  214161. hr = pDirectSound->Release();
  214162. pDirectSound = 0;
  214163. logError (hr);
  214164. }
  214165. }
  214166. const String open()
  214167. {
  214168. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214169. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214170. pDirectSound = 0;
  214171. pOutputBuffer = 0;
  214172. writeOffset = 0;
  214173. String error;
  214174. HRESULT hr = E_NOINTERFACE;
  214175. if (dsDirectSoundCreate != 0)
  214176. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214177. if (hr == S_OK)
  214178. {
  214179. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214180. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214181. const int numChannels = 2;
  214182. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214183. logError (hr);
  214184. if (hr == S_OK)
  214185. {
  214186. IDirectSoundBuffer* pPrimaryBuffer;
  214187. DSBUFFERDESC primaryDesc;
  214188. zerostruct (primaryDesc);
  214189. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214190. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214191. primaryDesc.dwBufferBytes = 0;
  214192. primaryDesc.lpwfxFormat = 0;
  214193. log ("opening dsound out step 2");
  214194. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214195. logError (hr);
  214196. if (hr == S_OK)
  214197. {
  214198. WAVEFORMATEX wfFormat;
  214199. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214200. wfFormat.nChannels = (unsigned short) numChannels;
  214201. wfFormat.nSamplesPerSec = sampleRate;
  214202. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214203. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214204. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214205. wfFormat.cbSize = 0;
  214206. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214207. logError (hr);
  214208. if (hr == S_OK)
  214209. {
  214210. DSBUFFERDESC secondaryDesc;
  214211. zerostruct (secondaryDesc);
  214212. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214213. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214214. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214215. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214216. secondaryDesc.lpwfxFormat = &wfFormat;
  214217. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214218. logError (hr);
  214219. if (hr == S_OK)
  214220. {
  214221. log ("opening dsound out step 3");
  214222. DWORD dwDataLen;
  214223. unsigned char* pDSBuffData;
  214224. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214225. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214226. logError (hr);
  214227. if (hr == S_OK)
  214228. {
  214229. zeromem (pDSBuffData, dwDataLen);
  214230. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214231. if (hr == S_OK)
  214232. {
  214233. hr = pOutputBuffer->SetCurrentPosition (0);
  214234. if (hr == S_OK)
  214235. {
  214236. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214237. if (hr == S_OK)
  214238. return String::empty;
  214239. }
  214240. }
  214241. }
  214242. }
  214243. }
  214244. }
  214245. }
  214246. }
  214247. error = getDSErrorMessage (hr);
  214248. close();
  214249. return error;
  214250. }
  214251. void synchronisePosition()
  214252. {
  214253. if (pOutputBuffer != 0)
  214254. {
  214255. DWORD playCursor;
  214256. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214257. }
  214258. }
  214259. bool service()
  214260. {
  214261. if (pOutputBuffer == 0)
  214262. return true;
  214263. DWORD playCursor, writeCursor;
  214264. for (;;)
  214265. {
  214266. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214267. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214268. {
  214269. pOutputBuffer->Restore();
  214270. continue;
  214271. }
  214272. if (hr == S_OK)
  214273. break;
  214274. logError (hr);
  214275. jassertfalse;
  214276. return true;
  214277. }
  214278. int playWriteGap = writeCursor - playCursor;
  214279. if (playWriteGap < 0)
  214280. playWriteGap += totalBytesPerBuffer;
  214281. int bytesEmpty = playCursor - writeOffset;
  214282. if (bytesEmpty < 0)
  214283. bytesEmpty += totalBytesPerBuffer;
  214284. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214285. {
  214286. writeOffset = writeCursor;
  214287. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214288. }
  214289. if (bytesEmpty >= bytesPerBuffer)
  214290. {
  214291. void* lpbuf1 = 0;
  214292. void* lpbuf2 = 0;
  214293. DWORD dwSize1 = 0;
  214294. DWORD dwSize2 = 0;
  214295. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214296. &lpbuf1, &dwSize1,
  214297. &lpbuf2, &dwSize2, 0);
  214298. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214299. {
  214300. pOutputBuffer->Restore();
  214301. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214302. &lpbuf1, &dwSize1,
  214303. &lpbuf2, &dwSize2, 0);
  214304. }
  214305. if (hr == S_OK)
  214306. {
  214307. if (bitDepth == 16)
  214308. {
  214309. int* dest = static_cast<int*> (lpbuf1);
  214310. const float* left = leftBuffer;
  214311. const float* right = rightBuffer;
  214312. int samples1 = dwSize1 >> 2;
  214313. int samples2 = dwSize2 >> 2;
  214314. if (left == 0)
  214315. {
  214316. while (--samples1 >= 0)
  214317. *dest++ = (convertInputValue (*right++) << 16);
  214318. dest = static_cast<int*> (lpbuf2);
  214319. while (--samples2 >= 0)
  214320. *dest++ = (convertInputValue (*right++) << 16);
  214321. }
  214322. else if (right == 0)
  214323. {
  214324. while (--samples1 >= 0)
  214325. *dest++ = (0xffff & convertInputValue (*left++));
  214326. dest = static_cast<int*> (lpbuf2);
  214327. while (--samples2 >= 0)
  214328. *dest++ = (0xffff & convertInputValue (*left++));
  214329. }
  214330. else
  214331. {
  214332. while (--samples1 >= 0)
  214333. {
  214334. const int l = convertInputValue (*left++);
  214335. const int r = convertInputValue (*right++);
  214336. *dest++ = (r << 16) | (0xffff & l);
  214337. }
  214338. dest = static_cast<int*> (lpbuf2);
  214339. while (--samples2 >= 0)
  214340. {
  214341. const int l = convertInputValue (*left++);
  214342. const int r = convertInputValue (*right++);
  214343. *dest++ = (r << 16) | (0xffff & l);
  214344. }
  214345. }
  214346. }
  214347. else
  214348. {
  214349. jassertfalse;
  214350. }
  214351. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214352. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214353. }
  214354. else
  214355. {
  214356. jassertfalse;
  214357. logError (hr);
  214358. }
  214359. bytesEmpty -= bytesPerBuffer;
  214360. return true;
  214361. }
  214362. else
  214363. {
  214364. return false;
  214365. }
  214366. }
  214367. int bitDepth;
  214368. bool doneFlag;
  214369. private:
  214370. String name;
  214371. LPGUID guid;
  214372. int sampleRate, bufferSizeSamples;
  214373. float* leftBuffer;
  214374. float* rightBuffer;
  214375. IDirectSound* pDirectSound;
  214376. IDirectSoundBuffer* pOutputBuffer;
  214377. DWORD writeOffset;
  214378. int totalBytesPerBuffer, bytesPerBuffer;
  214379. unsigned int lastPlayCursor;
  214380. static inline int convertInputValue (const float v) throw()
  214381. {
  214382. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  214383. }
  214384. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  214385. };
  214386. struct DSoundInternalInChannel
  214387. {
  214388. public:
  214389. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  214390. int bufferSize, float* left, float* right)
  214391. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  214392. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  214393. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  214394. {
  214395. }
  214396. ~DSoundInternalInChannel()
  214397. {
  214398. close();
  214399. }
  214400. void close()
  214401. {
  214402. HRESULT hr;
  214403. if (pInputBuffer != 0)
  214404. {
  214405. log ("closing dsound in: " + name);
  214406. hr = pInputBuffer->Stop();
  214407. logError (hr);
  214408. hr = pInputBuffer->Release();
  214409. pInputBuffer = 0;
  214410. logError (hr);
  214411. }
  214412. if (pDirectSoundCapture != 0)
  214413. {
  214414. hr = pDirectSoundCapture->Release();
  214415. pDirectSoundCapture = 0;
  214416. logError (hr);
  214417. }
  214418. if (pDirectSound != 0)
  214419. {
  214420. hr = pDirectSound->Release();
  214421. pDirectSound = 0;
  214422. logError (hr);
  214423. }
  214424. }
  214425. const String open()
  214426. {
  214427. log ("opening dsound in device: " + name
  214428. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214429. pDirectSound = 0;
  214430. pDirectSoundCapture = 0;
  214431. pInputBuffer = 0;
  214432. readOffset = 0;
  214433. totalBytesPerBuffer = 0;
  214434. String error;
  214435. HRESULT hr = E_NOINTERFACE;
  214436. if (dsDirectSoundCaptureCreate != 0)
  214437. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214438. logError (hr);
  214439. if (hr == S_OK)
  214440. {
  214441. const int numChannels = 2;
  214442. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214443. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214444. WAVEFORMATEX wfFormat;
  214445. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214446. wfFormat.nChannels = (unsigned short)numChannels;
  214447. wfFormat.nSamplesPerSec = sampleRate;
  214448. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214449. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214450. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214451. wfFormat.cbSize = 0;
  214452. DSCBUFFERDESC captureDesc;
  214453. zerostruct (captureDesc);
  214454. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214455. captureDesc.dwFlags = 0;
  214456. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214457. captureDesc.lpwfxFormat = &wfFormat;
  214458. log ("opening dsound in step 2");
  214459. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214460. logError (hr);
  214461. if (hr == S_OK)
  214462. {
  214463. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214464. logError (hr);
  214465. if (hr == S_OK)
  214466. return String::empty;
  214467. }
  214468. }
  214469. error = getDSErrorMessage (hr);
  214470. close();
  214471. return error;
  214472. }
  214473. void synchronisePosition()
  214474. {
  214475. if (pInputBuffer != 0)
  214476. {
  214477. DWORD capturePos;
  214478. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214479. }
  214480. }
  214481. bool service()
  214482. {
  214483. if (pInputBuffer == 0)
  214484. return true;
  214485. DWORD capturePos, readPos;
  214486. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214487. logError (hr);
  214488. if (hr != S_OK)
  214489. return true;
  214490. int bytesFilled = readPos - readOffset;
  214491. if (bytesFilled < 0)
  214492. bytesFilled += totalBytesPerBuffer;
  214493. if (bytesFilled >= bytesPerBuffer)
  214494. {
  214495. LPBYTE lpbuf1 = 0;
  214496. LPBYTE lpbuf2 = 0;
  214497. DWORD dwsize1 = 0;
  214498. DWORD dwsize2 = 0;
  214499. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  214500. (void**) &lpbuf1, &dwsize1,
  214501. (void**) &lpbuf2, &dwsize2, 0);
  214502. if (hr == S_OK)
  214503. {
  214504. if (bitDepth == 16)
  214505. {
  214506. const float g = 1.0f / 32768.0f;
  214507. float* destL = leftBuffer;
  214508. float* destR = rightBuffer;
  214509. int samples1 = dwsize1 >> 2;
  214510. int samples2 = dwsize2 >> 2;
  214511. const short* src = (const short*)lpbuf1;
  214512. if (destL == 0)
  214513. {
  214514. while (--samples1 >= 0)
  214515. {
  214516. ++src;
  214517. *destR++ = *src++ * g;
  214518. }
  214519. src = (const short*)lpbuf2;
  214520. while (--samples2 >= 0)
  214521. {
  214522. ++src;
  214523. *destR++ = *src++ * g;
  214524. }
  214525. }
  214526. else if (destR == 0)
  214527. {
  214528. while (--samples1 >= 0)
  214529. {
  214530. *destL++ = *src++ * g;
  214531. ++src;
  214532. }
  214533. src = (const short*)lpbuf2;
  214534. while (--samples2 >= 0)
  214535. {
  214536. *destL++ = *src++ * g;
  214537. ++src;
  214538. }
  214539. }
  214540. else
  214541. {
  214542. while (--samples1 >= 0)
  214543. {
  214544. *destL++ = *src++ * g;
  214545. *destR++ = *src++ * g;
  214546. }
  214547. src = (const short*)lpbuf2;
  214548. while (--samples2 >= 0)
  214549. {
  214550. *destL++ = *src++ * g;
  214551. *destR++ = *src++ * g;
  214552. }
  214553. }
  214554. }
  214555. else
  214556. {
  214557. jassertfalse;
  214558. }
  214559. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214560. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214561. }
  214562. else
  214563. {
  214564. logError (hr);
  214565. jassertfalse;
  214566. }
  214567. bytesFilled -= bytesPerBuffer;
  214568. return true;
  214569. }
  214570. else
  214571. {
  214572. return false;
  214573. }
  214574. }
  214575. unsigned int readOffset;
  214576. int bytesPerBuffer, totalBytesPerBuffer;
  214577. int bitDepth;
  214578. bool doneFlag;
  214579. private:
  214580. String name;
  214581. LPGUID guid;
  214582. int sampleRate, bufferSizeSamples;
  214583. float* leftBuffer;
  214584. float* rightBuffer;
  214585. IDirectSound* pDirectSound;
  214586. IDirectSoundCapture* pDirectSoundCapture;
  214587. IDirectSoundCaptureBuffer* pInputBuffer;
  214588. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  214589. };
  214590. class DSoundAudioIODevice : public AudioIODevice,
  214591. public Thread
  214592. {
  214593. public:
  214594. DSoundAudioIODevice (const String& deviceName,
  214595. const int outputDeviceIndex_,
  214596. const int inputDeviceIndex_)
  214597. : AudioIODevice (deviceName, "DirectSound"),
  214598. Thread ("Juce DSound"),
  214599. outputDeviceIndex (outputDeviceIndex_),
  214600. inputDeviceIndex (inputDeviceIndex_),
  214601. isOpen_ (false),
  214602. isStarted (false),
  214603. bufferSizeSamples (0),
  214604. totalSamplesOut (0),
  214605. sampleRate (0.0),
  214606. inputBuffers (1, 1),
  214607. outputBuffers (1, 1),
  214608. callback (0)
  214609. {
  214610. if (outputDeviceIndex_ >= 0)
  214611. {
  214612. outChannels.add (TRANS("Left"));
  214613. outChannels.add (TRANS("Right"));
  214614. }
  214615. if (inputDeviceIndex_ >= 0)
  214616. {
  214617. inChannels.add (TRANS("Left"));
  214618. inChannels.add (TRANS("Right"));
  214619. }
  214620. }
  214621. ~DSoundAudioIODevice()
  214622. {
  214623. close();
  214624. }
  214625. const String open (const BigInteger& inputChannels,
  214626. const BigInteger& outputChannels,
  214627. double sampleRate, int bufferSizeSamples)
  214628. {
  214629. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214630. isOpen_ = lastError.isEmpty();
  214631. return lastError;
  214632. }
  214633. void close()
  214634. {
  214635. stop();
  214636. if (isOpen_)
  214637. {
  214638. closeDevice();
  214639. isOpen_ = false;
  214640. }
  214641. }
  214642. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214643. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214644. double getCurrentSampleRate() { return sampleRate; }
  214645. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214646. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214647. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214648. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214649. const StringArray getOutputChannelNames() { return outChannels; }
  214650. const StringArray getInputChannelNames() { return inChannels; }
  214651. int getNumSampleRates() { return 4; }
  214652. int getDefaultBufferSize() { return 2560; }
  214653. int getNumBufferSizesAvailable() { return 50; }
  214654. double getSampleRate (int index)
  214655. {
  214656. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214657. return samps [jlimit (0, 3, index)];
  214658. }
  214659. int getBufferSizeSamples (int index)
  214660. {
  214661. int n = 64;
  214662. for (int i = 0; i < index; ++i)
  214663. n += (n < 512) ? 32
  214664. : ((n < 1024) ? 64
  214665. : ((n < 2048) ? 128 : 256));
  214666. return n;
  214667. }
  214668. int getCurrentBitDepth()
  214669. {
  214670. int i, bits = 256;
  214671. for (i = inChans.size(); --i >= 0;)
  214672. bits = jmin (bits, inChans[i]->bitDepth);
  214673. for (i = outChans.size(); --i >= 0;)
  214674. bits = jmin (bits, outChans[i]->bitDepth);
  214675. if (bits > 32)
  214676. bits = 16;
  214677. return bits;
  214678. }
  214679. void start (AudioIODeviceCallback* call)
  214680. {
  214681. if (isOpen_ && call != 0 && ! isStarted)
  214682. {
  214683. if (! isThreadRunning())
  214684. {
  214685. // something gone wrong and the thread's stopped..
  214686. isOpen_ = false;
  214687. return;
  214688. }
  214689. call->audioDeviceAboutToStart (this);
  214690. const ScopedLock sl (startStopLock);
  214691. callback = call;
  214692. isStarted = true;
  214693. }
  214694. }
  214695. void stop()
  214696. {
  214697. if (isStarted)
  214698. {
  214699. AudioIODeviceCallback* const callbackLocal = callback;
  214700. {
  214701. const ScopedLock sl (startStopLock);
  214702. isStarted = false;
  214703. }
  214704. if (callbackLocal != 0)
  214705. callbackLocal->audioDeviceStopped();
  214706. }
  214707. }
  214708. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214709. const String getLastError() { return lastError; }
  214710. StringArray inChannels, outChannels;
  214711. int outputDeviceIndex, inputDeviceIndex;
  214712. private:
  214713. bool isOpen_;
  214714. bool isStarted;
  214715. String lastError;
  214716. OwnedArray <DSoundInternalInChannel> inChans;
  214717. OwnedArray <DSoundInternalOutChannel> outChans;
  214718. WaitableEvent startEvent;
  214719. int bufferSizeSamples;
  214720. int volatile totalSamplesOut;
  214721. int64 volatile lastBlockTime;
  214722. double sampleRate;
  214723. BigInteger enabledInputs, enabledOutputs;
  214724. AudioSampleBuffer inputBuffers, outputBuffers;
  214725. AudioIODeviceCallback* callback;
  214726. CriticalSection startStopLock;
  214727. const String openDevice (const BigInteger& inputChannels,
  214728. const BigInteger& outputChannels,
  214729. double sampleRate_, int bufferSizeSamples_);
  214730. void closeDevice()
  214731. {
  214732. isStarted = false;
  214733. stopThread (5000);
  214734. inChans.clear();
  214735. outChans.clear();
  214736. inputBuffers.setSize (1, 1);
  214737. outputBuffers.setSize (1, 1);
  214738. }
  214739. void resync()
  214740. {
  214741. if (! threadShouldExit())
  214742. {
  214743. sleep (5);
  214744. int i;
  214745. for (i = 0; i < outChans.size(); ++i)
  214746. outChans.getUnchecked(i)->synchronisePosition();
  214747. for (i = 0; i < inChans.size(); ++i)
  214748. inChans.getUnchecked(i)->synchronisePosition();
  214749. }
  214750. }
  214751. public:
  214752. void run()
  214753. {
  214754. while (! threadShouldExit())
  214755. {
  214756. if (wait (100))
  214757. break;
  214758. }
  214759. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214760. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214761. while (! threadShouldExit())
  214762. {
  214763. int numToDo = 0;
  214764. uint32 startTime = Time::getMillisecondCounter();
  214765. int i;
  214766. for (i = inChans.size(); --i >= 0;)
  214767. {
  214768. inChans.getUnchecked(i)->doneFlag = false;
  214769. ++numToDo;
  214770. }
  214771. for (i = outChans.size(); --i >= 0;)
  214772. {
  214773. outChans.getUnchecked(i)->doneFlag = false;
  214774. ++numToDo;
  214775. }
  214776. if (numToDo > 0)
  214777. {
  214778. const int maxCount = 3;
  214779. int count = maxCount;
  214780. for (;;)
  214781. {
  214782. for (i = inChans.size(); --i >= 0;)
  214783. {
  214784. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214785. if ((! in->doneFlag) && in->service())
  214786. {
  214787. in->doneFlag = true;
  214788. --numToDo;
  214789. }
  214790. }
  214791. for (i = outChans.size(); --i >= 0;)
  214792. {
  214793. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214794. if ((! out->doneFlag) && out->service())
  214795. {
  214796. out->doneFlag = true;
  214797. --numToDo;
  214798. }
  214799. }
  214800. if (numToDo <= 0)
  214801. break;
  214802. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214803. {
  214804. resync();
  214805. break;
  214806. }
  214807. if (--count <= 0)
  214808. {
  214809. Sleep (1);
  214810. count = maxCount;
  214811. }
  214812. if (threadShouldExit())
  214813. return;
  214814. }
  214815. }
  214816. else
  214817. {
  214818. sleep (1);
  214819. }
  214820. const ScopedLock sl (startStopLock);
  214821. if (isStarted)
  214822. {
  214823. JUCE_TRY
  214824. {
  214825. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214826. inputBuffers.getNumChannels(),
  214827. outputBuffers.getArrayOfChannels(),
  214828. outputBuffers.getNumChannels(),
  214829. bufferSizeSamples);
  214830. }
  214831. JUCE_CATCH_EXCEPTION
  214832. totalSamplesOut += bufferSizeSamples;
  214833. }
  214834. else
  214835. {
  214836. outputBuffers.clear();
  214837. totalSamplesOut = 0;
  214838. sleep (1);
  214839. }
  214840. }
  214841. }
  214842. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214843. };
  214844. class DSoundAudioIODeviceType : public AudioIODeviceType
  214845. {
  214846. public:
  214847. DSoundAudioIODeviceType()
  214848. : AudioIODeviceType ("DirectSound"),
  214849. hasScanned (false)
  214850. {
  214851. initialiseDSoundFunctions();
  214852. }
  214853. void scanForDevices()
  214854. {
  214855. hasScanned = true;
  214856. outputDeviceNames.clear();
  214857. outputGuids.clear();
  214858. inputDeviceNames.clear();
  214859. inputGuids.clear();
  214860. if (dsDirectSoundEnumerateW != 0)
  214861. {
  214862. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214863. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214864. }
  214865. }
  214866. const StringArray getDeviceNames (bool wantInputNames) const
  214867. {
  214868. jassert (hasScanned); // need to call scanForDevices() before doing this
  214869. return wantInputNames ? inputDeviceNames
  214870. : outputDeviceNames;
  214871. }
  214872. int getDefaultDeviceIndex (bool /*forInput*/) const
  214873. {
  214874. jassert (hasScanned); // need to call scanForDevices() before doing this
  214875. return 0;
  214876. }
  214877. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214878. {
  214879. jassert (hasScanned); // need to call scanForDevices() before doing this
  214880. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214881. if (d == 0)
  214882. return -1;
  214883. return asInput ? d->inputDeviceIndex
  214884. : d->outputDeviceIndex;
  214885. }
  214886. bool hasSeparateInputsAndOutputs() const { return true; }
  214887. AudioIODevice* createDevice (const String& outputDeviceName,
  214888. const String& inputDeviceName)
  214889. {
  214890. jassert (hasScanned); // need to call scanForDevices() before doing this
  214891. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214892. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214893. if (outputIndex >= 0 || inputIndex >= 0)
  214894. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214895. : inputDeviceName,
  214896. outputIndex, inputIndex);
  214897. return 0;
  214898. }
  214899. StringArray outputDeviceNames, inputDeviceNames;
  214900. OwnedArray <GUID> outputGuids, inputGuids;
  214901. private:
  214902. bool hasScanned;
  214903. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214904. {
  214905. desc = desc.trim();
  214906. if (desc.isNotEmpty())
  214907. {
  214908. const String origDesc (desc);
  214909. int n = 2;
  214910. while (outputDeviceNames.contains (desc))
  214911. desc = origDesc + " (" + String (n++) + ")";
  214912. outputDeviceNames.add (desc);
  214913. if (lpGUID != 0)
  214914. outputGuids.add (new GUID (*lpGUID));
  214915. else
  214916. outputGuids.add (0);
  214917. }
  214918. return TRUE;
  214919. }
  214920. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214921. {
  214922. return ((DSoundAudioIODeviceType*) object)
  214923. ->outputEnumProc (lpGUID, String (description));
  214924. }
  214925. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214926. {
  214927. return ((DSoundAudioIODeviceType*) object)
  214928. ->outputEnumProc (lpGUID, String (description));
  214929. }
  214930. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214931. {
  214932. desc = desc.trim();
  214933. if (desc.isNotEmpty())
  214934. {
  214935. const String origDesc (desc);
  214936. int n = 2;
  214937. while (inputDeviceNames.contains (desc))
  214938. desc = origDesc + " (" + String (n++) + ")";
  214939. inputDeviceNames.add (desc);
  214940. if (lpGUID != 0)
  214941. inputGuids.add (new GUID (*lpGUID));
  214942. else
  214943. inputGuids.add (0);
  214944. }
  214945. return TRUE;
  214946. }
  214947. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214948. {
  214949. return ((DSoundAudioIODeviceType*) object)
  214950. ->inputEnumProc (lpGUID, String (description));
  214951. }
  214952. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214953. {
  214954. return ((DSoundAudioIODeviceType*) object)
  214955. ->inputEnumProc (lpGUID, String (description));
  214956. }
  214957. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214958. };
  214959. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214960. const BigInteger& outputChannels,
  214961. double sampleRate_, int bufferSizeSamples_)
  214962. {
  214963. closeDevice();
  214964. totalSamplesOut = 0;
  214965. sampleRate = sampleRate_;
  214966. if (bufferSizeSamples_ <= 0)
  214967. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214968. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214969. DSoundAudioIODeviceType dlh;
  214970. dlh.scanForDevices();
  214971. enabledInputs = inputChannels;
  214972. enabledInputs.setRange (inChannels.size(),
  214973. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214974. false);
  214975. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214976. inputBuffers.clear();
  214977. int i, numIns = 0;
  214978. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214979. {
  214980. float* left = 0;
  214981. if (enabledInputs[i])
  214982. left = inputBuffers.getSampleData (numIns++);
  214983. float* right = 0;
  214984. if (enabledInputs[i + 1])
  214985. right = inputBuffers.getSampleData (numIns++);
  214986. if (left != 0 || right != 0)
  214987. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214988. dlh.inputGuids [inputDeviceIndex],
  214989. (int) sampleRate, bufferSizeSamples,
  214990. left, right));
  214991. }
  214992. enabledOutputs = outputChannels;
  214993. enabledOutputs.setRange (outChannels.size(),
  214994. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214995. false);
  214996. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214997. outputBuffers.clear();
  214998. int numOuts = 0;
  214999. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215000. {
  215001. float* left = 0;
  215002. if (enabledOutputs[i])
  215003. left = outputBuffers.getSampleData (numOuts++);
  215004. float* right = 0;
  215005. if (enabledOutputs[i + 1])
  215006. right = outputBuffers.getSampleData (numOuts++);
  215007. if (left != 0 || right != 0)
  215008. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215009. dlh.outputGuids [outputDeviceIndex],
  215010. (int) sampleRate, bufferSizeSamples,
  215011. left, right));
  215012. }
  215013. String error;
  215014. // boost our priority while opening the devices to try to get better sync between them
  215015. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215016. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215017. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215018. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215019. for (i = 0; i < outChans.size(); ++i)
  215020. {
  215021. error = outChans[i]->open();
  215022. if (error.isNotEmpty())
  215023. {
  215024. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215025. break;
  215026. }
  215027. }
  215028. if (error.isEmpty())
  215029. {
  215030. for (i = 0; i < inChans.size(); ++i)
  215031. {
  215032. error = inChans[i]->open();
  215033. if (error.isNotEmpty())
  215034. {
  215035. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215036. break;
  215037. }
  215038. }
  215039. }
  215040. if (error.isEmpty())
  215041. {
  215042. totalSamplesOut = 0;
  215043. for (i = 0; i < outChans.size(); ++i)
  215044. outChans.getUnchecked(i)->synchronisePosition();
  215045. for (i = 0; i < inChans.size(); ++i)
  215046. inChans.getUnchecked(i)->synchronisePosition();
  215047. startThread (9);
  215048. sleep (10);
  215049. notify();
  215050. }
  215051. else
  215052. {
  215053. log (error);
  215054. }
  215055. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215056. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215057. return error;
  215058. }
  215059. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound()
  215060. {
  215061. return new DSoundAudioIODeviceType();
  215062. }
  215063. #undef log
  215064. #endif
  215065. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215066. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215067. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215068. // compiled on its own).
  215069. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215070. #ifndef WASAPI_ENABLE_LOGGING
  215071. #define WASAPI_ENABLE_LOGGING 0
  215072. #endif
  215073. namespace WasapiClasses
  215074. {
  215075. void logFailure (HRESULT hr)
  215076. {
  215077. (void) hr;
  215078. #if WASAPI_ENABLE_LOGGING
  215079. if (FAILED (hr))
  215080. {
  215081. String e;
  215082. e << Time::getCurrentTime().toString (true, true, true, true)
  215083. << " -- WASAPI error: ";
  215084. switch (hr)
  215085. {
  215086. case E_POINTER: e << "E_POINTER"; break;
  215087. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215088. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215089. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215090. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215091. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215092. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215093. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215094. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215095. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215096. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215097. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215098. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215099. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215100. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215101. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215102. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215103. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215104. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215105. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215106. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215107. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215108. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215109. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215110. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215111. default: e << String::toHexString ((int) hr); break;
  215112. }
  215113. DBG (e);
  215114. jassertfalse;
  215115. }
  215116. #endif
  215117. }
  215118. #undef check
  215119. bool check (HRESULT hr)
  215120. {
  215121. logFailure (hr);
  215122. return SUCCEEDED (hr);
  215123. }
  215124. const String getDeviceID (IMMDevice* const device)
  215125. {
  215126. String s;
  215127. WCHAR* deviceId = 0;
  215128. if (check (device->GetId (&deviceId)))
  215129. {
  215130. s = String (deviceId);
  215131. CoTaskMemFree (deviceId);
  215132. }
  215133. return s;
  215134. }
  215135. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215136. {
  215137. EDataFlow flow = eRender;
  215138. ComSmartPtr <IMMEndpoint> endPoint;
  215139. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215140. (void) check (endPoint->GetDataFlow (&flow));
  215141. return flow;
  215142. }
  215143. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215144. {
  215145. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215146. }
  215147. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215148. {
  215149. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215150. : sizeof (WAVEFORMATEX));
  215151. }
  215152. class WASAPIDeviceBase
  215153. {
  215154. public:
  215155. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215156. : device (device_),
  215157. sampleRate (0),
  215158. defaultSampleRate (0),
  215159. numChannels (0),
  215160. actualNumChannels (0),
  215161. minBufferSize (0),
  215162. defaultBufferSize (0),
  215163. latencySamples (0),
  215164. useExclusiveMode (useExclusiveMode_)
  215165. {
  215166. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215167. ComSmartPtr <IAudioClient> tempClient (createClient());
  215168. if (tempClient == 0)
  215169. return;
  215170. REFERENCE_TIME defaultPeriod, minPeriod;
  215171. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215172. return;
  215173. WAVEFORMATEX* mixFormat = 0;
  215174. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215175. return;
  215176. WAVEFORMATEXTENSIBLE format;
  215177. copyWavFormat (format, mixFormat);
  215178. CoTaskMemFree (mixFormat);
  215179. actualNumChannels = numChannels = format.Format.nChannels;
  215180. defaultSampleRate = format.Format.nSamplesPerSec;
  215181. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215182. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215183. rates.addUsingDefaultSort (defaultSampleRate);
  215184. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215185. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215186. {
  215187. if (ratesToTest[i] == defaultSampleRate)
  215188. continue;
  215189. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215190. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215191. (WAVEFORMATEX*) &format, 0)))
  215192. if (! rates.contains (ratesToTest[i]))
  215193. rates.addUsingDefaultSort (ratesToTest[i]);
  215194. }
  215195. }
  215196. ~WASAPIDeviceBase()
  215197. {
  215198. device = 0;
  215199. CloseHandle (clientEvent);
  215200. }
  215201. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215202. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215203. {
  215204. sampleRate = newSampleRate;
  215205. channels = newChannels;
  215206. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215207. numChannels = channels.getHighestBit() + 1;
  215208. if (numChannels == 0)
  215209. return true;
  215210. client = createClient();
  215211. if (client != 0
  215212. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215213. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215214. {
  215215. channelMaps.clear();
  215216. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215217. if (channels[i])
  215218. channelMaps.add (i);
  215219. REFERENCE_TIME latency;
  215220. if (check (client->GetStreamLatency (&latency)))
  215221. latencySamples = refTimeToSamples (latency, sampleRate);
  215222. (void) check (client->GetBufferSize (&actualBufferSize));
  215223. return check (client->SetEventHandle (clientEvent));
  215224. }
  215225. return false;
  215226. }
  215227. void closeClient()
  215228. {
  215229. if (client != 0)
  215230. client->Stop();
  215231. client = 0;
  215232. ResetEvent (clientEvent);
  215233. }
  215234. ComSmartPtr <IMMDevice> device;
  215235. ComSmartPtr <IAudioClient> client;
  215236. double sampleRate, defaultSampleRate;
  215237. int numChannels, actualNumChannels;
  215238. int minBufferSize, defaultBufferSize, latencySamples;
  215239. const bool useExclusiveMode;
  215240. Array <double> rates;
  215241. HANDLE clientEvent;
  215242. BigInteger channels;
  215243. Array <int> channelMaps;
  215244. UINT32 actualBufferSize;
  215245. int bytesPerSample;
  215246. virtual void updateFormat (bool isFloat) = 0;
  215247. private:
  215248. const ComSmartPtr <IAudioClient> createClient()
  215249. {
  215250. ComSmartPtr <IAudioClient> client;
  215251. if (device != 0)
  215252. {
  215253. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215254. logFailure (hr);
  215255. }
  215256. return client;
  215257. }
  215258. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215259. {
  215260. WAVEFORMATEXTENSIBLE format;
  215261. zerostruct (format);
  215262. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215263. {
  215264. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215265. }
  215266. else
  215267. {
  215268. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215269. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215270. }
  215271. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215272. format.Format.nChannels = (WORD) numChannels;
  215273. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215274. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215275. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215276. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215277. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215278. switch (numChannels)
  215279. {
  215280. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215281. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215282. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215283. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215284. 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;
  215285. default: break;
  215286. }
  215287. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215288. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215289. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215290. logFailure (hr);
  215291. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215292. {
  215293. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215294. hr = S_OK;
  215295. }
  215296. CoTaskMemFree (nearestFormat);
  215297. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215298. if (useExclusiveMode)
  215299. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215300. GUID session;
  215301. if (hr == S_OK
  215302. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215303. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215304. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215305. {
  215306. actualNumChannels = format.Format.nChannels;
  215307. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215308. bytesPerSample = format.Format.wBitsPerSample / 8;
  215309. updateFormat (isFloat);
  215310. return true;
  215311. }
  215312. return false;
  215313. }
  215314. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  215315. };
  215316. class WASAPIInputDevice : public WASAPIDeviceBase
  215317. {
  215318. public:
  215319. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215320. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215321. reservoir (1, 1)
  215322. {
  215323. }
  215324. ~WASAPIInputDevice()
  215325. {
  215326. close();
  215327. }
  215328. bool open (const double newSampleRate, const BigInteger& newChannels)
  215329. {
  215330. reservoirSize = 0;
  215331. reservoirCapacity = 16384;
  215332. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215333. return openClient (newSampleRate, newChannels)
  215334. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  215335. (void**) captureClient.resetAndGetPointerAddress())));
  215336. }
  215337. void close()
  215338. {
  215339. closeClient();
  215340. captureClient = 0;
  215341. reservoir.setSize (0);
  215342. }
  215343. template <class SourceType>
  215344. void updateFormatWithType (SourceType*)
  215345. {
  215346. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215347. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215348. }
  215349. void updateFormat (bool isFloat)
  215350. {
  215351. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215352. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215353. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215354. else updateFormatWithType ((AudioData::Int16*) 0);
  215355. }
  215356. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215357. {
  215358. if (numChannels <= 0)
  215359. return;
  215360. int offset = 0;
  215361. while (bufferSize > 0)
  215362. {
  215363. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215364. {
  215365. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215366. for (int i = 0; i < numDestBuffers; ++i)
  215367. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215368. bufferSize -= samplesToDo;
  215369. offset += samplesToDo;
  215370. reservoirSize = 0;
  215371. }
  215372. else
  215373. {
  215374. UINT32 packetLength = 0;
  215375. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215376. break;
  215377. if (packetLength == 0)
  215378. {
  215379. if (thread.threadShouldExit()
  215380. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215381. break;
  215382. continue;
  215383. }
  215384. uint8* inputData;
  215385. UINT32 numSamplesAvailable;
  215386. DWORD flags;
  215387. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215388. {
  215389. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215390. for (int i = 0; i < numDestBuffers; ++i)
  215391. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215392. bufferSize -= samplesToDo;
  215393. offset += samplesToDo;
  215394. if (samplesToDo < (int) numSamplesAvailable)
  215395. {
  215396. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215397. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215398. bytesPerSample * actualNumChannels * reservoirSize);
  215399. }
  215400. captureClient->ReleaseBuffer (numSamplesAvailable);
  215401. }
  215402. }
  215403. }
  215404. }
  215405. ComSmartPtr <IAudioCaptureClient> captureClient;
  215406. MemoryBlock reservoir;
  215407. int reservoirSize, reservoirCapacity;
  215408. ScopedPointer <AudioData::Converter> converter;
  215409. private:
  215410. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  215411. };
  215412. class WASAPIOutputDevice : public WASAPIDeviceBase
  215413. {
  215414. public:
  215415. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215416. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215417. {
  215418. }
  215419. ~WASAPIOutputDevice()
  215420. {
  215421. close();
  215422. }
  215423. bool open (const double newSampleRate, const BigInteger& newChannels)
  215424. {
  215425. return openClient (newSampleRate, newChannels)
  215426. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215427. }
  215428. void close()
  215429. {
  215430. closeClient();
  215431. renderClient = 0;
  215432. }
  215433. template <class DestType>
  215434. void updateFormatWithType (DestType*)
  215435. {
  215436. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215437. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215438. }
  215439. void updateFormat (bool isFloat)
  215440. {
  215441. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215442. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215443. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215444. else updateFormatWithType ((AudioData::Int16*) 0);
  215445. }
  215446. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215447. {
  215448. if (numChannels <= 0)
  215449. return;
  215450. int offset = 0;
  215451. while (bufferSize > 0)
  215452. {
  215453. UINT32 padding = 0;
  215454. if (! check (client->GetCurrentPadding (&padding)))
  215455. return;
  215456. int samplesToDo = useExclusiveMode ? bufferSize
  215457. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215458. if (samplesToDo <= 0)
  215459. {
  215460. if (thread.threadShouldExit()
  215461. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215462. break;
  215463. continue;
  215464. }
  215465. uint8* outputData = 0;
  215466. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215467. {
  215468. for (int i = 0; i < numSrcBuffers; ++i)
  215469. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  215470. renderClient->ReleaseBuffer (samplesToDo, 0);
  215471. offset += samplesToDo;
  215472. bufferSize -= samplesToDo;
  215473. }
  215474. }
  215475. }
  215476. ComSmartPtr <IAudioRenderClient> renderClient;
  215477. ScopedPointer <AudioData::Converter> converter;
  215478. private:
  215479. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  215480. };
  215481. class WASAPIAudioIODevice : public AudioIODevice,
  215482. public Thread
  215483. {
  215484. public:
  215485. WASAPIAudioIODevice (const String& deviceName,
  215486. const String& outputDeviceId_,
  215487. const String& inputDeviceId_,
  215488. const bool useExclusiveMode_)
  215489. : AudioIODevice (deviceName, "Windows Audio"),
  215490. Thread ("Juce WASAPI"),
  215491. outputDeviceId (outputDeviceId_),
  215492. inputDeviceId (inputDeviceId_),
  215493. useExclusiveMode (useExclusiveMode_),
  215494. isOpen_ (false),
  215495. isStarted (false),
  215496. currentBufferSizeSamples (0),
  215497. currentSampleRate (0),
  215498. callback (0)
  215499. {
  215500. }
  215501. ~WASAPIAudioIODevice()
  215502. {
  215503. close();
  215504. }
  215505. bool initialise()
  215506. {
  215507. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215508. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215509. latencyIn = latencyOut = 0;
  215510. Array <double> ratesIn, ratesOut;
  215511. if (createDevices())
  215512. {
  215513. jassert (inputDevice != 0 || outputDevice != 0);
  215514. if (inputDevice != 0 && outputDevice != 0)
  215515. {
  215516. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215517. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215518. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215519. sampleRates = inputDevice->rates;
  215520. sampleRates.removeValuesNotIn (outputDevice->rates);
  215521. }
  215522. else
  215523. {
  215524. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215525. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215526. defaultSampleRate = d->defaultSampleRate;
  215527. minBufferSize = d->minBufferSize;
  215528. defaultBufferSize = d->defaultBufferSize;
  215529. sampleRates = d->rates;
  215530. }
  215531. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215532. if (minBufferSize != defaultBufferSize)
  215533. bufferSizes.addUsingDefaultSort (minBufferSize);
  215534. int n = 64;
  215535. for (int i = 0; i < 40; ++i)
  215536. {
  215537. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215538. bufferSizes.addUsingDefaultSort (n);
  215539. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215540. }
  215541. return true;
  215542. }
  215543. return false;
  215544. }
  215545. const StringArray getOutputChannelNames()
  215546. {
  215547. StringArray outChannels;
  215548. if (outputDevice != 0)
  215549. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215550. outChannels.add ("Output channel " + String (i));
  215551. return outChannels;
  215552. }
  215553. const StringArray getInputChannelNames()
  215554. {
  215555. StringArray inChannels;
  215556. if (inputDevice != 0)
  215557. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215558. inChannels.add ("Input channel " + String (i));
  215559. return inChannels;
  215560. }
  215561. int getNumSampleRates() { return sampleRates.size(); }
  215562. double getSampleRate (int index) { return sampleRates [index]; }
  215563. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215564. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215565. int getDefaultBufferSize() { return defaultBufferSize; }
  215566. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215567. double getCurrentSampleRate() { return currentSampleRate; }
  215568. int getCurrentBitDepth() { return 32; }
  215569. int getOutputLatencyInSamples() { return latencyOut; }
  215570. int getInputLatencyInSamples() { return latencyIn; }
  215571. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215572. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215573. const String getLastError() { return lastError; }
  215574. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215575. double sampleRate, int bufferSizeSamples)
  215576. {
  215577. close();
  215578. lastError = String::empty;
  215579. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215580. {
  215581. lastError = "The input and output devices don't share a common sample rate!";
  215582. return lastError;
  215583. }
  215584. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215585. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215586. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215587. {
  215588. lastError = "Couldn't open the input device!";
  215589. return lastError;
  215590. }
  215591. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215592. {
  215593. close();
  215594. lastError = "Couldn't open the output device!";
  215595. return lastError;
  215596. }
  215597. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215598. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215599. startThread (8);
  215600. Thread::sleep (5);
  215601. if (inputDevice != 0 && inputDevice->client != 0)
  215602. {
  215603. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215604. HRESULT hr = inputDevice->client->Start();
  215605. logFailure (hr); //xxx handle this
  215606. }
  215607. if (outputDevice != 0 && outputDevice->client != 0)
  215608. {
  215609. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215610. HRESULT hr = outputDevice->client->Start();
  215611. logFailure (hr); //xxx handle this
  215612. }
  215613. isOpen_ = true;
  215614. return lastError;
  215615. }
  215616. void close()
  215617. {
  215618. stop();
  215619. signalThreadShouldExit();
  215620. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215621. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215622. stopThread (5000);
  215623. if (inputDevice != 0) inputDevice->close();
  215624. if (outputDevice != 0) outputDevice->close();
  215625. isOpen_ = false;
  215626. }
  215627. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215628. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215629. void start (AudioIODeviceCallback* call)
  215630. {
  215631. if (isOpen_ && call != 0 && ! isStarted)
  215632. {
  215633. if (! isThreadRunning())
  215634. {
  215635. // something's gone wrong and the thread's stopped..
  215636. isOpen_ = false;
  215637. return;
  215638. }
  215639. call->audioDeviceAboutToStart (this);
  215640. const ScopedLock sl (startStopLock);
  215641. callback = call;
  215642. isStarted = true;
  215643. }
  215644. }
  215645. void stop()
  215646. {
  215647. if (isStarted)
  215648. {
  215649. AudioIODeviceCallback* const callbackLocal = callback;
  215650. {
  215651. const ScopedLock sl (startStopLock);
  215652. isStarted = false;
  215653. }
  215654. if (callbackLocal != 0)
  215655. callbackLocal->audioDeviceStopped();
  215656. }
  215657. }
  215658. void setMMThreadPriority()
  215659. {
  215660. DynamicLibraryLoader dll ("avrt.dll");
  215661. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215662. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215663. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215664. {
  215665. DWORD dummy = 0;
  215666. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215667. if (h != 0)
  215668. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215669. }
  215670. }
  215671. void run()
  215672. {
  215673. setMMThreadPriority();
  215674. const int bufferSize = currentBufferSizeSamples;
  215675. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215676. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215677. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215678. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215679. float** const inputBuffers = ins.getArrayOfChannels();
  215680. float** const outputBuffers = outs.getArrayOfChannels();
  215681. ins.clear();
  215682. while (! threadShouldExit())
  215683. {
  215684. if (inputDevice != 0)
  215685. {
  215686. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215687. if (threadShouldExit())
  215688. break;
  215689. }
  215690. JUCE_TRY
  215691. {
  215692. const ScopedLock sl (startStopLock);
  215693. if (isStarted)
  215694. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215695. outputBuffers, numOutputBuffers, bufferSize);
  215696. else
  215697. outs.clear();
  215698. }
  215699. JUCE_CATCH_EXCEPTION
  215700. if (outputDevice != 0)
  215701. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215702. }
  215703. }
  215704. String outputDeviceId, inputDeviceId;
  215705. String lastError;
  215706. private:
  215707. // Device stats...
  215708. ScopedPointer<WASAPIInputDevice> inputDevice;
  215709. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215710. const bool useExclusiveMode;
  215711. double defaultSampleRate;
  215712. int minBufferSize, defaultBufferSize;
  215713. int latencyIn, latencyOut;
  215714. Array <double> sampleRates;
  215715. Array <int> bufferSizes;
  215716. // Active state...
  215717. bool isOpen_, isStarted;
  215718. int currentBufferSizeSamples;
  215719. double currentSampleRate;
  215720. AudioIODeviceCallback* callback;
  215721. CriticalSection startStopLock;
  215722. bool createDevices()
  215723. {
  215724. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215725. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215726. return false;
  215727. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215728. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215729. return false;
  215730. UINT32 numDevices = 0;
  215731. if (! check (deviceCollection->GetCount (&numDevices)))
  215732. return false;
  215733. for (UINT32 i = 0; i < numDevices; ++i)
  215734. {
  215735. ComSmartPtr <IMMDevice> device;
  215736. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215737. continue;
  215738. const String deviceId (getDeviceID (device));
  215739. if (deviceId.isEmpty())
  215740. continue;
  215741. const EDataFlow flow = getDataFlow (device);
  215742. if (deviceId == inputDeviceId && flow == eCapture)
  215743. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215744. else if (deviceId == outputDeviceId && flow == eRender)
  215745. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215746. }
  215747. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215748. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215749. }
  215750. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215751. };
  215752. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215753. {
  215754. public:
  215755. WASAPIAudioIODeviceType()
  215756. : AudioIODeviceType ("Windows Audio"),
  215757. hasScanned (false)
  215758. {
  215759. }
  215760. ~WASAPIAudioIODeviceType()
  215761. {
  215762. }
  215763. void scanForDevices()
  215764. {
  215765. hasScanned = true;
  215766. outputDeviceNames.clear();
  215767. inputDeviceNames.clear();
  215768. outputDeviceIds.clear();
  215769. inputDeviceIds.clear();
  215770. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215771. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215772. return;
  215773. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215774. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215775. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215776. UINT32 numDevices = 0;
  215777. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215778. && check (deviceCollection->GetCount (&numDevices))))
  215779. return;
  215780. for (UINT32 i = 0; i < numDevices; ++i)
  215781. {
  215782. ComSmartPtr <IMMDevice> device;
  215783. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215784. continue;
  215785. const String deviceId (getDeviceID (device));
  215786. DWORD state = 0;
  215787. if (! check (device->GetState (&state)))
  215788. continue;
  215789. if (state != DEVICE_STATE_ACTIVE)
  215790. continue;
  215791. String name;
  215792. {
  215793. ComSmartPtr <IPropertyStore> properties;
  215794. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215795. continue;
  215796. PROPVARIANT value;
  215797. PropVariantInit (&value);
  215798. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215799. name = value.pwszVal;
  215800. PropVariantClear (&value);
  215801. }
  215802. const EDataFlow flow = getDataFlow (device);
  215803. if (flow == eRender)
  215804. {
  215805. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215806. outputDeviceIds.insert (index, deviceId);
  215807. outputDeviceNames.insert (index, name);
  215808. }
  215809. else if (flow == eCapture)
  215810. {
  215811. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215812. inputDeviceIds.insert (index, deviceId);
  215813. inputDeviceNames.insert (index, name);
  215814. }
  215815. }
  215816. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215817. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215818. }
  215819. const StringArray getDeviceNames (bool wantInputNames) const
  215820. {
  215821. jassert (hasScanned); // need to call scanForDevices() before doing this
  215822. return wantInputNames ? inputDeviceNames
  215823. : outputDeviceNames;
  215824. }
  215825. int getDefaultDeviceIndex (bool /*forInput*/) const
  215826. {
  215827. jassert (hasScanned); // need to call scanForDevices() before doing this
  215828. return 0;
  215829. }
  215830. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215831. {
  215832. jassert (hasScanned); // need to call scanForDevices() before doing this
  215833. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215834. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215835. : outputDeviceIds.indexOf (d->outputDeviceId));
  215836. }
  215837. bool hasSeparateInputsAndOutputs() const { return true; }
  215838. AudioIODevice* createDevice (const String& outputDeviceName,
  215839. const String& inputDeviceName)
  215840. {
  215841. jassert (hasScanned); // need to call scanForDevices() before doing this
  215842. const bool useExclusiveMode = false;
  215843. ScopedPointer<WASAPIAudioIODevice> device;
  215844. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215845. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215846. if (outputIndex >= 0 || inputIndex >= 0)
  215847. {
  215848. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215849. : inputDeviceName,
  215850. outputDeviceIds [outputIndex],
  215851. inputDeviceIds [inputIndex],
  215852. useExclusiveMode);
  215853. if (! device->initialise())
  215854. device = 0;
  215855. }
  215856. return device.release();
  215857. }
  215858. StringArray outputDeviceNames, outputDeviceIds;
  215859. StringArray inputDeviceNames, inputDeviceIds;
  215860. private:
  215861. bool hasScanned;
  215862. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215863. {
  215864. String s;
  215865. IMMDevice* dev = 0;
  215866. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215867. eMultimedia, &dev)))
  215868. {
  215869. WCHAR* deviceId = 0;
  215870. if (check (dev->GetId (&deviceId)))
  215871. {
  215872. s = String (deviceId);
  215873. CoTaskMemFree (deviceId);
  215874. }
  215875. dev->Release();
  215876. }
  215877. return s;
  215878. }
  215879. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215880. };
  215881. }
  215882. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI()
  215883. {
  215884. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  215885. return new WasapiClasses::WASAPIAudioIODeviceType();
  215886. return 0;
  215887. }
  215888. #endif
  215889. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215890. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215891. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215892. // compiled on its own).
  215893. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215894. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215895. {
  215896. public:
  215897. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215898. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215899. const ComSmartPtr <IBaseFilter>& filter_,
  215900. int minWidth, int minHeight,
  215901. int maxWidth, int maxHeight)
  215902. : owner (owner_),
  215903. captureGraphBuilder (captureGraphBuilder_),
  215904. filter (filter_),
  215905. ok (false),
  215906. imageNeedsFlipping (false),
  215907. width (0),
  215908. height (0),
  215909. activeUsers (0),
  215910. recordNextFrameTime (false),
  215911. previewMaxFPS (60)
  215912. {
  215913. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215914. if (FAILED (hr))
  215915. return;
  215916. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215917. if (FAILED (hr))
  215918. return;
  215919. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215920. if (FAILED (hr))
  215921. return;
  215922. {
  215923. ComSmartPtr <IAMStreamConfig> streamConfig;
  215924. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215925. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215926. if (streamConfig != 0)
  215927. {
  215928. getVideoSizes (streamConfig);
  215929. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215930. return;
  215931. }
  215932. }
  215933. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215934. if (FAILED (hr))
  215935. return;
  215936. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215937. if (FAILED (hr))
  215938. return;
  215939. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215940. if (FAILED (hr))
  215941. return;
  215942. if (! connectFilters (filter, smartTee))
  215943. return;
  215944. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215945. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215946. if (FAILED (hr))
  215947. return;
  215948. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215949. if (FAILED (hr))
  215950. return;
  215951. AM_MEDIA_TYPE mt;
  215952. zerostruct (mt);
  215953. mt.majortype = MEDIATYPE_Video;
  215954. mt.subtype = MEDIASUBTYPE_RGB24;
  215955. mt.formattype = FORMAT_VideoInfo;
  215956. sampleGrabber->SetMediaType (&mt);
  215957. callback = new GrabberCallback (*this);
  215958. hr = sampleGrabber->SetCallback (callback, 1);
  215959. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215960. if (FAILED (hr))
  215961. return;
  215962. ComSmartPtr <IPin> grabberInputPin;
  215963. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215964. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215965. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215966. return;
  215967. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215968. if (FAILED (hr))
  215969. return;
  215970. zerostruct (mt);
  215971. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215972. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215973. width = pVih->bmiHeader.biWidth;
  215974. height = pVih->bmiHeader.biHeight;
  215975. ComSmartPtr <IBaseFilter> nullFilter;
  215976. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215977. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215978. if (connectFilters (sampleGrabberBase, nullFilter)
  215979. && addGraphToRot())
  215980. {
  215981. activeImage = Image (Image::RGB, width, height, true);
  215982. loadingImage = Image (Image::RGB, width, height, true);
  215983. ok = true;
  215984. }
  215985. }
  215986. ~DShowCameraDeviceInteral()
  215987. {
  215988. if (mediaControl != 0)
  215989. mediaControl->Stop();
  215990. removeGraphFromRot();
  215991. for (int i = viewerComps.size(); --i >= 0;)
  215992. viewerComps.getUnchecked(i)->ownerDeleted();
  215993. callback = 0;
  215994. graphBuilder = 0;
  215995. sampleGrabber = 0;
  215996. mediaControl = 0;
  215997. filter = 0;
  215998. captureGraphBuilder = 0;
  215999. smartTee = 0;
  216000. smartTeePreviewOutputPin = 0;
  216001. smartTeeCaptureOutputPin = 0;
  216002. asfWriter = 0;
  216003. }
  216004. void addUser()
  216005. {
  216006. if (ok && activeUsers++ == 0)
  216007. mediaControl->Run();
  216008. }
  216009. void removeUser()
  216010. {
  216011. if (ok && --activeUsers == 0)
  216012. mediaControl->Stop();
  216013. }
  216014. int getPreviewMaxFPS() const
  216015. {
  216016. return previewMaxFPS;
  216017. }
  216018. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216019. {
  216020. if (recordNextFrameTime)
  216021. {
  216022. const double defaultCameraLatency = 0.1;
  216023. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216024. recordNextFrameTime = false;
  216025. ComSmartPtr <IPin> pin;
  216026. if (getPin (filter, PINDIR_OUTPUT, pin))
  216027. {
  216028. ComSmartPtr <IAMPushSource> pushSource;
  216029. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216030. if (pushSource != 0)
  216031. {
  216032. REFERENCE_TIME latency = 0;
  216033. hr = pushSource->GetLatency (&latency);
  216034. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216035. }
  216036. }
  216037. }
  216038. {
  216039. const int lineStride = width * 3;
  216040. const ScopedLock sl (imageSwapLock);
  216041. {
  216042. const Image::BitmapData destData (loadingImage, 0, 0, width, height, Image::BitmapData::writeOnly);
  216043. for (int i = 0; i < height; ++i)
  216044. memcpy (destData.getLinePointer ((height - 1) - i),
  216045. buffer + lineStride * i,
  216046. lineStride);
  216047. }
  216048. imageNeedsFlipping = true;
  216049. }
  216050. if (listeners.size() > 0)
  216051. callListeners (loadingImage);
  216052. sendChangeMessage();
  216053. }
  216054. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216055. {
  216056. if (imageNeedsFlipping)
  216057. {
  216058. const ScopedLock sl (imageSwapLock);
  216059. swapVariables (loadingImage, activeImage);
  216060. imageNeedsFlipping = false;
  216061. }
  216062. RectanglePlacement rp (RectanglePlacement::centred);
  216063. double dx = 0, dy = 0, dw = width, dh = height;
  216064. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216065. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216066. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216067. {
  216068. Graphics::ScopedSaveState ss (g);
  216069. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216070. g.fillAll (Colours::black);
  216071. }
  216072. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216073. }
  216074. bool createFileCaptureFilter (const File& file, int quality)
  216075. {
  216076. removeFileCaptureFilter();
  216077. file.deleteFile();
  216078. mediaControl->Stop();
  216079. firstRecordedTime = Time();
  216080. recordNextFrameTime = true;
  216081. previewMaxFPS = 60;
  216082. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216083. if (SUCCEEDED (hr))
  216084. {
  216085. ComSmartPtr <IFileSinkFilter> fileSink;
  216086. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216087. if (SUCCEEDED (hr))
  216088. {
  216089. hr = fileSink->SetFileName (file.getFullPathName().toUTF16(), 0);
  216090. if (SUCCEEDED (hr))
  216091. {
  216092. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216093. if (SUCCEEDED (hr))
  216094. {
  216095. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216096. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216097. asfConfig->SetIndexMode (true);
  216098. ComSmartPtr <IWMProfileManager> profileManager;
  216099. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216100. // This gibberish is the DirectShow profile for a video-only wmv file.
  216101. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  216102. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  216103. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216104. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  216105. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216106. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  216107. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  216108. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  216109. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216110. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216111. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216112. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  216113. "biclrused=\"0\" biclrimportant=\"0\"/>"
  216114. "</videoinfoheader>"
  216115. "</wmmediatype>"
  216116. "</streamconfig>"
  216117. "</profile>");
  216118. const int fps[] = { 10, 15, 30 };
  216119. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  216120. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216121. maxFramesPerSecond = (quality >> 24) & 0xff;
  216122. prof = prof.replace ("$WIDTH", String (width))
  216123. .replace ("$HEIGHT", String (height))
  216124. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  216125. ComSmartPtr <IWMProfile> currentProfile;
  216126. hr = profileManager->LoadProfileByData (prof.toUTF16(), currentProfile.resetAndGetPointerAddress());
  216127. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216128. if (SUCCEEDED (hr))
  216129. {
  216130. ComSmartPtr <IPin> asfWriterInputPin;
  216131. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216132. {
  216133. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216134. if (SUCCEEDED (hr) && ok && activeUsers > 0
  216135. && SUCCEEDED (mediaControl->Run()))
  216136. {
  216137. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  216138. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216139. previewMaxFPS = (quality >> 16) & 0xff;
  216140. return true;
  216141. }
  216142. }
  216143. }
  216144. }
  216145. }
  216146. }
  216147. }
  216148. removeFileCaptureFilter();
  216149. if (ok && activeUsers > 0)
  216150. mediaControl->Run();
  216151. return false;
  216152. }
  216153. void removeFileCaptureFilter()
  216154. {
  216155. mediaControl->Stop();
  216156. if (asfWriter != 0)
  216157. {
  216158. graphBuilder->RemoveFilter (asfWriter);
  216159. asfWriter = 0;
  216160. }
  216161. if (ok && activeUsers > 0)
  216162. mediaControl->Run();
  216163. previewMaxFPS = 60;
  216164. }
  216165. void addListener (CameraDevice::Listener* listenerToAdd)
  216166. {
  216167. const ScopedLock sl (listenerLock);
  216168. if (listeners.size() == 0)
  216169. addUser();
  216170. listeners.addIfNotAlreadyThere (listenerToAdd);
  216171. }
  216172. void removeListener (CameraDevice::Listener* listenerToRemove)
  216173. {
  216174. const ScopedLock sl (listenerLock);
  216175. listeners.removeValue (listenerToRemove);
  216176. if (listeners.size() == 0)
  216177. removeUser();
  216178. }
  216179. void callListeners (const Image& image)
  216180. {
  216181. const ScopedLock sl (listenerLock);
  216182. for (int i = listeners.size(); --i >= 0;)
  216183. {
  216184. CameraDevice::Listener* const l = listeners[i];
  216185. if (l != 0)
  216186. l->imageReceived (image);
  216187. }
  216188. }
  216189. class DShowCaptureViewerComp : public Component,
  216190. public ChangeListener
  216191. {
  216192. public:
  216193. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216194. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  216195. {
  216196. setOpaque (true);
  216197. owner->addChangeListener (this);
  216198. owner->addUser();
  216199. owner->viewerComps.add (this);
  216200. setSize (owner->width, owner->height);
  216201. }
  216202. ~DShowCaptureViewerComp()
  216203. {
  216204. if (owner != 0)
  216205. {
  216206. owner->viewerComps.removeValue (this);
  216207. owner->removeUser();
  216208. owner->removeChangeListener (this);
  216209. }
  216210. }
  216211. void ownerDeleted()
  216212. {
  216213. owner = 0;
  216214. }
  216215. void paint (Graphics& g)
  216216. {
  216217. g.setColour (Colours::black);
  216218. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216219. if (owner != 0)
  216220. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216221. else
  216222. g.fillAll (Colours::black);
  216223. }
  216224. void changeListenerCallback (ChangeBroadcaster*)
  216225. {
  216226. const int64 now = Time::currentTimeMillis();
  216227. if (now >= lastRepaintTime + (1000 / maxFPS))
  216228. {
  216229. lastRepaintTime = now;
  216230. repaint();
  216231. if (owner != 0)
  216232. maxFPS = owner->getPreviewMaxFPS();
  216233. }
  216234. }
  216235. private:
  216236. DShowCameraDeviceInteral* owner;
  216237. int maxFPS;
  216238. int64 lastRepaintTime;
  216239. };
  216240. bool ok;
  216241. int width, height;
  216242. Time firstRecordedTime;
  216243. Array <DShowCaptureViewerComp*> viewerComps;
  216244. private:
  216245. CameraDevice* const owner;
  216246. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216247. ComSmartPtr <IBaseFilter> filter;
  216248. ComSmartPtr <IBaseFilter> smartTee;
  216249. ComSmartPtr <IGraphBuilder> graphBuilder;
  216250. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216251. ComSmartPtr <IMediaControl> mediaControl;
  216252. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216253. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216254. ComSmartPtr <IBaseFilter> asfWriter;
  216255. int activeUsers;
  216256. Array <int> widths, heights;
  216257. DWORD graphRegistrationID;
  216258. CriticalSection imageSwapLock;
  216259. bool imageNeedsFlipping;
  216260. Image loadingImage;
  216261. Image activeImage;
  216262. bool recordNextFrameTime;
  216263. int previewMaxFPS;
  216264. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216265. {
  216266. widths.clear();
  216267. heights.clear();
  216268. int count = 0, size = 0;
  216269. streamConfig->GetNumberOfCapabilities (&count, &size);
  216270. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216271. {
  216272. for (int i = 0; i < count; ++i)
  216273. {
  216274. VIDEO_STREAM_CONFIG_CAPS scc;
  216275. AM_MEDIA_TYPE* config;
  216276. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216277. if (SUCCEEDED (hr))
  216278. {
  216279. const int w = scc.InputSize.cx;
  216280. const int h = scc.InputSize.cy;
  216281. bool duplicate = false;
  216282. for (int j = widths.size(); --j >= 0;)
  216283. {
  216284. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216285. {
  216286. duplicate = true;
  216287. break;
  216288. }
  216289. }
  216290. if (! duplicate)
  216291. {
  216292. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216293. widths.add (w);
  216294. heights.add (h);
  216295. }
  216296. deleteMediaType (config);
  216297. }
  216298. }
  216299. }
  216300. }
  216301. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216302. const int minWidth, const int minHeight,
  216303. const int maxWidth, const int maxHeight)
  216304. {
  216305. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216306. streamConfig->GetNumberOfCapabilities (&count, &size);
  216307. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216308. {
  216309. AM_MEDIA_TYPE* config;
  216310. VIDEO_STREAM_CONFIG_CAPS scc;
  216311. for (int i = 0; i < count; ++i)
  216312. {
  216313. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216314. if (SUCCEEDED (hr))
  216315. {
  216316. if (scc.InputSize.cx >= minWidth
  216317. && scc.InputSize.cy >= minHeight
  216318. && scc.InputSize.cx <= maxWidth
  216319. && scc.InputSize.cy <= maxHeight)
  216320. {
  216321. int area = scc.InputSize.cx * scc.InputSize.cy;
  216322. if (area > bestArea)
  216323. {
  216324. bestIndex = i;
  216325. bestArea = area;
  216326. }
  216327. }
  216328. deleteMediaType (config);
  216329. }
  216330. }
  216331. if (bestIndex >= 0)
  216332. {
  216333. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216334. hr = streamConfig->SetFormat (config);
  216335. deleteMediaType (config);
  216336. return SUCCEEDED (hr);
  216337. }
  216338. }
  216339. return false;
  216340. }
  216341. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216342. {
  216343. ComSmartPtr <IEnumPins> enumerator;
  216344. ComSmartPtr <IPin> pin;
  216345. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216346. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216347. {
  216348. PIN_DIRECTION dir;
  216349. pin->QueryDirection (&dir);
  216350. if (wantedDirection == dir)
  216351. {
  216352. PIN_INFO info;
  216353. zerostruct (info);
  216354. pin->QueryPinInfo (&info);
  216355. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216356. {
  216357. result = pin;
  216358. return true;
  216359. }
  216360. }
  216361. }
  216362. return false;
  216363. }
  216364. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216365. {
  216366. ComSmartPtr <IPin> in, out;
  216367. return getPin (first, PINDIR_OUTPUT, out)
  216368. && getPin (second, PINDIR_INPUT, in)
  216369. && SUCCEEDED (graphBuilder->Connect (out, in));
  216370. }
  216371. bool addGraphToRot()
  216372. {
  216373. ComSmartPtr <IRunningObjectTable> rot;
  216374. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216375. return false;
  216376. ComSmartPtr <IMoniker> moniker;
  216377. WCHAR buffer[128];
  216378. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216379. if (FAILED (hr))
  216380. return false;
  216381. graphRegistrationID = 0;
  216382. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216383. }
  216384. void removeGraphFromRot()
  216385. {
  216386. ComSmartPtr <IRunningObjectTable> rot;
  216387. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216388. rot->Revoke (graphRegistrationID);
  216389. }
  216390. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216391. {
  216392. if (pmt->cbFormat != 0)
  216393. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216394. if (pmt->pUnk != 0)
  216395. pmt->pUnk->Release();
  216396. CoTaskMemFree (pmt);
  216397. }
  216398. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216399. {
  216400. public:
  216401. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216402. : owner (owner_)
  216403. {
  216404. }
  216405. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216406. {
  216407. return E_FAIL;
  216408. }
  216409. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216410. {
  216411. owner.handleFrame (time, buffer, bufferSize);
  216412. return S_OK;
  216413. }
  216414. private:
  216415. DShowCameraDeviceInteral& owner;
  216416. GrabberCallback (const GrabberCallback&);
  216417. GrabberCallback& operator= (const GrabberCallback&);
  216418. };
  216419. ComSmartPtr <GrabberCallback> callback;
  216420. Array <CameraDevice::Listener*> listeners;
  216421. CriticalSection listenerLock;
  216422. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  216423. };
  216424. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216425. : name (name_)
  216426. {
  216427. isRecording = false;
  216428. }
  216429. CameraDevice::~CameraDevice()
  216430. {
  216431. stopRecording();
  216432. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216433. internal = 0;
  216434. }
  216435. Component* CameraDevice::createViewerComponent()
  216436. {
  216437. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216438. }
  216439. const String CameraDevice::getFileExtension()
  216440. {
  216441. return ".wmv";
  216442. }
  216443. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216444. {
  216445. stopRecording();
  216446. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216447. d->addUser();
  216448. isRecording = d->createFileCaptureFilter (file, quality);
  216449. }
  216450. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216451. {
  216452. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216453. return d->firstRecordedTime;
  216454. }
  216455. void CameraDevice::stopRecording()
  216456. {
  216457. if (isRecording)
  216458. {
  216459. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216460. d->removeFileCaptureFilter();
  216461. d->removeUser();
  216462. isRecording = false;
  216463. }
  216464. }
  216465. void CameraDevice::addListener (Listener* listenerToAdd)
  216466. {
  216467. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216468. if (listenerToAdd != 0)
  216469. d->addListener (listenerToAdd);
  216470. }
  216471. void CameraDevice::removeListener (Listener* listenerToRemove)
  216472. {
  216473. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216474. if (listenerToRemove != 0)
  216475. d->removeListener (listenerToRemove);
  216476. }
  216477. namespace
  216478. {
  216479. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216480. const int deviceIndexToOpen,
  216481. String& name)
  216482. {
  216483. int index = 0;
  216484. ComSmartPtr <IBaseFilter> result;
  216485. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216486. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216487. if (SUCCEEDED (hr))
  216488. {
  216489. ComSmartPtr <IEnumMoniker> enumerator;
  216490. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216491. if (SUCCEEDED (hr) && enumerator != 0)
  216492. {
  216493. ComSmartPtr <IMoniker> moniker;
  216494. ULONG fetched;
  216495. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216496. {
  216497. ComSmartPtr <IBaseFilter> captureFilter;
  216498. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216499. if (SUCCEEDED (hr))
  216500. {
  216501. ComSmartPtr <IPropertyBag> propertyBag;
  216502. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216503. if (SUCCEEDED (hr))
  216504. {
  216505. VARIANT var;
  216506. var.vt = VT_BSTR;
  216507. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216508. propertyBag = 0;
  216509. if (SUCCEEDED (hr))
  216510. {
  216511. if (names != 0)
  216512. names->add (var.bstrVal);
  216513. if (index == deviceIndexToOpen)
  216514. {
  216515. name = var.bstrVal;
  216516. result = captureFilter;
  216517. break;
  216518. }
  216519. ++index;
  216520. }
  216521. }
  216522. }
  216523. }
  216524. }
  216525. }
  216526. return result;
  216527. }
  216528. }
  216529. const StringArray CameraDevice::getAvailableDevices()
  216530. {
  216531. StringArray devs;
  216532. String dummy;
  216533. enumerateCameras (&devs, -1, dummy);
  216534. return devs;
  216535. }
  216536. CameraDevice* CameraDevice::openDevice (int index,
  216537. int minWidth, int minHeight,
  216538. int maxWidth, int maxHeight)
  216539. {
  216540. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216541. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216542. if (SUCCEEDED (hr))
  216543. {
  216544. String name;
  216545. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216546. if (filter != 0)
  216547. {
  216548. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216549. DShowCameraDeviceInteral* const intern
  216550. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216551. minWidth, minHeight, maxWidth, maxHeight);
  216552. cam->internal = intern;
  216553. if (intern->ok)
  216554. return cam.release();
  216555. }
  216556. }
  216557. return 0;
  216558. }
  216559. #endif
  216560. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216561. #endif
  216562. // Auto-link the other win32 libs that are needed by library calls..
  216563. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216564. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216565. // Auto-links to various win32 libs that are needed by library calls..
  216566. #pragma comment(lib, "kernel32.lib")
  216567. #pragma comment(lib, "user32.lib")
  216568. #pragma comment(lib, "shell32.lib")
  216569. #pragma comment(lib, "gdi32.lib")
  216570. #pragma comment(lib, "vfw32.lib")
  216571. #pragma comment(lib, "comdlg32.lib")
  216572. #pragma comment(lib, "winmm.lib")
  216573. #pragma comment(lib, "wininet.lib")
  216574. #pragma comment(lib, "ole32.lib")
  216575. #pragma comment(lib, "oleaut32.lib")
  216576. #pragma comment(lib, "advapi32.lib")
  216577. #pragma comment(lib, "ws2_32.lib")
  216578. #pragma comment(lib, "version.lib")
  216579. #pragma comment(lib, "shlwapi.lib")
  216580. #ifdef _NATIVE_WCHAR_T_DEFINED
  216581. #ifdef _DEBUG
  216582. #pragma comment(lib, "comsuppwd.lib")
  216583. #else
  216584. #pragma comment(lib, "comsuppw.lib")
  216585. #endif
  216586. #else
  216587. #ifdef _DEBUG
  216588. #pragma comment(lib, "comsuppd.lib")
  216589. #else
  216590. #pragma comment(lib, "comsupp.lib")
  216591. #endif
  216592. #endif
  216593. #if JUCE_OPENGL
  216594. #pragma comment(lib, "OpenGL32.Lib")
  216595. #pragma comment(lib, "GlU32.Lib")
  216596. #endif
  216597. #if JUCE_QUICKTIME
  216598. #pragma comment (lib, "QTMLClient.lib")
  216599. #endif
  216600. #if JUCE_USE_CAMERA
  216601. #pragma comment (lib, "Strmiids.lib")
  216602. #pragma comment (lib, "wmvcore.lib")
  216603. #endif
  216604. #if JUCE_DIRECT2D
  216605. #pragma comment (lib, "Dwrite.lib")
  216606. #pragma comment (lib, "D2d1.lib")
  216607. #endif
  216608. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216609. #endif
  216610. END_JUCE_NAMESPACE
  216611. #endif
  216612. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216613. #elif JUCE_LINUX
  216614. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216615. /*
  216616. This file wraps together all the mac-specific code, so that
  216617. we can include all the native headers just once, and compile all our
  216618. platform-specific stuff in one big lump, keeping it out of the way of
  216619. the rest of the codebase.
  216620. */
  216621. #if JUCE_LINUX
  216622. #undef JUCE_BUILD_NATIVE
  216623. #define JUCE_BUILD_NATIVE 1
  216624. BEGIN_JUCE_NAMESPACE
  216625. #define JUCE_INCLUDED_FILE 1
  216626. // Now include the actual code files..
  216627. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216628. /*
  216629. This file contains posix routines that are common to both the Linux and Mac builds.
  216630. It gets included directly in the cpp files for these platforms.
  216631. */
  216632. CriticalSection::CriticalSection() throw()
  216633. {
  216634. pthread_mutexattr_t atts;
  216635. pthread_mutexattr_init (&atts);
  216636. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216637. #if ! JUCE_ANDROID
  216638. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216639. #endif
  216640. pthread_mutex_init (&internal, &atts);
  216641. }
  216642. CriticalSection::~CriticalSection() throw()
  216643. {
  216644. pthread_mutex_destroy (&internal);
  216645. }
  216646. void CriticalSection::enter() const throw()
  216647. {
  216648. pthread_mutex_lock (&internal);
  216649. }
  216650. bool CriticalSection::tryEnter() const throw()
  216651. {
  216652. return pthread_mutex_trylock (&internal) == 0;
  216653. }
  216654. void CriticalSection::exit() const throw()
  216655. {
  216656. pthread_mutex_unlock (&internal);
  216657. }
  216658. class WaitableEventImpl
  216659. {
  216660. public:
  216661. WaitableEventImpl (const bool manualReset_)
  216662. : triggered (false),
  216663. manualReset (manualReset_)
  216664. {
  216665. pthread_cond_init (&condition, 0);
  216666. pthread_mutexattr_t atts;
  216667. pthread_mutexattr_init (&atts);
  216668. #if ! JUCE_ANDROID
  216669. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216670. #endif
  216671. pthread_mutex_init (&mutex, &atts);
  216672. }
  216673. ~WaitableEventImpl()
  216674. {
  216675. pthread_cond_destroy (&condition);
  216676. pthread_mutex_destroy (&mutex);
  216677. }
  216678. bool wait (const int timeOutMillisecs) throw()
  216679. {
  216680. pthread_mutex_lock (&mutex);
  216681. if (! triggered)
  216682. {
  216683. if (timeOutMillisecs < 0)
  216684. {
  216685. do
  216686. {
  216687. pthread_cond_wait (&condition, &mutex);
  216688. }
  216689. while (! triggered);
  216690. }
  216691. else
  216692. {
  216693. struct timeval now;
  216694. gettimeofday (&now, 0);
  216695. struct timespec time;
  216696. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216697. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216698. if (time.tv_nsec >= 1000000000)
  216699. {
  216700. time.tv_nsec -= 1000000000;
  216701. time.tv_sec++;
  216702. }
  216703. do
  216704. {
  216705. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216706. {
  216707. pthread_mutex_unlock (&mutex);
  216708. return false;
  216709. }
  216710. }
  216711. while (! triggered);
  216712. }
  216713. }
  216714. if (! manualReset)
  216715. triggered = false;
  216716. pthread_mutex_unlock (&mutex);
  216717. return true;
  216718. }
  216719. void signal() throw()
  216720. {
  216721. pthread_mutex_lock (&mutex);
  216722. triggered = true;
  216723. pthread_cond_broadcast (&condition);
  216724. pthread_mutex_unlock (&mutex);
  216725. }
  216726. void reset() throw()
  216727. {
  216728. pthread_mutex_lock (&mutex);
  216729. triggered = false;
  216730. pthread_mutex_unlock (&mutex);
  216731. }
  216732. private:
  216733. pthread_cond_t condition;
  216734. pthread_mutex_t mutex;
  216735. bool triggered;
  216736. const bool manualReset;
  216737. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216738. };
  216739. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216740. : internal (new WaitableEventImpl (manualReset))
  216741. {
  216742. }
  216743. WaitableEvent::~WaitableEvent() throw()
  216744. {
  216745. delete static_cast <WaitableEventImpl*> (internal);
  216746. }
  216747. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216748. {
  216749. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216750. }
  216751. void WaitableEvent::signal() const throw()
  216752. {
  216753. static_cast <WaitableEventImpl*> (internal)->signal();
  216754. }
  216755. void WaitableEvent::reset() const throw()
  216756. {
  216757. static_cast <WaitableEventImpl*> (internal)->reset();
  216758. }
  216759. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216760. {
  216761. struct timespec time;
  216762. time.tv_sec = millisecs / 1000;
  216763. time.tv_nsec = (millisecs % 1000) * 1000000;
  216764. nanosleep (&time, 0);
  216765. }
  216766. const juce_wchar File::separator = '/';
  216767. const String File::separatorString ("/");
  216768. const File File::getCurrentWorkingDirectory()
  216769. {
  216770. HeapBlock<char> heapBuffer;
  216771. char localBuffer [1024];
  216772. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216773. int bufferSize = 4096;
  216774. while (cwd == 0 && errno == ERANGE)
  216775. {
  216776. heapBuffer.malloc (bufferSize);
  216777. cwd = getcwd (heapBuffer, bufferSize - 1);
  216778. bufferSize += 1024;
  216779. }
  216780. return File (String::fromUTF8 (cwd));
  216781. }
  216782. bool File::setAsCurrentWorkingDirectory() const
  216783. {
  216784. return chdir (getFullPathName().toUTF8()) == 0;
  216785. }
  216786. namespace
  216787. {
  216788. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216789. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216790. #else
  216791. typedef struct stat juce_statStruct;
  216792. #endif
  216793. bool juce_stat (const String& fileName, juce_statStruct& info)
  216794. {
  216795. return fileName.isNotEmpty()
  216796. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216797. && (stat64 (fileName.toUTF8(), &info) == 0);
  216798. #else
  216799. && (stat (fileName.toUTF8(), &info) == 0);
  216800. #endif
  216801. }
  216802. // if this file doesn't exist, find a parent of it that does..
  216803. bool juce_doStatFS (File f, struct statfs& result)
  216804. {
  216805. for (int i = 5; --i >= 0;)
  216806. {
  216807. if (f.exists())
  216808. break;
  216809. f = f.getParentDirectory();
  216810. }
  216811. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216812. }
  216813. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  216814. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216815. {
  216816. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216817. {
  216818. juce_statStruct info;
  216819. const bool statOk = juce_stat (path, info);
  216820. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216821. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216822. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  216823. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  216824. }
  216825. if (isReadOnly != 0)
  216826. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216827. }
  216828. }
  216829. bool File::isDirectory() const
  216830. {
  216831. juce_statStruct info;
  216832. return fullPath.isEmpty()
  216833. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216834. }
  216835. bool File::exists() const
  216836. {
  216837. juce_statStruct info;
  216838. return fullPath.isNotEmpty()
  216839. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216840. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216841. #else
  216842. && (lstat (fullPath.toUTF8(), &info) == 0);
  216843. #endif
  216844. }
  216845. bool File::existsAsFile() const
  216846. {
  216847. return exists() && ! isDirectory();
  216848. }
  216849. int64 File::getSize() const
  216850. {
  216851. juce_statStruct info;
  216852. return juce_stat (fullPath, info) ? info.st_size : 0;
  216853. }
  216854. bool File::hasWriteAccess() const
  216855. {
  216856. if (exists())
  216857. return access (fullPath.toUTF8(), W_OK) == 0;
  216858. if ((! isDirectory()) && fullPath.containsChar (separator))
  216859. return getParentDirectory().hasWriteAccess();
  216860. return false;
  216861. }
  216862. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216863. {
  216864. juce_statStruct info;
  216865. if (! juce_stat (fullPath, info))
  216866. return false;
  216867. info.st_mode &= 0777; // Just permissions
  216868. if (shouldBeReadOnly)
  216869. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216870. else
  216871. // Give everybody write permission?
  216872. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216873. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216874. }
  216875. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216876. {
  216877. modificationTime = 0;
  216878. accessTime = 0;
  216879. creationTime = 0;
  216880. juce_statStruct info;
  216881. if (juce_stat (fullPath, info))
  216882. {
  216883. modificationTime = (int64) info.st_mtime * 1000;
  216884. accessTime = (int64) info.st_atime * 1000;
  216885. creationTime = (int64) info.st_ctime * 1000;
  216886. }
  216887. }
  216888. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216889. {
  216890. juce_statStruct info;
  216891. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  216892. {
  216893. struct utimbuf times;
  216894. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  216895. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  216896. return utime (fullPath.toUTF8(), &times) == 0;
  216897. }
  216898. return false;
  216899. }
  216900. bool File::deleteFile() const
  216901. {
  216902. if (! exists())
  216903. return true;
  216904. if (isDirectory())
  216905. return rmdir (fullPath.toUTF8()) == 0;
  216906. return remove (fullPath.toUTF8()) == 0;
  216907. }
  216908. bool File::moveInternal (const File& dest) const
  216909. {
  216910. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216911. return true;
  216912. if (hasWriteAccess() && copyInternal (dest))
  216913. {
  216914. if (deleteFile())
  216915. return true;
  216916. dest.deleteFile();
  216917. }
  216918. return false;
  216919. }
  216920. void File::createDirectoryInternal (const String& fileName) const
  216921. {
  216922. mkdir (fileName.toUTF8(), 0777);
  216923. }
  216924. int64 juce_fileSetPosition (void* handle, int64 pos)
  216925. {
  216926. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216927. return pos;
  216928. return -1;
  216929. }
  216930. void FileInputStream::openHandle()
  216931. {
  216932. totalSize = file.getSize();
  216933. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216934. if (f != -1)
  216935. fileHandle = (void*) f;
  216936. }
  216937. void FileInputStream::closeHandle()
  216938. {
  216939. if (fileHandle != 0)
  216940. {
  216941. close ((int) (pointer_sized_int) fileHandle);
  216942. fileHandle = 0;
  216943. }
  216944. }
  216945. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216946. {
  216947. if (fileHandle != 0)
  216948. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216949. return 0;
  216950. }
  216951. void FileOutputStream::openHandle()
  216952. {
  216953. if (file.exists())
  216954. {
  216955. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216956. if (f != -1)
  216957. {
  216958. currentPosition = lseek (f, 0, SEEK_END);
  216959. if (currentPosition >= 0)
  216960. fileHandle = (void*) f;
  216961. else
  216962. close (f);
  216963. }
  216964. }
  216965. else
  216966. {
  216967. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216968. if (f != -1)
  216969. fileHandle = (void*) f;
  216970. }
  216971. }
  216972. void FileOutputStream::closeHandle()
  216973. {
  216974. if (fileHandle != 0)
  216975. {
  216976. close ((int) (pointer_sized_int) fileHandle);
  216977. fileHandle = 0;
  216978. }
  216979. }
  216980. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216981. {
  216982. if (fileHandle != 0)
  216983. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216984. return 0;
  216985. }
  216986. void FileOutputStream::flushInternal()
  216987. {
  216988. if (fileHandle != 0)
  216989. fsync ((int) (pointer_sized_int) fileHandle);
  216990. }
  216991. const File juce_getExecutableFile()
  216992. {
  216993. #if JUCE_ANDROID
  216994. return File (android.appFile);
  216995. #else
  216996. Dl_info exeInfo;
  216997. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  216998. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216999. #endif
  217000. }
  217001. int64 File::getBytesFreeOnVolume() const
  217002. {
  217003. struct statfs buf;
  217004. if (juce_doStatFS (*this, buf))
  217005. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217006. return 0;
  217007. }
  217008. int64 File::getVolumeTotalSize() const
  217009. {
  217010. struct statfs buf;
  217011. if (juce_doStatFS (*this, buf))
  217012. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217013. return 0;
  217014. }
  217015. const String File::getVolumeLabel() const
  217016. {
  217017. #if JUCE_MAC
  217018. struct VolAttrBuf
  217019. {
  217020. u_int32_t length;
  217021. attrreference_t mountPointRef;
  217022. char mountPointSpace [MAXPATHLEN];
  217023. } attrBuf;
  217024. struct attrlist attrList;
  217025. zerostruct (attrList);
  217026. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217027. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217028. File f (*this);
  217029. for (;;)
  217030. {
  217031. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217032. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217033. (int) attrBuf.mountPointRef.attr_length);
  217034. const File parent (f.getParentDirectory());
  217035. if (f == parent)
  217036. break;
  217037. f = parent;
  217038. }
  217039. #endif
  217040. return String::empty;
  217041. }
  217042. int File::getVolumeSerialNumber() const
  217043. {
  217044. int result = 0;
  217045. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  217046. char info [512];
  217047. #ifndef HDIO_GET_IDENTITY
  217048. #define HDIO_GET_IDENTITY 0x030d
  217049. #endif
  217050. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  217051. {
  217052. DBG (String (info + 20, 20));
  217053. result = String (info + 20, 20).trim().getIntValue();
  217054. }
  217055. close (fd);*/
  217056. return result;
  217057. }
  217058. void juce_runSystemCommand (const String& command)
  217059. {
  217060. int result = system (command.toUTF8());
  217061. (void) result;
  217062. }
  217063. const String juce_getOutputFromCommand (const String& command)
  217064. {
  217065. // slight bodge here, as we just pipe the output into a temp file and read it...
  217066. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217067. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217068. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217069. String result (tempFile.loadFileAsString());
  217070. tempFile.deleteFile();
  217071. return result;
  217072. }
  217073. class InterProcessLock::Pimpl
  217074. {
  217075. public:
  217076. Pimpl (const String& name, const int timeOutMillisecs)
  217077. : handle (0), refCount (1)
  217078. {
  217079. #if JUCE_MAC
  217080. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217081. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217082. #else
  217083. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217084. #endif
  217085. temp.create();
  217086. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217087. if (handle != 0)
  217088. {
  217089. struct flock fl;
  217090. zerostruct (fl);
  217091. fl.l_whence = SEEK_SET;
  217092. fl.l_type = F_WRLCK;
  217093. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217094. for (;;)
  217095. {
  217096. const int result = fcntl (handle, F_SETLK, &fl);
  217097. if (result >= 0)
  217098. return;
  217099. if (errno != EINTR)
  217100. {
  217101. if (timeOutMillisecs == 0
  217102. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217103. break;
  217104. Thread::sleep (10);
  217105. }
  217106. }
  217107. }
  217108. closeFile();
  217109. }
  217110. ~Pimpl()
  217111. {
  217112. closeFile();
  217113. }
  217114. void closeFile()
  217115. {
  217116. if (handle != 0)
  217117. {
  217118. struct flock fl;
  217119. zerostruct (fl);
  217120. fl.l_whence = SEEK_SET;
  217121. fl.l_type = F_UNLCK;
  217122. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217123. {}
  217124. close (handle);
  217125. handle = 0;
  217126. }
  217127. }
  217128. int handle, refCount;
  217129. };
  217130. InterProcessLock::InterProcessLock (const String& name_)
  217131. : name (name_)
  217132. {
  217133. }
  217134. InterProcessLock::~InterProcessLock()
  217135. {
  217136. }
  217137. bool InterProcessLock::enter (const int timeOutMillisecs)
  217138. {
  217139. const ScopedLock sl (lock);
  217140. if (pimpl == 0)
  217141. {
  217142. pimpl = new Pimpl (name, timeOutMillisecs);
  217143. if (pimpl->handle == 0)
  217144. pimpl = 0;
  217145. }
  217146. else
  217147. {
  217148. pimpl->refCount++;
  217149. }
  217150. return pimpl != 0;
  217151. }
  217152. void InterProcessLock::exit()
  217153. {
  217154. const ScopedLock sl (lock);
  217155. // Trying to release the lock too many times!
  217156. jassert (pimpl != 0);
  217157. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217158. pimpl = 0;
  217159. }
  217160. void JUCE_API juce_threadEntryPoint (void*);
  217161. void* threadEntryProc (void* userData)
  217162. {
  217163. JUCE_AUTORELEASEPOOL
  217164. #if JUCE_ANDROID
  217165. const AndroidThreadScope androidEnv;
  217166. #endif
  217167. juce_threadEntryPoint (userData);
  217168. return 0;
  217169. }
  217170. void Thread::launchThread()
  217171. {
  217172. threadHandle_ = 0;
  217173. pthread_t handle = 0;
  217174. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  217175. {
  217176. pthread_detach (handle);
  217177. threadHandle_ = (void*) handle;
  217178. threadId_ = (ThreadID) threadHandle_;
  217179. }
  217180. }
  217181. void Thread::closeThreadHandle()
  217182. {
  217183. threadId_ = 0;
  217184. threadHandle_ = 0;
  217185. }
  217186. void Thread::killThread()
  217187. {
  217188. if (threadHandle_ != 0)
  217189. {
  217190. #if JUCE_ANDROID
  217191. jassertfalse; // pthread_cancel not available!
  217192. #else
  217193. pthread_cancel ((pthread_t) threadHandle_);
  217194. #endif
  217195. }
  217196. }
  217197. void Thread::setCurrentThreadName (const String& name)
  217198. {
  217199. #if JUCE_MAC && defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  217200. pthread_setname_np (name.toUTF8());
  217201. #elif JUCE_LINUX
  217202. prctl (PR_SET_NAME, name.toUTF8().getAddress(), 0, 0, 0);
  217203. #endif
  217204. }
  217205. bool Thread::setThreadPriority (void* handle, int priority)
  217206. {
  217207. struct sched_param param;
  217208. int policy;
  217209. priority = jlimit (0, 10, priority);
  217210. if (handle == 0)
  217211. handle = (void*) pthread_self();
  217212. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217213. return false;
  217214. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217215. const int minPriority = sched_get_priority_min (policy);
  217216. const int maxPriority = sched_get_priority_max (policy);
  217217. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217218. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217219. }
  217220. Thread::ThreadID Thread::getCurrentThreadId()
  217221. {
  217222. return (ThreadID) pthread_self();
  217223. }
  217224. void Thread::yield()
  217225. {
  217226. sched_yield();
  217227. }
  217228. /* Remove this macro if you're having problems compiling the cpu affinity
  217229. calls (the API for these has changed about quite a bit in various Linux
  217230. versions, and a lot of distros seem to ship with obsolete versions)
  217231. */
  217232. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217233. #define SUPPORT_AFFINITIES 1
  217234. #endif
  217235. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217236. {
  217237. #if SUPPORT_AFFINITIES
  217238. cpu_set_t affinity;
  217239. CPU_ZERO (&affinity);
  217240. for (int i = 0; i < 32; ++i)
  217241. if ((affinityMask & (1 << i)) != 0)
  217242. CPU_SET (i, &affinity);
  217243. /*
  217244. N.B. If this line causes a compile error, then you've probably not got the latest
  217245. version of glibc installed.
  217246. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217247. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217248. */
  217249. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217250. sched_yield();
  217251. #else
  217252. /* affinities aren't supported because either the appropriate header files weren't found,
  217253. or the SUPPORT_AFFINITIES macro was turned off
  217254. */
  217255. jassertfalse;
  217256. (void) affinityMask;
  217257. #endif
  217258. }
  217259. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217260. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217261. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217262. // compiled on its own).
  217263. #if JUCE_INCLUDED_FILE
  217264. enum
  217265. {
  217266. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  217267. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  217268. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  217269. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  217270. };
  217271. bool File::copyInternal (const File& dest) const
  217272. {
  217273. FileInputStream in (*this);
  217274. if (dest.deleteFile())
  217275. {
  217276. {
  217277. FileOutputStream out (dest);
  217278. if (out.failedToOpen())
  217279. return false;
  217280. if (out.writeFromInputStream (in, -1) == getSize())
  217281. return true;
  217282. }
  217283. dest.deleteFile();
  217284. }
  217285. return false;
  217286. }
  217287. void File::findFileSystemRoots (Array<File>& destArray)
  217288. {
  217289. destArray.add (File ("/"));
  217290. }
  217291. bool File::isOnCDRomDrive() const
  217292. {
  217293. struct statfs buf;
  217294. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217295. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  217296. }
  217297. bool File::isOnHardDisk() const
  217298. {
  217299. struct statfs buf;
  217300. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217301. {
  217302. switch (buf.f_type)
  217303. {
  217304. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217305. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217306. case U_NFS_SUPER_MAGIC: // Network NFS
  217307. case U_SMB_SUPER_MAGIC: // Network Samba
  217308. return false;
  217309. default:
  217310. // Assume anything else is a hard-disk (but note it could
  217311. // be a RAM disk. There isn't a good way of determining
  217312. // this for sure)
  217313. return true;
  217314. }
  217315. }
  217316. // Assume so if this fails for some reason
  217317. return true;
  217318. }
  217319. bool File::isOnRemovableDrive() const
  217320. {
  217321. jassertfalse; // xxx not implemented for linux!
  217322. return false;
  217323. }
  217324. bool File::isHidden() const
  217325. {
  217326. return getFileName().startsWithChar ('.');
  217327. }
  217328. namespace
  217329. {
  217330. const File juce_readlink (const String& file, const File& defaultFile)
  217331. {
  217332. const int size = 8192;
  217333. HeapBlock<char> buffer;
  217334. buffer.malloc (size + 4);
  217335. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217336. if (numBytes > 0 && numBytes <= size)
  217337. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217338. return defaultFile;
  217339. }
  217340. }
  217341. const File File::getLinkedTarget() const
  217342. {
  217343. return juce_readlink (getFullPathName().toUTF8(), *this);
  217344. }
  217345. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217346. const File File::getSpecialLocation (const SpecialLocationType type)
  217347. {
  217348. switch (type)
  217349. {
  217350. case userHomeDirectory:
  217351. {
  217352. const char* homeDir = getenv ("HOME");
  217353. if (homeDir == 0)
  217354. {
  217355. struct passwd* const pw = getpwuid (getuid());
  217356. if (pw != 0)
  217357. homeDir = pw->pw_dir;
  217358. }
  217359. return File (String::fromUTF8 (homeDir));
  217360. }
  217361. case userDocumentsDirectory:
  217362. case userMusicDirectory:
  217363. case userMoviesDirectory:
  217364. case userApplicationDataDirectory:
  217365. return File ("~");
  217366. case userDesktopDirectory:
  217367. return File ("~/Desktop");
  217368. case commonApplicationDataDirectory:
  217369. return File ("/var");
  217370. case globalApplicationsDirectory:
  217371. return File ("/usr");
  217372. case tempDirectory:
  217373. {
  217374. File tmp ("/var/tmp");
  217375. if (! tmp.isDirectory())
  217376. {
  217377. tmp = "/tmp";
  217378. if (! tmp.isDirectory())
  217379. tmp = File::getCurrentWorkingDirectory();
  217380. }
  217381. return tmp;
  217382. }
  217383. case invokedExecutableFile:
  217384. if (juce_Argv0 != 0)
  217385. return File (String::fromUTF8 (juce_Argv0));
  217386. // deliberate fall-through...
  217387. case currentExecutableFile:
  217388. case currentApplicationFile:
  217389. return juce_getExecutableFile();
  217390. case hostApplicationPath:
  217391. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217392. default:
  217393. jassertfalse; // unknown type?
  217394. break;
  217395. }
  217396. return File::nonexistent;
  217397. }
  217398. const String File::getVersion() const
  217399. {
  217400. return String::empty; // xxx not yet implemented
  217401. }
  217402. bool File::moveToTrash() const
  217403. {
  217404. if (! exists())
  217405. return true;
  217406. File trashCan ("~/.Trash");
  217407. if (! trashCan.isDirectory())
  217408. trashCan = "~/.local/share/Trash/files";
  217409. if (! trashCan.isDirectory())
  217410. return false;
  217411. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217412. getFileExtension()));
  217413. }
  217414. class DirectoryIterator::NativeIterator::Pimpl
  217415. {
  217416. public:
  217417. Pimpl (const File& directory, const String& wildCard_)
  217418. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217419. wildCard (wildCard_),
  217420. dir (opendir (directory.getFullPathName().toUTF8()))
  217421. {
  217422. wildcardUTF8 = wildCard.toUTF8();
  217423. }
  217424. ~Pimpl()
  217425. {
  217426. if (dir != 0)
  217427. closedir (dir);
  217428. }
  217429. bool next (String& filenameFound,
  217430. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217431. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217432. {
  217433. if (dir != 0)
  217434. {
  217435. for (;;)
  217436. {
  217437. struct dirent* const de = readdir (dir);
  217438. if (de == 0)
  217439. break;
  217440. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217441. {
  217442. filenameFound = String::fromUTF8 (de->d_name);
  217443. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  217444. if (isHidden != 0)
  217445. *isHidden = filenameFound.startsWithChar ('.');
  217446. return true;
  217447. }
  217448. }
  217449. }
  217450. return false;
  217451. }
  217452. private:
  217453. String parentDir, wildCard;
  217454. const char* wildcardUTF8;
  217455. DIR* dir;
  217456. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  217457. };
  217458. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217459. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217460. {
  217461. }
  217462. DirectoryIterator::NativeIterator::~NativeIterator()
  217463. {
  217464. }
  217465. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217466. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217467. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217468. {
  217469. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217470. }
  217471. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217472. {
  217473. String cmdString (fileName.replace (" ", "\\ ",false));
  217474. cmdString << " " << parameters;
  217475. if (URL::isProbablyAWebsiteURL (fileName)
  217476. || cmdString.startsWithIgnoreCase ("file:")
  217477. || URL::isProbablyAnEmailAddress (fileName))
  217478. {
  217479. // create a command that tries to launch a bunch of likely browsers
  217480. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217481. StringArray cmdLines;
  217482. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217483. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217484. cmdString = cmdLines.joinIntoString (" || ");
  217485. }
  217486. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217487. const int cpid = fork();
  217488. if (cpid == 0)
  217489. {
  217490. setsid();
  217491. // Child process
  217492. execve (argv[0], (char**) argv, environ);
  217493. exit (0);
  217494. }
  217495. return cpid >= 0;
  217496. }
  217497. void File::revealToUser() const
  217498. {
  217499. if (isDirectory())
  217500. startAsProcess();
  217501. else if (getParentDirectory().exists())
  217502. getParentDirectory().startAsProcess();
  217503. }
  217504. #endif
  217505. /*** End of inlined file: juce_linux_Files.cpp ***/
  217506. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217507. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217508. // compiled on its own).
  217509. #if JUCE_INCLUDED_FILE
  217510. struct NamedPipeInternal
  217511. {
  217512. String pipeInName, pipeOutName;
  217513. int pipeIn, pipeOut;
  217514. bool volatile createdPipe, blocked, stopReadOperation;
  217515. static void signalHandler (int) {}
  217516. };
  217517. void NamedPipe::cancelPendingReads()
  217518. {
  217519. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217520. {
  217521. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217522. intern->stopReadOperation = true;
  217523. char buffer [1] = { 0 };
  217524. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217525. (void) bytesWritten;
  217526. int timeout = 2000;
  217527. while (intern->blocked && --timeout >= 0)
  217528. Thread::sleep (2);
  217529. intern->stopReadOperation = false;
  217530. }
  217531. }
  217532. void NamedPipe::close()
  217533. {
  217534. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217535. if (intern != 0)
  217536. {
  217537. internal = 0;
  217538. if (intern->pipeIn != -1)
  217539. ::close (intern->pipeIn);
  217540. if (intern->pipeOut != -1)
  217541. ::close (intern->pipeOut);
  217542. if (intern->createdPipe)
  217543. {
  217544. unlink (intern->pipeInName.toUTF8());
  217545. unlink (intern->pipeOutName.toUTF8());
  217546. }
  217547. delete intern;
  217548. }
  217549. }
  217550. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217551. {
  217552. close();
  217553. NamedPipeInternal* const intern = new NamedPipeInternal();
  217554. internal = intern;
  217555. intern->createdPipe = createPipe;
  217556. intern->blocked = false;
  217557. intern->stopReadOperation = false;
  217558. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217559. siginterrupt (SIGPIPE, 1);
  217560. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217561. intern->pipeInName = pipePath + "_in";
  217562. intern->pipeOutName = pipePath + "_out";
  217563. intern->pipeIn = -1;
  217564. intern->pipeOut = -1;
  217565. if (createPipe)
  217566. {
  217567. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217568. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217569. {
  217570. delete intern;
  217571. internal = 0;
  217572. return false;
  217573. }
  217574. }
  217575. return true;
  217576. }
  217577. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217578. {
  217579. int bytesRead = -1;
  217580. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217581. if (intern != 0)
  217582. {
  217583. intern->blocked = true;
  217584. if (intern->pipeIn == -1)
  217585. {
  217586. if (intern->createdPipe)
  217587. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217588. else
  217589. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217590. if (intern->pipeIn == -1)
  217591. {
  217592. intern->blocked = false;
  217593. return -1;
  217594. }
  217595. }
  217596. bytesRead = 0;
  217597. char* p = static_cast<char*> (destBuffer);
  217598. while (bytesRead < maxBytesToRead)
  217599. {
  217600. const int bytesThisTime = maxBytesToRead - bytesRead;
  217601. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217602. if (numRead <= 0 || intern->stopReadOperation)
  217603. {
  217604. bytesRead = -1;
  217605. break;
  217606. }
  217607. bytesRead += numRead;
  217608. p += bytesRead;
  217609. }
  217610. intern->blocked = false;
  217611. }
  217612. return bytesRead;
  217613. }
  217614. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217615. {
  217616. int bytesWritten = -1;
  217617. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217618. if (intern != 0)
  217619. {
  217620. if (intern->pipeOut == -1)
  217621. {
  217622. if (intern->createdPipe)
  217623. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217624. else
  217625. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217626. if (intern->pipeOut == -1)
  217627. {
  217628. return -1;
  217629. }
  217630. }
  217631. const char* p = static_cast<const char*> (sourceBuffer);
  217632. bytesWritten = 0;
  217633. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217634. while (bytesWritten < numBytesToWrite
  217635. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217636. {
  217637. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217638. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217639. if (numWritten <= 0)
  217640. {
  217641. bytesWritten = -1;
  217642. break;
  217643. }
  217644. bytesWritten += numWritten;
  217645. p += bytesWritten;
  217646. }
  217647. }
  217648. return bytesWritten;
  217649. }
  217650. #endif
  217651. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217652. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217653. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217654. // compiled on its own).
  217655. #if JUCE_INCLUDED_FILE
  217656. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217657. {
  217658. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217659. if (s != -1)
  217660. {
  217661. char buf [1024];
  217662. struct ifconf ifc;
  217663. ifc.ifc_len = sizeof (buf);
  217664. ifc.ifc_buf = buf;
  217665. ioctl (s, SIOCGIFCONF, &ifc);
  217666. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217667. {
  217668. struct ifreq ifr;
  217669. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217670. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217671. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217672. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217673. {
  217674. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217675. }
  217676. }
  217677. close (s);
  217678. }
  217679. }
  217680. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217681. const String& emailSubject,
  217682. const String& bodyText,
  217683. const StringArray& filesToAttach)
  217684. {
  217685. jassertfalse; // xxx todo
  217686. return false;
  217687. }
  217688. class WebInputStream : public InputStream
  217689. {
  217690. public:
  217691. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217692. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217693. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217694. : socketHandle (-1), levelsOfRedirection (0),
  217695. address (address_), headers (headers_), postData (postData_), position (0),
  217696. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217697. {
  217698. createConnection (progressCallback, progressCallbackContext);
  217699. if (responseHeaders != 0 && ! isError())
  217700. {
  217701. for (int i = 0; i < headerLines.size(); ++i)
  217702. {
  217703. const String& headersEntry = headerLines[i];
  217704. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217705. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217706. const String previousValue ((*responseHeaders) [key]);
  217707. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217708. }
  217709. }
  217710. }
  217711. ~WebInputStream()
  217712. {
  217713. closeSocket();
  217714. }
  217715. bool isError() const { return socketHandle < 0; }
  217716. bool isExhausted() { return finished; }
  217717. int64 getPosition() { return position; }
  217718. int64 getTotalLength()
  217719. {
  217720. jassertfalse; //xxx to do
  217721. return -1;
  217722. }
  217723. int read (void* buffer, int bytesToRead)
  217724. {
  217725. if (finished || isError())
  217726. return 0;
  217727. fd_set readbits;
  217728. FD_ZERO (&readbits);
  217729. FD_SET (socketHandle, &readbits);
  217730. struct timeval tv;
  217731. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217732. tv.tv_usec = 0;
  217733. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217734. return 0; // (timeout)
  217735. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217736. if (bytesRead == 0)
  217737. finished = true;
  217738. position += bytesRead;
  217739. return bytesRead;
  217740. }
  217741. bool setPosition (int64 wantedPos)
  217742. {
  217743. if (isError())
  217744. return false;
  217745. if (wantedPos != position)
  217746. {
  217747. finished = false;
  217748. if (wantedPos < position)
  217749. {
  217750. closeSocket();
  217751. position = 0;
  217752. createConnection (0, 0);
  217753. }
  217754. skipNextBytes (wantedPos - position);
  217755. }
  217756. return true;
  217757. }
  217758. private:
  217759. int socketHandle, levelsOfRedirection;
  217760. StringArray headerLines;
  217761. String address, headers;
  217762. MemoryBlock postData;
  217763. int64 position;
  217764. bool finished;
  217765. const bool isPost;
  217766. const int timeOutMs;
  217767. void closeSocket()
  217768. {
  217769. if (socketHandle >= 0)
  217770. close (socketHandle);
  217771. socketHandle = -1;
  217772. levelsOfRedirection = 0;
  217773. }
  217774. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217775. {
  217776. closeSocket();
  217777. uint32 timeOutTime = Time::getMillisecondCounter();
  217778. if (timeOutMs == 0)
  217779. timeOutTime += 60000;
  217780. else if (timeOutMs < 0)
  217781. timeOutTime = 0xffffffff;
  217782. else
  217783. timeOutTime += timeOutMs;
  217784. String hostName, hostPath;
  217785. int hostPort;
  217786. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217787. return;
  217788. const struct hostent* host = 0;
  217789. int port = 0;
  217790. String proxyName, proxyPath;
  217791. int proxyPort = 0;
  217792. String proxyURL (getenv ("http_proxy"));
  217793. if (proxyURL.startsWithIgnoreCase ("http://"))
  217794. {
  217795. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217796. return;
  217797. host = gethostbyname (proxyName.toUTF8());
  217798. port = proxyPort;
  217799. }
  217800. else
  217801. {
  217802. host = gethostbyname (hostName.toUTF8());
  217803. port = hostPort;
  217804. }
  217805. if (host == 0)
  217806. return;
  217807. {
  217808. struct sockaddr_in socketAddress;
  217809. zerostruct (socketAddress);
  217810. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217811. socketAddress.sin_family = host->h_addrtype;
  217812. socketAddress.sin_port = htons (port);
  217813. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217814. if (socketHandle == -1)
  217815. return;
  217816. int receiveBufferSize = 16384;
  217817. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217818. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217819. #if JUCE_MAC
  217820. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217821. #endif
  217822. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217823. {
  217824. closeSocket();
  217825. return;
  217826. }
  217827. }
  217828. {
  217829. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217830. hostPath, address, headers, postData, isPost));
  217831. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217832. {
  217833. closeSocket();
  217834. return;
  217835. }
  217836. }
  217837. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217838. if (responseHeader.isNotEmpty())
  217839. {
  217840. headerLines.clear();
  217841. headerLines.addLines (responseHeader);
  217842. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217843. .substring (0, 3).getIntValue();
  217844. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217845. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217846. String location (findHeaderItem (headerLines, "Location:"));
  217847. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217848. {
  217849. if (! location.startsWithIgnoreCase ("http://"))
  217850. location = "http://" + location;
  217851. if (++levelsOfRedirection <= 3)
  217852. {
  217853. address = location;
  217854. createConnection (progressCallback, progressCallbackContext);
  217855. return;
  217856. }
  217857. }
  217858. else
  217859. {
  217860. levelsOfRedirection = 0;
  217861. return;
  217862. }
  217863. }
  217864. closeSocket();
  217865. }
  217866. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217867. {
  217868. int bytesRead = 0, numConsecutiveLFs = 0;
  217869. MemoryBlock buffer (1024, true);
  217870. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217871. && Time::getMillisecondCounter() <= timeOutTime)
  217872. {
  217873. fd_set readbits;
  217874. FD_ZERO (&readbits);
  217875. FD_SET (socketHandle, &readbits);
  217876. struct timeval tv;
  217877. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217878. tv.tv_usec = 0;
  217879. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217880. return String::empty; // (timeout)
  217881. buffer.ensureSize (bytesRead + 8, true);
  217882. char* const dest = (char*) buffer.getData() + bytesRead;
  217883. if (recv (socketHandle, dest, 1, 0) == -1)
  217884. return String::empty;
  217885. const char lastByte = *dest;
  217886. ++bytesRead;
  217887. if (lastByte == '\n')
  217888. ++numConsecutiveLFs;
  217889. else if (lastByte != '\r')
  217890. numConsecutiveLFs = 0;
  217891. }
  217892. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217893. if (header.startsWithIgnoreCase ("HTTP/"))
  217894. return header.trimEnd();
  217895. return String::empty;
  217896. }
  217897. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217898. const String& proxyName, const int proxyPort,
  217899. const String& hostPath, const String& originalURL,
  217900. const String& headers, const MemoryBlock& postData,
  217901. const bool isPost)
  217902. {
  217903. String header (isPost ? "POST " : "GET ");
  217904. if (proxyName.isEmpty())
  217905. {
  217906. header << hostPath << " HTTP/1.0\r\nHost: "
  217907. << hostName << ':' << hostPort;
  217908. }
  217909. else
  217910. {
  217911. header << originalURL << " HTTP/1.0\r\nHost: "
  217912. << proxyName << ':' << proxyPort;
  217913. }
  217914. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217915. << "\r\nConnection: Close\r\nContent-Length: "
  217916. << (int) postData.getSize() << "\r\n"
  217917. << headers << "\r\n";
  217918. MemoryBlock mb;
  217919. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217920. mb.append (postData.getData(), postData.getSize());
  217921. return mb;
  217922. }
  217923. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217924. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217925. {
  217926. size_t totalHeaderSent = 0;
  217927. while (totalHeaderSent < requestHeader.getSize())
  217928. {
  217929. if (Time::getMillisecondCounter() > timeOutTime)
  217930. return false;
  217931. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217932. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217933. return false;
  217934. totalHeaderSent += numToSend;
  217935. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217936. return false;
  217937. }
  217938. return true;
  217939. }
  217940. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217941. {
  217942. if (! url.startsWithIgnoreCase ("http://"))
  217943. return false;
  217944. const int nextSlash = url.indexOfChar (7, '/');
  217945. int nextColon = url.indexOfChar (7, ':');
  217946. if (nextColon > nextSlash && nextSlash > 0)
  217947. nextColon = -1;
  217948. if (nextColon >= 0)
  217949. {
  217950. host = url.substring (7, nextColon);
  217951. if (nextSlash >= 0)
  217952. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217953. else
  217954. port = url.substring (nextColon + 1).getIntValue();
  217955. }
  217956. else
  217957. {
  217958. port = 80;
  217959. if (nextSlash >= 0)
  217960. host = url.substring (7, nextSlash);
  217961. else
  217962. host = url.substring (7);
  217963. }
  217964. if (nextSlash >= 0)
  217965. path = url.substring (nextSlash);
  217966. else
  217967. path = "/";
  217968. return true;
  217969. }
  217970. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217971. {
  217972. for (int i = 0; i < lines.size(); ++i)
  217973. if (lines[i].startsWithIgnoreCase (itemName))
  217974. return lines[i].substring (itemName.length()).trim();
  217975. return String::empty;
  217976. }
  217977. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217978. };
  217979. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217980. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217981. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217982. {
  217983. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217984. progressCallback, progressCallbackContext,
  217985. headers, timeOutMs, responseHeaders));
  217986. return wi->isError() ? 0 : wi.release();
  217987. }
  217988. #endif
  217989. /*** End of inlined file: juce_linux_Network.cpp ***/
  217990. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217991. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217992. // compiled on its own).
  217993. #if JUCE_INCLUDED_FILE
  217994. void Logger::outputDebugString (const String& text)
  217995. {
  217996. std::cerr << text << std::endl;
  217997. }
  217998. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217999. {
  218000. return Linux;
  218001. }
  218002. const String SystemStats::getOperatingSystemName()
  218003. {
  218004. return "Linux";
  218005. }
  218006. bool SystemStats::isOperatingSystem64Bit()
  218007. {
  218008. #if JUCE_64BIT
  218009. return true;
  218010. #else
  218011. //xxx not sure how to find this out?..
  218012. return false;
  218013. #endif
  218014. }
  218015. namespace LinuxStatsHelpers
  218016. {
  218017. const String getCpuInfo (const char* const key)
  218018. {
  218019. StringArray lines;
  218020. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218021. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218022. if (lines[i].startsWithIgnoreCase (key))
  218023. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218024. return String::empty;
  218025. }
  218026. }
  218027. const String SystemStats::getCpuVendor()
  218028. {
  218029. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  218030. }
  218031. int SystemStats::getCpuSpeedInMegaherz()
  218032. {
  218033. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  218034. }
  218035. int SystemStats::getMemorySizeInMegabytes()
  218036. {
  218037. struct sysinfo sysi;
  218038. if (sysinfo (&sysi) == 0)
  218039. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218040. return 0;
  218041. }
  218042. int SystemStats::getPageSize()
  218043. {
  218044. return sysconf (_SC_PAGESIZE);
  218045. }
  218046. const String SystemStats::getLogonName()
  218047. {
  218048. const char* user = getenv ("USER");
  218049. if (user == 0)
  218050. {
  218051. struct passwd* const pw = getpwuid (getuid());
  218052. if (pw != 0)
  218053. user = pw->pw_name;
  218054. }
  218055. return String::fromUTF8 (user);
  218056. }
  218057. const String SystemStats::getFullUserName()
  218058. {
  218059. return getLogonName();
  218060. }
  218061. void SystemStats::initialiseStats()
  218062. {
  218063. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  218064. cpuFlags.hasMMX = flags.contains ("mmx");
  218065. cpuFlags.hasSSE = flags.contains ("sse");
  218066. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218067. cpuFlags.has3DNow = flags.contains ("3dnow");
  218068. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  218069. }
  218070. void PlatformUtilities::fpuReset()
  218071. {
  218072. }
  218073. uint32 juce_millisecondsSinceStartup() throw()
  218074. {
  218075. timespec t;
  218076. clock_gettime (CLOCK_MONOTONIC, &t);
  218077. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  218078. }
  218079. int64 Time::getHighResolutionTicks() throw()
  218080. {
  218081. timespec t;
  218082. clock_gettime (CLOCK_MONOTONIC, &t);
  218083. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  218084. }
  218085. int64 Time::getHighResolutionTicksPerSecond() throw()
  218086. {
  218087. return 1000000; // (microseconds)
  218088. }
  218089. double Time::getMillisecondCounterHiRes() throw()
  218090. {
  218091. return getHighResolutionTicks() * 0.001;
  218092. }
  218093. bool Time::setSystemTimeToThisTime() const
  218094. {
  218095. timeval t;
  218096. t.tv_sec = millisSinceEpoch / 1000;
  218097. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  218098. return settimeofday (&t, 0) == 0;
  218099. }
  218100. #endif
  218101. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218102. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218103. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218104. // compiled on its own).
  218105. #if JUCE_INCLUDED_FILE
  218106. /*
  218107. Note that a lot of methods that you'd expect to find in this file actually
  218108. live in juce_posix_SharedCode.h!
  218109. */
  218110. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218111. void Process::setPriority (ProcessPriority prior)
  218112. {
  218113. struct sched_param param;
  218114. int policy, maxp, minp;
  218115. const int p = (int) prior;
  218116. if (p <= 1)
  218117. policy = SCHED_OTHER;
  218118. else
  218119. policy = SCHED_RR;
  218120. minp = sched_get_priority_min (policy);
  218121. maxp = sched_get_priority_max (policy);
  218122. if (p < 2)
  218123. param.sched_priority = 0;
  218124. else if (p == 2 )
  218125. // Set to middle of lower realtime priority range
  218126. param.sched_priority = minp + (maxp - minp) / 4;
  218127. else
  218128. // Set to middle of higher realtime priority range
  218129. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218130. pthread_setschedparam (pthread_self(), policy, &param);
  218131. }
  218132. void Process::terminate()
  218133. {
  218134. exit (0);
  218135. }
  218136. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  218137. {
  218138. static char testResult = 0;
  218139. if (testResult == 0)
  218140. {
  218141. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218142. if (testResult >= 0)
  218143. {
  218144. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218145. testResult = 1;
  218146. }
  218147. }
  218148. return testResult < 0;
  218149. }
  218150. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218151. {
  218152. return juce_isRunningUnderDebugger();
  218153. }
  218154. void Process::raisePrivilege()
  218155. {
  218156. // If running suid root, change effective user
  218157. // to root
  218158. if (geteuid() != 0 && getuid() == 0)
  218159. {
  218160. setreuid (geteuid(), getuid());
  218161. setregid (getegid(), getgid());
  218162. }
  218163. }
  218164. void Process::lowerPrivilege()
  218165. {
  218166. // If runing suid root, change effective user
  218167. // back to real user
  218168. if (geteuid() == 0 && getuid() != 0)
  218169. {
  218170. setreuid (geteuid(), getuid());
  218171. setregid (getegid(), getgid());
  218172. }
  218173. }
  218174. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218175. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218176. {
  218177. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218178. }
  218179. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218180. {
  218181. dlclose(handle);
  218182. }
  218183. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218184. {
  218185. return dlsym (libraryHandle, procedureName.toCString());
  218186. }
  218187. #endif
  218188. #endif
  218189. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218190. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218191. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218192. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218193. // compiled on its own).
  218194. #if JUCE_INCLUDED_FILE
  218195. extern Display* display;
  218196. extern Window juce_messageWindowHandle;
  218197. namespace ClipboardHelpers
  218198. {
  218199. static String localClipboardContent;
  218200. static Atom atom_UTF8_STRING;
  218201. static Atom atom_CLIPBOARD;
  218202. static Atom atom_TARGETS;
  218203. static void initSelectionAtoms()
  218204. {
  218205. static bool isInitialised = false;
  218206. if (! isInitialised)
  218207. {
  218208. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218209. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218210. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218211. }
  218212. }
  218213. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218214. // works only for strings shorter than 1000000 bytes
  218215. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218216. {
  218217. String returnData;
  218218. char* clipData;
  218219. Atom actualType;
  218220. int actualFormat;
  218221. unsigned long numItems, bytesLeft;
  218222. if (XGetWindowProperty (display, window, prop,
  218223. 0L /* offset */, 1000000 /* length (max) */, False,
  218224. AnyPropertyType /* format */,
  218225. &actualType, &actualFormat, &numItems, &bytesLeft,
  218226. (unsigned char**) &clipData) == Success)
  218227. {
  218228. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218229. returnData = String::fromUTF8 (clipData, numItems);
  218230. else if (actualType == XA_STRING && actualFormat == 8)
  218231. returnData = String (clipData, numItems);
  218232. if (clipData != 0)
  218233. XFree (clipData);
  218234. jassert (bytesLeft == 0 || numItems == 1000000);
  218235. }
  218236. XDeleteProperty (display, window, prop);
  218237. return returnData;
  218238. }
  218239. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218240. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218241. {
  218242. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218243. // The selection owner will be asked to set the JUCE_SEL property on the
  218244. // juce_messageWindowHandle with the selection content
  218245. XConvertSelection (display, selection, requestedFormat, property_name,
  218246. juce_messageWindowHandle, CurrentTime);
  218247. int count = 50; // will wait at most for 200 ms
  218248. while (--count >= 0)
  218249. {
  218250. XEvent event;
  218251. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218252. {
  218253. if (event.xselection.property == property_name)
  218254. {
  218255. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218256. selectionContent = readWindowProperty (event.xselection.requestor,
  218257. event.xselection.property,
  218258. requestedFormat);
  218259. return true;
  218260. }
  218261. else
  218262. {
  218263. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218264. }
  218265. }
  218266. // not very elegant.. we could do a select() or something like that...
  218267. // however clipboard content requesting is inherently slow on x11, it
  218268. // often takes 50ms or more so...
  218269. Thread::sleep (4);
  218270. }
  218271. return false;
  218272. }
  218273. }
  218274. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218275. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218276. {
  218277. ClipboardHelpers::initSelectionAtoms();
  218278. // the selection content is sent to the target window as a window property
  218279. XSelectionEvent reply;
  218280. reply.type = SelectionNotify;
  218281. reply.display = evt.display;
  218282. reply.requestor = evt.requestor;
  218283. reply.selection = evt.selection;
  218284. reply.target = evt.target;
  218285. reply.property = None; // == "fail"
  218286. reply.time = evt.time;
  218287. HeapBlock <char> data;
  218288. int propertyFormat = 0, numDataItems = 0;
  218289. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218290. {
  218291. if (evt.target == XA_STRING)
  218292. {
  218293. // format data according to system locale
  218294. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218295. data.calloc (numDataItems + 1);
  218296. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218297. propertyFormat = 8; // bits/item
  218298. }
  218299. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218300. {
  218301. // translate to utf8
  218302. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218303. data.calloc (numDataItems + 1);
  218304. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218305. propertyFormat = 8; // bits/item
  218306. }
  218307. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218308. {
  218309. // another application wants to know what we are able to send
  218310. numDataItems = 2;
  218311. propertyFormat = 32; // atoms are 32-bit
  218312. data.calloc (numDataItems * 4);
  218313. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218314. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218315. atoms[1] = XA_STRING;
  218316. }
  218317. }
  218318. else
  218319. {
  218320. DBG ("requested unsupported clipboard");
  218321. }
  218322. if (data != 0)
  218323. {
  218324. const int maxReasonableSelectionSize = 1000000;
  218325. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218326. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218327. {
  218328. XChangeProperty (evt.display, evt.requestor,
  218329. evt.property, evt.target,
  218330. propertyFormat /* 8 or 32 */, PropModeReplace,
  218331. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218332. reply.property = evt.property; // " == success"
  218333. }
  218334. }
  218335. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218336. }
  218337. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218338. {
  218339. ClipboardHelpers::initSelectionAtoms();
  218340. ClipboardHelpers::localClipboardContent = clipText;
  218341. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218342. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218343. }
  218344. const String SystemClipboard::getTextFromClipboard()
  218345. {
  218346. ClipboardHelpers::initSelectionAtoms();
  218347. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218348. level" clipboard that is supposed to be filled by ctrl-C
  218349. etc). When a clipboard manager is running, the content of this
  218350. selection is preserved even when the original selection owner
  218351. exits.
  218352. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218353. filled by good old x11 apps such as xterm)
  218354. */
  218355. String content;
  218356. Atom selection = XA_PRIMARY;
  218357. Window selectionOwner = None;
  218358. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218359. {
  218360. selection = ClipboardHelpers::atom_CLIPBOARD;
  218361. selectionOwner = XGetSelectionOwner (display, selection);
  218362. }
  218363. if (selectionOwner != None)
  218364. {
  218365. if (selectionOwner == juce_messageWindowHandle)
  218366. {
  218367. content = ClipboardHelpers::localClipboardContent;
  218368. }
  218369. else
  218370. {
  218371. // first try: we want an utf8 string
  218372. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218373. if (! ok)
  218374. {
  218375. // second chance, ask for a good old locale-dependent string ..
  218376. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218377. }
  218378. }
  218379. }
  218380. return content;
  218381. }
  218382. #endif
  218383. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218384. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218385. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218386. // compiled on its own).
  218387. #if JUCE_INCLUDED_FILE
  218388. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218389. #define JUCE_DEBUG_XERRORS 1
  218390. #endif
  218391. Display* display = 0;
  218392. Window juce_messageWindowHandle = None;
  218393. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218394. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218395. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218396. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218397. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218398. class InternalMessageQueue
  218399. {
  218400. public:
  218401. InternalMessageQueue()
  218402. : bytesInSocket (0),
  218403. totalEventCount (0)
  218404. {
  218405. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218406. (void) ret; jassert (ret == 0);
  218407. //setNonBlocking (fd[0]);
  218408. //setNonBlocking (fd[1]);
  218409. }
  218410. ~InternalMessageQueue()
  218411. {
  218412. close (fd[0]);
  218413. close (fd[1]);
  218414. clearSingletonInstance();
  218415. }
  218416. void postMessage (Message* msg)
  218417. {
  218418. const int maxBytesInSocketQueue = 128;
  218419. ScopedLock sl (lock);
  218420. queue.add (msg);
  218421. if (bytesInSocket < maxBytesInSocketQueue)
  218422. {
  218423. ++bytesInSocket;
  218424. ScopedUnlock ul (lock);
  218425. const unsigned char x = 0xff;
  218426. size_t bytesWritten = write (fd[0], &x, 1);
  218427. (void) bytesWritten;
  218428. }
  218429. }
  218430. bool isEmpty() const
  218431. {
  218432. ScopedLock sl (lock);
  218433. return queue.size() == 0;
  218434. }
  218435. bool dispatchNextEvent()
  218436. {
  218437. // This alternates between giving priority to XEvents or internal messages,
  218438. // to keep everything running smoothly..
  218439. if ((++totalEventCount & 1) != 0)
  218440. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218441. else
  218442. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218443. }
  218444. // Wait for an event (either XEvent, or an internal Message)
  218445. bool sleepUntilEvent (const int timeoutMs)
  218446. {
  218447. if (! isEmpty())
  218448. return true;
  218449. if (display != 0)
  218450. {
  218451. ScopedXLock xlock;
  218452. if (XPending (display))
  218453. return true;
  218454. }
  218455. struct timeval tv;
  218456. tv.tv_sec = 0;
  218457. tv.tv_usec = timeoutMs * 1000;
  218458. int fd0 = getWaitHandle();
  218459. int fdmax = fd0;
  218460. fd_set readset;
  218461. FD_ZERO (&readset);
  218462. FD_SET (fd0, &readset);
  218463. if (display != 0)
  218464. {
  218465. ScopedXLock xlock;
  218466. int fd1 = XConnectionNumber (display);
  218467. FD_SET (fd1, &readset);
  218468. fdmax = jmax (fd0, fd1);
  218469. }
  218470. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218471. return (ret > 0); // ret <= 0 if error or timeout
  218472. }
  218473. struct MessageThreadFuncCall
  218474. {
  218475. enum { uniqueID = 0x73774623 };
  218476. MessageCallbackFunction* func;
  218477. void* parameter;
  218478. void* result;
  218479. CriticalSection lock;
  218480. WaitableEvent event;
  218481. };
  218482. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218483. private:
  218484. CriticalSection lock;
  218485. ReferenceCountedArray <Message> queue;
  218486. int fd[2];
  218487. int bytesInSocket;
  218488. int totalEventCount;
  218489. int getWaitHandle() const throw() { return fd[1]; }
  218490. static bool setNonBlocking (int handle)
  218491. {
  218492. int socketFlags = fcntl (handle, F_GETFL, 0);
  218493. if (socketFlags == -1)
  218494. return false;
  218495. socketFlags |= O_NONBLOCK;
  218496. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218497. }
  218498. static bool dispatchNextXEvent()
  218499. {
  218500. if (display == 0)
  218501. return false;
  218502. XEvent evt;
  218503. {
  218504. ScopedXLock xlock;
  218505. if (! XPending (display))
  218506. return false;
  218507. XNextEvent (display, &evt);
  218508. }
  218509. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218510. juce_handleSelectionRequest (evt.xselectionrequest);
  218511. else if (evt.xany.window != juce_messageWindowHandle)
  218512. juce_windowMessageReceive (&evt);
  218513. return true;
  218514. }
  218515. const Message::Ptr popNextMessage()
  218516. {
  218517. const ScopedLock sl (lock);
  218518. if (bytesInSocket > 0)
  218519. {
  218520. --bytesInSocket;
  218521. const ScopedUnlock ul (lock);
  218522. unsigned char x;
  218523. size_t numBytes = read (fd[1], &x, 1);
  218524. (void) numBytes;
  218525. }
  218526. return queue.removeAndReturn (0);
  218527. }
  218528. bool dispatchNextInternalMessage()
  218529. {
  218530. const Message::Ptr msg (popNextMessage());
  218531. if (msg == 0)
  218532. return false;
  218533. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218534. {
  218535. // Handle callback message
  218536. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218537. call->result = (*(call->func)) (call->parameter);
  218538. call->event.signal();
  218539. }
  218540. else
  218541. {
  218542. // Handle "normal" messages
  218543. MessageManager::getInstance()->deliverMessage (msg);
  218544. }
  218545. return true;
  218546. }
  218547. };
  218548. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218549. namespace LinuxErrorHandling
  218550. {
  218551. static bool errorOccurred = false;
  218552. static bool keyboardBreakOccurred = false;
  218553. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218554. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218555. // Usually happens when client-server connection is broken
  218556. static int ioErrorHandler (Display* display)
  218557. {
  218558. DBG ("ERROR: connection to X server broken.. terminating.");
  218559. if (JUCEApplication::isStandaloneApp())
  218560. MessageManager::getInstance()->stopDispatchLoop();
  218561. errorOccurred = true;
  218562. return 0;
  218563. }
  218564. // A protocol error has occurred
  218565. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218566. {
  218567. #if JUCE_DEBUG_XERRORS
  218568. char errorStr[64] = { 0 };
  218569. char requestStr[64] = { 0 };
  218570. XGetErrorText (display, event->error_code, errorStr, 64);
  218571. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218572. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218573. #endif
  218574. return 0;
  218575. }
  218576. static void installXErrorHandlers()
  218577. {
  218578. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218579. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218580. }
  218581. static void removeXErrorHandlers()
  218582. {
  218583. if (JUCEApplication::isStandaloneApp())
  218584. {
  218585. XSetIOErrorHandler (oldIOErrorHandler);
  218586. oldIOErrorHandler = 0;
  218587. XSetErrorHandler (oldErrorHandler);
  218588. oldErrorHandler = 0;
  218589. }
  218590. }
  218591. static void keyboardBreakSignalHandler (int sig)
  218592. {
  218593. if (sig == SIGINT)
  218594. keyboardBreakOccurred = true;
  218595. }
  218596. static void installKeyboardBreakHandler()
  218597. {
  218598. struct sigaction saction;
  218599. sigset_t maskSet;
  218600. sigemptyset (&maskSet);
  218601. saction.sa_handler = keyboardBreakSignalHandler;
  218602. saction.sa_mask = maskSet;
  218603. saction.sa_flags = 0;
  218604. sigaction (SIGINT, &saction, 0);
  218605. }
  218606. }
  218607. void MessageManager::doPlatformSpecificInitialisation()
  218608. {
  218609. if (JUCEApplication::isStandaloneApp())
  218610. {
  218611. // Initialise xlib for multiple thread support
  218612. static bool initThreadCalled = false;
  218613. if (! initThreadCalled)
  218614. {
  218615. if (! XInitThreads())
  218616. {
  218617. // This is fatal! Print error and closedown
  218618. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218619. Process::terminate();
  218620. return;
  218621. }
  218622. initThreadCalled = true;
  218623. }
  218624. LinuxErrorHandling::installXErrorHandlers();
  218625. LinuxErrorHandling::installKeyboardBreakHandler();
  218626. }
  218627. // Create the internal message queue
  218628. InternalMessageQueue::getInstance();
  218629. // Try to connect to a display
  218630. String displayName (getenv ("DISPLAY"));
  218631. if (displayName.isEmpty())
  218632. displayName = ":0.0";
  218633. display = XOpenDisplay (displayName.toCString());
  218634. if (display != 0) // This is not fatal! we can run headless.
  218635. {
  218636. // Create a context to store user data associated with Windows we create in WindowDriver
  218637. windowHandleXContext = XUniqueContext();
  218638. // We're only interested in client messages for this window, which are always sent
  218639. XSetWindowAttributes swa;
  218640. swa.event_mask = NoEventMask;
  218641. // Create our message window (this will never be mapped)
  218642. const int screen = DefaultScreen (display);
  218643. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218644. 0, 0, 1, 1, 0, 0, InputOnly,
  218645. DefaultVisual (display, screen),
  218646. CWEventMask, &swa);
  218647. }
  218648. }
  218649. void MessageManager::doPlatformSpecificShutdown()
  218650. {
  218651. InternalMessageQueue::deleteInstance();
  218652. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218653. {
  218654. XDestroyWindow (display, juce_messageWindowHandle);
  218655. XCloseDisplay (display);
  218656. juce_messageWindowHandle = 0;
  218657. display = 0;
  218658. LinuxErrorHandling::removeXErrorHandlers();
  218659. }
  218660. }
  218661. bool juce_postMessageToSystemQueue (Message* message)
  218662. {
  218663. if (LinuxErrorHandling::errorOccurred)
  218664. return false;
  218665. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218666. return true;
  218667. }
  218668. void MessageManager::broadcastMessage (const String& value)
  218669. {
  218670. /* TODO */
  218671. }
  218672. class AsyncFunctionCaller : public AsyncUpdater
  218673. {
  218674. public:
  218675. static void* call (MessageCallbackFunction* func_, void* parameter_)
  218676. {
  218677. if (MessageManager::getInstance()->isThisTheMessageThread())
  218678. return func_ (parameter_);
  218679. AsyncFunctionCaller caller (func_, parameter_);
  218680. caller.triggerAsyncUpdate();
  218681. caller.finished.wait();
  218682. return caller.result;
  218683. }
  218684. void handleAsyncUpdate()
  218685. {
  218686. result = (*func) (parameter);
  218687. finished.signal();
  218688. }
  218689. private:
  218690. WaitableEvent finished;
  218691. MessageCallbackFunction* func;
  218692. void* parameter;
  218693. void* volatile result;
  218694. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  218695. : result (0), func (func_), parameter (parameter_)
  218696. {}
  218697. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  218698. };
  218699. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218700. {
  218701. if (LinuxErrorHandling::errorOccurred)
  218702. return 0;
  218703. return AsyncFunctionCaller::call (func, parameter);
  218704. }
  218705. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218706. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218707. {
  218708. while (! LinuxErrorHandling::errorOccurred)
  218709. {
  218710. if (LinuxErrorHandling::keyboardBreakOccurred)
  218711. {
  218712. LinuxErrorHandling::errorOccurred = true;
  218713. if (JUCEApplication::isStandaloneApp())
  218714. Process::terminate();
  218715. break;
  218716. }
  218717. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218718. return true;
  218719. if (returnIfNoPendingMessages)
  218720. break;
  218721. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218722. }
  218723. return false;
  218724. }
  218725. #endif
  218726. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218727. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218728. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218729. // compiled on its own).
  218730. #if JUCE_INCLUDED_FILE
  218731. class FreeTypeFontFace
  218732. {
  218733. public:
  218734. enum FontStyle
  218735. {
  218736. Plain = 0,
  218737. Bold = 1,
  218738. Italic = 2
  218739. };
  218740. FreeTypeFontFace (const String& familyName)
  218741. : hasSerif (false),
  218742. monospaced (false)
  218743. {
  218744. family = familyName;
  218745. }
  218746. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218747. {
  218748. if (names [(int) style].fileName.isEmpty())
  218749. {
  218750. names [(int) style].fileName = name;
  218751. names [(int) style].faceIndex = faceIndex;
  218752. }
  218753. }
  218754. const String& getFamilyName() const throw() { return family; }
  218755. const String& getFileName (const int style, int& faceIndex) const throw()
  218756. {
  218757. faceIndex = names[style].faceIndex;
  218758. return names[style].fileName;
  218759. }
  218760. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218761. bool getMonospaced() const throw() { return monospaced; }
  218762. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218763. bool getSerif() const throw() { return hasSerif; }
  218764. private:
  218765. String family;
  218766. struct FontNameIndex
  218767. {
  218768. String fileName;
  218769. int faceIndex;
  218770. };
  218771. FontNameIndex names[4];
  218772. bool hasSerif, monospaced;
  218773. };
  218774. class FreeTypeInterface : public DeletedAtShutdown
  218775. {
  218776. public:
  218777. FreeTypeInterface()
  218778. : ftLib (0),
  218779. lastFace (0),
  218780. lastBold (false),
  218781. lastItalic (false)
  218782. {
  218783. if (FT_Init_FreeType (&ftLib) != 0)
  218784. {
  218785. ftLib = 0;
  218786. DBG ("Failed to initialize FreeType");
  218787. }
  218788. StringArray fontDirs;
  218789. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218790. fontDirs.removeEmptyStrings (true);
  218791. if (fontDirs.size() == 0)
  218792. {
  218793. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218794. if (fontsInfo != 0)
  218795. {
  218796. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218797. {
  218798. fontDirs.add (e->getAllSubText().trim());
  218799. }
  218800. }
  218801. }
  218802. if (fontDirs.size() == 0)
  218803. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218804. for (int i = 0; i < fontDirs.size(); ++i)
  218805. enumerateFaces (fontDirs[i]);
  218806. }
  218807. ~FreeTypeInterface()
  218808. {
  218809. if (lastFace != 0)
  218810. FT_Done_Face (lastFace);
  218811. if (ftLib != 0)
  218812. FT_Done_FreeType (ftLib);
  218813. clearSingletonInstance();
  218814. }
  218815. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218816. {
  218817. for (int i = 0; i < faces.size(); i++)
  218818. if (faces[i]->getFamilyName() == familyName)
  218819. return faces[i];
  218820. if (! create)
  218821. return 0;
  218822. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218823. faces.add (newFace);
  218824. return newFace;
  218825. }
  218826. // Enumerate all font faces available in a given directory
  218827. void enumerateFaces (const String& path)
  218828. {
  218829. File dirPath (path);
  218830. if (path.isEmpty() || ! dirPath.isDirectory())
  218831. return;
  218832. DirectoryIterator di (dirPath, true);
  218833. while (di.next())
  218834. {
  218835. File possible (di.getFile());
  218836. if (possible.hasFileExtension ("ttf")
  218837. || possible.hasFileExtension ("pfb")
  218838. || possible.hasFileExtension ("pcf"))
  218839. {
  218840. FT_Face face;
  218841. int faceIndex = 0;
  218842. int numFaces = 0;
  218843. do
  218844. {
  218845. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218846. faceIndex, &face) == 0)
  218847. {
  218848. if (faceIndex == 0)
  218849. numFaces = face->num_faces;
  218850. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218851. {
  218852. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218853. int style = (int) FreeTypeFontFace::Plain;
  218854. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218855. style |= (int) FreeTypeFontFace::Bold;
  218856. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218857. style |= (int) FreeTypeFontFace::Italic;
  218858. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218859. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218860. // Surely there must be a better way to do this?
  218861. const String name (face->family_name);
  218862. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218863. || name.containsIgnoreCase ("Verdana")
  218864. || name.containsIgnoreCase ("Arial")));
  218865. }
  218866. FT_Done_Face (face);
  218867. }
  218868. ++faceIndex;
  218869. }
  218870. while (faceIndex < numFaces);
  218871. }
  218872. }
  218873. }
  218874. // Create a FreeType face object for a given font
  218875. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218876. {
  218877. FT_Face face = 0;
  218878. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218879. {
  218880. face = lastFace;
  218881. }
  218882. else
  218883. {
  218884. if (lastFace != 0)
  218885. {
  218886. FT_Done_Face (lastFace);
  218887. lastFace = 0;
  218888. }
  218889. lastFontName = fontName;
  218890. lastBold = bold;
  218891. lastItalic = italic;
  218892. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218893. if (ftFace != 0)
  218894. {
  218895. int style = (int) FreeTypeFontFace::Plain;
  218896. if (bold)
  218897. style |= (int) FreeTypeFontFace::Bold;
  218898. if (italic)
  218899. style |= (int) FreeTypeFontFace::Italic;
  218900. int faceIndex;
  218901. String fileName (ftFace->getFileName (style, faceIndex));
  218902. if (fileName.isEmpty())
  218903. {
  218904. style ^= (int) FreeTypeFontFace::Bold;
  218905. fileName = ftFace->getFileName (style, faceIndex);
  218906. if (fileName.isEmpty())
  218907. {
  218908. style ^= (int) FreeTypeFontFace::Bold;
  218909. style ^= (int) FreeTypeFontFace::Italic;
  218910. fileName = ftFace->getFileName (style, faceIndex);
  218911. if (! fileName.length())
  218912. {
  218913. style ^= (int) FreeTypeFontFace::Bold;
  218914. fileName = ftFace->getFileName (style, faceIndex);
  218915. }
  218916. }
  218917. }
  218918. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218919. {
  218920. face = lastFace;
  218921. // If there isn't a unicode charmap then select the first one.
  218922. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218923. FT_Set_Charmap (face, face->charmaps[0]);
  218924. }
  218925. }
  218926. }
  218927. return face;
  218928. }
  218929. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218930. {
  218931. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218932. const float height = (float) (face->ascender - face->descender);
  218933. const float scaleX = 1.0f / height;
  218934. const float scaleY = -1.0f / height;
  218935. Path destShape;
  218936. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218937. || face->glyph->format != ft_glyph_format_outline)
  218938. {
  218939. return false;
  218940. }
  218941. const FT_Outline* const outline = &face->glyph->outline;
  218942. const short* const contours = outline->contours;
  218943. const char* const tags = outline->tags;
  218944. FT_Vector* const points = outline->points;
  218945. for (int c = 0; c < outline->n_contours; c++)
  218946. {
  218947. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218948. const int endPoint = contours[c];
  218949. for (int p = startPoint; p <= endPoint; p++)
  218950. {
  218951. const float x = scaleX * points[p].x;
  218952. const float y = scaleY * points[p].y;
  218953. if (p == startPoint)
  218954. {
  218955. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218956. {
  218957. float x2 = scaleX * points [endPoint].x;
  218958. float y2 = scaleY * points [endPoint].y;
  218959. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218960. {
  218961. x2 = (x + x2) * 0.5f;
  218962. y2 = (y + y2) * 0.5f;
  218963. }
  218964. destShape.startNewSubPath (x2, y2);
  218965. }
  218966. else
  218967. {
  218968. destShape.startNewSubPath (x, y);
  218969. }
  218970. }
  218971. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218972. {
  218973. if (p != startPoint)
  218974. destShape.lineTo (x, y);
  218975. }
  218976. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218977. {
  218978. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218979. float x2 = scaleX * points [nextIndex].x;
  218980. float y2 = scaleY * points [nextIndex].y;
  218981. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218982. {
  218983. x2 = (x + x2) * 0.5f;
  218984. y2 = (y + y2) * 0.5f;
  218985. }
  218986. else
  218987. {
  218988. ++p;
  218989. }
  218990. destShape.quadraticTo (x, y, x2, y2);
  218991. }
  218992. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218993. {
  218994. if (p >= endPoint)
  218995. return false;
  218996. const int next1 = p + 1;
  218997. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218998. const float x2 = scaleX * points [next1].x;
  218999. const float y2 = scaleY * points [next1].y;
  219000. const float x3 = scaleX * points [next2].x;
  219001. const float y3 = scaleY * points [next2].y;
  219002. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219003. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219004. return false;
  219005. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219006. p += 2;
  219007. }
  219008. }
  219009. destShape.closeSubPath();
  219010. }
  219011. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219012. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219013. addKerning (face, dest, character, glyphIndex);
  219014. return true;
  219015. }
  219016. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219017. {
  219018. const float height = (float) (face->ascender - face->descender);
  219019. uint32 rightGlyphIndex;
  219020. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219021. while (rightGlyphIndex != 0)
  219022. {
  219023. FT_Vector kerning;
  219024. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219025. {
  219026. if (kerning.x != 0)
  219027. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219028. }
  219029. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219030. }
  219031. }
  219032. // Add a glyph to a font
  219033. bool addGlyphToFont (const uint32 character, const String& fontName,
  219034. bool bold, bool italic, CustomTypeface& dest)
  219035. {
  219036. FT_Face face = createFT_Face (fontName, bold, italic);
  219037. return face != 0 && addGlyph (face, dest, character);
  219038. }
  219039. void getFamilyNames (StringArray& familyNames) const
  219040. {
  219041. for (int i = 0; i < faces.size(); i++)
  219042. familyNames.add (faces[i]->getFamilyName());
  219043. }
  219044. void getMonospacedNames (StringArray& monoSpaced) const
  219045. {
  219046. for (int i = 0; i < faces.size(); i++)
  219047. if (faces[i]->getMonospaced())
  219048. monoSpaced.add (faces[i]->getFamilyName());
  219049. }
  219050. void getSerifNames (StringArray& serif) const
  219051. {
  219052. for (int i = 0; i < faces.size(); i++)
  219053. if (faces[i]->getSerif())
  219054. serif.add (faces[i]->getFamilyName());
  219055. }
  219056. void getSansSerifNames (StringArray& sansSerif) const
  219057. {
  219058. for (int i = 0; i < faces.size(); i++)
  219059. if (! faces[i]->getSerif())
  219060. sansSerif.add (faces[i]->getFamilyName());
  219061. }
  219062. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219063. private:
  219064. FT_Library ftLib;
  219065. FT_Face lastFace;
  219066. String lastFontName;
  219067. bool lastBold, lastItalic;
  219068. OwnedArray<FreeTypeFontFace> faces;
  219069. };
  219070. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219071. class FreetypeTypeface : public CustomTypeface
  219072. {
  219073. public:
  219074. FreetypeTypeface (const Font& font)
  219075. {
  219076. FT_Face face = FreeTypeInterface::getInstance()
  219077. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219078. if (face == 0)
  219079. {
  219080. #if JUCE_DEBUG
  219081. String msg ("Failed to create typeface: ");
  219082. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219083. DBG (msg);
  219084. #endif
  219085. }
  219086. else
  219087. {
  219088. setCharacteristics (font.getTypefaceName(),
  219089. face->ascender / (float) (face->ascender - face->descender),
  219090. font.isBold(), font.isItalic(),
  219091. L' ');
  219092. }
  219093. }
  219094. bool loadGlyphIfPossible (juce_wchar character)
  219095. {
  219096. return FreeTypeInterface::getInstance()
  219097. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219098. }
  219099. };
  219100. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219101. {
  219102. return new FreetypeTypeface (font);
  219103. }
  219104. const StringArray Font::findAllTypefaceNames()
  219105. {
  219106. StringArray s;
  219107. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219108. s.sort (true);
  219109. return s;
  219110. }
  219111. namespace
  219112. {
  219113. const String pickBestFont (const StringArray& names,
  219114. const char* const choicesString)
  219115. {
  219116. StringArray choices;
  219117. choices.addTokens (String (choicesString), ",", String::empty);
  219118. choices.trim();
  219119. choices.removeEmptyStrings();
  219120. int i, j;
  219121. for (j = 0; j < choices.size(); ++j)
  219122. if (names.contains (choices[j], true))
  219123. return choices[j];
  219124. for (j = 0; j < choices.size(); ++j)
  219125. for (i = 0; i < names.size(); i++)
  219126. if (names[i].startsWithIgnoreCase (choices[j]))
  219127. return names[i];
  219128. for (j = 0; j < choices.size(); ++j)
  219129. for (i = 0; i < names.size(); i++)
  219130. if (names[i].containsIgnoreCase (choices[j]))
  219131. return names[i];
  219132. return names[0];
  219133. }
  219134. const String linux_getDefaultSansSerifFontName()
  219135. {
  219136. StringArray allFonts;
  219137. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219138. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219139. }
  219140. const String linux_getDefaultSerifFontName()
  219141. {
  219142. StringArray allFonts;
  219143. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219144. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219145. }
  219146. const String linux_getDefaultMonospacedFontName()
  219147. {
  219148. StringArray allFonts;
  219149. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219150. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219151. }
  219152. }
  219153. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  219154. {
  219155. defaultSans = linux_getDefaultSansSerifFontName();
  219156. defaultSerif = linux_getDefaultSerifFontName();
  219157. defaultFixed = linux_getDefaultMonospacedFontName();
  219158. }
  219159. #endif
  219160. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219161. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219162. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219163. // compiled on its own).
  219164. #if JUCE_INCLUDED_FILE
  219165. // These are defined in juce_linux_Messaging.cpp
  219166. extern Display* display;
  219167. extern XContext windowHandleXContext;
  219168. namespace Atoms
  219169. {
  219170. enum ProtocolItems
  219171. {
  219172. TAKE_FOCUS = 0,
  219173. DELETE_WINDOW = 1,
  219174. PING = 2
  219175. };
  219176. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219177. ActiveWin, Pid, WindowType, WindowState,
  219178. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219179. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219180. XdndActionDescription, XdndActionCopy,
  219181. allowedActions[5],
  219182. allowedMimeTypes[2];
  219183. const unsigned long DndVersion = 3;
  219184. static void initialiseAtoms()
  219185. {
  219186. static bool atomsInitialised = false;
  219187. if (! atomsInitialised)
  219188. {
  219189. atomsInitialised = true;
  219190. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219191. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219192. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219193. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219194. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219195. State = XInternAtom (display, "WM_STATE", True);
  219196. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219197. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219198. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219199. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219200. XdndAware = XInternAtom (display, "XdndAware", False);
  219201. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219202. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219203. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219204. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219205. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219206. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219207. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219208. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219209. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219210. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219211. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219212. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219213. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219214. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219215. allowedActions[1] = XdndActionCopy;
  219216. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219217. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219218. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219219. }
  219220. }
  219221. }
  219222. namespace Keys
  219223. {
  219224. enum MouseButtons
  219225. {
  219226. NoButton = 0,
  219227. LeftButton = 1,
  219228. MiddleButton = 2,
  219229. RightButton = 3,
  219230. WheelUp = 4,
  219231. WheelDown = 5
  219232. };
  219233. static int AltMask = 0;
  219234. static int NumLockMask = 0;
  219235. static bool numLock = false;
  219236. static bool capsLock = false;
  219237. static char keyStates [32];
  219238. static const int extendedKeyModifier = 0x10000000;
  219239. }
  219240. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219241. {
  219242. int keysym;
  219243. if (keyCode & Keys::extendedKeyModifier)
  219244. {
  219245. keysym = 0xff00 | (keyCode & 0xff);
  219246. }
  219247. else
  219248. {
  219249. keysym = keyCode;
  219250. if (keysym == (XK_Tab & 0xff)
  219251. || keysym == (XK_Return & 0xff)
  219252. || keysym == (XK_Escape & 0xff)
  219253. || keysym == (XK_BackSpace & 0xff))
  219254. {
  219255. keysym |= 0xff00;
  219256. }
  219257. }
  219258. ScopedXLock xlock;
  219259. const int keycode = XKeysymToKeycode (display, keysym);
  219260. const int keybyte = keycode >> 3;
  219261. const int keybit = (1 << (keycode & 7));
  219262. return (Keys::keyStates [keybyte] & keybit) != 0;
  219263. }
  219264. #if JUCE_USE_XSHM
  219265. namespace XSHMHelpers
  219266. {
  219267. static int trappedErrorCode = 0;
  219268. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219269. {
  219270. trappedErrorCode = err->error_code;
  219271. return 0;
  219272. }
  219273. static bool isShmAvailable() throw()
  219274. {
  219275. static bool isChecked = false;
  219276. static bool isAvailable = false;
  219277. if (! isChecked)
  219278. {
  219279. isChecked = true;
  219280. int major, minor;
  219281. Bool pixmaps;
  219282. ScopedXLock xlock;
  219283. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219284. {
  219285. trappedErrorCode = 0;
  219286. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219287. XShmSegmentInfo segmentInfo;
  219288. zerostruct (segmentInfo);
  219289. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219290. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219291. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219292. xImage->bytes_per_line * xImage->height,
  219293. IPC_CREAT | 0777)) >= 0)
  219294. {
  219295. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219296. if (segmentInfo.shmaddr != (void*) -1)
  219297. {
  219298. segmentInfo.readOnly = False;
  219299. xImage->data = segmentInfo.shmaddr;
  219300. XSync (display, False);
  219301. if (XShmAttach (display, &segmentInfo) != 0)
  219302. {
  219303. XSync (display, False);
  219304. XShmDetach (display, &segmentInfo);
  219305. isAvailable = true;
  219306. }
  219307. }
  219308. XFlush (display);
  219309. XDestroyImage (xImage);
  219310. shmdt (segmentInfo.shmaddr);
  219311. }
  219312. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219313. XSetErrorHandler (oldHandler);
  219314. if (trappedErrorCode != 0)
  219315. isAvailable = false;
  219316. }
  219317. }
  219318. return isAvailable;
  219319. }
  219320. }
  219321. #endif
  219322. #if JUCE_USE_XRENDER
  219323. namespace XRender
  219324. {
  219325. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219326. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219327. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219328. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219329. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219330. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219331. static tXRenderFindFormat xRenderFindFormat = 0;
  219332. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219333. static bool isAvailable()
  219334. {
  219335. static bool hasLoaded = false;
  219336. if (! hasLoaded)
  219337. {
  219338. ScopedXLock xlock;
  219339. hasLoaded = true;
  219340. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219341. if (h != 0)
  219342. {
  219343. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219344. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219345. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219346. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219347. }
  219348. if (xRenderQueryVersion != 0
  219349. && xRenderFindStandardFormat != 0
  219350. && xRenderFindFormat != 0
  219351. && xRenderFindVisualFormat != 0)
  219352. {
  219353. int major, minor;
  219354. if (xRenderQueryVersion (display, &major, &minor))
  219355. return true;
  219356. }
  219357. xRenderQueryVersion = 0;
  219358. }
  219359. return xRenderQueryVersion != 0;
  219360. }
  219361. static XRenderPictFormat* findPictureFormat()
  219362. {
  219363. ScopedXLock xlock;
  219364. XRenderPictFormat* pictFormat = 0;
  219365. if (isAvailable())
  219366. {
  219367. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219368. if (pictFormat == 0)
  219369. {
  219370. XRenderPictFormat desiredFormat;
  219371. desiredFormat.type = PictTypeDirect;
  219372. desiredFormat.depth = 32;
  219373. desiredFormat.direct.alphaMask = 0xff;
  219374. desiredFormat.direct.redMask = 0xff;
  219375. desiredFormat.direct.greenMask = 0xff;
  219376. desiredFormat.direct.blueMask = 0xff;
  219377. desiredFormat.direct.alpha = 24;
  219378. desiredFormat.direct.red = 16;
  219379. desiredFormat.direct.green = 8;
  219380. desiredFormat.direct.blue = 0;
  219381. pictFormat = xRenderFindFormat (display,
  219382. PictFormatType | PictFormatDepth
  219383. | PictFormatRedMask | PictFormatRed
  219384. | PictFormatGreenMask | PictFormatGreen
  219385. | PictFormatBlueMask | PictFormatBlue
  219386. | PictFormatAlphaMask | PictFormatAlpha,
  219387. &desiredFormat,
  219388. 0);
  219389. }
  219390. }
  219391. return pictFormat;
  219392. }
  219393. }
  219394. #endif
  219395. namespace Visuals
  219396. {
  219397. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219398. {
  219399. ScopedXLock xlock;
  219400. Visual* visual = 0;
  219401. int numVisuals = 0;
  219402. long desiredMask = VisualNoMask;
  219403. XVisualInfo desiredVisual;
  219404. desiredVisual.screen = DefaultScreen (display);
  219405. desiredVisual.depth = desiredDepth;
  219406. desiredMask = VisualScreenMask | VisualDepthMask;
  219407. if (desiredDepth == 32)
  219408. {
  219409. desiredVisual.c_class = TrueColor;
  219410. desiredVisual.red_mask = 0x00FF0000;
  219411. desiredVisual.green_mask = 0x0000FF00;
  219412. desiredVisual.blue_mask = 0x000000FF;
  219413. desiredVisual.bits_per_rgb = 8;
  219414. desiredMask |= VisualClassMask;
  219415. desiredMask |= VisualRedMaskMask;
  219416. desiredMask |= VisualGreenMaskMask;
  219417. desiredMask |= VisualBlueMaskMask;
  219418. desiredMask |= VisualBitsPerRGBMask;
  219419. }
  219420. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219421. desiredMask,
  219422. &desiredVisual,
  219423. &numVisuals);
  219424. if (xvinfos != 0)
  219425. {
  219426. for (int i = 0; i < numVisuals; i++)
  219427. {
  219428. if (xvinfos[i].depth == desiredDepth)
  219429. {
  219430. visual = xvinfos[i].visual;
  219431. break;
  219432. }
  219433. }
  219434. XFree (xvinfos);
  219435. }
  219436. return visual;
  219437. }
  219438. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219439. {
  219440. Visual* visual = 0;
  219441. if (desiredDepth == 32)
  219442. {
  219443. #if JUCE_USE_XSHM
  219444. if (XSHMHelpers::isShmAvailable())
  219445. {
  219446. #if JUCE_USE_XRENDER
  219447. if (XRender::isAvailable())
  219448. {
  219449. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219450. if (pictFormat != 0)
  219451. {
  219452. int numVisuals = 0;
  219453. XVisualInfo desiredVisual;
  219454. desiredVisual.screen = DefaultScreen (display);
  219455. desiredVisual.depth = 32;
  219456. desiredVisual.bits_per_rgb = 8;
  219457. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219458. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219459. &desiredVisual, &numVisuals);
  219460. if (xvinfos != 0)
  219461. {
  219462. for (int i = 0; i < numVisuals; ++i)
  219463. {
  219464. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219465. if (pictVisualFormat != 0
  219466. && pictVisualFormat->type == PictTypeDirect
  219467. && pictVisualFormat->direct.alphaMask)
  219468. {
  219469. visual = xvinfos[i].visual;
  219470. matchedDepth = 32;
  219471. break;
  219472. }
  219473. }
  219474. XFree (xvinfos);
  219475. }
  219476. }
  219477. }
  219478. #endif
  219479. if (visual == 0)
  219480. {
  219481. visual = findVisualWithDepth (32);
  219482. if (visual != 0)
  219483. matchedDepth = 32;
  219484. }
  219485. }
  219486. #endif
  219487. }
  219488. if (visual == 0 && desiredDepth >= 24)
  219489. {
  219490. visual = findVisualWithDepth (24);
  219491. if (visual != 0)
  219492. matchedDepth = 24;
  219493. }
  219494. if (visual == 0 && desiredDepth >= 16)
  219495. {
  219496. visual = findVisualWithDepth (16);
  219497. if (visual != 0)
  219498. matchedDepth = 16;
  219499. }
  219500. return visual;
  219501. }
  219502. }
  219503. class XBitmapImage : public Image::SharedImage
  219504. {
  219505. public:
  219506. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219507. const bool clearImage, const int imageDepth_, Visual* visual)
  219508. : Image::SharedImage (format_, w, h),
  219509. imageDepth (imageDepth_),
  219510. gc (None)
  219511. {
  219512. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219513. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219514. lineStride = ((w * pixelStride + 3) & ~3);
  219515. ScopedXLock xlock;
  219516. #if JUCE_USE_XSHM
  219517. usingXShm = false;
  219518. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219519. {
  219520. zerostruct (segmentInfo);
  219521. segmentInfo.shmid = -1;
  219522. segmentInfo.shmaddr = (char *) -1;
  219523. segmentInfo.readOnly = False;
  219524. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219525. if (xImage != 0)
  219526. {
  219527. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219528. xImage->bytes_per_line * xImage->height,
  219529. IPC_CREAT | 0777)) >= 0)
  219530. {
  219531. if (segmentInfo.shmid != -1)
  219532. {
  219533. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219534. if (segmentInfo.shmaddr != (void*) -1)
  219535. {
  219536. segmentInfo.readOnly = False;
  219537. xImage->data = segmentInfo.shmaddr;
  219538. imageData = (uint8*) segmentInfo.shmaddr;
  219539. if (XShmAttach (display, &segmentInfo) != 0)
  219540. usingXShm = true;
  219541. else
  219542. jassertfalse;
  219543. }
  219544. else
  219545. {
  219546. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219547. }
  219548. }
  219549. }
  219550. }
  219551. }
  219552. if (! usingXShm)
  219553. #endif
  219554. {
  219555. imageDataAllocated.malloc (lineStride * h);
  219556. imageData = imageDataAllocated;
  219557. if (format_ == Image::ARGB && clearImage)
  219558. zeromem (imageData, h * lineStride);
  219559. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219560. xImage->width = w;
  219561. xImage->height = h;
  219562. xImage->xoffset = 0;
  219563. xImage->format = ZPixmap;
  219564. xImage->data = (char*) imageData;
  219565. xImage->byte_order = ImageByteOrder (display);
  219566. xImage->bitmap_unit = BitmapUnit (display);
  219567. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219568. xImage->bitmap_pad = 32;
  219569. xImage->depth = pixelStride * 8;
  219570. xImage->bytes_per_line = lineStride;
  219571. xImage->bits_per_pixel = pixelStride * 8;
  219572. xImage->red_mask = 0x00FF0000;
  219573. xImage->green_mask = 0x0000FF00;
  219574. xImage->blue_mask = 0x000000FF;
  219575. if (imageDepth == 16)
  219576. {
  219577. const int pixelStride = 2;
  219578. const int lineStride = ((w * pixelStride + 3) & ~3);
  219579. imageData16Bit.malloc (lineStride * h);
  219580. xImage->data = imageData16Bit;
  219581. xImage->bitmap_pad = 16;
  219582. xImage->depth = pixelStride * 8;
  219583. xImage->bytes_per_line = lineStride;
  219584. xImage->bits_per_pixel = pixelStride * 8;
  219585. xImage->red_mask = visual->red_mask;
  219586. xImage->green_mask = visual->green_mask;
  219587. xImage->blue_mask = visual->blue_mask;
  219588. }
  219589. if (! XInitImage (xImage))
  219590. jassertfalse;
  219591. }
  219592. }
  219593. ~XBitmapImage()
  219594. {
  219595. ScopedXLock xlock;
  219596. if (gc != None)
  219597. XFreeGC (display, gc);
  219598. #if JUCE_USE_XSHM
  219599. if (usingXShm)
  219600. {
  219601. XShmDetach (display, &segmentInfo);
  219602. XFlush (display);
  219603. XDestroyImage (xImage);
  219604. shmdt (segmentInfo.shmaddr);
  219605. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219606. }
  219607. else
  219608. #endif
  219609. {
  219610. xImage->data = 0;
  219611. XDestroyImage (xImage);
  219612. }
  219613. }
  219614. Image::ImageType getType() const { return Image::NativeImage; }
  219615. LowLevelGraphicsContext* createLowLevelContext()
  219616. {
  219617. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219618. }
  219619. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  219620. {
  219621. bitmap.data = imageData + x * pixelStride + y * lineStride;
  219622. bitmap.pixelFormat = format;
  219623. bitmap.lineStride = lineStride;
  219624. bitmap.pixelStride = pixelStride;
  219625. }
  219626. SharedImage* clone()
  219627. {
  219628. jassertfalse;
  219629. return 0;
  219630. }
  219631. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219632. {
  219633. ScopedXLock xlock;
  219634. if (gc == None)
  219635. {
  219636. XGCValues gcvalues;
  219637. gcvalues.foreground = None;
  219638. gcvalues.background = None;
  219639. gcvalues.function = GXcopy;
  219640. gcvalues.plane_mask = AllPlanes;
  219641. gcvalues.clip_mask = None;
  219642. gcvalues.graphics_exposures = False;
  219643. gc = XCreateGC (display, window,
  219644. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219645. &gcvalues);
  219646. }
  219647. if (imageDepth == 16)
  219648. {
  219649. const uint32 rMask = xImage->red_mask;
  219650. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219651. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219652. const uint32 gMask = xImage->green_mask;
  219653. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219654. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219655. const uint32 bMask = xImage->blue_mask;
  219656. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219657. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219658. const Image::BitmapData srcData (Image (this), Image::BitmapData::readOnly);
  219659. for (int y = sy; y < sy + dh; ++y)
  219660. {
  219661. const uint8* p = srcData.getPixelPointer (sx, y);
  219662. for (int x = sx; x < sx + dw; ++x)
  219663. {
  219664. const PixelRGB* const pixel = (const PixelRGB*) p;
  219665. p += srcData.pixelStride;
  219666. XPutPixel (xImage, x, y,
  219667. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219668. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219669. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219670. }
  219671. }
  219672. }
  219673. // blit results to screen.
  219674. #if JUCE_USE_XSHM
  219675. if (usingXShm)
  219676. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219677. else
  219678. #endif
  219679. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219680. }
  219681. private:
  219682. XImage* xImage;
  219683. const int imageDepth;
  219684. HeapBlock <uint8> imageDataAllocated;
  219685. HeapBlock <char> imageData16Bit;
  219686. int pixelStride, lineStride;
  219687. uint8* imageData;
  219688. GC gc;
  219689. #if JUCE_USE_XSHM
  219690. XShmSegmentInfo segmentInfo;
  219691. bool usingXShm;
  219692. #endif
  219693. static int getShiftNeeded (const uint32 mask) throw()
  219694. {
  219695. for (int i = 32; --i >= 0;)
  219696. if (((mask >> i) & 1) != 0)
  219697. return i - 7;
  219698. jassertfalse;
  219699. return 0;
  219700. }
  219701. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219702. };
  219703. namespace PixmapHelpers
  219704. {
  219705. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219706. {
  219707. ScopedXLock xlock;
  219708. const int width = image.getWidth();
  219709. const int height = image.getHeight();
  219710. HeapBlock <uint32> colour (width * height);
  219711. int index = 0;
  219712. for (int y = 0; y < height; ++y)
  219713. for (int x = 0; x < width; ++x)
  219714. colour[index++] = image.getPixelAt (x, y).getARGB();
  219715. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219716. 0, reinterpret_cast<char*> (colour.getData()),
  219717. width, height, 32, 0);
  219718. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219719. width, height, 24);
  219720. GC gc = XCreateGC (display, pixmap, 0, 0);
  219721. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219722. XFreeGC (display, gc);
  219723. return pixmap;
  219724. }
  219725. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219726. {
  219727. ScopedXLock xlock;
  219728. const int width = image.getWidth();
  219729. const int height = image.getHeight();
  219730. const int stride = (width + 7) >> 3;
  219731. HeapBlock <char> mask;
  219732. mask.calloc (stride * height);
  219733. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219734. for (int y = 0; y < height; ++y)
  219735. {
  219736. for (int x = 0; x < width; ++x)
  219737. {
  219738. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219739. const int offset = y * stride + (x >> 3);
  219740. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219741. mask[offset] |= bit;
  219742. }
  219743. }
  219744. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219745. mask.getData(), width, height, 1, 0, 1);
  219746. }
  219747. }
  219748. class LinuxComponentPeer : public ComponentPeer
  219749. {
  219750. public:
  219751. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219752. : ComponentPeer (component, windowStyleFlags),
  219753. windowH (0),
  219754. parentWindow (0),
  219755. wx (0),
  219756. wy (0),
  219757. ww (0),
  219758. wh (0),
  219759. fullScreen (false),
  219760. mapped (false),
  219761. visual (0),
  219762. depth (0)
  219763. {
  219764. // it's dangerous to create a window on a thread other than the message thread..
  219765. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219766. repainter = new LinuxRepaintManager (this);
  219767. createWindow();
  219768. setTitle (component->getName());
  219769. }
  219770. ~LinuxComponentPeer()
  219771. {
  219772. // it's dangerous to delete a window on a thread other than the message thread..
  219773. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219774. deleteIconPixmaps();
  219775. destroyWindow();
  219776. windowH = 0;
  219777. }
  219778. void* getNativeHandle() const
  219779. {
  219780. return (void*) windowH;
  219781. }
  219782. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219783. {
  219784. XPointer peer = 0;
  219785. ScopedXLock xlock;
  219786. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219787. {
  219788. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219789. peer = 0;
  219790. }
  219791. return (LinuxComponentPeer*) peer;
  219792. }
  219793. void setVisible (bool shouldBeVisible)
  219794. {
  219795. ScopedXLock xlock;
  219796. if (shouldBeVisible)
  219797. XMapWindow (display, windowH);
  219798. else
  219799. XUnmapWindow (display, windowH);
  219800. }
  219801. void setTitle (const String& title)
  219802. {
  219803. XTextProperty nameProperty;
  219804. char* strings[] = { const_cast <char*> (title.toUTF8().getAddress()) };
  219805. ScopedXLock xlock;
  219806. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219807. {
  219808. XSetWMName (display, windowH, &nameProperty);
  219809. XSetWMIconName (display, windowH, &nameProperty);
  219810. XFree (nameProperty.value);
  219811. }
  219812. }
  219813. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219814. {
  219815. fullScreen = isNowFullScreen;
  219816. if (windowH != 0)
  219817. {
  219818. WeakReference<Component> deletionChecker (component);
  219819. wx = x;
  219820. wy = y;
  219821. ww = jmax (1, w);
  219822. wh = jmax (1, h);
  219823. ScopedXLock xlock;
  219824. // Make sure the Window manager does what we want
  219825. XSizeHints* hints = XAllocSizeHints();
  219826. hints->flags = USSize | USPosition;
  219827. hints->width = ww;
  219828. hints->height = wh;
  219829. hints->x = wx;
  219830. hints->y = wy;
  219831. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219832. {
  219833. hints->min_width = hints->max_width = hints->width;
  219834. hints->min_height = hints->max_height = hints->height;
  219835. hints->flags |= PMinSize | PMaxSize;
  219836. }
  219837. XSetWMNormalHints (display, windowH, hints);
  219838. XFree (hints);
  219839. XMoveResizeWindow (display, windowH,
  219840. wx - windowBorder.getLeft(),
  219841. wy - windowBorder.getTop(), ww, wh);
  219842. if (deletionChecker != 0)
  219843. {
  219844. updateBorderSize();
  219845. handleMovedOrResized();
  219846. }
  219847. }
  219848. }
  219849. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219850. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219851. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219852. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219853. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219854. {
  219855. return relativePosition + getScreenPosition();
  219856. }
  219857. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219858. {
  219859. return screenPosition - getScreenPosition();
  219860. }
  219861. void setAlpha (float newAlpha)
  219862. {
  219863. //xxx todo!
  219864. }
  219865. void setMinimised (bool shouldBeMinimised)
  219866. {
  219867. if (shouldBeMinimised)
  219868. {
  219869. Window root = RootWindow (display, DefaultScreen (display));
  219870. XClientMessageEvent clientMsg;
  219871. clientMsg.display = display;
  219872. clientMsg.window = windowH;
  219873. clientMsg.type = ClientMessage;
  219874. clientMsg.format = 32;
  219875. clientMsg.message_type = Atoms::ChangeState;
  219876. clientMsg.data.l[0] = IconicState;
  219877. ScopedXLock xlock;
  219878. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219879. }
  219880. else
  219881. {
  219882. setVisible (true);
  219883. }
  219884. }
  219885. bool isMinimised() const
  219886. {
  219887. bool minimised = false;
  219888. unsigned char* stateProp;
  219889. unsigned long nitems, bytesLeft;
  219890. Atom actualType;
  219891. int actualFormat;
  219892. ScopedXLock xlock;
  219893. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219894. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219895. &stateProp) == Success
  219896. && actualType == Atoms::State
  219897. && actualFormat == 32
  219898. && nitems > 0)
  219899. {
  219900. if (((unsigned long*) stateProp)[0] == IconicState)
  219901. minimised = true;
  219902. XFree (stateProp);
  219903. }
  219904. return minimised;
  219905. }
  219906. void setFullScreen (const bool shouldBeFullScreen)
  219907. {
  219908. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219909. setMinimised (false);
  219910. if (fullScreen != shouldBeFullScreen)
  219911. {
  219912. if (shouldBeFullScreen)
  219913. r = Desktop::getInstance().getMainMonitorArea();
  219914. if (! r.isEmpty())
  219915. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219916. getComponent()->repaint();
  219917. }
  219918. }
  219919. bool isFullScreen() const
  219920. {
  219921. return fullScreen;
  219922. }
  219923. bool isChildWindowOf (Window possibleParent) const
  219924. {
  219925. Window* windowList = 0;
  219926. uint32 windowListSize = 0;
  219927. Window parent, root;
  219928. ScopedXLock xlock;
  219929. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219930. {
  219931. if (windowList != 0)
  219932. XFree (windowList);
  219933. return parent == possibleParent;
  219934. }
  219935. return false;
  219936. }
  219937. bool isFrontWindow() const
  219938. {
  219939. Window* windowList = 0;
  219940. uint32 windowListSize = 0;
  219941. bool result = false;
  219942. ScopedXLock xlock;
  219943. Window parent, root = RootWindow (display, DefaultScreen (display));
  219944. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219945. {
  219946. for (int i = windowListSize; --i >= 0;)
  219947. {
  219948. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219949. if (peer != 0)
  219950. {
  219951. result = (peer == this);
  219952. break;
  219953. }
  219954. }
  219955. }
  219956. if (windowList != 0)
  219957. XFree (windowList);
  219958. return result;
  219959. }
  219960. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219961. {
  219962. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219963. return false;
  219964. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219965. {
  219966. Component* const c = Desktop::getInstance().getComponent (i);
  219967. if (c == getComponent())
  219968. break;
  219969. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219970. return false;
  219971. }
  219972. if (trueIfInAChildWindow)
  219973. return true;
  219974. ::Window root, child;
  219975. unsigned int bw, depth;
  219976. int wx, wy, w, h;
  219977. ScopedXLock xlock;
  219978. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219979. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219980. &bw, &depth))
  219981. {
  219982. return false;
  219983. }
  219984. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219985. return false;
  219986. return child == None;
  219987. }
  219988. const BorderSize<int> getFrameSize() const
  219989. {
  219990. return BorderSize<int>();
  219991. }
  219992. bool setAlwaysOnTop (bool alwaysOnTop)
  219993. {
  219994. return false;
  219995. }
  219996. void toFront (bool makeActive)
  219997. {
  219998. if (makeActive)
  219999. {
  220000. setVisible (true);
  220001. grabFocus();
  220002. }
  220003. XEvent ev;
  220004. ev.xclient.type = ClientMessage;
  220005. ev.xclient.serial = 0;
  220006. ev.xclient.send_event = True;
  220007. ev.xclient.message_type = Atoms::ActiveWin;
  220008. ev.xclient.window = windowH;
  220009. ev.xclient.format = 32;
  220010. ev.xclient.data.l[0] = 2;
  220011. ev.xclient.data.l[1] = CurrentTime;
  220012. ev.xclient.data.l[2] = 0;
  220013. ev.xclient.data.l[3] = 0;
  220014. ev.xclient.data.l[4] = 0;
  220015. {
  220016. ScopedXLock xlock;
  220017. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220018. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220019. XWindowAttributes attr;
  220020. XGetWindowAttributes (display, windowH, &attr);
  220021. if (component->isAlwaysOnTop())
  220022. XRaiseWindow (display, windowH);
  220023. XSync (display, False);
  220024. }
  220025. handleBroughtToFront();
  220026. }
  220027. void toBehind (ComponentPeer* other)
  220028. {
  220029. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220030. jassert (otherPeer != 0); // wrong type of window?
  220031. if (otherPeer != 0)
  220032. {
  220033. setMinimised (false);
  220034. Window newStack[] = { otherPeer->windowH, windowH };
  220035. ScopedXLock xlock;
  220036. XRestackWindows (display, newStack, 2);
  220037. }
  220038. }
  220039. bool isFocused() const
  220040. {
  220041. int revert = 0;
  220042. Window focusedWindow = 0;
  220043. ScopedXLock xlock;
  220044. XGetInputFocus (display, &focusedWindow, &revert);
  220045. return focusedWindow == windowH;
  220046. }
  220047. void grabFocus()
  220048. {
  220049. XWindowAttributes atts;
  220050. ScopedXLock xlock;
  220051. if (windowH != 0
  220052. && XGetWindowAttributes (display, windowH, &atts)
  220053. && atts.map_state == IsViewable
  220054. && ! isFocused())
  220055. {
  220056. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220057. isActiveApplication = true;
  220058. }
  220059. }
  220060. void textInputRequired (const Point<int>&)
  220061. {
  220062. }
  220063. void repaint (const Rectangle<int>& area)
  220064. {
  220065. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220066. }
  220067. void performAnyPendingRepaintsNow()
  220068. {
  220069. repainter->performAnyPendingRepaintsNow();
  220070. }
  220071. void setIcon (const Image& newIcon)
  220072. {
  220073. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220074. HeapBlock <unsigned long> data (dataSize);
  220075. int index = 0;
  220076. data[index++] = newIcon.getWidth();
  220077. data[index++] = newIcon.getHeight();
  220078. for (int y = 0; y < newIcon.getHeight(); ++y)
  220079. for (int x = 0; x < newIcon.getWidth(); ++x)
  220080. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220081. ScopedXLock xlock;
  220082. XChangeProperty (display, windowH,
  220083. XInternAtom (display, "_NET_WM_ICON", False),
  220084. XA_CARDINAL, 32, PropModeReplace,
  220085. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220086. deleteIconPixmaps();
  220087. XWMHints* wmHints = XGetWMHints (display, windowH);
  220088. if (wmHints == 0)
  220089. wmHints = XAllocWMHints();
  220090. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220091. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  220092. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  220093. XSetWMHints (display, windowH, wmHints);
  220094. XFree (wmHints);
  220095. XSync (display, False);
  220096. }
  220097. void deleteIconPixmaps()
  220098. {
  220099. ScopedXLock xlock;
  220100. XWMHints* wmHints = XGetWMHints (display, windowH);
  220101. if (wmHints != 0)
  220102. {
  220103. if ((wmHints->flags & IconPixmapHint) != 0)
  220104. {
  220105. wmHints->flags &= ~IconPixmapHint;
  220106. XFreePixmap (display, wmHints->icon_pixmap);
  220107. }
  220108. if ((wmHints->flags & IconMaskHint) != 0)
  220109. {
  220110. wmHints->flags &= ~IconMaskHint;
  220111. XFreePixmap (display, wmHints->icon_mask);
  220112. }
  220113. XSetWMHints (display, windowH, wmHints);
  220114. XFree (wmHints);
  220115. }
  220116. }
  220117. void handleWindowMessage (XEvent* event)
  220118. {
  220119. switch (event->xany.type)
  220120. {
  220121. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  220122. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  220123. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  220124. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  220125. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  220126. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  220127. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  220128. case FocusIn: handleFocusInEvent(); break;
  220129. case FocusOut: handleFocusOutEvent(); break;
  220130. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  220131. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  220132. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  220133. case SelectionNotify: handleDragAndDropSelection (event); break;
  220134. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  220135. case ReparentNotify: handleReparentNotifyEvent(); break;
  220136. case GravityNotify: handleGravityNotify(); break;
  220137. case CirculateNotify:
  220138. case CreateNotify:
  220139. case DestroyNotify:
  220140. // Think we can ignore these
  220141. break;
  220142. case MapNotify:
  220143. mapped = true;
  220144. handleBroughtToFront();
  220145. break;
  220146. case UnmapNotify:
  220147. mapped = false;
  220148. break;
  220149. case SelectionClear:
  220150. case SelectionRequest:
  220151. break;
  220152. default:
  220153. #if JUCE_USE_XSHM
  220154. {
  220155. ScopedXLock xlock;
  220156. if (event->xany.type == XShmGetEventBase (display))
  220157. repainter->notifyPaintCompleted();
  220158. }
  220159. #endif
  220160. break;
  220161. }
  220162. }
  220163. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  220164. {
  220165. char utf8 [64] = { 0 };
  220166. juce_wchar unicodeChar = 0;
  220167. int keyCode = 0;
  220168. bool keyDownChange = false;
  220169. KeySym sym;
  220170. {
  220171. ScopedXLock xlock;
  220172. updateKeyStates (keyEvent->keycode, true);
  220173. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220174. ::setlocale (LC_ALL, "");
  220175. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220176. ::setlocale (LC_ALL, oldLocale);
  220177. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220178. keyCode = (int) unicodeChar;
  220179. if (keyCode < 0x20)
  220180. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220181. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220182. }
  220183. const ModifierKeys oldMods (currentModifiers);
  220184. bool keyPressed = false;
  220185. if ((sym & 0xff00) == 0xff00)
  220186. {
  220187. switch (sym) // Translate keypad
  220188. {
  220189. case XK_KP_Divide: keyCode = XK_slash; break;
  220190. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  220191. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  220192. case XK_KP_Add: keyCode = XK_plus; break;
  220193. case XK_KP_Enter: keyCode = XK_Return; break;
  220194. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  220195. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  220196. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  220197. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  220198. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  220199. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  220200. case XK_KP_5: keyCode = XK_5; break;
  220201. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  220202. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  220203. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  220204. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  220205. default: break;
  220206. }
  220207. switch (sym)
  220208. {
  220209. case XK_Left:
  220210. case XK_Right:
  220211. case XK_Up:
  220212. case XK_Down:
  220213. case XK_Page_Up:
  220214. case XK_Page_Down:
  220215. case XK_End:
  220216. case XK_Home:
  220217. case XK_Delete:
  220218. case XK_Insert:
  220219. keyPressed = true;
  220220. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220221. break;
  220222. case XK_Tab:
  220223. case XK_Return:
  220224. case XK_Escape:
  220225. case XK_BackSpace:
  220226. keyPressed = true;
  220227. keyCode &= 0xff;
  220228. break;
  220229. default:
  220230. if (sym >= XK_F1 && sym <= XK_F16)
  220231. {
  220232. keyPressed = true;
  220233. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220234. }
  220235. break;
  220236. }
  220237. }
  220238. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220239. keyPressed = true;
  220240. if (oldMods != currentModifiers)
  220241. handleModifierKeysChange();
  220242. if (keyDownChange)
  220243. handleKeyUpOrDown (true);
  220244. if (keyPressed)
  220245. handleKeyPress (keyCode, unicodeChar);
  220246. }
  220247. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  220248. {
  220249. updateKeyStates (keyEvent->keycode, false);
  220250. KeySym sym;
  220251. {
  220252. ScopedXLock xlock;
  220253. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220254. }
  220255. const ModifierKeys oldMods (currentModifiers);
  220256. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220257. if (oldMods != currentModifiers)
  220258. handleModifierKeysChange();
  220259. if (keyDownChange)
  220260. handleKeyUpOrDown (false);
  220261. }
  220262. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  220263. {
  220264. updateKeyModifiers (buttonPressEvent->state);
  220265. bool buttonMsg = false;
  220266. const int map = pointerMap [buttonPressEvent->button - Button1];
  220267. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220268. {
  220269. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220270. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220271. }
  220272. if (map == Keys::LeftButton)
  220273. {
  220274. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220275. buttonMsg = true;
  220276. }
  220277. else if (map == Keys::RightButton)
  220278. {
  220279. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220280. buttonMsg = true;
  220281. }
  220282. else if (map == Keys::MiddleButton)
  220283. {
  220284. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220285. buttonMsg = true;
  220286. }
  220287. if (buttonMsg)
  220288. {
  220289. toFront (true);
  220290. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220291. getEventTime (buttonPressEvent->time));
  220292. }
  220293. clearLastMousePos();
  220294. }
  220295. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  220296. {
  220297. updateKeyModifiers (buttonRelEvent->state);
  220298. const int map = pointerMap [buttonRelEvent->button - Button1];
  220299. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220300. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220301. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220302. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220303. getEventTime (buttonRelEvent->time));
  220304. clearLastMousePos();
  220305. }
  220306. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  220307. {
  220308. updateKeyModifiers (movedEvent->state);
  220309. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  220310. if (lastMousePos != mousePos)
  220311. {
  220312. lastMousePos = mousePos;
  220313. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220314. {
  220315. Window wRoot = 0, wParent = 0;
  220316. {
  220317. ScopedXLock xlock;
  220318. unsigned int numChildren;
  220319. Window* wChild = 0;
  220320. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220321. }
  220322. if (wParent != 0
  220323. && wParent != windowH
  220324. && wParent != wRoot)
  220325. {
  220326. parentWindow = wParent;
  220327. updateBounds();
  220328. }
  220329. else
  220330. {
  220331. parentWindow = 0;
  220332. }
  220333. }
  220334. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220335. }
  220336. }
  220337. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  220338. {
  220339. clearLastMousePos();
  220340. if (! currentModifiers.isAnyMouseButtonDown())
  220341. {
  220342. updateKeyModifiers (enterEvent->state);
  220343. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220344. }
  220345. }
  220346. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  220347. {
  220348. // Suppress the normal leave if we've got a pointer grab, or if
  220349. // it's a bogus one caused by clicking a mouse button when running
  220350. // in a Window manager
  220351. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220352. || leaveEvent->mode == NotifyUngrab)
  220353. {
  220354. updateKeyModifiers (leaveEvent->state);
  220355. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220356. }
  220357. }
  220358. void handleFocusInEvent()
  220359. {
  220360. isActiveApplication = true;
  220361. if (isFocused())
  220362. handleFocusGain();
  220363. }
  220364. void handleFocusOutEvent()
  220365. {
  220366. isActiveApplication = false;
  220367. if (! isFocused())
  220368. handleFocusLoss();
  220369. }
  220370. void handleExposeEvent (XExposeEvent* exposeEvent)
  220371. {
  220372. // Batch together all pending expose events
  220373. XEvent nextEvent;
  220374. ScopedXLock xlock;
  220375. if (exposeEvent->window != windowH)
  220376. {
  220377. Window child;
  220378. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220379. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220380. &child);
  220381. }
  220382. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220383. exposeEvent->width, exposeEvent->height));
  220384. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220385. {
  220386. XPeekEvent (display, (XEvent*) &nextEvent);
  220387. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  220388. break;
  220389. XNextEvent (display, (XEvent*) &nextEvent);
  220390. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220391. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220392. nextExposeEvent->width, nextExposeEvent->height));
  220393. }
  220394. }
  220395. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  220396. {
  220397. updateBounds();
  220398. updateBorderSize();
  220399. handleMovedOrResized();
  220400. // if the native title bar is dragged, need to tell any active menus, etc.
  220401. if ((styleFlags & windowHasTitleBar) != 0
  220402. && component->isCurrentlyBlockedByAnotherModalComponent())
  220403. {
  220404. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220405. if (currentModalComp != 0)
  220406. currentModalComp->inputAttemptWhenModal();
  220407. }
  220408. if (confEvent->window == windowH
  220409. && confEvent->above != 0
  220410. && isFrontWindow())
  220411. {
  220412. handleBroughtToFront();
  220413. }
  220414. }
  220415. void handleReparentNotifyEvent()
  220416. {
  220417. parentWindow = 0;
  220418. Window wRoot = 0;
  220419. Window* wChild = 0;
  220420. unsigned int numChildren;
  220421. {
  220422. ScopedXLock xlock;
  220423. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220424. }
  220425. if (parentWindow == windowH || parentWindow == wRoot)
  220426. parentWindow = 0;
  220427. handleGravityNotify();
  220428. }
  220429. void handleGravityNotify()
  220430. {
  220431. updateBounds();
  220432. updateBorderSize();
  220433. handleMovedOrResized();
  220434. }
  220435. void handleMappingNotify (XMappingEvent* const mappingEvent)
  220436. {
  220437. if (mappingEvent->request != MappingPointer)
  220438. {
  220439. // Deal with modifier/keyboard mapping
  220440. ScopedXLock xlock;
  220441. XRefreshKeyboardMapping (mappingEvent);
  220442. updateModifierMappings();
  220443. }
  220444. }
  220445. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  220446. {
  220447. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220448. {
  220449. const Atom atom = (Atom) clientMsg->data.l[0];
  220450. if (atom == Atoms::ProtocolList [Atoms::PING])
  220451. {
  220452. Window root = RootWindow (display, DefaultScreen (display));
  220453. clientMsg->window = root;
  220454. XSendEvent (display, root, False, NoEventMask, event);
  220455. XFlush (display);
  220456. }
  220457. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220458. {
  220459. XWindowAttributes atts;
  220460. ScopedXLock xlock;
  220461. if (clientMsg->window != 0
  220462. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220463. {
  220464. if (atts.map_state == IsViewable)
  220465. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220466. }
  220467. }
  220468. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220469. {
  220470. handleUserClosingWindow();
  220471. }
  220472. }
  220473. else if (clientMsg->message_type == Atoms::XdndEnter)
  220474. {
  220475. handleDragAndDropEnter (clientMsg);
  220476. }
  220477. else if (clientMsg->message_type == Atoms::XdndLeave)
  220478. {
  220479. resetDragAndDrop();
  220480. }
  220481. else if (clientMsg->message_type == Atoms::XdndPosition)
  220482. {
  220483. handleDragAndDropPosition (clientMsg);
  220484. }
  220485. else if (clientMsg->message_type == Atoms::XdndDrop)
  220486. {
  220487. handleDragAndDropDrop (clientMsg);
  220488. }
  220489. else if (clientMsg->message_type == Atoms::XdndStatus)
  220490. {
  220491. handleDragAndDropStatus (clientMsg);
  220492. }
  220493. else if (clientMsg->message_type == Atoms::XdndFinished)
  220494. {
  220495. resetDragAndDrop();
  220496. }
  220497. }
  220498. void showMouseCursor (Cursor cursor) throw()
  220499. {
  220500. ScopedXLock xlock;
  220501. XDefineCursor (display, windowH, cursor);
  220502. }
  220503. void setTaskBarIcon (const Image& image)
  220504. {
  220505. ScopedXLock xlock;
  220506. taskbarImage = image;
  220507. Screen* const screen = XDefaultScreenOfDisplay (display);
  220508. const int screenNumber = XScreenNumberOfScreen (screen);
  220509. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220510. screenAtom << screenNumber;
  220511. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220512. XGrabServer (display);
  220513. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220514. if (managerWin != None)
  220515. XSelectInput (display, managerWin, StructureNotifyMask);
  220516. XUngrabServer (display);
  220517. XFlush (display);
  220518. if (managerWin != None)
  220519. {
  220520. XEvent ev;
  220521. zerostruct (ev);
  220522. ev.xclient.type = ClientMessage;
  220523. ev.xclient.window = managerWin;
  220524. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220525. ev.xclient.format = 32;
  220526. ev.xclient.data.l[0] = CurrentTime;
  220527. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220528. ev.xclient.data.l[2] = windowH;
  220529. ev.xclient.data.l[3] = 0;
  220530. ev.xclient.data.l[4] = 0;
  220531. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220532. XSync (display, False);
  220533. }
  220534. // For older KDE's ...
  220535. long atomData = 1;
  220536. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220537. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220538. // For more recent KDE's...
  220539. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220540. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220541. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220542. XSizeHints* hints = XAllocSizeHints();
  220543. hints->flags = PMinSize;
  220544. hints->min_width = 22;
  220545. hints->min_height = 22;
  220546. XSetWMNormalHints (display, windowH, hints);
  220547. XFree (hints);
  220548. }
  220549. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220550. bool dontRepaint;
  220551. static ModifierKeys currentModifiers;
  220552. static bool isActiveApplication;
  220553. private:
  220554. class LinuxRepaintManager : public Timer
  220555. {
  220556. public:
  220557. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220558. : peer (peer_),
  220559. lastTimeImageUsed (0)
  220560. {
  220561. #if JUCE_USE_XSHM
  220562. shmCompletedDrawing = true;
  220563. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220564. if (useARGBImagesForRendering)
  220565. {
  220566. ScopedXLock xlock;
  220567. XShmSegmentInfo segmentinfo;
  220568. XImage* const testImage
  220569. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220570. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220571. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220572. XDestroyImage (testImage);
  220573. }
  220574. #endif
  220575. }
  220576. void timerCallback()
  220577. {
  220578. #if JUCE_USE_XSHM
  220579. if (! shmCompletedDrawing)
  220580. return;
  220581. #endif
  220582. if (! regionsNeedingRepaint.isEmpty())
  220583. {
  220584. stopTimer();
  220585. performAnyPendingRepaintsNow();
  220586. }
  220587. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220588. {
  220589. stopTimer();
  220590. image = Image::null;
  220591. }
  220592. }
  220593. void repaint (const Rectangle<int>& area)
  220594. {
  220595. if (! isTimerRunning())
  220596. startTimer (repaintTimerPeriod);
  220597. regionsNeedingRepaint.add (area);
  220598. }
  220599. void performAnyPendingRepaintsNow()
  220600. {
  220601. #if JUCE_USE_XSHM
  220602. if (! shmCompletedDrawing)
  220603. {
  220604. startTimer (repaintTimerPeriod);
  220605. return;
  220606. }
  220607. #endif
  220608. peer->clearMaskedRegion();
  220609. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220610. regionsNeedingRepaint.clear();
  220611. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220612. if (! totalArea.isEmpty())
  220613. {
  220614. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220615. || image.getHeight() < totalArea.getHeight())
  220616. {
  220617. #if JUCE_USE_XSHM
  220618. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220619. : Image::RGB,
  220620. #else
  220621. image = Image (new XBitmapImage (Image::RGB,
  220622. #endif
  220623. (totalArea.getWidth() + 31) & ~31,
  220624. (totalArea.getHeight() + 31) & ~31,
  220625. false, peer->depth, peer->visual));
  220626. }
  220627. startTimer (repaintTimerPeriod);
  220628. RectangleList adjustedList (originalRepaintRegion);
  220629. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220630. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220631. if (peer->depth == 32)
  220632. {
  220633. RectangleList::Iterator i (originalRepaintRegion);
  220634. while (i.next())
  220635. image.clear (*i.getRectangle() - totalArea.getPosition());
  220636. }
  220637. peer->handlePaint (context);
  220638. if (! peer->maskedRegion.isEmpty())
  220639. originalRepaintRegion.subtract (peer->maskedRegion);
  220640. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220641. {
  220642. #if JUCE_USE_XSHM
  220643. shmCompletedDrawing = false;
  220644. #endif
  220645. const Rectangle<int>& r = *i.getRectangle();
  220646. static_cast<XBitmapImage*> (image.getSharedImage())
  220647. ->blitToWindow (peer->windowH,
  220648. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220649. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220650. }
  220651. }
  220652. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220653. startTimer (repaintTimerPeriod);
  220654. }
  220655. #if JUCE_USE_XSHM
  220656. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220657. #endif
  220658. private:
  220659. enum { repaintTimerPeriod = 1000 / 100 };
  220660. LinuxComponentPeer* const peer;
  220661. Image image;
  220662. uint32 lastTimeImageUsed;
  220663. RectangleList regionsNeedingRepaint;
  220664. #if JUCE_USE_XSHM
  220665. bool useARGBImagesForRendering, shmCompletedDrawing;
  220666. #endif
  220667. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220668. };
  220669. ScopedPointer <LinuxRepaintManager> repainter;
  220670. friend class LinuxRepaintManager;
  220671. Window windowH, parentWindow;
  220672. int wx, wy, ww, wh;
  220673. Image taskbarImage;
  220674. bool fullScreen, mapped;
  220675. Visual* visual;
  220676. int depth;
  220677. BorderSize<int> windowBorder;
  220678. struct MotifWmHints
  220679. {
  220680. unsigned long flags;
  220681. unsigned long functions;
  220682. unsigned long decorations;
  220683. long input_mode;
  220684. unsigned long status;
  220685. };
  220686. static void updateKeyStates (const int keycode, const bool press) throw()
  220687. {
  220688. const int keybyte = keycode >> 3;
  220689. const int keybit = (1 << (keycode & 7));
  220690. if (press)
  220691. Keys::keyStates [keybyte] |= keybit;
  220692. else
  220693. Keys::keyStates [keybyte] &= ~keybit;
  220694. }
  220695. static void updateKeyModifiers (const int status) throw()
  220696. {
  220697. int keyMods = 0;
  220698. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220699. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220700. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220701. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220702. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220703. Keys::capsLock = ((status & LockMask) != 0);
  220704. }
  220705. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220706. {
  220707. int modifier = 0;
  220708. bool isModifier = true;
  220709. switch (sym)
  220710. {
  220711. case XK_Shift_L:
  220712. case XK_Shift_R:
  220713. modifier = ModifierKeys::shiftModifier;
  220714. break;
  220715. case XK_Control_L:
  220716. case XK_Control_R:
  220717. modifier = ModifierKeys::ctrlModifier;
  220718. break;
  220719. case XK_Alt_L:
  220720. case XK_Alt_R:
  220721. modifier = ModifierKeys::altModifier;
  220722. break;
  220723. case XK_Num_Lock:
  220724. if (press)
  220725. Keys::numLock = ! Keys::numLock;
  220726. break;
  220727. case XK_Caps_Lock:
  220728. if (press)
  220729. Keys::capsLock = ! Keys::capsLock;
  220730. break;
  220731. case XK_Scroll_Lock:
  220732. break;
  220733. default:
  220734. isModifier = false;
  220735. break;
  220736. }
  220737. if (modifier != 0)
  220738. {
  220739. if (press)
  220740. currentModifiers = currentModifiers.withFlags (modifier);
  220741. else
  220742. currentModifiers = currentModifiers.withoutFlags (modifier);
  220743. }
  220744. return isModifier;
  220745. }
  220746. // Alt and Num lock are not defined by standard X
  220747. // modifier constants: check what they're mapped to
  220748. static void updateModifierMappings() throw()
  220749. {
  220750. ScopedXLock xlock;
  220751. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220752. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220753. Keys::AltMask = 0;
  220754. Keys::NumLockMask = 0;
  220755. XModifierKeymap* mapping = XGetModifierMapping (display);
  220756. if (mapping)
  220757. {
  220758. for (int i = 0; i < 8; i++)
  220759. {
  220760. if (mapping->modifiermap [i << 1] == altLeftCode)
  220761. Keys::AltMask = 1 << i;
  220762. else if (mapping->modifiermap [i << 1] == numLockCode)
  220763. Keys::NumLockMask = 1 << i;
  220764. }
  220765. XFreeModifiermap (mapping);
  220766. }
  220767. }
  220768. void removeWindowDecorations (Window wndH)
  220769. {
  220770. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220771. if (hints != None)
  220772. {
  220773. MotifWmHints motifHints;
  220774. zerostruct (motifHints);
  220775. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220776. motifHints.decorations = 0;
  220777. ScopedXLock xlock;
  220778. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220779. (unsigned char*) &motifHints, 4);
  220780. }
  220781. hints = XInternAtom (display, "_WIN_HINTS", True);
  220782. if (hints != None)
  220783. {
  220784. long gnomeHints = 0;
  220785. ScopedXLock xlock;
  220786. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220787. (unsigned char*) &gnomeHints, 1);
  220788. }
  220789. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220790. if (hints != None)
  220791. {
  220792. long kwmHints = 2; /*KDE_tinyDecoration*/
  220793. ScopedXLock xlock;
  220794. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220795. (unsigned char*) &kwmHints, 1);
  220796. }
  220797. }
  220798. void addWindowButtons (Window wndH)
  220799. {
  220800. ScopedXLock xlock;
  220801. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220802. if (hints != None)
  220803. {
  220804. MotifWmHints motifHints;
  220805. zerostruct (motifHints);
  220806. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220807. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220808. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220809. if ((styleFlags & windowHasCloseButton) != 0)
  220810. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220811. if ((styleFlags & windowHasMinimiseButton) != 0)
  220812. {
  220813. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220814. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220815. }
  220816. if ((styleFlags & windowHasMaximiseButton) != 0)
  220817. {
  220818. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220819. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220820. }
  220821. if ((styleFlags & windowIsResizable) != 0)
  220822. {
  220823. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220824. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220825. }
  220826. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220827. }
  220828. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220829. if (hints != None)
  220830. {
  220831. int netHints [6];
  220832. int num = 0;
  220833. if ((styleFlags & windowIsResizable) != 0)
  220834. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220835. if ((styleFlags & windowHasMaximiseButton) != 0)
  220836. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220837. if ((styleFlags & windowHasMinimiseButton) != 0)
  220838. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220839. if ((styleFlags & windowHasCloseButton) != 0)
  220840. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220841. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220842. }
  220843. }
  220844. void setWindowType()
  220845. {
  220846. int netHints [2];
  220847. int numHints = 0;
  220848. if ((styleFlags & windowIsTemporary) != 0
  220849. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220850. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220851. else
  220852. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220853. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220854. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220855. (unsigned char*) &netHints, numHints);
  220856. numHints = 0;
  220857. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220858. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220859. if (component->isAlwaysOnTop())
  220860. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220861. if (numHints > 0)
  220862. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220863. (unsigned char*) &netHints, numHints);
  220864. }
  220865. void createWindow()
  220866. {
  220867. ScopedXLock xlock;
  220868. Atoms::initialiseAtoms();
  220869. resetDragAndDrop();
  220870. // Get defaults for various properties
  220871. const int screen = DefaultScreen (display);
  220872. Window root = RootWindow (display, screen);
  220873. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220874. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220875. if (visual == 0)
  220876. {
  220877. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220878. Process::terminate();
  220879. }
  220880. // Create and install a colormap suitable fr our visual
  220881. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220882. XInstallColormap (display, colormap);
  220883. // Set up the window attributes
  220884. XSetWindowAttributes swa;
  220885. swa.border_pixel = 0;
  220886. swa.background_pixmap = None;
  220887. swa.colormap = colormap;
  220888. swa.event_mask = getAllEventsMask();
  220889. windowH = XCreateWindow (display, root,
  220890. 0, 0, 1, 1,
  220891. 0, depth, InputOutput, visual,
  220892. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220893. &swa);
  220894. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220895. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220896. GrabModeAsync, GrabModeAsync, None, None);
  220897. // Set the window context to identify the window handle object
  220898. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220899. {
  220900. // Failed
  220901. jassertfalse;
  220902. Logger::outputDebugString ("Failed to create context information for window.\n");
  220903. XDestroyWindow (display, windowH);
  220904. windowH = 0;
  220905. return;
  220906. }
  220907. // Set window manager hints
  220908. XWMHints* wmHints = XAllocWMHints();
  220909. wmHints->flags = InputHint | StateHint;
  220910. wmHints->input = True; // Locally active input model
  220911. wmHints->initial_state = NormalState;
  220912. XSetWMHints (display, windowH, wmHints);
  220913. XFree (wmHints);
  220914. // Set the window type
  220915. setWindowType();
  220916. // Define decoration
  220917. if ((styleFlags & windowHasTitleBar) == 0)
  220918. removeWindowDecorations (windowH);
  220919. else
  220920. addWindowButtons (windowH);
  220921. setTitle (getComponent()->getName());
  220922. // Associate the PID, allowing to be shut down when something goes wrong
  220923. unsigned long pid = getpid();
  220924. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220925. (unsigned char*) &pid, 1);
  220926. // Set window manager protocols
  220927. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220928. (unsigned char*) Atoms::ProtocolList, 2);
  220929. // Set drag and drop flags
  220930. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220931. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220932. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220933. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220934. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220935. (const unsigned char*) "", 0);
  220936. unsigned long dndVersion = Atoms::DndVersion;
  220937. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220938. (const unsigned char*) &dndVersion, 1);
  220939. // Initialise the pointer and keyboard mapping
  220940. // This is not the same as the logical pointer mapping the X server uses:
  220941. // we don't mess with this.
  220942. static bool mappingInitialised = false;
  220943. if (! mappingInitialised)
  220944. {
  220945. mappingInitialised = true;
  220946. const int numButtons = XGetPointerMapping (display, 0, 0);
  220947. if (numButtons == 2)
  220948. {
  220949. pointerMap[0] = Keys::LeftButton;
  220950. pointerMap[1] = Keys::RightButton;
  220951. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220952. }
  220953. else if (numButtons >= 3)
  220954. {
  220955. pointerMap[0] = Keys::LeftButton;
  220956. pointerMap[1] = Keys::MiddleButton;
  220957. pointerMap[2] = Keys::RightButton;
  220958. if (numButtons >= 5)
  220959. {
  220960. pointerMap[3] = Keys::WheelUp;
  220961. pointerMap[4] = Keys::WheelDown;
  220962. }
  220963. }
  220964. updateModifierMappings();
  220965. }
  220966. }
  220967. void destroyWindow()
  220968. {
  220969. ScopedXLock xlock;
  220970. XPointer handlePointer;
  220971. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220972. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220973. XDestroyWindow (display, windowH);
  220974. // Wait for it to complete and then remove any events for this
  220975. // window from the event queue.
  220976. XSync (display, false);
  220977. XEvent event;
  220978. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220979. {}
  220980. }
  220981. static int getAllEventsMask() throw()
  220982. {
  220983. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220984. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220985. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220986. }
  220987. static int64 getEventTime (::Time t)
  220988. {
  220989. static int64 eventTimeOffset = 0x12345678;
  220990. const int64 thisMessageTime = t;
  220991. if (eventTimeOffset == 0x12345678)
  220992. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220993. return eventTimeOffset + thisMessageTime;
  220994. }
  220995. void updateBorderSize()
  220996. {
  220997. if ((styleFlags & windowHasTitleBar) == 0)
  220998. {
  220999. windowBorder = BorderSize<int> (0);
  221000. }
  221001. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221002. {
  221003. ScopedXLock xlock;
  221004. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221005. if (hints != None)
  221006. {
  221007. unsigned char* data = 0;
  221008. unsigned long nitems, bytesLeft;
  221009. Atom actualType;
  221010. int actualFormat;
  221011. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221012. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221013. &data) == Success)
  221014. {
  221015. const unsigned long* const sizes = (const unsigned long*) data;
  221016. if (actualFormat == 32)
  221017. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  221018. (int) sizes[3], (int) sizes[1]);
  221019. XFree (data);
  221020. }
  221021. }
  221022. }
  221023. }
  221024. void updateBounds()
  221025. {
  221026. jassert (windowH != 0);
  221027. if (windowH != 0)
  221028. {
  221029. Window root, child;
  221030. unsigned int bw, depth;
  221031. ScopedXLock xlock;
  221032. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221033. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221034. &bw, &depth))
  221035. {
  221036. wx = wy = ww = wh = 0;
  221037. }
  221038. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221039. {
  221040. wx = wy = 0;
  221041. }
  221042. }
  221043. }
  221044. void resetDragAndDrop()
  221045. {
  221046. dragAndDropFiles.clear();
  221047. lastDropPos = Point<int> (-1, -1);
  221048. dragAndDropCurrentMimeType = 0;
  221049. dragAndDropSourceWindow = 0;
  221050. srcMimeTypeAtomList.clear();
  221051. }
  221052. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221053. {
  221054. msg.type = ClientMessage;
  221055. msg.display = display;
  221056. msg.window = dragAndDropSourceWindow;
  221057. msg.format = 32;
  221058. msg.data.l[0] = windowH;
  221059. ScopedXLock xlock;
  221060. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221061. }
  221062. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221063. {
  221064. XClientMessageEvent msg;
  221065. zerostruct (msg);
  221066. msg.message_type = Atoms::XdndStatus;
  221067. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221068. msg.data.l[4] = dropAction;
  221069. sendDragAndDropMessage (msg);
  221070. }
  221071. void sendDragAndDropLeave()
  221072. {
  221073. XClientMessageEvent msg;
  221074. zerostruct (msg);
  221075. msg.message_type = Atoms::XdndLeave;
  221076. sendDragAndDropMessage (msg);
  221077. }
  221078. void sendDragAndDropFinish()
  221079. {
  221080. XClientMessageEvent msg;
  221081. zerostruct (msg);
  221082. msg.message_type = Atoms::XdndFinished;
  221083. sendDragAndDropMessage (msg);
  221084. }
  221085. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221086. {
  221087. if ((clientMsg->data.l[1] & 1) == 0)
  221088. {
  221089. sendDragAndDropLeave();
  221090. if (dragAndDropFiles.size() > 0)
  221091. handleFileDragExit (dragAndDropFiles);
  221092. dragAndDropFiles.clear();
  221093. }
  221094. }
  221095. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221096. {
  221097. if (dragAndDropSourceWindow == 0)
  221098. return;
  221099. dragAndDropSourceWindow = clientMsg->data.l[0];
  221100. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221101. (int) clientMsg->data.l[2] & 0xffff);
  221102. dropPos -= getScreenPosition();
  221103. if (lastDropPos != dropPos)
  221104. {
  221105. lastDropPos = dropPos;
  221106. dragAndDropTimestamp = clientMsg->data.l[3];
  221107. Atom targetAction = Atoms::XdndActionCopy;
  221108. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221109. {
  221110. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221111. {
  221112. targetAction = Atoms::allowedActions[i];
  221113. break;
  221114. }
  221115. }
  221116. sendDragAndDropStatus (true, targetAction);
  221117. if (dragAndDropFiles.size() == 0)
  221118. updateDraggedFileList (clientMsg);
  221119. if (dragAndDropFiles.size() > 0)
  221120. handleFileDragMove (dragAndDropFiles, dropPos);
  221121. }
  221122. }
  221123. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221124. {
  221125. if (dragAndDropFiles.size() == 0)
  221126. updateDraggedFileList (clientMsg);
  221127. const StringArray files (dragAndDropFiles);
  221128. const Point<int> lastPos (lastDropPos);
  221129. sendDragAndDropFinish();
  221130. resetDragAndDrop();
  221131. if (files.size() > 0)
  221132. handleFileDragDrop (files, lastPos);
  221133. }
  221134. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221135. {
  221136. dragAndDropFiles.clear();
  221137. srcMimeTypeAtomList.clear();
  221138. dragAndDropCurrentMimeType = 0;
  221139. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221140. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221141. {
  221142. dragAndDropSourceWindow = 0;
  221143. return;
  221144. }
  221145. dragAndDropSourceWindow = clientMsg->data.l[0];
  221146. if ((clientMsg->data.l[1] & 1) != 0)
  221147. {
  221148. Atom actual;
  221149. int format;
  221150. unsigned long count = 0, remaining = 0;
  221151. unsigned char* data = 0;
  221152. ScopedXLock xlock;
  221153. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221154. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221155. &count, &remaining, &data);
  221156. if (data != 0)
  221157. {
  221158. if (actual == XA_ATOM && format == 32 && count != 0)
  221159. {
  221160. const unsigned long* const types = (const unsigned long*) data;
  221161. for (unsigned int i = 0; i < count; ++i)
  221162. if (types[i] != None)
  221163. srcMimeTypeAtomList.add (types[i]);
  221164. }
  221165. XFree (data);
  221166. }
  221167. }
  221168. if (srcMimeTypeAtomList.size() == 0)
  221169. {
  221170. for (int i = 2; i < 5; ++i)
  221171. if (clientMsg->data.l[i] != None)
  221172. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221173. if (srcMimeTypeAtomList.size() == 0)
  221174. {
  221175. dragAndDropSourceWindow = 0;
  221176. return;
  221177. }
  221178. }
  221179. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221180. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221181. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221182. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221183. handleDragAndDropPosition (clientMsg);
  221184. }
  221185. void handleDragAndDropSelection (const XEvent* const evt)
  221186. {
  221187. dragAndDropFiles.clear();
  221188. if (evt->xselection.property != 0)
  221189. {
  221190. StringArray lines;
  221191. {
  221192. MemoryBlock dropData;
  221193. for (;;)
  221194. {
  221195. Atom actual;
  221196. uint8* data = 0;
  221197. unsigned long count = 0, remaining = 0;
  221198. int format = 0;
  221199. ScopedXLock xlock;
  221200. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221201. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221202. &format, &count, &remaining, &data) == Success)
  221203. {
  221204. dropData.append (data, count * format / 8);
  221205. XFree (data);
  221206. if (remaining == 0)
  221207. break;
  221208. }
  221209. else
  221210. {
  221211. XFree (data);
  221212. break;
  221213. }
  221214. }
  221215. lines.addLines (dropData.toString());
  221216. }
  221217. for (int i = 0; i < lines.size(); ++i)
  221218. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221219. dragAndDropFiles.trim();
  221220. dragAndDropFiles.removeEmptyStrings();
  221221. }
  221222. }
  221223. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221224. {
  221225. dragAndDropFiles.clear();
  221226. if (dragAndDropSourceWindow != None
  221227. && dragAndDropCurrentMimeType != 0)
  221228. {
  221229. dragAndDropTimestamp = clientMsg->data.l[2];
  221230. ScopedXLock xlock;
  221231. XConvertSelection (display,
  221232. Atoms::XdndSelection,
  221233. dragAndDropCurrentMimeType,
  221234. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221235. windowH,
  221236. dragAndDropTimestamp);
  221237. }
  221238. }
  221239. StringArray dragAndDropFiles;
  221240. int dragAndDropTimestamp;
  221241. Point<int> lastDropPos;
  221242. Atom dragAndDropCurrentMimeType;
  221243. Window dragAndDropSourceWindow;
  221244. Array <Atom> srcMimeTypeAtomList;
  221245. static int pointerMap[5];
  221246. static Point<int> lastMousePos;
  221247. static void clearLastMousePos() throw()
  221248. {
  221249. lastMousePos = Point<int> (0x100000, 0x100000);
  221250. }
  221251. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  221252. };
  221253. ModifierKeys LinuxComponentPeer::currentModifiers;
  221254. bool LinuxComponentPeer::isActiveApplication = false;
  221255. int LinuxComponentPeer::pointerMap[5];
  221256. Point<int> LinuxComponentPeer::lastMousePos;
  221257. bool Process::isForegroundProcess()
  221258. {
  221259. return LinuxComponentPeer::isActiveApplication;
  221260. }
  221261. void ModifierKeys::updateCurrentModifiers() throw()
  221262. {
  221263. currentModifiers = LinuxComponentPeer::currentModifiers;
  221264. }
  221265. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221266. {
  221267. Window root, child;
  221268. int x, y, winx, winy;
  221269. unsigned int mask;
  221270. int mouseMods = 0;
  221271. ScopedXLock xlock;
  221272. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221273. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221274. {
  221275. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221276. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221277. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221278. }
  221279. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221280. return LinuxComponentPeer::currentModifiers;
  221281. }
  221282. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221283. {
  221284. if (enableOrDisable)
  221285. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221286. }
  221287. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221288. {
  221289. return new LinuxComponentPeer (this, styleFlags);
  221290. }
  221291. // (this callback is hooked up in the messaging code)
  221292. void juce_windowMessageReceive (XEvent* event)
  221293. {
  221294. if (event->xany.window != None)
  221295. {
  221296. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221297. if (ComponentPeer::isValidPeer (peer))
  221298. peer->handleWindowMessage (event);
  221299. }
  221300. else
  221301. {
  221302. switch (event->xany.type)
  221303. {
  221304. case KeymapNotify:
  221305. {
  221306. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221307. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221308. break;
  221309. }
  221310. default:
  221311. break;
  221312. }
  221313. }
  221314. }
  221315. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221316. {
  221317. if (display == 0)
  221318. return;
  221319. #if JUCE_USE_XINERAMA
  221320. int major_opcode, first_event, first_error;
  221321. ScopedXLock xlock;
  221322. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221323. {
  221324. typedef Bool (*tXineramaIsActive) (Display*);
  221325. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221326. static tXineramaIsActive xXineramaIsActive = 0;
  221327. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221328. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221329. {
  221330. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221331. if (h == 0)
  221332. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221333. if (h != 0)
  221334. {
  221335. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221336. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221337. }
  221338. }
  221339. if (xXineramaIsActive != 0
  221340. && xXineramaQueryScreens != 0
  221341. && xXineramaIsActive (display))
  221342. {
  221343. int numMonitors = 0;
  221344. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221345. if (screens != 0)
  221346. {
  221347. for (int i = numMonitors; --i >= 0;)
  221348. {
  221349. int index = screens[i].screen_number;
  221350. if (index >= 0)
  221351. {
  221352. while (monitorCoords.size() < index)
  221353. monitorCoords.add (Rectangle<int>());
  221354. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221355. screens[i].y_org,
  221356. screens[i].width,
  221357. screens[i].height));
  221358. }
  221359. }
  221360. XFree (screens);
  221361. }
  221362. }
  221363. }
  221364. if (monitorCoords.size() == 0)
  221365. #endif
  221366. {
  221367. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221368. if (hints != None)
  221369. {
  221370. const int numMonitors = ScreenCount (display);
  221371. for (int i = 0; i < numMonitors; ++i)
  221372. {
  221373. Window root = RootWindow (display, i);
  221374. unsigned long nitems, bytesLeft;
  221375. Atom actualType;
  221376. int actualFormat;
  221377. unsigned char* data = 0;
  221378. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221379. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221380. &data) == Success)
  221381. {
  221382. const long* const position = (const long*) data;
  221383. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221384. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221385. position[2], position[3]));
  221386. XFree (data);
  221387. }
  221388. }
  221389. }
  221390. if (monitorCoords.size() == 0)
  221391. {
  221392. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221393. DisplayHeight (display, DefaultScreen (display))));
  221394. }
  221395. }
  221396. }
  221397. void Desktop::createMouseInputSources()
  221398. {
  221399. mouseSources.add (new MouseInputSource (0, true));
  221400. }
  221401. bool Desktop::canUseSemiTransparentWindows() throw()
  221402. {
  221403. int matchedDepth = 0;
  221404. const int desiredDepth = 32;
  221405. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221406. && (matchedDepth == desiredDepth);
  221407. }
  221408. const Point<int> MouseInputSource::getCurrentMousePosition()
  221409. {
  221410. Window root, child;
  221411. int x, y, winx, winy;
  221412. unsigned int mask;
  221413. ScopedXLock xlock;
  221414. if (XQueryPointer (display,
  221415. RootWindow (display, DefaultScreen (display)),
  221416. &root, &child,
  221417. &x, &y, &winx, &winy, &mask) == False)
  221418. {
  221419. // Pointer not on the default screen
  221420. x = y = -1;
  221421. }
  221422. return Point<int> (x, y);
  221423. }
  221424. void Desktop::setMousePosition (const Point<int>& newPosition)
  221425. {
  221426. ScopedXLock xlock;
  221427. Window root = RootWindow (display, DefaultScreen (display));
  221428. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221429. }
  221430. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  221431. {
  221432. return upright;
  221433. }
  221434. static bool screenSaverAllowed = true;
  221435. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221436. {
  221437. if (screenSaverAllowed != isEnabled)
  221438. {
  221439. screenSaverAllowed = isEnabled;
  221440. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221441. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221442. if (xScreenSaverSuspend == 0)
  221443. {
  221444. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221445. if (h != 0)
  221446. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221447. }
  221448. ScopedXLock xlock;
  221449. if (xScreenSaverSuspend != 0)
  221450. xScreenSaverSuspend (display, ! isEnabled);
  221451. }
  221452. }
  221453. bool Desktop::isScreenSaverEnabled()
  221454. {
  221455. return screenSaverAllowed;
  221456. }
  221457. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221458. {
  221459. ScopedXLock xlock;
  221460. const unsigned int imageW = image.getWidth();
  221461. const unsigned int imageH = image.getHeight();
  221462. #if JUCE_USE_XCURSOR
  221463. {
  221464. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221465. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221466. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221467. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221468. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221469. static tXcursorImageCreate xXcursorImageCreate = 0;
  221470. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221471. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221472. static bool hasBeenLoaded = false;
  221473. if (! hasBeenLoaded)
  221474. {
  221475. hasBeenLoaded = true;
  221476. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221477. if (h != 0)
  221478. {
  221479. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221480. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221481. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221482. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221483. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221484. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221485. || ! xXcursorSupportsARGB (display))
  221486. xXcursorSupportsARGB = 0;
  221487. }
  221488. }
  221489. if (xXcursorSupportsARGB != 0)
  221490. {
  221491. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221492. if (xcImage != 0)
  221493. {
  221494. xcImage->xhot = hotspotX;
  221495. xcImage->yhot = hotspotY;
  221496. XcursorPixel* dest = xcImage->pixels;
  221497. for (int y = 0; y < (int) imageH; ++y)
  221498. for (int x = 0; x < (int) imageW; ++x)
  221499. *dest++ = image.getPixelAt (x, y).getARGB();
  221500. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221501. xXcursorImageDestroy (xcImage);
  221502. if (result != 0)
  221503. return result;
  221504. }
  221505. }
  221506. }
  221507. #endif
  221508. Window root = RootWindow (display, DefaultScreen (display));
  221509. unsigned int cursorW, cursorH;
  221510. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221511. return 0;
  221512. Image im (Image::ARGB, cursorW, cursorH, true);
  221513. {
  221514. Graphics g (im);
  221515. if (imageW > cursorW || imageH > cursorH)
  221516. {
  221517. hotspotX = (hotspotX * cursorW) / imageW;
  221518. hotspotY = (hotspotY * cursorH) / imageH;
  221519. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221520. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221521. false);
  221522. }
  221523. else
  221524. {
  221525. g.drawImageAt (image, 0, 0);
  221526. }
  221527. }
  221528. const int stride = (cursorW + 7) >> 3;
  221529. HeapBlock <char> maskPlane, sourcePlane;
  221530. maskPlane.calloc (stride * cursorH);
  221531. sourcePlane.calloc (stride * cursorH);
  221532. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221533. for (int y = cursorH; --y >= 0;)
  221534. {
  221535. for (int x = cursorW; --x >= 0;)
  221536. {
  221537. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221538. const int offset = y * stride + (x >> 3);
  221539. const Colour c (im.getPixelAt (x, y));
  221540. if (c.getAlpha() >= 128)
  221541. maskPlane[offset] |= mask;
  221542. if (c.getBrightness() >= 0.5f)
  221543. sourcePlane[offset] |= mask;
  221544. }
  221545. }
  221546. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221547. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221548. XColor white, black;
  221549. black.red = black.green = black.blue = 0;
  221550. white.red = white.green = white.blue = 0xffff;
  221551. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221552. XFreePixmap (display, sourcePixmap);
  221553. XFreePixmap (display, maskPixmap);
  221554. return result;
  221555. }
  221556. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221557. {
  221558. ScopedXLock xlock;
  221559. if (cursorHandle != 0)
  221560. XFreeCursor (display, (Cursor) cursorHandle);
  221561. }
  221562. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221563. {
  221564. unsigned int shape;
  221565. switch (type)
  221566. {
  221567. case NormalCursor: return None; // Use parent cursor
  221568. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221569. case WaitCursor: shape = XC_watch; break;
  221570. case IBeamCursor: shape = XC_xterm; break;
  221571. case PointingHandCursor: shape = XC_hand2; break;
  221572. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221573. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221574. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221575. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221576. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221577. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221578. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221579. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221580. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221581. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221582. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221583. case CrosshairCursor: shape = XC_crosshair; break;
  221584. case DraggingHandCursor:
  221585. {
  221586. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221587. 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,
  221588. 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 };
  221589. const int dragHandDataSize = 99;
  221590. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221591. }
  221592. case CopyingCursor:
  221593. {
  221594. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221595. 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,
  221596. 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,
  221597. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221598. const int copyCursorSize = 119;
  221599. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221600. }
  221601. default:
  221602. jassertfalse;
  221603. return None;
  221604. }
  221605. ScopedXLock xlock;
  221606. return (void*) XCreateFontCursor (display, shape);
  221607. }
  221608. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221609. {
  221610. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221611. if (lp != 0)
  221612. lp->showMouseCursor ((Cursor) getHandle());
  221613. }
  221614. void MouseCursor::showInAllWindows() const
  221615. {
  221616. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221617. showInWindow (ComponentPeer::getPeer (i));
  221618. }
  221619. const Image juce_createIconForFile (const File& file)
  221620. {
  221621. return Image::null;
  221622. }
  221623. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221624. {
  221625. return createSoftwareImage (format, width, height, clearImage);
  221626. }
  221627. #if JUCE_OPENGL
  221628. class WindowedGLContext : public OpenGLContext
  221629. {
  221630. public:
  221631. WindowedGLContext (Component* const component,
  221632. const OpenGLPixelFormat& pixelFormat_,
  221633. GLXContext sharedContext)
  221634. : renderContext (0),
  221635. embeddedWindow (0),
  221636. pixelFormat (pixelFormat_),
  221637. swapInterval (0)
  221638. {
  221639. jassert (component != 0);
  221640. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221641. if (peer == 0)
  221642. return;
  221643. ScopedXLock xlock;
  221644. XSync (display, False);
  221645. GLint attribs [64];
  221646. int n = 0;
  221647. attribs[n++] = GLX_RGBA;
  221648. attribs[n++] = GLX_DOUBLEBUFFER;
  221649. attribs[n++] = GLX_RED_SIZE;
  221650. attribs[n++] = pixelFormat.redBits;
  221651. attribs[n++] = GLX_GREEN_SIZE;
  221652. attribs[n++] = pixelFormat.greenBits;
  221653. attribs[n++] = GLX_BLUE_SIZE;
  221654. attribs[n++] = pixelFormat.blueBits;
  221655. attribs[n++] = GLX_ALPHA_SIZE;
  221656. attribs[n++] = pixelFormat.alphaBits;
  221657. attribs[n++] = GLX_DEPTH_SIZE;
  221658. attribs[n++] = pixelFormat.depthBufferBits;
  221659. attribs[n++] = GLX_STENCIL_SIZE;
  221660. attribs[n++] = pixelFormat.stencilBufferBits;
  221661. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221662. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221663. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221664. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221665. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221666. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221667. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221668. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221669. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221670. attribs[n++] = None;
  221671. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221672. if (bestVisual == 0)
  221673. return;
  221674. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221675. Window windowH = (Window) peer->getNativeHandle();
  221676. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221677. XSetWindowAttributes swa;
  221678. swa.colormap = colourMap;
  221679. swa.border_pixel = 0;
  221680. swa.event_mask = ExposureMask | StructureNotifyMask;
  221681. embeddedWindow = XCreateWindow (display, windowH,
  221682. 0, 0, 1, 1, 0,
  221683. bestVisual->depth,
  221684. InputOutput,
  221685. bestVisual->visual,
  221686. CWBorderPixel | CWColormap | CWEventMask,
  221687. &swa);
  221688. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221689. XMapWindow (display, embeddedWindow);
  221690. XFreeColormap (display, colourMap);
  221691. XFree (bestVisual);
  221692. XSync (display, False);
  221693. }
  221694. ~WindowedGLContext()
  221695. {
  221696. ScopedXLock xlock;
  221697. deleteContext();
  221698. XUnmapWindow (display, embeddedWindow);
  221699. XDestroyWindow (display, embeddedWindow);
  221700. }
  221701. void deleteContext()
  221702. {
  221703. makeInactive();
  221704. if (renderContext != 0)
  221705. {
  221706. ScopedXLock xlock;
  221707. glXDestroyContext (display, renderContext);
  221708. renderContext = 0;
  221709. }
  221710. }
  221711. bool makeActive() const throw()
  221712. {
  221713. jassert (renderContext != 0);
  221714. ScopedXLock xlock;
  221715. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221716. && XSync (display, False);
  221717. }
  221718. bool makeInactive() const throw()
  221719. {
  221720. ScopedXLock xlock;
  221721. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221722. }
  221723. bool isActive() const throw()
  221724. {
  221725. ScopedXLock xlock;
  221726. return glXGetCurrentContext() == renderContext;
  221727. }
  221728. const OpenGLPixelFormat getPixelFormat() const
  221729. {
  221730. return pixelFormat;
  221731. }
  221732. void* getRawContext() const throw()
  221733. {
  221734. return renderContext;
  221735. }
  221736. void updateWindowPosition (int x, int y, int w, int h, int)
  221737. {
  221738. ScopedXLock xlock;
  221739. XMoveResizeWindow (display, embeddedWindow,
  221740. x, y, jmax (1, w), jmax (1, h));
  221741. }
  221742. void swapBuffers()
  221743. {
  221744. ScopedXLock xlock;
  221745. glXSwapBuffers (display, embeddedWindow);
  221746. }
  221747. bool setSwapInterval (const int numFramesPerSwap)
  221748. {
  221749. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221750. if (GLXSwapIntervalSGI != 0)
  221751. {
  221752. swapInterval = numFramesPerSwap;
  221753. GLXSwapIntervalSGI (numFramesPerSwap);
  221754. return true;
  221755. }
  221756. return false;
  221757. }
  221758. int getSwapInterval() const
  221759. {
  221760. return swapInterval;
  221761. }
  221762. void repaint()
  221763. {
  221764. }
  221765. GLXContext renderContext;
  221766. private:
  221767. Window embeddedWindow;
  221768. OpenGLPixelFormat pixelFormat;
  221769. int swapInterval;
  221770. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221771. };
  221772. OpenGLContext* OpenGLComponent::createContext()
  221773. {
  221774. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221775. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221776. return (c->renderContext != 0) ? c.release() : 0;
  221777. }
  221778. void juce_glViewport (const int w, const int h)
  221779. {
  221780. glViewport (0, 0, w, h);
  221781. }
  221782. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221783. OwnedArray <OpenGLPixelFormat>& results)
  221784. {
  221785. results.add (new OpenGLPixelFormat()); // xxx
  221786. }
  221787. #endif
  221788. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221789. {
  221790. jassertfalse; // not implemented!
  221791. return false;
  221792. }
  221793. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221794. {
  221795. jassertfalse; // not implemented!
  221796. return false;
  221797. }
  221798. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221799. {
  221800. if (! isOnDesktop ())
  221801. addToDesktop (0);
  221802. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221803. if (wp != 0)
  221804. {
  221805. wp->setTaskBarIcon (newImage);
  221806. setVisible (true);
  221807. toFront (false);
  221808. repaint();
  221809. }
  221810. }
  221811. void SystemTrayIconComponent::paint (Graphics& g)
  221812. {
  221813. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221814. if (wp != 0)
  221815. {
  221816. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221817. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221818. false);
  221819. }
  221820. }
  221821. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221822. {
  221823. // xxx not yet implemented!
  221824. }
  221825. void PlatformUtilities::beep()
  221826. {
  221827. std::cout << "\a" << std::flush;
  221828. }
  221829. bool AlertWindow::showNativeDialogBox (const String& title,
  221830. const String& bodyText,
  221831. bool isOkCancel)
  221832. {
  221833. // use a non-native one for the time being..
  221834. if (isOkCancel)
  221835. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221836. else
  221837. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221838. return true;
  221839. }
  221840. const int KeyPress::spaceKey = XK_space & 0xff;
  221841. const int KeyPress::returnKey = XK_Return & 0xff;
  221842. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221843. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221844. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221845. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221846. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221847. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221848. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221849. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221850. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221851. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221852. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221853. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221854. const int KeyPress::tabKey = XK_Tab & 0xff;
  221855. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221856. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221857. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221858. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221859. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221860. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221861. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221862. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221863. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221864. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221865. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221866. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221867. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221868. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221869. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221870. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221871. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221872. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221873. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221874. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221875. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221876. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221877. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221878. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221879. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221880. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221881. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221882. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221883. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221884. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221885. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221886. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221887. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221888. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221889. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221890. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221891. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221892. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221893. #endif
  221894. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221895. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221896. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221897. // compiled on its own).
  221898. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221899. namespace
  221900. {
  221901. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221902. {
  221903. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221904. snd_pcm_hw_params_t* hwParams;
  221905. snd_pcm_hw_params_alloca (&hwParams);
  221906. for (int i = 0; ratesToTry[i] != 0; ++i)
  221907. {
  221908. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221909. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221910. {
  221911. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221912. }
  221913. }
  221914. }
  221915. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221916. {
  221917. snd_pcm_hw_params_t *params;
  221918. snd_pcm_hw_params_alloca (&params);
  221919. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221920. {
  221921. snd_pcm_hw_params_get_channels_min (params, minChans);
  221922. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221923. }
  221924. }
  221925. void getDeviceProperties (const String& deviceID,
  221926. unsigned int& minChansOut,
  221927. unsigned int& maxChansOut,
  221928. unsigned int& minChansIn,
  221929. unsigned int& maxChansIn,
  221930. Array <int>& rates)
  221931. {
  221932. if (deviceID.isEmpty())
  221933. return;
  221934. snd_ctl_t* handle;
  221935. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221936. {
  221937. snd_pcm_info_t* info;
  221938. snd_pcm_info_alloca (&info);
  221939. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221940. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221941. snd_pcm_info_set_subdevice (info, 0);
  221942. if (snd_ctl_pcm_info (handle, info) >= 0)
  221943. {
  221944. snd_pcm_t* pcmHandle;
  221945. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221946. {
  221947. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221948. getDeviceSampleRates (pcmHandle, rates);
  221949. snd_pcm_close (pcmHandle);
  221950. }
  221951. }
  221952. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221953. if (snd_ctl_pcm_info (handle, info) >= 0)
  221954. {
  221955. snd_pcm_t* pcmHandle;
  221956. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221957. {
  221958. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221959. if (rates.size() == 0)
  221960. getDeviceSampleRates (pcmHandle, rates);
  221961. snd_pcm_close (pcmHandle);
  221962. }
  221963. }
  221964. snd_ctl_close (handle);
  221965. }
  221966. }
  221967. }
  221968. class ALSADevice
  221969. {
  221970. public:
  221971. ALSADevice (const String& deviceID, bool forInput)
  221972. : handle (0),
  221973. bitDepth (16),
  221974. numChannelsRunning (0),
  221975. latency (0),
  221976. isInput (forInput),
  221977. isInterleaved (true)
  221978. {
  221979. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221980. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221981. SND_PCM_ASYNC));
  221982. }
  221983. ~ALSADevice()
  221984. {
  221985. if (handle != 0)
  221986. snd_pcm_close (handle);
  221987. }
  221988. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221989. {
  221990. if (handle == 0)
  221991. return false;
  221992. snd_pcm_hw_params_t* hwParams;
  221993. snd_pcm_hw_params_alloca (&hwParams);
  221994. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221995. return false;
  221996. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221997. isInterleaved = false;
  221998. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221999. isInterleaved = true;
  222000. else
  222001. {
  222002. jassertfalse;
  222003. return false;
  222004. }
  222005. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  222006. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  222007. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  222008. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  222009. SND_PCM_FORMAT_S32_BE, 32,
  222010. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  222011. SND_PCM_FORMAT_S24_3BE, 24,
  222012. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  222013. SND_PCM_FORMAT_S16_BE, 16 };
  222014. bitDepth = 0;
  222015. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  222016. {
  222017. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222018. {
  222019. bitDepth = formatsToTry [i + 1] & 255;
  222020. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  222021. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  222022. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  222023. break;
  222024. }
  222025. }
  222026. if (bitDepth == 0)
  222027. {
  222028. error = "device doesn't support a compatible PCM format";
  222029. DBG ("ALSA error: " + error + "\n");
  222030. return false;
  222031. }
  222032. int dir = 0;
  222033. unsigned int periods = 4;
  222034. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222035. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222036. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222037. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222038. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222039. || failed (snd_pcm_hw_params (handle, hwParams)))
  222040. {
  222041. return false;
  222042. }
  222043. snd_pcm_uframes_t frames = 0;
  222044. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222045. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222046. latency = 0;
  222047. else
  222048. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222049. snd_pcm_sw_params_t* swParams;
  222050. snd_pcm_sw_params_alloca (&swParams);
  222051. snd_pcm_uframes_t boundary;
  222052. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222053. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222054. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222055. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222056. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222057. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222058. || failed (snd_pcm_sw_params (handle, swParams)))
  222059. {
  222060. return false;
  222061. }
  222062. #if 0
  222063. // enable this to dump the config of the devices that get opened
  222064. snd_output_t* out;
  222065. snd_output_stdio_attach (&out, stderr, 0);
  222066. snd_pcm_hw_params_dump (hwParams, out);
  222067. snd_pcm_sw_params_dump (swParams, out);
  222068. #endif
  222069. numChannelsRunning = numChannels;
  222070. return true;
  222071. }
  222072. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222073. {
  222074. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222075. float** const data = outputChannelBuffer.getArrayOfChannels();
  222076. snd_pcm_sframes_t numDone = 0;
  222077. if (isInterleaved)
  222078. {
  222079. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222080. for (int i = 0; i < numChannelsRunning; ++i)
  222081. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222082. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222083. }
  222084. else
  222085. {
  222086. for (int i = 0; i < numChannelsRunning; ++i)
  222087. converter->convertSamples (data[i], data[i], numSamples);
  222088. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222089. }
  222090. if (failed (numDone))
  222091. {
  222092. if (numDone == -EPIPE)
  222093. {
  222094. if (failed (snd_pcm_prepare (handle)))
  222095. return false;
  222096. }
  222097. else if (numDone != -ESTRPIPE)
  222098. return false;
  222099. }
  222100. return true;
  222101. }
  222102. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222103. {
  222104. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222105. float** const data = inputChannelBuffer.getArrayOfChannels();
  222106. if (isInterleaved)
  222107. {
  222108. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222109. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  222110. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222111. if (failed (num))
  222112. {
  222113. if (num == -EPIPE)
  222114. {
  222115. if (failed (snd_pcm_prepare (handle)))
  222116. return false;
  222117. }
  222118. else if (num != -ESTRPIPE)
  222119. return false;
  222120. }
  222121. for (int i = 0; i < numChannelsRunning; ++i)
  222122. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222123. }
  222124. else
  222125. {
  222126. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222127. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222128. return false;
  222129. for (int i = 0; i < numChannelsRunning; ++i)
  222130. converter->convertSamples (data[i], data[i], numSamples);
  222131. }
  222132. return true;
  222133. }
  222134. snd_pcm_t* handle;
  222135. String error;
  222136. int bitDepth, numChannelsRunning, latency;
  222137. private:
  222138. const bool isInput;
  222139. bool isInterleaved;
  222140. MemoryBlock scratch;
  222141. ScopedPointer<AudioData::Converter> converter;
  222142. template <class SampleType>
  222143. struct ConverterHelper
  222144. {
  222145. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222146. {
  222147. if (forInput)
  222148. {
  222149. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222150. if (isLittleEndian)
  222151. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222152. else
  222153. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222154. }
  222155. else
  222156. {
  222157. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222158. if (isLittleEndian)
  222159. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222160. else
  222161. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222162. }
  222163. }
  222164. };
  222165. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222166. {
  222167. switch (bitDepth)
  222168. {
  222169. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222170. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222171. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222172. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222173. default: jassertfalse; break; // unsupported format!
  222174. }
  222175. return 0;
  222176. }
  222177. bool failed (const int errorNum)
  222178. {
  222179. if (errorNum >= 0)
  222180. return false;
  222181. error = snd_strerror (errorNum);
  222182. DBG ("ALSA error: " + error + "\n");
  222183. return true;
  222184. }
  222185. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  222186. };
  222187. class ALSAThread : public Thread
  222188. {
  222189. public:
  222190. ALSAThread (const String& inputId_,
  222191. const String& outputId_)
  222192. : Thread ("Juce ALSA"),
  222193. sampleRate (0),
  222194. bufferSize (0),
  222195. outputLatency (0),
  222196. inputLatency (0),
  222197. callback (0),
  222198. inputId (inputId_),
  222199. outputId (outputId_),
  222200. numCallbacks (0),
  222201. inputChannelBuffer (1, 1),
  222202. outputChannelBuffer (1, 1)
  222203. {
  222204. initialiseRatesAndChannels();
  222205. }
  222206. ~ALSAThread()
  222207. {
  222208. close();
  222209. }
  222210. void open (BigInteger inputChannels,
  222211. BigInteger outputChannels,
  222212. const double sampleRate_,
  222213. const int bufferSize_)
  222214. {
  222215. close();
  222216. error = String::empty;
  222217. sampleRate = sampleRate_;
  222218. bufferSize = bufferSize_;
  222219. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222220. inputChannelBuffer.clear();
  222221. inputChannelDataForCallback.clear();
  222222. currentInputChans.clear();
  222223. if (inputChannels.getHighestBit() >= 0)
  222224. {
  222225. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222226. {
  222227. if (inputChannels[i])
  222228. {
  222229. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222230. currentInputChans.setBit (i);
  222231. }
  222232. }
  222233. }
  222234. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222235. outputChannelBuffer.clear();
  222236. outputChannelDataForCallback.clear();
  222237. currentOutputChans.clear();
  222238. if (outputChannels.getHighestBit() >= 0)
  222239. {
  222240. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222241. {
  222242. if (outputChannels[i])
  222243. {
  222244. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222245. currentOutputChans.setBit (i);
  222246. }
  222247. }
  222248. }
  222249. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222250. {
  222251. outputDevice = new ALSADevice (outputId, false);
  222252. if (outputDevice->error.isNotEmpty())
  222253. {
  222254. error = outputDevice->error;
  222255. outputDevice = 0;
  222256. return;
  222257. }
  222258. currentOutputChans.setRange (0, minChansOut, true);
  222259. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222260. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222261. bufferSize))
  222262. {
  222263. error = outputDevice->error;
  222264. outputDevice = 0;
  222265. return;
  222266. }
  222267. outputLatency = outputDevice->latency;
  222268. }
  222269. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222270. {
  222271. inputDevice = new ALSADevice (inputId, true);
  222272. if (inputDevice->error.isNotEmpty())
  222273. {
  222274. error = inputDevice->error;
  222275. inputDevice = 0;
  222276. return;
  222277. }
  222278. currentInputChans.setRange (0, minChansIn, true);
  222279. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222280. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222281. bufferSize))
  222282. {
  222283. error = inputDevice->error;
  222284. inputDevice = 0;
  222285. return;
  222286. }
  222287. inputLatency = inputDevice->latency;
  222288. }
  222289. if (outputDevice == 0 && inputDevice == 0)
  222290. {
  222291. error = "no channels";
  222292. return;
  222293. }
  222294. if (outputDevice != 0 && inputDevice != 0)
  222295. {
  222296. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222297. }
  222298. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222299. return;
  222300. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222301. return;
  222302. startThread (9);
  222303. int count = 1000;
  222304. while (numCallbacks == 0)
  222305. {
  222306. sleep (5);
  222307. if (--count < 0 || ! isThreadRunning())
  222308. {
  222309. error = "device didn't start";
  222310. break;
  222311. }
  222312. }
  222313. }
  222314. void close()
  222315. {
  222316. stopThread (6000);
  222317. inputDevice = 0;
  222318. outputDevice = 0;
  222319. inputChannelBuffer.setSize (1, 1);
  222320. outputChannelBuffer.setSize (1, 1);
  222321. numCallbacks = 0;
  222322. }
  222323. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222324. {
  222325. const ScopedLock sl (callbackLock);
  222326. callback = newCallback;
  222327. }
  222328. void run()
  222329. {
  222330. while (! threadShouldExit())
  222331. {
  222332. if (inputDevice != 0)
  222333. {
  222334. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222335. {
  222336. DBG ("ALSA: read failure");
  222337. break;
  222338. }
  222339. }
  222340. if (threadShouldExit())
  222341. break;
  222342. {
  222343. const ScopedLock sl (callbackLock);
  222344. ++numCallbacks;
  222345. if (callback != 0)
  222346. {
  222347. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222348. inputChannelDataForCallback.size(),
  222349. outputChannelDataForCallback.getRawDataPointer(),
  222350. outputChannelDataForCallback.size(),
  222351. bufferSize);
  222352. }
  222353. else
  222354. {
  222355. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222356. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222357. }
  222358. }
  222359. if (outputDevice != 0)
  222360. {
  222361. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222362. if (threadShouldExit())
  222363. break;
  222364. failed (snd_pcm_avail_update (outputDevice->handle));
  222365. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222366. {
  222367. DBG ("ALSA: write failure");
  222368. break;
  222369. }
  222370. }
  222371. }
  222372. }
  222373. int getBitDepth() const throw()
  222374. {
  222375. if (outputDevice != 0)
  222376. return outputDevice->bitDepth;
  222377. if (inputDevice != 0)
  222378. return inputDevice->bitDepth;
  222379. return 16;
  222380. }
  222381. String error;
  222382. double sampleRate;
  222383. int bufferSize, outputLatency, inputLatency;
  222384. BigInteger currentInputChans, currentOutputChans;
  222385. Array <int> sampleRates;
  222386. StringArray channelNamesOut, channelNamesIn;
  222387. AudioIODeviceCallback* callback;
  222388. private:
  222389. const String inputId, outputId;
  222390. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222391. int numCallbacks;
  222392. CriticalSection callbackLock;
  222393. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222394. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222395. unsigned int minChansOut, maxChansOut;
  222396. unsigned int minChansIn, maxChansIn;
  222397. bool failed (const int errorNum)
  222398. {
  222399. if (errorNum >= 0)
  222400. return false;
  222401. error = snd_strerror (errorNum);
  222402. DBG ("ALSA error: " + error + "\n");
  222403. return true;
  222404. }
  222405. void initialiseRatesAndChannels()
  222406. {
  222407. sampleRates.clear();
  222408. channelNamesOut.clear();
  222409. channelNamesIn.clear();
  222410. minChansOut = 0;
  222411. maxChansOut = 0;
  222412. minChansIn = 0;
  222413. maxChansIn = 0;
  222414. unsigned int dummy = 0;
  222415. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222416. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222417. unsigned int i;
  222418. for (i = 0; i < maxChansOut; ++i)
  222419. channelNamesOut.add ("channel " + String ((int) i + 1));
  222420. for (i = 0; i < maxChansIn; ++i)
  222421. channelNamesIn.add ("channel " + String ((int) i + 1));
  222422. }
  222423. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  222424. };
  222425. class ALSAAudioIODevice : public AudioIODevice
  222426. {
  222427. public:
  222428. ALSAAudioIODevice (const String& deviceName,
  222429. const String& inputId_,
  222430. const String& outputId_)
  222431. : AudioIODevice (deviceName, "ALSA"),
  222432. inputId (inputId_),
  222433. outputId (outputId_),
  222434. isOpen_ (false),
  222435. isStarted (false),
  222436. internal (inputId_, outputId_)
  222437. {
  222438. }
  222439. ~ALSAAudioIODevice()
  222440. {
  222441. close();
  222442. }
  222443. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222444. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222445. int getNumSampleRates() { return internal.sampleRates.size(); }
  222446. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222447. int getDefaultBufferSize() { return 512; }
  222448. int getNumBufferSizesAvailable() { return 50; }
  222449. int getBufferSizeSamples (int index)
  222450. {
  222451. int n = 16;
  222452. for (int i = 0; i < index; ++i)
  222453. n += n < 64 ? 16
  222454. : (n < 512 ? 32
  222455. : (n < 1024 ? 64
  222456. : (n < 2048 ? 128 : 256)));
  222457. return n;
  222458. }
  222459. const String open (const BigInteger& inputChannels,
  222460. const BigInteger& outputChannels,
  222461. double sampleRate,
  222462. int bufferSizeSamples)
  222463. {
  222464. close();
  222465. if (bufferSizeSamples <= 0)
  222466. bufferSizeSamples = getDefaultBufferSize();
  222467. if (sampleRate <= 0)
  222468. {
  222469. for (int i = 0; i < getNumSampleRates(); ++i)
  222470. {
  222471. if (getSampleRate (i) >= 44100)
  222472. {
  222473. sampleRate = getSampleRate (i);
  222474. break;
  222475. }
  222476. }
  222477. }
  222478. internal.open (inputChannels, outputChannels,
  222479. sampleRate, bufferSizeSamples);
  222480. isOpen_ = internal.error.isEmpty();
  222481. return internal.error;
  222482. }
  222483. void close()
  222484. {
  222485. stop();
  222486. internal.close();
  222487. isOpen_ = false;
  222488. }
  222489. bool isOpen() { return isOpen_; }
  222490. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222491. const String getLastError() { return internal.error; }
  222492. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222493. double getCurrentSampleRate() { return internal.sampleRate; }
  222494. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222495. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222496. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222497. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222498. int getInputLatencyInSamples() { return internal.inputLatency; }
  222499. void start (AudioIODeviceCallback* callback)
  222500. {
  222501. if (! isOpen_)
  222502. callback = 0;
  222503. if (callback != 0)
  222504. callback->audioDeviceAboutToStart (this);
  222505. internal.setCallback (callback);
  222506. isStarted = (callback != 0);
  222507. }
  222508. void stop()
  222509. {
  222510. AudioIODeviceCallback* const oldCallback = internal.callback;
  222511. start (0);
  222512. if (oldCallback != 0)
  222513. oldCallback->audioDeviceStopped();
  222514. }
  222515. String inputId, outputId;
  222516. private:
  222517. bool isOpen_, isStarted;
  222518. ALSAThread internal;
  222519. };
  222520. class ALSAAudioIODeviceType : public AudioIODeviceType
  222521. {
  222522. public:
  222523. ALSAAudioIODeviceType()
  222524. : AudioIODeviceType ("ALSA"),
  222525. hasScanned (false)
  222526. {
  222527. }
  222528. ~ALSAAudioIODeviceType()
  222529. {
  222530. }
  222531. void scanForDevices()
  222532. {
  222533. if (hasScanned)
  222534. return;
  222535. hasScanned = true;
  222536. inputNames.clear();
  222537. inputIds.clear();
  222538. outputNames.clear();
  222539. outputIds.clear();
  222540. /* void** hints = 0;
  222541. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222542. {
  222543. for (void** hint = hints; *hint != 0; ++hint)
  222544. {
  222545. const String name (getHint (*hint, "NAME"));
  222546. if (name.isNotEmpty())
  222547. {
  222548. const String ioid (getHint (*hint, "IOID"));
  222549. String desc (getHint (*hint, "DESC"));
  222550. if (desc.isEmpty())
  222551. desc = name;
  222552. desc = desc.replaceCharacters ("\n\r", " ");
  222553. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222554. if (ioid.isEmpty() || ioid == "Input")
  222555. {
  222556. inputNames.add (desc);
  222557. inputIds.add (name);
  222558. }
  222559. if (ioid.isEmpty() || ioid == "Output")
  222560. {
  222561. outputNames.add (desc);
  222562. outputIds.add (name);
  222563. }
  222564. }
  222565. }
  222566. snd_device_name_free_hint (hints);
  222567. }
  222568. */
  222569. snd_ctl_t* handle = 0;
  222570. snd_ctl_card_info_t* info = 0;
  222571. snd_ctl_card_info_alloca (&info);
  222572. int cardNum = -1;
  222573. while (outputIds.size() + inputIds.size() <= 32)
  222574. {
  222575. snd_card_next (&cardNum);
  222576. if (cardNum < 0)
  222577. break;
  222578. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222579. {
  222580. if (snd_ctl_card_info (handle, info) >= 0)
  222581. {
  222582. String cardId (snd_ctl_card_info_get_id (info));
  222583. if (cardId.removeCharacters ("0123456789").isEmpty())
  222584. cardId = String (cardNum);
  222585. int device = -1;
  222586. for (;;)
  222587. {
  222588. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222589. break;
  222590. String id, name;
  222591. id << "hw:" << cardId << ',' << device;
  222592. bool isInput, isOutput;
  222593. if (testDevice (id, isInput, isOutput))
  222594. {
  222595. name << snd_ctl_card_info_get_name (info);
  222596. if (name.isEmpty())
  222597. name = id;
  222598. if (isInput)
  222599. {
  222600. inputNames.add (name);
  222601. inputIds.add (id);
  222602. }
  222603. if (isOutput)
  222604. {
  222605. outputNames.add (name);
  222606. outputIds.add (id);
  222607. }
  222608. }
  222609. }
  222610. }
  222611. snd_ctl_close (handle);
  222612. }
  222613. }
  222614. inputNames.appendNumbersToDuplicates (false, true);
  222615. outputNames.appendNumbersToDuplicates (false, true);
  222616. }
  222617. const StringArray getDeviceNames (bool wantInputNames) const
  222618. {
  222619. jassert (hasScanned); // need to call scanForDevices() before doing this
  222620. return wantInputNames ? inputNames : outputNames;
  222621. }
  222622. int getDefaultDeviceIndex (bool forInput) const
  222623. {
  222624. jassert (hasScanned); // need to call scanForDevices() before doing this
  222625. return 0;
  222626. }
  222627. bool hasSeparateInputsAndOutputs() const { return true; }
  222628. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222629. {
  222630. jassert (hasScanned); // need to call scanForDevices() before doing this
  222631. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222632. if (d == 0)
  222633. return -1;
  222634. return asInput ? inputIds.indexOf (d->inputId)
  222635. : outputIds.indexOf (d->outputId);
  222636. }
  222637. AudioIODevice* createDevice (const String& outputDeviceName,
  222638. const String& inputDeviceName)
  222639. {
  222640. jassert (hasScanned); // need to call scanForDevices() before doing this
  222641. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222642. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222643. String deviceName (outputIndex >= 0 ? outputDeviceName
  222644. : inputDeviceName);
  222645. if (inputIndex >= 0 || outputIndex >= 0)
  222646. return new ALSAAudioIODevice (deviceName,
  222647. inputIds [inputIndex],
  222648. outputIds [outputIndex]);
  222649. return 0;
  222650. }
  222651. private:
  222652. StringArray inputNames, outputNames, inputIds, outputIds;
  222653. bool hasScanned;
  222654. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222655. {
  222656. unsigned int minChansOut = 0, maxChansOut = 0;
  222657. unsigned int minChansIn = 0, maxChansIn = 0;
  222658. Array <int> rates;
  222659. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222660. DBG ("ALSA device: " + id
  222661. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222662. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222663. + " rates=" + String (rates.size()));
  222664. isInput = maxChansIn > 0;
  222665. isOutput = maxChansOut > 0;
  222666. return (isInput || isOutput) && rates.size() > 0;
  222667. }
  222668. /*static const String getHint (void* hint, const char* type)
  222669. {
  222670. char* const n = snd_device_name_get_hint (hint, type);
  222671. const String s ((const char*) n);
  222672. free (n);
  222673. return s;
  222674. }*/
  222675. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222676. };
  222677. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA()
  222678. {
  222679. return new ALSAAudioIODeviceType();
  222680. }
  222681. #endif
  222682. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222683. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222684. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222685. // compiled on its own).
  222686. #ifdef JUCE_INCLUDED_FILE
  222687. #if JUCE_JACK
  222688. static void* juce_libjack_handle = 0;
  222689. void* juce_load_jack_function (const char* const name)
  222690. {
  222691. if (juce_libjack_handle == 0)
  222692. return 0;
  222693. return dlsym (juce_libjack_handle, name);
  222694. }
  222695. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222696. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222697. return_type fn_name argument_types { \
  222698. static fn_name##_ptr_t fn = 0; \
  222699. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222700. if (fn) return (*fn)arguments; \
  222701. else return 0; \
  222702. }
  222703. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222704. typedef void (*fn_name##_ptr_t)argument_types; \
  222705. void fn_name argument_types { \
  222706. static fn_name##_ptr_t fn = 0; \
  222707. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222708. if (fn) (*fn)arguments; \
  222709. }
  222710. 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));
  222711. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222712. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222713. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222714. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222715. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222716. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222717. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222718. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222719. 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));
  222720. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222721. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222722. 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));
  222723. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222724. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222725. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222726. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222727. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222728. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222729. #if JUCE_DEBUG
  222730. #define JACK_LOGGING_ENABLED 1
  222731. #endif
  222732. #if JACK_LOGGING_ENABLED
  222733. namespace
  222734. {
  222735. void jack_Log (const String& s)
  222736. {
  222737. std::cerr << s << std::endl;
  222738. }
  222739. void dumpJackErrorMessage (const jack_status_t status)
  222740. {
  222741. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222742. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222743. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222744. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222745. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222746. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222747. }
  222748. }
  222749. #else
  222750. #define dumpJackErrorMessage(a) {}
  222751. #define jack_Log(...) {}
  222752. #endif
  222753. #ifndef JUCE_JACK_CLIENT_NAME
  222754. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222755. #endif
  222756. class JackAudioIODevice : public AudioIODevice
  222757. {
  222758. public:
  222759. JackAudioIODevice (const String& deviceName,
  222760. const String& inputId_,
  222761. const String& outputId_)
  222762. : AudioIODevice (deviceName, "JACK"),
  222763. inputId (inputId_),
  222764. outputId (outputId_),
  222765. isOpen_ (false),
  222766. callback (0),
  222767. totalNumberOfInputChannels (0),
  222768. totalNumberOfOutputChannels (0)
  222769. {
  222770. jassert (deviceName.isNotEmpty());
  222771. jack_status_t status;
  222772. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222773. if (client == 0)
  222774. {
  222775. dumpJackErrorMessage (status);
  222776. }
  222777. else
  222778. {
  222779. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222780. // open input ports
  222781. const StringArray inputChannels (getInputChannelNames());
  222782. for (int i = 0; i < inputChannels.size(); i++)
  222783. {
  222784. String inputName;
  222785. inputName << "in_" << ++totalNumberOfInputChannels;
  222786. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222787. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222788. }
  222789. // open output ports
  222790. const StringArray outputChannels (getOutputChannelNames());
  222791. for (int i = 0; i < outputChannels.size (); i++)
  222792. {
  222793. String outputName;
  222794. outputName << "out_" << ++totalNumberOfOutputChannels;
  222795. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222796. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222797. }
  222798. inChans.calloc (totalNumberOfInputChannels + 2);
  222799. outChans.calloc (totalNumberOfOutputChannels + 2);
  222800. }
  222801. }
  222802. ~JackAudioIODevice()
  222803. {
  222804. close();
  222805. if (client != 0)
  222806. {
  222807. JUCE_NAMESPACE::jack_client_close (client);
  222808. client = 0;
  222809. }
  222810. }
  222811. const StringArray getChannelNames (bool forInput) const
  222812. {
  222813. StringArray names;
  222814. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222815. forInput ? JackPortIsInput : JackPortIsOutput);
  222816. if (ports != 0)
  222817. {
  222818. int j = 0;
  222819. while (ports[j] != 0)
  222820. {
  222821. const String portName (ports [j++]);
  222822. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222823. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222824. }
  222825. free (ports);
  222826. }
  222827. return names;
  222828. }
  222829. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222830. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222831. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222832. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222833. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222834. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222835. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222836. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222837. double sampleRate, int bufferSizeSamples)
  222838. {
  222839. if (client == 0)
  222840. {
  222841. lastError = "No JACK client running";
  222842. return lastError;
  222843. }
  222844. lastError = String::empty;
  222845. close();
  222846. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222847. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222848. JUCE_NAMESPACE::jack_activate (client);
  222849. isOpen_ = true;
  222850. if (! inputChannels.isZero())
  222851. {
  222852. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222853. if (ports != 0)
  222854. {
  222855. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222856. for (int i = 0; i < numInputChannels; ++i)
  222857. {
  222858. const String portName (ports[i]);
  222859. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222860. {
  222861. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222862. if (error != 0)
  222863. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222864. }
  222865. }
  222866. free (ports);
  222867. }
  222868. }
  222869. if (! outputChannels.isZero())
  222870. {
  222871. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222872. if (ports != 0)
  222873. {
  222874. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222875. for (int i = 0; i < numOutputChannels; ++i)
  222876. {
  222877. const String portName (ports[i]);
  222878. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222879. {
  222880. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222881. if (error != 0)
  222882. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222883. }
  222884. }
  222885. free (ports);
  222886. }
  222887. }
  222888. return lastError;
  222889. }
  222890. void close()
  222891. {
  222892. stop();
  222893. if (client != 0)
  222894. {
  222895. JUCE_NAMESPACE::jack_deactivate (client);
  222896. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222897. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222898. }
  222899. isOpen_ = false;
  222900. }
  222901. void start (AudioIODeviceCallback* newCallback)
  222902. {
  222903. if (isOpen_ && newCallback != callback)
  222904. {
  222905. if (newCallback != 0)
  222906. newCallback->audioDeviceAboutToStart (this);
  222907. AudioIODeviceCallback* const oldCallback = callback;
  222908. {
  222909. const ScopedLock sl (callbackLock);
  222910. callback = newCallback;
  222911. }
  222912. if (oldCallback != 0)
  222913. oldCallback->audioDeviceStopped();
  222914. }
  222915. }
  222916. void stop()
  222917. {
  222918. start (0);
  222919. }
  222920. bool isOpen() { return isOpen_; }
  222921. bool isPlaying() { return callback != 0; }
  222922. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222923. double getCurrentSampleRate() { return getSampleRate (0); }
  222924. int getCurrentBitDepth() { return 32; }
  222925. const String getLastError() { return lastError; }
  222926. const BigInteger getActiveOutputChannels() const
  222927. {
  222928. BigInteger outputBits;
  222929. for (int i = 0; i < outputPorts.size(); i++)
  222930. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222931. outputBits.setBit (i);
  222932. return outputBits;
  222933. }
  222934. const BigInteger getActiveInputChannels() const
  222935. {
  222936. BigInteger inputBits;
  222937. for (int i = 0; i < inputPorts.size(); i++)
  222938. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222939. inputBits.setBit (i);
  222940. return inputBits;
  222941. }
  222942. int getOutputLatencyInSamples()
  222943. {
  222944. int latency = 0;
  222945. for (int i = 0; i < outputPorts.size(); i++)
  222946. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222947. return latency;
  222948. }
  222949. int getInputLatencyInSamples()
  222950. {
  222951. int latency = 0;
  222952. for (int i = 0; i < inputPorts.size(); i++)
  222953. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222954. return latency;
  222955. }
  222956. String inputId, outputId;
  222957. private:
  222958. void process (const int numSamples)
  222959. {
  222960. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222961. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222962. {
  222963. jack_default_audio_sample_t* in
  222964. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222965. if (in != 0)
  222966. inChans [numActiveInChans++] = (float*) in;
  222967. }
  222968. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222969. {
  222970. jack_default_audio_sample_t* out
  222971. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222972. if (out != 0)
  222973. outChans [numActiveOutChans++] = (float*) out;
  222974. }
  222975. const ScopedLock sl (callbackLock);
  222976. if (callback != 0)
  222977. {
  222978. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222979. outChans, numActiveOutChans, numSamples);
  222980. }
  222981. else
  222982. {
  222983. for (i = 0; i < numActiveOutChans; ++i)
  222984. zeromem (outChans[i], sizeof (float) * numSamples);
  222985. }
  222986. }
  222987. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222988. {
  222989. if (callbackArgument != 0)
  222990. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222991. return 0;
  222992. }
  222993. static void threadInitCallback (void* callbackArgument)
  222994. {
  222995. jack_Log ("JackAudioIODevice::initialise");
  222996. }
  222997. static void shutdownCallback (void* callbackArgument)
  222998. {
  222999. jack_Log ("JackAudioIODevice::shutdown");
  223000. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223001. if (device != 0)
  223002. {
  223003. device->client = 0;
  223004. device->close();
  223005. }
  223006. }
  223007. static void errorCallback (const char* msg)
  223008. {
  223009. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223010. }
  223011. bool isOpen_;
  223012. jack_client_t* client;
  223013. String lastError;
  223014. AudioIODeviceCallback* callback;
  223015. CriticalSection callbackLock;
  223016. HeapBlock <float*> inChans, outChans;
  223017. int totalNumberOfInputChannels;
  223018. int totalNumberOfOutputChannels;
  223019. Array<void*> inputPorts, outputPorts;
  223020. };
  223021. class JackAudioIODeviceType : public AudioIODeviceType
  223022. {
  223023. public:
  223024. JackAudioIODeviceType()
  223025. : AudioIODeviceType ("JACK"),
  223026. hasScanned (false)
  223027. {
  223028. }
  223029. ~JackAudioIODeviceType()
  223030. {
  223031. }
  223032. void scanForDevices()
  223033. {
  223034. hasScanned = true;
  223035. inputNames.clear();
  223036. inputIds.clear();
  223037. outputNames.clear();
  223038. outputIds.clear();
  223039. if (juce_libjack_handle == 0)
  223040. {
  223041. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223042. if (juce_libjack_handle == 0)
  223043. return;
  223044. }
  223045. // open a dummy client
  223046. jack_status_t status;
  223047. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223048. if (client == 0)
  223049. {
  223050. dumpJackErrorMessage (status);
  223051. }
  223052. else
  223053. {
  223054. // scan for output devices
  223055. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223056. if (ports != 0)
  223057. {
  223058. int j = 0;
  223059. while (ports[j] != 0)
  223060. {
  223061. String clientName (ports[j]);
  223062. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223063. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223064. && ! inputNames.contains (clientName))
  223065. {
  223066. inputNames.add (clientName);
  223067. inputIds.add (ports [j]);
  223068. }
  223069. ++j;
  223070. }
  223071. free (ports);
  223072. }
  223073. // scan for input devices
  223074. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223075. if (ports != 0)
  223076. {
  223077. int j = 0;
  223078. while (ports[j] != 0)
  223079. {
  223080. String clientName (ports[j]);
  223081. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223082. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223083. && ! outputNames.contains (clientName))
  223084. {
  223085. outputNames.add (clientName);
  223086. outputIds.add (ports [j]);
  223087. }
  223088. ++j;
  223089. }
  223090. free (ports);
  223091. }
  223092. JUCE_NAMESPACE::jack_client_close (client);
  223093. }
  223094. }
  223095. const StringArray getDeviceNames (bool wantInputNames) const
  223096. {
  223097. jassert (hasScanned); // need to call scanForDevices() before doing this
  223098. return wantInputNames ? inputNames : outputNames;
  223099. }
  223100. int getDefaultDeviceIndex (bool forInput) const
  223101. {
  223102. jassert (hasScanned); // need to call scanForDevices() before doing this
  223103. return 0;
  223104. }
  223105. bool hasSeparateInputsAndOutputs() const { return true; }
  223106. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223107. {
  223108. jassert (hasScanned); // need to call scanForDevices() before doing this
  223109. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223110. if (d == 0)
  223111. return -1;
  223112. return asInput ? inputIds.indexOf (d->inputId)
  223113. : outputIds.indexOf (d->outputId);
  223114. }
  223115. AudioIODevice* createDevice (const String& outputDeviceName,
  223116. const String& inputDeviceName)
  223117. {
  223118. jassert (hasScanned); // need to call scanForDevices() before doing this
  223119. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223120. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223121. if (inputIndex >= 0 || outputIndex >= 0)
  223122. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223123. : inputDeviceName,
  223124. inputIds [inputIndex],
  223125. outputIds [outputIndex]);
  223126. return 0;
  223127. }
  223128. private:
  223129. StringArray inputNames, outputNames, inputIds, outputIds;
  223130. bool hasScanned;
  223131. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  223132. };
  223133. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK()
  223134. {
  223135. return new JackAudioIODeviceType();
  223136. }
  223137. #endif
  223138. #endif
  223139. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223140. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223141. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223142. // compiled on its own).
  223143. #if JUCE_INCLUDED_FILE
  223144. #if JUCE_ALSA
  223145. namespace
  223146. {
  223147. snd_seq_t* iterateMidiDevices (const bool forInput,
  223148. StringArray& deviceNamesFound,
  223149. const int deviceIndexToOpen)
  223150. {
  223151. snd_seq_t* returnedHandle = 0;
  223152. snd_seq_t* seqHandle;
  223153. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223154. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223155. {
  223156. snd_seq_system_info_t* systemInfo;
  223157. snd_seq_client_info_t* clientInfo;
  223158. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223159. {
  223160. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223161. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223162. {
  223163. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223164. while (--numClients >= 0 && returnedHandle == 0)
  223165. {
  223166. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223167. {
  223168. snd_seq_port_info_t* portInfo;
  223169. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223170. {
  223171. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223172. const int client = snd_seq_client_info_get_client (clientInfo);
  223173. snd_seq_port_info_set_client (portInfo, client);
  223174. snd_seq_port_info_set_port (portInfo, -1);
  223175. while (--numPorts >= 0)
  223176. {
  223177. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223178. && (snd_seq_port_info_get_capability (portInfo)
  223179. & (forInput ? SND_SEQ_PORT_CAP_READ
  223180. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223181. {
  223182. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223183. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223184. {
  223185. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223186. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223187. if (sourcePort != -1)
  223188. {
  223189. snd_seq_set_client_name (seqHandle,
  223190. forInput ? "Juce Midi Input"
  223191. : "Juce Midi Output");
  223192. const int portId
  223193. = snd_seq_create_simple_port (seqHandle,
  223194. forInput ? "Juce Midi In Port"
  223195. : "Juce Midi Out Port",
  223196. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223197. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223198. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223199. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223200. returnedHandle = seqHandle;
  223201. }
  223202. }
  223203. }
  223204. }
  223205. snd_seq_port_info_free (portInfo);
  223206. }
  223207. }
  223208. }
  223209. snd_seq_client_info_free (clientInfo);
  223210. }
  223211. snd_seq_system_info_free (systemInfo);
  223212. }
  223213. if (returnedHandle == 0)
  223214. snd_seq_close (seqHandle);
  223215. }
  223216. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223217. return returnedHandle;
  223218. }
  223219. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  223220. {
  223221. snd_seq_t* seqHandle = 0;
  223222. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223223. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223224. {
  223225. snd_seq_set_client_name (seqHandle,
  223226. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223227. const int portId
  223228. = snd_seq_create_simple_port (seqHandle,
  223229. forInput ? "in"
  223230. : "out",
  223231. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223232. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223233. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223234. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223235. if (portId < 0)
  223236. {
  223237. snd_seq_close (seqHandle);
  223238. seqHandle = 0;
  223239. }
  223240. }
  223241. return seqHandle;
  223242. }
  223243. }
  223244. class MidiOutputDevice
  223245. {
  223246. public:
  223247. MidiOutputDevice (MidiOutput* const midiOutput_,
  223248. snd_seq_t* const seqHandle_)
  223249. :
  223250. midiOutput (midiOutput_),
  223251. seqHandle (seqHandle_),
  223252. maxEventSize (16 * 1024)
  223253. {
  223254. jassert (seqHandle != 0 && midiOutput != 0);
  223255. snd_midi_event_new (maxEventSize, &midiParser);
  223256. }
  223257. ~MidiOutputDevice()
  223258. {
  223259. snd_midi_event_free (midiParser);
  223260. snd_seq_close (seqHandle);
  223261. }
  223262. void sendMessageNow (const MidiMessage& message)
  223263. {
  223264. if (message.getRawDataSize() > maxEventSize)
  223265. {
  223266. maxEventSize = message.getRawDataSize();
  223267. snd_midi_event_free (midiParser);
  223268. snd_midi_event_new (maxEventSize, &midiParser);
  223269. }
  223270. snd_seq_event_t event;
  223271. snd_seq_ev_clear (&event);
  223272. snd_midi_event_encode (midiParser,
  223273. message.getRawData(),
  223274. message.getRawDataSize(),
  223275. &event);
  223276. snd_midi_event_reset_encode (midiParser);
  223277. snd_seq_ev_set_source (&event, 0);
  223278. snd_seq_ev_set_subs (&event);
  223279. snd_seq_ev_set_direct (&event);
  223280. snd_seq_event_output (seqHandle, &event);
  223281. snd_seq_drain_output (seqHandle);
  223282. }
  223283. private:
  223284. MidiOutput* const midiOutput;
  223285. snd_seq_t* const seqHandle;
  223286. snd_midi_event_t* midiParser;
  223287. int maxEventSize;
  223288. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  223289. };
  223290. const StringArray MidiOutput::getDevices()
  223291. {
  223292. StringArray devices;
  223293. iterateMidiDevices (false, devices, -1);
  223294. return devices;
  223295. }
  223296. int MidiOutput::getDefaultDeviceIndex()
  223297. {
  223298. return 0;
  223299. }
  223300. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223301. {
  223302. MidiOutput* newDevice = 0;
  223303. StringArray devices;
  223304. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223305. if (handle != 0)
  223306. {
  223307. newDevice = new MidiOutput();
  223308. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223309. }
  223310. return newDevice;
  223311. }
  223312. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223313. {
  223314. MidiOutput* newDevice = 0;
  223315. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223316. if (handle != 0)
  223317. {
  223318. newDevice = new MidiOutput();
  223319. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223320. }
  223321. return newDevice;
  223322. }
  223323. MidiOutput::~MidiOutput()
  223324. {
  223325. delete static_cast <MidiOutputDevice*> (internal);
  223326. }
  223327. void MidiOutput::reset()
  223328. {
  223329. }
  223330. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223331. {
  223332. return false;
  223333. }
  223334. void MidiOutput::setVolume (float leftVol, float rightVol)
  223335. {
  223336. }
  223337. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223338. {
  223339. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223340. }
  223341. class MidiInputThread : public Thread
  223342. {
  223343. public:
  223344. MidiInputThread (MidiInput* const midiInput_,
  223345. snd_seq_t* const seqHandle_,
  223346. MidiInputCallback* const callback_)
  223347. : Thread ("Juce MIDI Input"),
  223348. midiInput (midiInput_),
  223349. seqHandle (seqHandle_),
  223350. callback (callback_)
  223351. {
  223352. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223353. }
  223354. ~MidiInputThread()
  223355. {
  223356. snd_seq_close (seqHandle);
  223357. }
  223358. void run()
  223359. {
  223360. const int maxEventSize = 16 * 1024;
  223361. snd_midi_event_t* midiParser;
  223362. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223363. {
  223364. HeapBlock <uint8> buffer (maxEventSize);
  223365. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223366. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223367. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223368. while (! threadShouldExit())
  223369. {
  223370. if (poll (pfd, numPfds, 500) > 0)
  223371. {
  223372. snd_seq_event_t* inputEvent = 0;
  223373. snd_seq_nonblock (seqHandle, 1);
  223374. do
  223375. {
  223376. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223377. {
  223378. // xxx what about SYSEXes that are too big for the buffer?
  223379. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223380. snd_midi_event_reset_decode (midiParser);
  223381. if (numBytes > 0)
  223382. {
  223383. const MidiMessage message ((const uint8*) buffer,
  223384. numBytes,
  223385. Time::getMillisecondCounter() * 0.001);
  223386. callback->handleIncomingMidiMessage (midiInput, message);
  223387. }
  223388. snd_seq_free_event (inputEvent);
  223389. }
  223390. }
  223391. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223392. snd_seq_free_event (inputEvent);
  223393. }
  223394. }
  223395. snd_midi_event_free (midiParser);
  223396. }
  223397. };
  223398. private:
  223399. MidiInput* const midiInput;
  223400. snd_seq_t* const seqHandle;
  223401. MidiInputCallback* const callback;
  223402. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  223403. };
  223404. MidiInput::MidiInput (const String& name_)
  223405. : name (name_),
  223406. internal (0)
  223407. {
  223408. }
  223409. MidiInput::~MidiInput()
  223410. {
  223411. stop();
  223412. delete static_cast <MidiInputThread*> (internal);
  223413. }
  223414. void MidiInput::start()
  223415. {
  223416. static_cast <MidiInputThread*> (internal)->startThread();
  223417. }
  223418. void MidiInput::stop()
  223419. {
  223420. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223421. }
  223422. int MidiInput::getDefaultDeviceIndex()
  223423. {
  223424. return 0;
  223425. }
  223426. const StringArray MidiInput::getDevices()
  223427. {
  223428. StringArray devices;
  223429. iterateMidiDevices (true, devices, -1);
  223430. return devices;
  223431. }
  223432. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223433. {
  223434. MidiInput* newDevice = 0;
  223435. StringArray devices;
  223436. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223437. if (handle != 0)
  223438. {
  223439. newDevice = new MidiInput (devices [deviceIndex]);
  223440. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223441. }
  223442. return newDevice;
  223443. }
  223444. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223445. {
  223446. MidiInput* newDevice = 0;
  223447. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223448. if (handle != 0)
  223449. {
  223450. newDevice = new MidiInput (deviceName);
  223451. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223452. }
  223453. return newDevice;
  223454. }
  223455. #else
  223456. // (These are just stub functions if ALSA is unavailable...)
  223457. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223458. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223459. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223460. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223461. MidiOutput::~MidiOutput() {}
  223462. void MidiOutput::reset() {}
  223463. bool MidiOutput::getVolume (float&, float&) { return false; }
  223464. void MidiOutput::setVolume (float, float) {}
  223465. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223466. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223467. MidiInput::~MidiInput() {}
  223468. void MidiInput::start() {}
  223469. void MidiInput::stop() {}
  223470. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223471. const StringArray MidiInput::getDevices() { return StringArray(); }
  223472. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223473. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223474. #endif
  223475. #endif
  223476. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223477. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223478. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223479. // compiled on its own).
  223480. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223481. AudioCDReader::AudioCDReader()
  223482. : AudioFormatReader (0, "CD Audio")
  223483. {
  223484. }
  223485. const StringArray AudioCDReader::getAvailableCDNames()
  223486. {
  223487. StringArray names;
  223488. return names;
  223489. }
  223490. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223491. {
  223492. return 0;
  223493. }
  223494. AudioCDReader::~AudioCDReader()
  223495. {
  223496. }
  223497. void AudioCDReader::refreshTrackLengths()
  223498. {
  223499. }
  223500. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223501. int64 startSampleInFile, int numSamples)
  223502. {
  223503. return false;
  223504. }
  223505. bool AudioCDReader::isCDStillPresent() const
  223506. {
  223507. return false;
  223508. }
  223509. bool AudioCDReader::isTrackAudio (int trackNum) const
  223510. {
  223511. return false;
  223512. }
  223513. void AudioCDReader::enableIndexScanning (bool b)
  223514. {
  223515. }
  223516. int AudioCDReader::getLastIndex() const
  223517. {
  223518. return 0;
  223519. }
  223520. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223521. {
  223522. return Array<int>();
  223523. }
  223524. #endif
  223525. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223526. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223527. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223528. // compiled on its own).
  223529. #if JUCE_INCLUDED_FILE
  223530. void FileChooser::showPlatformDialog (Array<File>& results,
  223531. const String& title,
  223532. const File& file,
  223533. const String& filters,
  223534. bool isDirectory,
  223535. bool selectsFiles,
  223536. bool isSave,
  223537. bool warnAboutOverwritingExistingFiles,
  223538. bool selectMultipleFiles,
  223539. FilePreviewComponent* previewComponent)
  223540. {
  223541. const String separator (":");
  223542. String command ("zenity --file-selection");
  223543. if (title.isNotEmpty())
  223544. command << " --title=\"" << title << "\"";
  223545. if (file != File::nonexistent)
  223546. command << " --filename=\"" << file.getFullPathName () << "\"";
  223547. if (isDirectory)
  223548. command << " --directory";
  223549. if (isSave)
  223550. command << " --save";
  223551. if (selectMultipleFiles)
  223552. command << " --multiple --separator=\"" << separator << "\"";
  223553. command << " 2>&1";
  223554. MemoryOutputStream result;
  223555. int status = -1;
  223556. FILE* stream = popen (command.toUTF8(), "r");
  223557. if (stream != 0)
  223558. {
  223559. for (;;)
  223560. {
  223561. char buffer [1024];
  223562. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223563. if (bytesRead <= 0)
  223564. break;
  223565. result.write (buffer, bytesRead);
  223566. }
  223567. status = pclose (stream);
  223568. }
  223569. if (status == 0)
  223570. {
  223571. StringArray tokens;
  223572. if (selectMultipleFiles)
  223573. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223574. else
  223575. tokens.add (result.toUTF8());
  223576. for (int i = 0; i < tokens.size(); i++)
  223577. results.add (File (tokens[i]));
  223578. return;
  223579. }
  223580. //xxx ain't got one!
  223581. jassertfalse;
  223582. }
  223583. #endif
  223584. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223585. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223586. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223587. // compiled on its own).
  223588. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223589. /*
  223590. Sorry.. This class isn't implemented on Linux!
  223591. */
  223592. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223593. : browser (0),
  223594. blankPageShown (false),
  223595. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223596. {
  223597. setOpaque (true);
  223598. }
  223599. WebBrowserComponent::~WebBrowserComponent()
  223600. {
  223601. }
  223602. void WebBrowserComponent::goToURL (const String& url,
  223603. const StringArray* headers,
  223604. const MemoryBlock* postData)
  223605. {
  223606. lastURL = url;
  223607. lastHeaders.clear();
  223608. if (headers != 0)
  223609. lastHeaders = *headers;
  223610. lastPostData.setSize (0);
  223611. if (postData != 0)
  223612. lastPostData = *postData;
  223613. blankPageShown = false;
  223614. }
  223615. void WebBrowserComponent::stop()
  223616. {
  223617. }
  223618. void WebBrowserComponent::goBack()
  223619. {
  223620. lastURL = String::empty;
  223621. blankPageShown = false;
  223622. }
  223623. void WebBrowserComponent::goForward()
  223624. {
  223625. lastURL = String::empty;
  223626. }
  223627. void WebBrowserComponent::refresh()
  223628. {
  223629. }
  223630. void WebBrowserComponent::paint (Graphics& g)
  223631. {
  223632. g.fillAll (Colours::white);
  223633. }
  223634. void WebBrowserComponent::checkWindowAssociation()
  223635. {
  223636. }
  223637. void WebBrowserComponent::reloadLastURL()
  223638. {
  223639. if (lastURL.isNotEmpty())
  223640. {
  223641. goToURL (lastURL, &lastHeaders, &lastPostData);
  223642. lastURL = String::empty;
  223643. }
  223644. }
  223645. void WebBrowserComponent::parentHierarchyChanged()
  223646. {
  223647. checkWindowAssociation();
  223648. }
  223649. void WebBrowserComponent::resized()
  223650. {
  223651. }
  223652. void WebBrowserComponent::visibilityChanged()
  223653. {
  223654. checkWindowAssociation();
  223655. }
  223656. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223657. {
  223658. return true;
  223659. }
  223660. #endif
  223661. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223662. #endif
  223663. END_JUCE_NAMESPACE
  223664. #endif
  223665. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223666. #elif JUCE_MAC || JUCE_IOS
  223667. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223668. /*
  223669. This file wraps together all the mac-specific code, so that
  223670. we can include all the native headers just once, and compile all our
  223671. platform-specific stuff in one big lump, keeping it out of the way of
  223672. the rest of the codebase.
  223673. */
  223674. #if JUCE_MAC || JUCE_IOS
  223675. #undef JUCE_BUILD_NATIVE
  223676. #define JUCE_BUILD_NATIVE 1
  223677. BEGIN_JUCE_NAMESPACE
  223678. #undef Point
  223679. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223680. namespace
  223681. {
  223682. template <class RectType>
  223683. const Rectangle<int> convertToRectInt (const RectType& r)
  223684. {
  223685. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223686. }
  223687. template <class RectType>
  223688. const Rectangle<float> convertToRectFloat (const RectType& r)
  223689. {
  223690. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223691. }
  223692. template <class RectType>
  223693. CGRect convertToCGRect (const RectType& r)
  223694. {
  223695. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223696. }
  223697. }
  223698. class MessageQueue
  223699. {
  223700. public:
  223701. MessageQueue()
  223702. {
  223703. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
  223704. runLoop = CFRunLoopGetMain();
  223705. #else
  223706. runLoop = CFRunLoopGetCurrent();
  223707. #endif
  223708. CFRunLoopSourceContext sourceContext;
  223709. zerostruct (sourceContext);
  223710. sourceContext.info = this;
  223711. sourceContext.perform = runLoopSourceCallback;
  223712. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223713. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223714. }
  223715. ~MessageQueue()
  223716. {
  223717. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223718. CFRunLoopSourceInvalidate (runLoopSource);
  223719. CFRelease (runLoopSource);
  223720. }
  223721. void post (Message* const message)
  223722. {
  223723. messages.add (message);
  223724. CFRunLoopSourceSignal (runLoopSource);
  223725. CFRunLoopWakeUp (runLoop);
  223726. }
  223727. private:
  223728. ReferenceCountedArray <Message, CriticalSection> messages;
  223729. CriticalSection lock;
  223730. CFRunLoopRef runLoop;
  223731. CFRunLoopSourceRef runLoopSource;
  223732. bool deliverNextMessage()
  223733. {
  223734. const Message::Ptr nextMessage (messages.removeAndReturn (0));
  223735. if (nextMessage == 0)
  223736. return false;
  223737. const ScopedAutoReleasePool pool;
  223738. MessageManager::getInstance()->deliverMessage (nextMessage);
  223739. return true;
  223740. }
  223741. void runLoopCallback()
  223742. {
  223743. for (int i = 4; --i >= 0;)
  223744. if (! deliverNextMessage())
  223745. return;
  223746. CFRunLoopSourceSignal (runLoopSource);
  223747. CFRunLoopWakeUp (runLoop);
  223748. }
  223749. static void runLoopSourceCallback (void* info)
  223750. {
  223751. static_cast <MessageQueue*> (info)->runLoopCallback();
  223752. }
  223753. };
  223754. #endif
  223755. #define JUCE_INCLUDED_FILE 1
  223756. // Now include the actual code files..
  223757. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223758. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223759. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223760. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223761. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223762. actually calling into a similarly named class in the other module's address space.
  223763. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223764. have unique names, and should avoid this problem.
  223765. If you're using the amalgamated version, you can just set this macro to something unique before
  223766. you include juce_amalgamated.cpp.
  223767. */
  223768. #ifndef JUCE_ObjCExtraSuffix
  223769. #define JUCE_ObjCExtraSuffix 3
  223770. #endif
  223771. #ifndef DOXYGEN
  223772. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223773. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223774. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223775. #endif
  223776. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223777. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223778. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223779. // compiled on its own).
  223780. #if JUCE_INCLUDED_FILE
  223781. namespace
  223782. {
  223783. const String nsStringToJuce (NSString* s)
  223784. {
  223785. return String::fromUTF8 ([s UTF8String]);
  223786. }
  223787. NSString* juceStringToNS (const String& s)
  223788. {
  223789. return [NSString stringWithUTF8String: s.toUTF8()];
  223790. }
  223791. const String convertUTF16ToString (const UniChar* utf16)
  223792. {
  223793. String s;
  223794. while (*utf16 != 0)
  223795. s += (juce_wchar) *utf16++;
  223796. return s;
  223797. }
  223798. }
  223799. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223800. {
  223801. String result;
  223802. if (cfString != 0)
  223803. {
  223804. CFRange range = { 0, CFStringGetLength (cfString) };
  223805. HeapBlock <UniChar> u (range.length + 1);
  223806. CFStringGetCharacters (cfString, range, u);
  223807. u[range.length] = 0;
  223808. result = convertUTF16ToString (u);
  223809. }
  223810. return result;
  223811. }
  223812. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223813. {
  223814. const int len = s.length();
  223815. HeapBlock <UniChar> temp (len + 2);
  223816. for (int i = 0; i <= len; ++i)
  223817. temp[i] = s[i];
  223818. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223819. }
  223820. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223821. {
  223822. #if JUCE_IOS
  223823. const ScopedAutoReleasePool pool;
  223824. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223825. #else
  223826. UnicodeMapping map;
  223827. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223828. kUnicodeNoSubset,
  223829. kTextEncodingDefaultFormat);
  223830. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223831. kUnicodeCanonicalCompVariant,
  223832. kTextEncodingDefaultFormat);
  223833. map.mappingVersion = kUnicodeUseLatestMapping;
  223834. UnicodeToTextInfo conversionInfo = 0;
  223835. String result;
  223836. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223837. {
  223838. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (s.getCharPointer());
  223839. HeapBlock <char> tempOut;
  223840. tempOut.calloc (bytesNeeded + 4);
  223841. ByteCount bytesRead = 0;
  223842. ByteCount outputBufferSize = 0;
  223843. if (ConvertFromUnicodeToText (conversionInfo,
  223844. bytesNeeded, (ConstUniCharArrayPtr) s.toUTF16().getAddress(),
  223845. kUnicodeDefaultDirectionMask,
  223846. 0, 0, 0, 0,
  223847. bytesNeeded, &bytesRead,
  223848. &outputBufferSize, tempOut) == noErr)
  223849. {
  223850. result = String (CharPointer_UTF16 ((CharPointer_UTF16::CharType*) tempOut.getData()));
  223851. }
  223852. DisposeUnicodeToTextInfo (&conversionInfo);
  223853. }
  223854. return result;
  223855. #endif
  223856. }
  223857. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223858. void SystemClipboard::copyTextToClipboard (const String& text)
  223859. {
  223860. #if JUCE_IOS
  223861. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223862. forPasteboardType: @"public.text"];
  223863. #else
  223864. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223865. owner: nil];
  223866. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223867. forType: NSStringPboardType];
  223868. #endif
  223869. }
  223870. const String SystemClipboard::getTextFromClipboard()
  223871. {
  223872. #if JUCE_IOS
  223873. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223874. #else
  223875. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223876. #endif
  223877. return text == 0 ? String::empty
  223878. : nsStringToJuce (text);
  223879. }
  223880. #endif
  223881. #endif
  223882. /*** End of inlined file: juce_mac_Strings.mm ***/
  223883. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223884. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223885. // compiled on its own).
  223886. #if JUCE_INCLUDED_FILE
  223887. namespace SystemStatsHelpers
  223888. {
  223889. static int64 highResTimerFrequency = 0;
  223890. static double highResTimerToMillisecRatio = 0;
  223891. #if JUCE_INTEL
  223892. void doCPUID (uint32& a, uint32& b, uint32& c, uint32& d, uint32 type)
  223893. {
  223894. uint32 la = a, lb = b, lc = c, ld = d;
  223895. asm ("mov %%ebx, %%esi \n\t"
  223896. "cpuid \n\t"
  223897. "xchg %%esi, %%ebx"
  223898. : "=a" (la), "=S" (lb), "=c" (lc), "=d" (ld) : "a" (type)
  223899. #if JUCE_64BIT
  223900. , "b" (lb), "c" (lc), "d" (ld)
  223901. #endif
  223902. );
  223903. a = la; b = lb; c = lc; d = ld;
  223904. }
  223905. #endif
  223906. }
  223907. void SystemStats::initialiseStats()
  223908. {
  223909. using namespace SystemStatsHelpers;
  223910. static bool initialised = false;
  223911. if (! initialised)
  223912. {
  223913. initialised = true;
  223914. #if JUCE_MAC
  223915. [NSApplication sharedApplication];
  223916. #endif
  223917. #if JUCE_INTEL
  223918. uint32 familyModel = 0, extFeatures = 0, features = 0, dummy = 0;
  223919. doCPUID (familyModel, extFeatures, dummy, features, 1);
  223920. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223921. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223922. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223923. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223924. #else
  223925. cpuFlags.hasMMX = false;
  223926. cpuFlags.hasSSE = false;
  223927. cpuFlags.hasSSE2 = false;
  223928. cpuFlags.has3DNow = false;
  223929. #endif
  223930. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223931. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223932. #else
  223933. cpuFlags.numCpus = (int) MPProcessors();
  223934. #endif
  223935. mach_timebase_info_data_t timebase;
  223936. (void) mach_timebase_info (&timebase);
  223937. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223938. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223939. String s (SystemStats::getJUCEVersion());
  223940. rlimit lim;
  223941. getrlimit (RLIMIT_NOFILE, &lim);
  223942. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223943. setrlimit (RLIMIT_NOFILE, &lim);
  223944. }
  223945. }
  223946. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223947. {
  223948. return MacOSX;
  223949. }
  223950. const String SystemStats::getOperatingSystemName()
  223951. {
  223952. return "Mac OS X";
  223953. }
  223954. #if ! JUCE_IOS
  223955. int PlatformUtilities::getOSXMinorVersionNumber()
  223956. {
  223957. SInt32 versionMinor = 0;
  223958. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223959. (void) err;
  223960. jassert (err == noErr);
  223961. return (int) versionMinor;
  223962. }
  223963. #endif
  223964. bool SystemStats::isOperatingSystem64Bit()
  223965. {
  223966. #if JUCE_IOS
  223967. return false;
  223968. #elif JUCE_64BIT
  223969. return true;
  223970. #else
  223971. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223972. #endif
  223973. }
  223974. int SystemStats::getMemorySizeInMegabytes()
  223975. {
  223976. uint64 mem = 0;
  223977. size_t memSize = sizeof (mem);
  223978. int mib[] = { CTL_HW, HW_MEMSIZE };
  223979. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223980. return (int) (mem / (1024 * 1024));
  223981. }
  223982. const String SystemStats::getCpuVendor()
  223983. {
  223984. #if JUCE_INTEL
  223985. uint32 dummy = 0;
  223986. uint32 vendor[4];
  223987. zerostruct (vendor);
  223988. SystemStatsHelpers::doCPUID (dummy, vendor[0], vendor[2], vendor[1], 0);
  223989. return String (reinterpret_cast <const char*> (vendor), 12);
  223990. #else
  223991. return String::empty;
  223992. #endif
  223993. }
  223994. int SystemStats::getCpuSpeedInMegaherz()
  223995. {
  223996. uint64 speedHz = 0;
  223997. size_t speedSize = sizeof (speedHz);
  223998. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223999. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224000. #if JUCE_BIG_ENDIAN
  224001. if (speedSize == 4)
  224002. speedHz >>= 32;
  224003. #endif
  224004. return (int) (speedHz / 1000000);
  224005. }
  224006. const String SystemStats::getLogonName()
  224007. {
  224008. return nsStringToJuce (NSUserName());
  224009. }
  224010. const String SystemStats::getFullUserName()
  224011. {
  224012. return nsStringToJuce (NSFullUserName());
  224013. }
  224014. uint32 juce_millisecondsSinceStartup() throw()
  224015. {
  224016. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224017. }
  224018. double Time::getMillisecondCounterHiRes() throw()
  224019. {
  224020. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224021. }
  224022. int64 Time::getHighResolutionTicks() throw()
  224023. {
  224024. return (int64) mach_absolute_time();
  224025. }
  224026. int64 Time::getHighResolutionTicksPerSecond() throw()
  224027. {
  224028. return SystemStatsHelpers::highResTimerFrequency;
  224029. }
  224030. bool Time::setSystemTimeToThisTime() const
  224031. {
  224032. jassertfalse;
  224033. return false;
  224034. }
  224035. int SystemStats::getPageSize()
  224036. {
  224037. return (int) NSPageSize();
  224038. }
  224039. void PlatformUtilities::fpuReset()
  224040. {
  224041. }
  224042. #endif
  224043. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224044. /*** Start of inlined file: juce_mac_Network.mm ***/
  224045. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224046. // compiled on its own).
  224047. #if JUCE_INCLUDED_FILE
  224048. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  224049. {
  224050. ifaddrs* addrs = 0;
  224051. if (getifaddrs (&addrs) == 0)
  224052. {
  224053. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  224054. {
  224055. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224056. if (sto->ss_family == AF_LINK)
  224057. {
  224058. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224059. #ifndef IFT_ETHER
  224060. #define IFT_ETHER 6
  224061. #endif
  224062. if (sadd->sdl_type == IFT_ETHER)
  224063. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  224064. }
  224065. }
  224066. freeifaddrs (addrs);
  224067. }
  224068. }
  224069. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224070. const String& emailSubject,
  224071. const String& bodyText,
  224072. const StringArray& filesToAttach)
  224073. {
  224074. #if JUCE_IOS
  224075. //xxx probably need to use MFMailComposeViewController
  224076. jassertfalse;
  224077. return false;
  224078. #else
  224079. const ScopedAutoReleasePool pool;
  224080. String script;
  224081. script << "tell application \"Mail\"\r\n"
  224082. "set newMessage to make new outgoing message with properties {subject:\""
  224083. << emailSubject.replace ("\"", "\\\"")
  224084. << "\", content:\""
  224085. << bodyText.replace ("\"", "\\\"")
  224086. << "\" & return & return}\r\n"
  224087. "tell newMessage\r\n"
  224088. "set visible to true\r\n"
  224089. "set sender to \"sdfsdfsdfewf\"\r\n"
  224090. "make new to recipient at end of to recipients with properties {address:\""
  224091. << targetEmailAddress
  224092. << "\"}\r\n";
  224093. for (int i = 0; i < filesToAttach.size(); ++i)
  224094. {
  224095. script << "tell content\r\n"
  224096. "make new attachment with properties {file name:\""
  224097. << filesToAttach[i].replace ("\"", "\\\"")
  224098. << "\"} at after the last paragraph\r\n"
  224099. "end tell\r\n";
  224100. }
  224101. script << "end tell\r\n"
  224102. "end tell\r\n";
  224103. NSAppleScript* s = [[NSAppleScript alloc]
  224104. initWithSource: juceStringToNS (script)];
  224105. NSDictionary* error = 0;
  224106. const bool ok = [s executeAndReturnError: &error] != nil;
  224107. [s release];
  224108. return ok;
  224109. #endif
  224110. }
  224111. END_JUCE_NAMESPACE
  224112. using namespace JUCE_NAMESPACE;
  224113. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224114. @interface JuceURLConnection : NSObject
  224115. {
  224116. @public
  224117. NSURLRequest* request;
  224118. NSURLConnection* connection;
  224119. NSMutableData* data;
  224120. Thread* runLoopThread;
  224121. bool initialised, hasFailed, hasFinished;
  224122. int position;
  224123. int64 contentLength;
  224124. NSDictionary* headers;
  224125. NSLock* dataLock;
  224126. }
  224127. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224128. - (void) dealloc;
  224129. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224130. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224131. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224132. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224133. - (BOOL) isOpen;
  224134. - (int) read: (char*) dest numBytes: (int) num;
  224135. - (int) readPosition;
  224136. - (void) stop;
  224137. - (void) createConnection;
  224138. @end
  224139. class JuceURLConnectionMessageThread : public Thread
  224140. {
  224141. public:
  224142. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224143. : Thread ("http connection"),
  224144. owner (owner_)
  224145. {
  224146. }
  224147. ~JuceURLConnectionMessageThread()
  224148. {
  224149. stopThread (10000);
  224150. }
  224151. void run()
  224152. {
  224153. [owner createConnection];
  224154. while (! threadShouldExit())
  224155. {
  224156. const ScopedAutoReleasePool pool;
  224157. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224158. }
  224159. }
  224160. private:
  224161. JuceURLConnection* owner;
  224162. };
  224163. @implementation JuceURLConnection
  224164. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224165. withCallback: (URL::OpenStreamProgressCallback*) callback
  224166. withContext: (void*) context;
  224167. {
  224168. [super init];
  224169. request = req;
  224170. [request retain];
  224171. data = [[NSMutableData data] retain];
  224172. dataLock = [[NSLock alloc] init];
  224173. connection = 0;
  224174. initialised = false;
  224175. hasFailed = false;
  224176. hasFinished = false;
  224177. contentLength = -1;
  224178. headers = 0;
  224179. runLoopThread = new JuceURLConnectionMessageThread (self);
  224180. runLoopThread->startThread();
  224181. while (runLoopThread->isThreadRunning() && ! initialised)
  224182. {
  224183. if (callback != 0)
  224184. callback (context, -1, (int) [[request HTTPBody] length]);
  224185. Thread::sleep (1);
  224186. }
  224187. return self;
  224188. }
  224189. - (void) dealloc
  224190. {
  224191. [self stop];
  224192. deleteAndZero (runLoopThread);
  224193. [connection release];
  224194. [data release];
  224195. [dataLock release];
  224196. [request release];
  224197. [headers release];
  224198. [super dealloc];
  224199. }
  224200. - (void) createConnection
  224201. {
  224202. NSUInteger oldRetainCount = [self retainCount];
  224203. connection = [[NSURLConnection alloc] initWithRequest: request
  224204. delegate: self];
  224205. if (oldRetainCount == [self retainCount])
  224206. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224207. if (connection == nil)
  224208. runLoopThread->signalThreadShouldExit();
  224209. }
  224210. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224211. {
  224212. (void) conn;
  224213. [dataLock lock];
  224214. [data setLength: 0];
  224215. [dataLock unlock];
  224216. initialised = true;
  224217. contentLength = [response expectedContentLength];
  224218. [headers release];
  224219. headers = 0;
  224220. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224221. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224222. }
  224223. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224224. {
  224225. (void) conn;
  224226. DBG (nsStringToJuce ([error description]));
  224227. hasFailed = true;
  224228. initialised = true;
  224229. if (runLoopThread != 0)
  224230. runLoopThread->signalThreadShouldExit();
  224231. }
  224232. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224233. {
  224234. (void) conn;
  224235. [dataLock lock];
  224236. [data appendData: newData];
  224237. [dataLock unlock];
  224238. initialised = true;
  224239. }
  224240. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224241. {
  224242. (void) conn;
  224243. hasFinished = true;
  224244. initialised = true;
  224245. if (runLoopThread != 0)
  224246. runLoopThread->signalThreadShouldExit();
  224247. }
  224248. - (BOOL) isOpen
  224249. {
  224250. return connection != 0 && ! hasFailed;
  224251. }
  224252. - (int) readPosition
  224253. {
  224254. return position;
  224255. }
  224256. - (int) read: (char*) dest numBytes: (int) numNeeded
  224257. {
  224258. int numDone = 0;
  224259. while (numNeeded > 0)
  224260. {
  224261. int available = jmin (numNeeded, (int) [data length]);
  224262. if (available > 0)
  224263. {
  224264. [dataLock lock];
  224265. [data getBytes: dest length: available];
  224266. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224267. [dataLock unlock];
  224268. numDone += available;
  224269. numNeeded -= available;
  224270. dest += available;
  224271. }
  224272. else
  224273. {
  224274. if (hasFailed || hasFinished)
  224275. break;
  224276. Thread::sleep (1);
  224277. }
  224278. }
  224279. position += numDone;
  224280. return numDone;
  224281. }
  224282. - (void) stop
  224283. {
  224284. [connection cancel];
  224285. if (runLoopThread != 0)
  224286. runLoopThread->stopThread (10000);
  224287. }
  224288. @end
  224289. BEGIN_JUCE_NAMESPACE
  224290. class WebInputStream : public InputStream
  224291. {
  224292. public:
  224293. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  224294. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  224295. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  224296. : connection (nil),
  224297. address (address_), headers (headers_), postData (postData_), position (0),
  224298. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  224299. {
  224300. JUCE_AUTORELEASEPOOL
  224301. connection = createConnection (progressCallback, progressCallbackContext);
  224302. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  224303. {
  224304. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  224305. NSString* key;
  224306. while ((key = [enumerator nextObject]) != nil)
  224307. responseHeaders->set (nsStringToJuce (key),
  224308. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  224309. }
  224310. }
  224311. ~WebInputStream()
  224312. {
  224313. close();
  224314. }
  224315. bool isError() const { return connection == nil; }
  224316. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  224317. bool isExhausted() { return finished; }
  224318. int64 getPosition() { return position; }
  224319. int read (void* buffer, int bytesToRead)
  224320. {
  224321. if (finished || isError())
  224322. {
  224323. return 0;
  224324. }
  224325. else
  224326. {
  224327. JUCE_AUTORELEASEPOOL
  224328. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  224329. position += bytesRead;
  224330. if (bytesRead == 0)
  224331. finished = true;
  224332. return bytesRead;
  224333. }
  224334. }
  224335. bool setPosition (int64 wantedPos)
  224336. {
  224337. if (wantedPos != position)
  224338. {
  224339. finished = false;
  224340. if (wantedPos < position)
  224341. {
  224342. close();
  224343. position = 0;
  224344. connection = createConnection (0, 0);
  224345. }
  224346. skipNextBytes (wantedPos - position);
  224347. }
  224348. return true;
  224349. }
  224350. private:
  224351. JuceURLConnection* connection;
  224352. String address, headers;
  224353. MemoryBlock postData;
  224354. int64 position;
  224355. bool finished;
  224356. const bool isPost;
  224357. const int timeOutMs;
  224358. void close()
  224359. {
  224360. [connection stop];
  224361. [connection release];
  224362. connection = nil;
  224363. }
  224364. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  224365. void* progressCallbackContext)
  224366. {
  224367. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  224368. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224369. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224370. if (req == nil)
  224371. return 0;
  224372. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224373. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224374. StringArray headerLines;
  224375. headerLines.addLines (headers);
  224376. headerLines.removeEmptyStrings (true);
  224377. for (int i = 0; i < headerLines.size(); ++i)
  224378. {
  224379. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224380. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224381. if (key.isNotEmpty() && value.isNotEmpty())
  224382. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224383. }
  224384. if (isPost && postData.getSize() > 0)
  224385. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224386. length: postData.getSize()]];
  224387. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224388. withCallback: progressCallback
  224389. withContext: progressCallbackContext];
  224390. if ([s isOpen])
  224391. return s;
  224392. [s release];
  224393. return 0;
  224394. }
  224395. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  224396. };
  224397. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  224398. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  224399. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  224400. {
  224401. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  224402. progressCallback, progressCallbackContext,
  224403. headers, timeOutMs, responseHeaders));
  224404. return wi->isError() ? 0 : wi.release();
  224405. }
  224406. #endif
  224407. /*** End of inlined file: juce_mac_Network.mm ***/
  224408. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224409. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224410. // compiled on its own).
  224411. #if JUCE_INCLUDED_FILE
  224412. struct NamedPipeInternal
  224413. {
  224414. String pipeInName, pipeOutName;
  224415. int pipeIn, pipeOut;
  224416. bool volatile createdPipe, blocked, stopReadOperation;
  224417. static void signalHandler (int) {}
  224418. };
  224419. void NamedPipe::cancelPendingReads()
  224420. {
  224421. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224422. {
  224423. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224424. intern->stopReadOperation = true;
  224425. char buffer [1] = { 0 };
  224426. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224427. (void) bytesWritten;
  224428. int timeout = 2000;
  224429. while (intern->blocked && --timeout >= 0)
  224430. Thread::sleep (2);
  224431. intern->stopReadOperation = false;
  224432. }
  224433. }
  224434. void NamedPipe::close()
  224435. {
  224436. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224437. if (intern != 0)
  224438. {
  224439. internal = 0;
  224440. if (intern->pipeIn != -1)
  224441. ::close (intern->pipeIn);
  224442. if (intern->pipeOut != -1)
  224443. ::close (intern->pipeOut);
  224444. if (intern->createdPipe)
  224445. {
  224446. unlink (intern->pipeInName.toUTF8());
  224447. unlink (intern->pipeOutName.toUTF8());
  224448. }
  224449. delete intern;
  224450. }
  224451. }
  224452. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224453. {
  224454. close();
  224455. NamedPipeInternal* const intern = new NamedPipeInternal();
  224456. internal = intern;
  224457. intern->createdPipe = createPipe;
  224458. intern->blocked = false;
  224459. intern->stopReadOperation = false;
  224460. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224461. siginterrupt (SIGPIPE, 1);
  224462. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224463. intern->pipeInName = pipePath + "_in";
  224464. intern->pipeOutName = pipePath + "_out";
  224465. intern->pipeIn = -1;
  224466. intern->pipeOut = -1;
  224467. if (createPipe)
  224468. {
  224469. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224470. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224471. {
  224472. delete intern;
  224473. internal = 0;
  224474. return false;
  224475. }
  224476. }
  224477. return true;
  224478. }
  224479. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224480. {
  224481. int bytesRead = -1;
  224482. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224483. if (intern != 0)
  224484. {
  224485. intern->blocked = true;
  224486. if (intern->pipeIn == -1)
  224487. {
  224488. if (intern->createdPipe)
  224489. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224490. else
  224491. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224492. if (intern->pipeIn == -1)
  224493. {
  224494. intern->blocked = false;
  224495. return -1;
  224496. }
  224497. }
  224498. bytesRead = 0;
  224499. char* p = static_cast<char*> (destBuffer);
  224500. while (bytesRead < maxBytesToRead)
  224501. {
  224502. const int bytesThisTime = maxBytesToRead - bytesRead;
  224503. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224504. if (numRead <= 0 || intern->stopReadOperation)
  224505. {
  224506. bytesRead = -1;
  224507. break;
  224508. }
  224509. bytesRead += numRead;
  224510. p += bytesRead;
  224511. }
  224512. intern->blocked = false;
  224513. }
  224514. return bytesRead;
  224515. }
  224516. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224517. {
  224518. int bytesWritten = -1;
  224519. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224520. if (intern != 0)
  224521. {
  224522. if (intern->pipeOut == -1)
  224523. {
  224524. if (intern->createdPipe)
  224525. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224526. else
  224527. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224528. if (intern->pipeOut == -1)
  224529. {
  224530. return -1;
  224531. }
  224532. }
  224533. const char* p = static_cast<const char*> (sourceBuffer);
  224534. bytesWritten = 0;
  224535. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224536. while (bytesWritten < numBytesToWrite
  224537. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224538. {
  224539. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224540. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224541. if (numWritten <= 0)
  224542. {
  224543. bytesWritten = -1;
  224544. break;
  224545. }
  224546. bytesWritten += numWritten;
  224547. p += bytesWritten;
  224548. }
  224549. }
  224550. return bytesWritten;
  224551. }
  224552. #endif
  224553. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224554. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224555. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224556. // compiled on its own).
  224557. #if JUCE_INCLUDED_FILE
  224558. /*
  224559. Note that a lot of methods that you'd expect to find in this file actually
  224560. live in juce_posix_SharedCode.h!
  224561. */
  224562. bool Process::isForegroundProcess()
  224563. {
  224564. #if JUCE_MAC
  224565. return [NSApp isActive];
  224566. #else
  224567. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224568. #endif
  224569. }
  224570. void Process::raisePrivilege()
  224571. {
  224572. jassertfalse;
  224573. }
  224574. void Process::lowerPrivilege()
  224575. {
  224576. jassertfalse;
  224577. }
  224578. void Process::terminate()
  224579. {
  224580. exit (0);
  224581. }
  224582. void Process::setPriority (ProcessPriority)
  224583. {
  224584. // xxx
  224585. }
  224586. #endif
  224587. /*** End of inlined file: juce_mac_Threads.mm ***/
  224588. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224589. /*
  224590. This file contains posix routines that are common to both the Linux and Mac builds.
  224591. It gets included directly in the cpp files for these platforms.
  224592. */
  224593. CriticalSection::CriticalSection() throw()
  224594. {
  224595. pthread_mutexattr_t atts;
  224596. pthread_mutexattr_init (&atts);
  224597. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224598. #if ! JUCE_ANDROID
  224599. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224600. #endif
  224601. pthread_mutex_init (&internal, &atts);
  224602. }
  224603. CriticalSection::~CriticalSection() throw()
  224604. {
  224605. pthread_mutex_destroy (&internal);
  224606. }
  224607. void CriticalSection::enter() const throw()
  224608. {
  224609. pthread_mutex_lock (&internal);
  224610. }
  224611. bool CriticalSection::tryEnter() const throw()
  224612. {
  224613. return pthread_mutex_trylock (&internal) == 0;
  224614. }
  224615. void CriticalSection::exit() const throw()
  224616. {
  224617. pthread_mutex_unlock (&internal);
  224618. }
  224619. class WaitableEventImpl
  224620. {
  224621. public:
  224622. WaitableEventImpl (const bool manualReset_)
  224623. : triggered (false),
  224624. manualReset (manualReset_)
  224625. {
  224626. pthread_cond_init (&condition, 0);
  224627. pthread_mutexattr_t atts;
  224628. pthread_mutexattr_init (&atts);
  224629. #if ! JUCE_ANDROID
  224630. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224631. #endif
  224632. pthread_mutex_init (&mutex, &atts);
  224633. }
  224634. ~WaitableEventImpl()
  224635. {
  224636. pthread_cond_destroy (&condition);
  224637. pthread_mutex_destroy (&mutex);
  224638. }
  224639. bool wait (const int timeOutMillisecs) throw()
  224640. {
  224641. pthread_mutex_lock (&mutex);
  224642. if (! triggered)
  224643. {
  224644. if (timeOutMillisecs < 0)
  224645. {
  224646. do
  224647. {
  224648. pthread_cond_wait (&condition, &mutex);
  224649. }
  224650. while (! triggered);
  224651. }
  224652. else
  224653. {
  224654. struct timeval now;
  224655. gettimeofday (&now, 0);
  224656. struct timespec time;
  224657. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224658. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224659. if (time.tv_nsec >= 1000000000)
  224660. {
  224661. time.tv_nsec -= 1000000000;
  224662. time.tv_sec++;
  224663. }
  224664. do
  224665. {
  224666. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224667. {
  224668. pthread_mutex_unlock (&mutex);
  224669. return false;
  224670. }
  224671. }
  224672. while (! triggered);
  224673. }
  224674. }
  224675. if (! manualReset)
  224676. triggered = false;
  224677. pthread_mutex_unlock (&mutex);
  224678. return true;
  224679. }
  224680. void signal() throw()
  224681. {
  224682. pthread_mutex_lock (&mutex);
  224683. triggered = true;
  224684. pthread_cond_broadcast (&condition);
  224685. pthread_mutex_unlock (&mutex);
  224686. }
  224687. void reset() throw()
  224688. {
  224689. pthread_mutex_lock (&mutex);
  224690. triggered = false;
  224691. pthread_mutex_unlock (&mutex);
  224692. }
  224693. private:
  224694. pthread_cond_t condition;
  224695. pthread_mutex_t mutex;
  224696. bool triggered;
  224697. const bool manualReset;
  224698. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224699. };
  224700. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224701. : internal (new WaitableEventImpl (manualReset))
  224702. {
  224703. }
  224704. WaitableEvent::~WaitableEvent() throw()
  224705. {
  224706. delete static_cast <WaitableEventImpl*> (internal);
  224707. }
  224708. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224709. {
  224710. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224711. }
  224712. void WaitableEvent::signal() const throw()
  224713. {
  224714. static_cast <WaitableEventImpl*> (internal)->signal();
  224715. }
  224716. void WaitableEvent::reset() const throw()
  224717. {
  224718. static_cast <WaitableEventImpl*> (internal)->reset();
  224719. }
  224720. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224721. {
  224722. struct timespec time;
  224723. time.tv_sec = millisecs / 1000;
  224724. time.tv_nsec = (millisecs % 1000) * 1000000;
  224725. nanosleep (&time, 0);
  224726. }
  224727. const juce_wchar File::separator = '/';
  224728. const String File::separatorString ("/");
  224729. const File File::getCurrentWorkingDirectory()
  224730. {
  224731. HeapBlock<char> heapBuffer;
  224732. char localBuffer [1024];
  224733. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224734. int bufferSize = 4096;
  224735. while (cwd == 0 && errno == ERANGE)
  224736. {
  224737. heapBuffer.malloc (bufferSize);
  224738. cwd = getcwd (heapBuffer, bufferSize - 1);
  224739. bufferSize += 1024;
  224740. }
  224741. return File (String::fromUTF8 (cwd));
  224742. }
  224743. bool File::setAsCurrentWorkingDirectory() const
  224744. {
  224745. return chdir (getFullPathName().toUTF8()) == 0;
  224746. }
  224747. namespace
  224748. {
  224749. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224750. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224751. #else
  224752. typedef struct stat juce_statStruct;
  224753. #endif
  224754. bool juce_stat (const String& fileName, juce_statStruct& info)
  224755. {
  224756. return fileName.isNotEmpty()
  224757. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224758. && (stat64 (fileName.toUTF8(), &info) == 0);
  224759. #else
  224760. && (stat (fileName.toUTF8(), &info) == 0);
  224761. #endif
  224762. }
  224763. // if this file doesn't exist, find a parent of it that does..
  224764. bool juce_doStatFS (File f, struct statfs& result)
  224765. {
  224766. for (int i = 5; --i >= 0;)
  224767. {
  224768. if (f.exists())
  224769. break;
  224770. f = f.getParentDirectory();
  224771. }
  224772. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224773. }
  224774. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  224775. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224776. {
  224777. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224778. {
  224779. juce_statStruct info;
  224780. const bool statOk = juce_stat (path, info);
  224781. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224782. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224783. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  224784. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  224785. }
  224786. if (isReadOnly != 0)
  224787. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224788. }
  224789. }
  224790. bool File::isDirectory() const
  224791. {
  224792. juce_statStruct info;
  224793. return fullPath.isEmpty()
  224794. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224795. }
  224796. bool File::exists() const
  224797. {
  224798. juce_statStruct info;
  224799. return fullPath.isNotEmpty()
  224800. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224801. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224802. #else
  224803. && (lstat (fullPath.toUTF8(), &info) == 0);
  224804. #endif
  224805. }
  224806. bool File::existsAsFile() const
  224807. {
  224808. return exists() && ! isDirectory();
  224809. }
  224810. int64 File::getSize() const
  224811. {
  224812. juce_statStruct info;
  224813. return juce_stat (fullPath, info) ? info.st_size : 0;
  224814. }
  224815. bool File::hasWriteAccess() const
  224816. {
  224817. if (exists())
  224818. return access (fullPath.toUTF8(), W_OK) == 0;
  224819. if ((! isDirectory()) && fullPath.containsChar (separator))
  224820. return getParentDirectory().hasWriteAccess();
  224821. return false;
  224822. }
  224823. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224824. {
  224825. juce_statStruct info;
  224826. if (! juce_stat (fullPath, info))
  224827. return false;
  224828. info.st_mode &= 0777; // Just permissions
  224829. if (shouldBeReadOnly)
  224830. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224831. else
  224832. // Give everybody write permission?
  224833. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224834. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224835. }
  224836. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224837. {
  224838. modificationTime = 0;
  224839. accessTime = 0;
  224840. creationTime = 0;
  224841. juce_statStruct info;
  224842. if (juce_stat (fullPath, info))
  224843. {
  224844. modificationTime = (int64) info.st_mtime * 1000;
  224845. accessTime = (int64) info.st_atime * 1000;
  224846. creationTime = (int64) info.st_ctime * 1000;
  224847. }
  224848. }
  224849. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224850. {
  224851. juce_statStruct info;
  224852. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  224853. {
  224854. struct utimbuf times;
  224855. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  224856. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  224857. return utime (fullPath.toUTF8(), &times) == 0;
  224858. }
  224859. return false;
  224860. }
  224861. bool File::deleteFile() const
  224862. {
  224863. if (! exists())
  224864. return true;
  224865. if (isDirectory())
  224866. return rmdir (fullPath.toUTF8()) == 0;
  224867. return remove (fullPath.toUTF8()) == 0;
  224868. }
  224869. bool File::moveInternal (const File& dest) const
  224870. {
  224871. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224872. return true;
  224873. if (hasWriteAccess() && copyInternal (dest))
  224874. {
  224875. if (deleteFile())
  224876. return true;
  224877. dest.deleteFile();
  224878. }
  224879. return false;
  224880. }
  224881. void File::createDirectoryInternal (const String& fileName) const
  224882. {
  224883. mkdir (fileName.toUTF8(), 0777);
  224884. }
  224885. int64 juce_fileSetPosition (void* handle, int64 pos)
  224886. {
  224887. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224888. return pos;
  224889. return -1;
  224890. }
  224891. void FileInputStream::openHandle()
  224892. {
  224893. totalSize = file.getSize();
  224894. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224895. if (f != -1)
  224896. fileHandle = (void*) f;
  224897. }
  224898. void FileInputStream::closeHandle()
  224899. {
  224900. if (fileHandle != 0)
  224901. {
  224902. close ((int) (pointer_sized_int) fileHandle);
  224903. fileHandle = 0;
  224904. }
  224905. }
  224906. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224907. {
  224908. if (fileHandle != 0)
  224909. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224910. return 0;
  224911. }
  224912. void FileOutputStream::openHandle()
  224913. {
  224914. if (file.exists())
  224915. {
  224916. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224917. if (f != -1)
  224918. {
  224919. currentPosition = lseek (f, 0, SEEK_END);
  224920. if (currentPosition >= 0)
  224921. fileHandle = (void*) f;
  224922. else
  224923. close (f);
  224924. }
  224925. }
  224926. else
  224927. {
  224928. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224929. if (f != -1)
  224930. fileHandle = (void*) f;
  224931. }
  224932. }
  224933. void FileOutputStream::closeHandle()
  224934. {
  224935. if (fileHandle != 0)
  224936. {
  224937. close ((int) (pointer_sized_int) fileHandle);
  224938. fileHandle = 0;
  224939. }
  224940. }
  224941. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224942. {
  224943. if (fileHandle != 0)
  224944. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224945. return 0;
  224946. }
  224947. void FileOutputStream::flushInternal()
  224948. {
  224949. if (fileHandle != 0)
  224950. fsync ((int) (pointer_sized_int) fileHandle);
  224951. }
  224952. const File juce_getExecutableFile()
  224953. {
  224954. #if JUCE_ANDROID
  224955. return File (android.appFile);
  224956. #else
  224957. Dl_info exeInfo;
  224958. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  224959. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224960. #endif
  224961. }
  224962. int64 File::getBytesFreeOnVolume() const
  224963. {
  224964. struct statfs buf;
  224965. if (juce_doStatFS (*this, buf))
  224966. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224967. return 0;
  224968. }
  224969. int64 File::getVolumeTotalSize() const
  224970. {
  224971. struct statfs buf;
  224972. if (juce_doStatFS (*this, buf))
  224973. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224974. return 0;
  224975. }
  224976. const String File::getVolumeLabel() const
  224977. {
  224978. #if JUCE_MAC
  224979. struct VolAttrBuf
  224980. {
  224981. u_int32_t length;
  224982. attrreference_t mountPointRef;
  224983. char mountPointSpace [MAXPATHLEN];
  224984. } attrBuf;
  224985. struct attrlist attrList;
  224986. zerostruct (attrList);
  224987. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224988. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224989. File f (*this);
  224990. for (;;)
  224991. {
  224992. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224993. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224994. (int) attrBuf.mountPointRef.attr_length);
  224995. const File parent (f.getParentDirectory());
  224996. if (f == parent)
  224997. break;
  224998. f = parent;
  224999. }
  225000. #endif
  225001. return String::empty;
  225002. }
  225003. int File::getVolumeSerialNumber() const
  225004. {
  225005. int result = 0;
  225006. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  225007. char info [512];
  225008. #ifndef HDIO_GET_IDENTITY
  225009. #define HDIO_GET_IDENTITY 0x030d
  225010. #endif
  225011. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  225012. {
  225013. DBG (String (info + 20, 20));
  225014. result = String (info + 20, 20).trim().getIntValue();
  225015. }
  225016. close (fd);*/
  225017. return result;
  225018. }
  225019. void juce_runSystemCommand (const String& command)
  225020. {
  225021. int result = system (command.toUTF8());
  225022. (void) result;
  225023. }
  225024. const String juce_getOutputFromCommand (const String& command)
  225025. {
  225026. // slight bodge here, as we just pipe the output into a temp file and read it...
  225027. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225028. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225029. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225030. String result (tempFile.loadFileAsString());
  225031. tempFile.deleteFile();
  225032. return result;
  225033. }
  225034. class InterProcessLock::Pimpl
  225035. {
  225036. public:
  225037. Pimpl (const String& name, const int timeOutMillisecs)
  225038. : handle (0), refCount (1)
  225039. {
  225040. #if JUCE_MAC
  225041. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225042. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225043. #else
  225044. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225045. #endif
  225046. temp.create();
  225047. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225048. if (handle != 0)
  225049. {
  225050. struct flock fl;
  225051. zerostruct (fl);
  225052. fl.l_whence = SEEK_SET;
  225053. fl.l_type = F_WRLCK;
  225054. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225055. for (;;)
  225056. {
  225057. const int result = fcntl (handle, F_SETLK, &fl);
  225058. if (result >= 0)
  225059. return;
  225060. if (errno != EINTR)
  225061. {
  225062. if (timeOutMillisecs == 0
  225063. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225064. break;
  225065. Thread::sleep (10);
  225066. }
  225067. }
  225068. }
  225069. closeFile();
  225070. }
  225071. ~Pimpl()
  225072. {
  225073. closeFile();
  225074. }
  225075. void closeFile()
  225076. {
  225077. if (handle != 0)
  225078. {
  225079. struct flock fl;
  225080. zerostruct (fl);
  225081. fl.l_whence = SEEK_SET;
  225082. fl.l_type = F_UNLCK;
  225083. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225084. {}
  225085. close (handle);
  225086. handle = 0;
  225087. }
  225088. }
  225089. int handle, refCount;
  225090. };
  225091. InterProcessLock::InterProcessLock (const String& name_)
  225092. : name (name_)
  225093. {
  225094. }
  225095. InterProcessLock::~InterProcessLock()
  225096. {
  225097. }
  225098. bool InterProcessLock::enter (const int timeOutMillisecs)
  225099. {
  225100. const ScopedLock sl (lock);
  225101. if (pimpl == 0)
  225102. {
  225103. pimpl = new Pimpl (name, timeOutMillisecs);
  225104. if (pimpl->handle == 0)
  225105. pimpl = 0;
  225106. }
  225107. else
  225108. {
  225109. pimpl->refCount++;
  225110. }
  225111. return pimpl != 0;
  225112. }
  225113. void InterProcessLock::exit()
  225114. {
  225115. const ScopedLock sl (lock);
  225116. // Trying to release the lock too many times!
  225117. jassert (pimpl != 0);
  225118. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225119. pimpl = 0;
  225120. }
  225121. void JUCE_API juce_threadEntryPoint (void*);
  225122. void* threadEntryProc (void* userData)
  225123. {
  225124. JUCE_AUTORELEASEPOOL
  225125. #if JUCE_ANDROID
  225126. const AndroidThreadScope androidEnv;
  225127. #endif
  225128. juce_threadEntryPoint (userData);
  225129. return 0;
  225130. }
  225131. void Thread::launchThread()
  225132. {
  225133. threadHandle_ = 0;
  225134. pthread_t handle = 0;
  225135. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  225136. {
  225137. pthread_detach (handle);
  225138. threadHandle_ = (void*) handle;
  225139. threadId_ = (ThreadID) threadHandle_;
  225140. }
  225141. }
  225142. void Thread::closeThreadHandle()
  225143. {
  225144. threadId_ = 0;
  225145. threadHandle_ = 0;
  225146. }
  225147. void Thread::killThread()
  225148. {
  225149. if (threadHandle_ != 0)
  225150. {
  225151. #if JUCE_ANDROID
  225152. jassertfalse; // pthread_cancel not available!
  225153. #else
  225154. pthread_cancel ((pthread_t) threadHandle_);
  225155. #endif
  225156. }
  225157. }
  225158. void Thread::setCurrentThreadName (const String& name)
  225159. {
  225160. #if JUCE_MAC && defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225161. pthread_setname_np (name.toUTF8());
  225162. #elif JUCE_LINUX
  225163. prctl (PR_SET_NAME, name.toUTF8().getAddress(), 0, 0, 0);
  225164. #endif
  225165. }
  225166. bool Thread::setThreadPriority (void* handle, int priority)
  225167. {
  225168. struct sched_param param;
  225169. int policy;
  225170. priority = jlimit (0, 10, priority);
  225171. if (handle == 0)
  225172. handle = (void*) pthread_self();
  225173. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225174. return false;
  225175. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225176. const int minPriority = sched_get_priority_min (policy);
  225177. const int maxPriority = sched_get_priority_max (policy);
  225178. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225179. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225180. }
  225181. Thread::ThreadID Thread::getCurrentThreadId()
  225182. {
  225183. return (ThreadID) pthread_self();
  225184. }
  225185. void Thread::yield()
  225186. {
  225187. sched_yield();
  225188. }
  225189. /* Remove this macro if you're having problems compiling the cpu affinity
  225190. calls (the API for these has changed about quite a bit in various Linux
  225191. versions, and a lot of distros seem to ship with obsolete versions)
  225192. */
  225193. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225194. #define SUPPORT_AFFINITIES 1
  225195. #endif
  225196. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225197. {
  225198. #if SUPPORT_AFFINITIES
  225199. cpu_set_t affinity;
  225200. CPU_ZERO (&affinity);
  225201. for (int i = 0; i < 32; ++i)
  225202. if ((affinityMask & (1 << i)) != 0)
  225203. CPU_SET (i, &affinity);
  225204. /*
  225205. N.B. If this line causes a compile error, then you've probably not got the latest
  225206. version of glibc installed.
  225207. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225208. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225209. */
  225210. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225211. sched_yield();
  225212. #else
  225213. /* affinities aren't supported because either the appropriate header files weren't found,
  225214. or the SUPPORT_AFFINITIES macro was turned off
  225215. */
  225216. jassertfalse;
  225217. (void) affinityMask;
  225218. #endif
  225219. }
  225220. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225221. /*** Start of inlined file: juce_mac_Files.mm ***/
  225222. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225223. // compiled on its own).
  225224. #if JUCE_INCLUDED_FILE
  225225. /*
  225226. Note that a lot of methods that you'd expect to find in this file actually
  225227. live in juce_posix_SharedCode.h!
  225228. */
  225229. bool File::copyInternal (const File& dest) const
  225230. {
  225231. const ScopedAutoReleasePool pool;
  225232. NSFileManager* fm = [NSFileManager defaultManager];
  225233. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225234. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225235. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225236. toPath: juceStringToNS (dest.getFullPathName())
  225237. error: nil];
  225238. #else
  225239. && [fm copyPath: juceStringToNS (fullPath)
  225240. toPath: juceStringToNS (dest.getFullPathName())
  225241. handler: nil];
  225242. #endif
  225243. }
  225244. void File::findFileSystemRoots (Array<File>& destArray)
  225245. {
  225246. destArray.add (File ("/"));
  225247. }
  225248. namespace FileHelpers
  225249. {
  225250. bool isFileOnDriveType (const File& f, const char* const* types)
  225251. {
  225252. struct statfs buf;
  225253. if (juce_doStatFS (f, buf))
  225254. {
  225255. const String type (buf.f_fstypename);
  225256. while (*types != 0)
  225257. if (type.equalsIgnoreCase (*types++))
  225258. return true;
  225259. }
  225260. return false;
  225261. }
  225262. bool isHiddenFile (const String& path)
  225263. {
  225264. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225265. const ScopedAutoReleasePool pool;
  225266. NSNumber* hidden = nil;
  225267. NSError* err = nil;
  225268. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225269. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225270. && [hidden boolValue];
  225271. #else
  225272. #if JUCE_IOS
  225273. return File (path).getFileName().startsWithChar ('.');
  225274. #else
  225275. FSRef ref;
  225276. LSItemInfoRecord info;
  225277. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8().getAddress(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225278. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225279. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225280. #endif
  225281. #endif
  225282. }
  225283. #if JUCE_IOS
  225284. const String getIOSSystemLocation (NSSearchPathDirectory type)
  225285. {
  225286. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  225287. objectAtIndex: 0]);
  225288. }
  225289. #endif
  225290. bool launchExecutable (const String& pathAndArguments)
  225291. {
  225292. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225293. const int cpid = fork();
  225294. if (cpid == 0)
  225295. {
  225296. // Child process
  225297. if (execve (argv[0], (char**) argv, 0) < 0)
  225298. exit (0);
  225299. }
  225300. else
  225301. {
  225302. if (cpid < 0)
  225303. return false;
  225304. }
  225305. return true;
  225306. }
  225307. }
  225308. bool File::isOnCDRomDrive() const
  225309. {
  225310. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225311. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  225312. }
  225313. bool File::isOnHardDisk() const
  225314. {
  225315. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225316. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  225317. }
  225318. bool File::isOnRemovableDrive() const
  225319. {
  225320. #if JUCE_IOS
  225321. return false; // xxx is this possible?
  225322. #else
  225323. const ScopedAutoReleasePool pool;
  225324. BOOL removable = false;
  225325. [[NSWorkspace sharedWorkspace]
  225326. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225327. isRemovable: &removable
  225328. isWritable: nil
  225329. isUnmountable: nil
  225330. description: nil
  225331. type: nil];
  225332. return removable;
  225333. #endif
  225334. }
  225335. bool File::isHidden() const
  225336. {
  225337. return FileHelpers::isHiddenFile (getFullPathName());
  225338. }
  225339. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225340. const File File::getSpecialLocation (const SpecialLocationType type)
  225341. {
  225342. const ScopedAutoReleasePool pool;
  225343. String resultPath;
  225344. switch (type)
  225345. {
  225346. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225347. #if JUCE_IOS
  225348. case userDocumentsDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDocumentDirectory); break;
  225349. case userDesktopDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDesktopDirectory); break;
  225350. case tempDirectory:
  225351. {
  225352. File tmp (FileHelpers::getIOSSystemLocation (NSCachesDirectory));
  225353. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  225354. tmp.createDirectory();
  225355. return tmp.getFullPathName();
  225356. }
  225357. #else
  225358. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225359. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225360. case tempDirectory:
  225361. {
  225362. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225363. tmp.createDirectory();
  225364. return tmp.getFullPathName();
  225365. }
  225366. #endif
  225367. case userMusicDirectory: resultPath = "~/Music"; break;
  225368. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225369. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225370. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225371. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225372. case invokedExecutableFile:
  225373. if (juce_Argv0 != 0)
  225374. return File (String::fromUTF8 (juce_Argv0));
  225375. // deliberate fall-through...
  225376. case currentExecutableFile:
  225377. return juce_getExecutableFile();
  225378. case currentApplicationFile:
  225379. {
  225380. const File exe (juce_getExecutableFile());
  225381. const File parent (exe.getParentDirectory());
  225382. #if JUCE_IOS
  225383. return parent;
  225384. #else
  225385. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225386. ? parent.getParentDirectory().getParentDirectory()
  225387. : exe;
  225388. #endif
  225389. }
  225390. case hostApplicationPath:
  225391. {
  225392. unsigned int size = 8192;
  225393. HeapBlock<char> buffer;
  225394. buffer.calloc (size + 8);
  225395. _NSGetExecutablePath (buffer.getData(), &size);
  225396. return String::fromUTF8 (buffer, size);
  225397. }
  225398. default:
  225399. jassertfalse; // unknown type?
  225400. break;
  225401. }
  225402. if (resultPath.isNotEmpty())
  225403. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225404. return File::nonexistent;
  225405. }
  225406. const String File::getVersion() const
  225407. {
  225408. const ScopedAutoReleasePool pool;
  225409. String result;
  225410. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225411. if (bundle != 0)
  225412. {
  225413. NSDictionary* info = [bundle infoDictionary];
  225414. if (info != 0)
  225415. {
  225416. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225417. if (name != nil)
  225418. result = nsStringToJuce (name);
  225419. }
  225420. }
  225421. return result;
  225422. }
  225423. const File File::getLinkedTarget() const
  225424. {
  225425. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225426. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225427. #else
  225428. // (the cast here avoids a deprecation warning)
  225429. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225430. #endif
  225431. if (dest != nil)
  225432. return File (nsStringToJuce (dest));
  225433. return *this;
  225434. }
  225435. bool File::moveToTrash() const
  225436. {
  225437. if (! exists())
  225438. return true;
  225439. #if JUCE_IOS
  225440. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225441. #else
  225442. const ScopedAutoReleasePool pool;
  225443. NSString* p = juceStringToNS (getFullPathName());
  225444. return [[NSWorkspace sharedWorkspace]
  225445. performFileOperation: NSWorkspaceRecycleOperation
  225446. source: [p stringByDeletingLastPathComponent]
  225447. destination: @""
  225448. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225449. tag: nil ];
  225450. #endif
  225451. }
  225452. class DirectoryIterator::NativeIterator::Pimpl
  225453. {
  225454. public:
  225455. Pimpl (const File& directory, const String& wildCard_)
  225456. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225457. wildCard (wildCard_),
  225458. enumerator (0)
  225459. {
  225460. const ScopedAutoReleasePool pool;
  225461. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225462. wildcardUTF8 = wildCard.toUTF8();
  225463. }
  225464. ~Pimpl()
  225465. {
  225466. [enumerator release];
  225467. }
  225468. bool next (String& filenameFound,
  225469. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225470. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225471. {
  225472. const ScopedAutoReleasePool pool;
  225473. for (;;)
  225474. {
  225475. NSString* file;
  225476. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225477. return false;
  225478. [enumerator skipDescendents];
  225479. filenameFound = nsStringToJuce (file);
  225480. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225481. continue;
  225482. const String path (parentDir + filenameFound);
  225483. updateStatInfoForFile (path, isDir, fileSize, modTime, creationTime, isReadOnly);
  225484. if (isHidden != 0)
  225485. *isHidden = FileHelpers::isHiddenFile (path);
  225486. return true;
  225487. }
  225488. }
  225489. private:
  225490. String parentDir, wildCard;
  225491. const char* wildcardUTF8;
  225492. NSDirectoryEnumerator* enumerator;
  225493. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  225494. };
  225495. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225496. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225497. {
  225498. }
  225499. DirectoryIterator::NativeIterator::~NativeIterator()
  225500. {
  225501. }
  225502. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225503. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225504. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225505. {
  225506. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225507. }
  225508. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225509. {
  225510. #if JUCE_IOS
  225511. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225512. #else
  225513. const ScopedAutoReleasePool pool;
  225514. if (parameters.isEmpty())
  225515. {
  225516. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225517. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225518. }
  225519. bool ok = false;
  225520. if (PlatformUtilities::isBundle (fileName))
  225521. {
  225522. NSMutableArray* urls = [NSMutableArray array];
  225523. StringArray docs;
  225524. docs.addTokens (parameters, true);
  225525. for (int i = 0; i < docs.size(); ++i)
  225526. [urls addObject: juceStringToNS (docs[i])];
  225527. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225528. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225529. options: 0
  225530. additionalEventParamDescriptor: nil
  225531. launchIdentifiers: nil];
  225532. }
  225533. else if (File (fileName).exists())
  225534. {
  225535. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  225536. }
  225537. return ok;
  225538. #endif
  225539. }
  225540. void File::revealToUser() const
  225541. {
  225542. #if ! JUCE_IOS
  225543. if (exists())
  225544. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225545. else if (getParentDirectory().exists())
  225546. getParentDirectory().revealToUser();
  225547. #endif
  225548. }
  225549. #if ! JUCE_IOS
  225550. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225551. {
  225552. return FSPathMakeRef (reinterpret_cast <const UInt8*> (path.toUTF8().getAddress()), destFSRef, 0) == noErr;
  225553. }
  225554. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225555. {
  225556. char path [2048];
  225557. zerostruct (path);
  225558. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225559. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225560. return String::empty;
  225561. }
  225562. #endif
  225563. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225564. {
  225565. const ScopedAutoReleasePool pool;
  225566. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225567. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225568. #else
  225569. // (the cast here avoids a deprecation warning)
  225570. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225571. #endif
  225572. return [fileDict fileHFSTypeCode];
  225573. }
  225574. bool PlatformUtilities::isBundle (const String& filename)
  225575. {
  225576. #if JUCE_IOS
  225577. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225578. #else
  225579. const ScopedAutoReleasePool pool;
  225580. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225581. #endif
  225582. }
  225583. #endif
  225584. /*** End of inlined file: juce_mac_Files.mm ***/
  225585. #if JUCE_IOS
  225586. /*** Start of inlined file: juce_ios_MiscUtilities.mm ***/
  225587. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225588. // compiled on its own).
  225589. #if JUCE_INCLUDED_FILE
  225590. END_JUCE_NAMESPACE
  225591. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225592. {
  225593. }
  225594. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225595. - (void) applicationWillTerminate: (UIApplication*) application;
  225596. @end
  225597. @implementation JuceAppStartupDelegate
  225598. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225599. {
  225600. initialiseJuce_GUI();
  225601. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225602. exit (0);
  225603. }
  225604. - (void) applicationWillTerminate: (UIApplication*) application
  225605. {
  225606. JUCEApplication::appWillTerminateByForce();
  225607. }
  225608. @end
  225609. BEGIN_JUCE_NAMESPACE
  225610. int juce_iOSMain (int argc, const char* argv[])
  225611. {
  225612. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225613. }
  225614. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225615. {
  225616. pool = [[NSAutoreleasePool alloc] init];
  225617. }
  225618. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225619. {
  225620. [((NSAutoreleasePool*) pool) release];
  225621. }
  225622. void PlatformUtilities::beep()
  225623. {
  225624. //xxx
  225625. //AudioServicesPlaySystemSound ();
  225626. }
  225627. void PlatformUtilities::addItemToDock (const File& file)
  225628. {
  225629. }
  225630. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225631. END_JUCE_NAMESPACE
  225632. @interface JuceAlertBoxDelegate : NSObject
  225633. {
  225634. @public
  225635. bool clickedOk;
  225636. }
  225637. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225638. @end
  225639. @implementation JuceAlertBoxDelegate
  225640. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225641. {
  225642. clickedOk = (buttonIndex == 0);
  225643. alertView.hidden = true;
  225644. }
  225645. @end
  225646. BEGIN_JUCE_NAMESPACE
  225647. // (This function is used directly by other bits of code)
  225648. bool juce_iPhoneShowModalAlert (const String& title,
  225649. const String& bodyText,
  225650. NSString* okButtonText,
  225651. NSString* cancelButtonText)
  225652. {
  225653. const ScopedAutoReleasePool pool;
  225654. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225655. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225656. message: juceStringToNS (bodyText)
  225657. delegate: callback
  225658. cancelButtonTitle: okButtonText
  225659. otherButtonTitles: cancelButtonText, nil];
  225660. [alert retain];
  225661. [alert show];
  225662. while (! alert.hidden && alert.superview != nil)
  225663. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225664. const bool result = callback->clickedOk;
  225665. [alert release];
  225666. [callback release];
  225667. return result;
  225668. }
  225669. bool AlertWindow::showNativeDialogBox (const String& title,
  225670. const String& bodyText,
  225671. bool isOkCancel)
  225672. {
  225673. return juce_iPhoneShowModalAlert (title, bodyText,
  225674. @"OK",
  225675. isOkCancel ? @"Cancel" : nil);
  225676. }
  225677. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225678. {
  225679. jassertfalse; // no such thing on the iphone!
  225680. return false;
  225681. }
  225682. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225683. {
  225684. jassertfalse; // no such thing on the iphone!
  225685. return false;
  225686. }
  225687. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225688. {
  225689. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225690. }
  225691. bool Desktop::isScreenSaverEnabled()
  225692. {
  225693. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225694. }
  225695. #endif
  225696. #endif
  225697. /*** End of inlined file: juce_ios_MiscUtilities.mm ***/
  225698. #else
  225699. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225700. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225701. // compiled on its own).
  225702. #if JUCE_INCLUDED_FILE
  225703. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225704. {
  225705. pool = [[NSAutoreleasePool alloc] init];
  225706. }
  225707. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225708. {
  225709. [((NSAutoreleasePool*) pool) release];
  225710. }
  225711. void PlatformUtilities::beep()
  225712. {
  225713. NSBeep();
  225714. }
  225715. void PlatformUtilities::addItemToDock (const File& file)
  225716. {
  225717. // check that it's not already there...
  225718. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225719. .containsIgnoreCase (file.getFullPathName()))
  225720. {
  225721. 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>"
  225722. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225723. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225724. }
  225725. }
  225726. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225727. bool AlertWindow::showNativeDialogBox (const String& title,
  225728. const String& bodyText,
  225729. bool isOkCancel)
  225730. {
  225731. const ScopedAutoReleasePool pool;
  225732. return NSRunAlertPanel (juceStringToNS (title),
  225733. juceStringToNS (bodyText),
  225734. @"Ok",
  225735. isOkCancel ? @"Cancel" : nil,
  225736. nil) == NSAlertDefaultReturn;
  225737. }
  225738. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225739. {
  225740. if (files.size() == 0)
  225741. return false;
  225742. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225743. if (draggingSource == 0)
  225744. {
  225745. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225746. return false;
  225747. }
  225748. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225749. if (sourceComp == 0)
  225750. {
  225751. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225752. return false;
  225753. }
  225754. const ScopedAutoReleasePool pool;
  225755. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225756. if (view == 0)
  225757. return false;
  225758. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225759. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225760. owner: nil];
  225761. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225762. for (int i = 0; i < files.size(); ++i)
  225763. [filesArray addObject: juceStringToNS (files[i])];
  225764. [pboard setPropertyList: filesArray
  225765. forType: NSFilenamesPboardType];
  225766. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225767. fromView: nil];
  225768. dragPosition.x -= 16;
  225769. dragPosition.y -= 16;
  225770. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225771. at: dragPosition
  225772. offset: NSMakeSize (0, 0)
  225773. event: [[view window] currentEvent]
  225774. pasteboard: pboard
  225775. source: view
  225776. slideBack: YES];
  225777. return true;
  225778. }
  225779. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225780. {
  225781. jassertfalse; // not implemented!
  225782. return false;
  225783. }
  225784. bool Desktop::canUseSemiTransparentWindows() throw()
  225785. {
  225786. return true;
  225787. }
  225788. const Point<int> MouseInputSource::getCurrentMousePosition()
  225789. {
  225790. const ScopedAutoReleasePool pool;
  225791. const NSPoint p ([NSEvent mouseLocation]);
  225792. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225793. }
  225794. void Desktop::setMousePosition (const Point<int>& newPosition)
  225795. {
  225796. // this rubbish needs to be done around the warp call, to avoid causing a
  225797. // bizarre glitch..
  225798. CGAssociateMouseAndMouseCursorPosition (false);
  225799. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225800. CGAssociateMouseAndMouseCursorPosition (true);
  225801. }
  225802. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225803. {
  225804. return upright;
  225805. }
  225806. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225807. class ScreenSaverDefeater : public Timer,
  225808. public DeletedAtShutdown
  225809. {
  225810. public:
  225811. ScreenSaverDefeater()
  225812. {
  225813. startTimer (10000);
  225814. timerCallback();
  225815. }
  225816. ~ScreenSaverDefeater() {}
  225817. void timerCallback()
  225818. {
  225819. if (Process::isForegroundProcess())
  225820. UpdateSystemActivity (UsrActivity);
  225821. }
  225822. };
  225823. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225824. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225825. {
  225826. if (isEnabled)
  225827. deleteAndZero (screenSaverDefeater);
  225828. else if (screenSaverDefeater == 0)
  225829. screenSaverDefeater = new ScreenSaverDefeater();
  225830. }
  225831. bool Desktop::isScreenSaverEnabled()
  225832. {
  225833. return screenSaverDefeater == 0;
  225834. }
  225835. #else
  225836. static IOPMAssertionID screenSaverDisablerID = 0;
  225837. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225838. {
  225839. if (isEnabled)
  225840. {
  225841. if (screenSaverDisablerID != 0)
  225842. {
  225843. IOPMAssertionRelease (screenSaverDisablerID);
  225844. screenSaverDisablerID = 0;
  225845. }
  225846. }
  225847. else
  225848. {
  225849. if (screenSaverDisablerID == 0)
  225850. {
  225851. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225852. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225853. CFSTR ("Juce"), &screenSaverDisablerID);
  225854. #else
  225855. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225856. &screenSaverDisablerID);
  225857. #endif
  225858. }
  225859. }
  225860. }
  225861. bool Desktop::isScreenSaverEnabled()
  225862. {
  225863. return screenSaverDisablerID == 0;
  225864. }
  225865. #endif
  225866. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225867. {
  225868. const ScopedAutoReleasePool pool;
  225869. monitorCoords.clear();
  225870. NSArray* screens = [NSScreen screens];
  225871. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225872. for (unsigned int i = 0; i < [screens count]; ++i)
  225873. {
  225874. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225875. NSRect r = clipToWorkArea ? [s visibleFrame]
  225876. : [s frame];
  225877. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225878. monitorCoords.add (convertToRectInt (r));
  225879. }
  225880. jassert (monitorCoords.size() > 0);
  225881. }
  225882. #endif
  225883. #endif
  225884. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225885. #endif
  225886. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225887. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225888. // compiled on its own).
  225889. #if JUCE_INCLUDED_FILE
  225890. void Logger::outputDebugString (const String& text)
  225891. {
  225892. std::cerr << text << std::endl;
  225893. }
  225894. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225895. {
  225896. static char testResult = 0;
  225897. if (testResult == 0)
  225898. {
  225899. struct kinfo_proc info;
  225900. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225901. size_t sz = sizeof (info);
  225902. sysctl (m, 4, &info, &sz, 0, 0);
  225903. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225904. }
  225905. return testResult > 0;
  225906. }
  225907. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225908. {
  225909. return juce_isRunningUnderDebugger();
  225910. }
  225911. #endif
  225912. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225913. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225914. #if JUCE_IOS
  225915. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225916. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225917. // compiled on its own).
  225918. #if JUCE_INCLUDED_FILE
  225919. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225920. #define SUPPORT_10_4_FONTS 1
  225921. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225922. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225923. #define SUPPORT_ONLY_10_4_FONTS 1
  225924. #endif
  225925. END_JUCE_NAMESPACE
  225926. @interface NSFont (PrivateHack)
  225927. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225928. @end
  225929. BEGIN_JUCE_NAMESPACE
  225930. #endif
  225931. class MacTypeface : public Typeface
  225932. {
  225933. public:
  225934. MacTypeface (const Font& font)
  225935. : Typeface (font.getTypefaceName())
  225936. {
  225937. const ScopedAutoReleasePool pool;
  225938. renderingTransform = CGAffineTransformIdentity;
  225939. bool needsItalicTransform = false;
  225940. #if JUCE_IOS
  225941. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225942. if (font.isItalic() || font.isBold())
  225943. {
  225944. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225945. for (NSString* i in familyFonts)
  225946. {
  225947. const String fn (nsStringToJuce (i));
  225948. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225949. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225950. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225951. || afterDash.containsIgnoreCase ("italic")
  225952. || fn.endsWithIgnoreCase ("oblique")
  225953. || fn.endsWithIgnoreCase ("italic");
  225954. if (probablyBold == font.isBold()
  225955. && probablyItalic == font.isItalic())
  225956. {
  225957. fontName = i;
  225958. needsItalicTransform = false;
  225959. break;
  225960. }
  225961. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225962. {
  225963. fontName = i;
  225964. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225965. }
  225966. }
  225967. if (needsItalicTransform)
  225968. renderingTransform.c = 0.15f;
  225969. }
  225970. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225971. const int ascender = abs (CGFontGetAscent (fontRef));
  225972. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225973. ascent = ascender / totalHeight;
  225974. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225975. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225976. #else
  225977. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225978. if (font.isItalic())
  225979. {
  225980. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225981. toHaveTrait: NSItalicFontMask];
  225982. if (newFont == nsFont)
  225983. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225984. nsFont = newFont;
  225985. }
  225986. if (font.isBold())
  225987. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225988. [nsFont retain];
  225989. ascent = std::abs ((float) [nsFont ascender]);
  225990. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225991. ascent /= totalSize;
  225992. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225993. if (needsItalicTransform)
  225994. {
  225995. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225996. renderingTransform.c = 0.15f;
  225997. }
  225998. #if SUPPORT_ONLY_10_4_FONTS
  225999. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226000. if (atsFont == 0)
  226001. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226002. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226003. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226004. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226005. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226006. #else
  226007. #if SUPPORT_10_4_FONTS
  226008. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226009. {
  226010. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226011. if (atsFont == 0)
  226012. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226013. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226014. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226015. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226016. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226017. }
  226018. else
  226019. #endif
  226020. {
  226021. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226022. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226023. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226024. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226025. }
  226026. #endif
  226027. #endif
  226028. }
  226029. ~MacTypeface()
  226030. {
  226031. #if ! JUCE_IOS
  226032. [nsFont release];
  226033. #endif
  226034. if (fontRef != 0)
  226035. CGFontRelease (fontRef);
  226036. }
  226037. float getAscent() const
  226038. {
  226039. return ascent;
  226040. }
  226041. float getDescent() const
  226042. {
  226043. return 1.0f - ascent;
  226044. }
  226045. float getStringWidth (const String& text)
  226046. {
  226047. if (fontRef == 0 || text.isEmpty())
  226048. return 0;
  226049. const int length = text.length();
  226050. HeapBlock <CGGlyph> glyphs;
  226051. createGlyphsForString (text.getCharPointer(), length, glyphs);
  226052. float x = 0;
  226053. #if SUPPORT_ONLY_10_4_FONTS
  226054. HeapBlock <NSSize> advances (length);
  226055. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226056. for (int i = 0; i < length; ++i)
  226057. x += advances[i].width;
  226058. #else
  226059. #if SUPPORT_10_4_FONTS
  226060. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226061. {
  226062. HeapBlock <NSSize> advances (length);
  226063. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226064. for (int i = 0; i < length; ++i)
  226065. x += advances[i].width;
  226066. }
  226067. else
  226068. #endif
  226069. {
  226070. HeapBlock <int> advances (length);
  226071. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226072. for (int i = 0; i < length; ++i)
  226073. x += advances[i];
  226074. }
  226075. #endif
  226076. return x * unitsToHeightScaleFactor;
  226077. }
  226078. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226079. {
  226080. xOffsets.add (0);
  226081. if (fontRef == 0 || text.isEmpty())
  226082. return;
  226083. const int length = text.length();
  226084. HeapBlock <CGGlyph> glyphs;
  226085. createGlyphsForString (text.getCharPointer(), length, glyphs);
  226086. #if SUPPORT_ONLY_10_4_FONTS
  226087. HeapBlock <NSSize> advances (length);
  226088. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226089. int x = 0;
  226090. for (int i = 0; i < length; ++i)
  226091. {
  226092. x += advances[i].width;
  226093. xOffsets.add (x * unitsToHeightScaleFactor);
  226094. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226095. }
  226096. #else
  226097. #if SUPPORT_10_4_FONTS
  226098. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226099. {
  226100. HeapBlock <NSSize> advances (length);
  226101. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226102. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226103. float x = 0;
  226104. for (int i = 0; i < length; ++i)
  226105. {
  226106. x += advances[i].width;
  226107. xOffsets.add (x * unitsToHeightScaleFactor);
  226108. resultGlyphs.add (nsGlyphs[i]);
  226109. }
  226110. }
  226111. else
  226112. #endif
  226113. {
  226114. HeapBlock <int> advances (length);
  226115. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226116. {
  226117. int x = 0;
  226118. for (int i = 0; i < length; ++i)
  226119. {
  226120. x += advances [i];
  226121. xOffsets.add (x * unitsToHeightScaleFactor);
  226122. resultGlyphs.add (glyphs[i]);
  226123. }
  226124. }
  226125. }
  226126. #endif
  226127. }
  226128. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform)
  226129. {
  226130. Path path;
  226131. if (getOutlineForGlyph (glyphNumber, path) && ! path.isEmpty())
  226132. return new EdgeTable (path.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  226133. path, transform);
  226134. return 0;
  226135. }
  226136. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226137. {
  226138. #if JUCE_IOS
  226139. return false;
  226140. #else
  226141. if (nsFont == 0)
  226142. return false;
  226143. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226144. jassert (path.isEmpty());
  226145. const ScopedAutoReleasePool pool;
  226146. NSBezierPath* bez = [NSBezierPath bezierPath];
  226147. [bez moveToPoint: NSMakePoint (0, 0)];
  226148. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226149. inFont: nsFont];
  226150. for (int i = 0; i < [bez elementCount]; ++i)
  226151. {
  226152. NSPoint p[3];
  226153. switch ([bez elementAtIndex: i associatedPoints: p])
  226154. {
  226155. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  226156. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  226157. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  226158. (float) p[1].x, (float) -p[1].y,
  226159. (float) p[2].x, (float) -p[2].y); break;
  226160. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  226161. default: jassertfalse; break;
  226162. }
  226163. }
  226164. path.applyTransform (pathTransform);
  226165. return true;
  226166. #endif
  226167. }
  226168. CGFontRef fontRef;
  226169. float fontHeightToCGSizeFactor;
  226170. CGAffineTransform renderingTransform;
  226171. private:
  226172. float ascent, unitsToHeightScaleFactor;
  226173. #if JUCE_IOS
  226174. #else
  226175. NSFont* nsFont;
  226176. AffineTransform pathTransform;
  226177. #endif
  226178. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  226179. {
  226180. #if SUPPORT_10_4_FONTS
  226181. #if ! SUPPORT_ONLY_10_4_FONTS
  226182. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226183. #endif
  226184. {
  226185. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226186. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226187. for (int i = 0; i < length; ++i)
  226188. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  226189. return;
  226190. }
  226191. #endif
  226192. #if ! SUPPORT_ONLY_10_4_FONTS
  226193. if (charToGlyphMapper == 0)
  226194. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226195. glyphs.malloc (length);
  226196. for (int i = 0; i < length; ++i)
  226197. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  226198. #endif
  226199. }
  226200. #if ! SUPPORT_ONLY_10_4_FONTS
  226201. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226202. class CharToGlyphMapper
  226203. {
  226204. public:
  226205. CharToGlyphMapper (CGFontRef fontRef)
  226206. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226207. idRangeOffset (0), glyphIndexes (0)
  226208. {
  226209. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226210. if (cmapTable != 0)
  226211. {
  226212. const int numSubtables = getValue16 (cmapTable, 2);
  226213. for (int i = 0; i < numSubtables; ++i)
  226214. {
  226215. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226216. {
  226217. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226218. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226219. {
  226220. const int length = getValue16 (cmapTable, offset + 2);
  226221. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226222. segCount = segCountX2 / 2;
  226223. const int endCodeOffset = offset + 14;
  226224. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226225. const int idDeltaOffset = startCodeOffset + segCountX2;
  226226. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226227. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226228. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226229. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226230. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226231. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226232. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226233. }
  226234. break;
  226235. }
  226236. }
  226237. CFRelease (cmapTable);
  226238. }
  226239. }
  226240. ~CharToGlyphMapper()
  226241. {
  226242. if (endCode != 0)
  226243. {
  226244. CFRelease (endCode);
  226245. CFRelease (startCode);
  226246. CFRelease (idDelta);
  226247. CFRelease (idRangeOffset);
  226248. CFRelease (glyphIndexes);
  226249. }
  226250. }
  226251. int getGlyphForCharacter (const juce_wchar c) const
  226252. {
  226253. for (int i = 0; i < segCount; ++i)
  226254. {
  226255. if (getValue16 (endCode, i * 2) >= c)
  226256. {
  226257. const int start = getValue16 (startCode, i * 2);
  226258. if (start > c)
  226259. break;
  226260. const int delta = getValue16 (idDelta, i * 2);
  226261. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226262. if (rangeOffset == 0)
  226263. return delta + c;
  226264. else
  226265. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226266. }
  226267. }
  226268. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226269. return jmax (-1, (int) c - 29);
  226270. }
  226271. private:
  226272. int segCount;
  226273. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226274. static uint16 getValue16 (CFDataRef data, const int index)
  226275. {
  226276. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226277. }
  226278. static uint32 getValue32 (CFDataRef data, const int index)
  226279. {
  226280. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226281. }
  226282. };
  226283. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226284. #endif
  226285. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  226286. };
  226287. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226288. {
  226289. return new MacTypeface (font);
  226290. }
  226291. const StringArray Font::findAllTypefaceNames()
  226292. {
  226293. StringArray names;
  226294. const ScopedAutoReleasePool pool;
  226295. #if JUCE_IOS
  226296. NSArray* fonts = [UIFont familyNames];
  226297. #else
  226298. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226299. #endif
  226300. for (unsigned int i = 0; i < [fonts count]; ++i)
  226301. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226302. names.sort (true);
  226303. return names;
  226304. }
  226305. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  226306. {
  226307. #if JUCE_IOS
  226308. defaultSans = "Helvetica";
  226309. defaultSerif = "Times New Roman";
  226310. defaultFixed = "Courier New";
  226311. #else
  226312. defaultSans = "Lucida Grande";
  226313. defaultSerif = "Times New Roman";
  226314. defaultFixed = "Monaco";
  226315. #endif
  226316. defaultFallback = "Arial Unicode MS";
  226317. }
  226318. #endif
  226319. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226320. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226321. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226322. // compiled on its own).
  226323. #if JUCE_INCLUDED_FILE
  226324. class CoreGraphicsImage : public Image::SharedImage
  226325. {
  226326. public:
  226327. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226328. : Image::SharedImage (format_, width_, height_)
  226329. {
  226330. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226331. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226332. imageData.allocate (lineStride * jmax (1, height), clearImage);
  226333. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226334. : CGColorSpaceCreateDeviceRGB();
  226335. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226336. colourSpace, getCGImageFlags (format_));
  226337. CGColorSpaceRelease (colourSpace);
  226338. }
  226339. ~CoreGraphicsImage()
  226340. {
  226341. CGContextRelease (context);
  226342. }
  226343. Image::ImageType getType() const { return Image::NativeImage; }
  226344. LowLevelGraphicsContext* createLowLevelContext();
  226345. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  226346. {
  226347. bitmap.data = imageData + x * pixelStride + y * lineStride;
  226348. bitmap.pixelFormat = format;
  226349. bitmap.lineStride = lineStride;
  226350. bitmap.pixelStride = pixelStride;
  226351. }
  226352. SharedImage* clone()
  226353. {
  226354. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226355. memcpy (im->imageData, imageData, lineStride * height);
  226356. return im;
  226357. }
  226358. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  226359. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  226360. {
  226361. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226362. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226363. {
  226364. return CGBitmapContextCreateImage (nativeImage->context);
  226365. }
  226366. else
  226367. {
  226368. const Image::BitmapData srcData (juceImage, Image::BitmapData::readOnly);
  226369. CGDataProviderRef provider;
  226370. if (mustOutliveSource)
  226371. {
  226372. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  226373. provider = CGDataProviderCreateWithCFData (data);
  226374. CFRelease (data);
  226375. }
  226376. else
  226377. {
  226378. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226379. }
  226380. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226381. 8, srcData.pixelStride * 8, srcData.lineStride,
  226382. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226383. 0, true, kCGRenderingIntentDefault);
  226384. CGDataProviderRelease (provider);
  226385. return imageRef;
  226386. }
  226387. }
  226388. #if JUCE_MAC
  226389. static NSImage* createNSImage (const Image& image)
  226390. {
  226391. const ScopedAutoReleasePool pool;
  226392. NSImage* im = [[NSImage alloc] init];
  226393. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226394. [im lockFocus];
  226395. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226396. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  226397. CGColorSpaceRelease (colourSpace);
  226398. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226399. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226400. CGImageRelease (imageRef);
  226401. [im unlockFocus];
  226402. return im;
  226403. }
  226404. #endif
  226405. CGContextRef context;
  226406. HeapBlock<uint8> imageData;
  226407. int pixelStride, lineStride;
  226408. private:
  226409. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226410. {
  226411. #if JUCE_BIG_ENDIAN
  226412. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226413. #else
  226414. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226415. #endif
  226416. }
  226417. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  226418. };
  226419. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226420. {
  226421. #if USE_COREGRAPHICS_RENDERING
  226422. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226423. #else
  226424. return createSoftwareImage (format, width, height, clearImage);
  226425. #endif
  226426. }
  226427. class CoreGraphicsContext : public LowLevelGraphicsContext
  226428. {
  226429. public:
  226430. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226431. : context (context_),
  226432. flipHeight (flipHeight_),
  226433. lastClipRectIsValid (false),
  226434. state (new SavedState()),
  226435. numGradientLookupEntries (0)
  226436. {
  226437. CGContextRetain (context);
  226438. CGContextSaveGState(context);
  226439. CGContextSetShouldSmoothFonts (context, true);
  226440. CGContextSetShouldAntialias (context, true);
  226441. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226442. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226443. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226444. gradientCallbacks.version = 0;
  226445. gradientCallbacks.evaluate = gradientCallback;
  226446. gradientCallbacks.releaseInfo = 0;
  226447. setFont (Font());
  226448. }
  226449. ~CoreGraphicsContext()
  226450. {
  226451. CGContextRestoreGState (context);
  226452. CGContextRelease (context);
  226453. CGColorSpaceRelease (rgbColourSpace);
  226454. CGColorSpaceRelease (greyColourSpace);
  226455. }
  226456. bool isVectorDevice() const { return false; }
  226457. void setOrigin (int x, int y)
  226458. {
  226459. CGContextTranslateCTM (context, x, -y);
  226460. if (lastClipRectIsValid)
  226461. lastClipRect.translate (-x, -y);
  226462. }
  226463. void addTransform (const AffineTransform& transform)
  226464. {
  226465. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  226466. .translated (0, flipHeight)
  226467. .followedBy (transform)
  226468. .translated (0, -flipHeight)
  226469. .scaled (1.0f, -1.0f));
  226470. lastClipRectIsValid = false;
  226471. }
  226472. float getScaleFactor()
  226473. {
  226474. CGAffineTransform t = CGContextGetCTM (context);
  226475. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  226476. }
  226477. bool clipToRectangle (const Rectangle<int>& r)
  226478. {
  226479. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226480. if (lastClipRectIsValid)
  226481. {
  226482. // This is actually incorrect, because the actual clip region may be complex, and
  226483. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226484. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226485. // when calculating the resultant clip bounds, and makes the same mistake!
  226486. lastClipRect = lastClipRect.getIntersection (r);
  226487. return ! lastClipRect.isEmpty();
  226488. }
  226489. return ! isClipEmpty();
  226490. }
  226491. bool clipToRectangleList (const RectangleList& clipRegion)
  226492. {
  226493. if (clipRegion.isEmpty())
  226494. {
  226495. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226496. lastClipRectIsValid = true;
  226497. lastClipRect = Rectangle<int>();
  226498. return false;
  226499. }
  226500. else
  226501. {
  226502. const int numRects = clipRegion.getNumRectangles();
  226503. HeapBlock <CGRect> rects (numRects);
  226504. for (int i = 0; i < numRects; ++i)
  226505. {
  226506. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226507. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226508. }
  226509. CGContextClipToRects (context, rects, numRects);
  226510. lastClipRectIsValid = false;
  226511. return ! isClipEmpty();
  226512. }
  226513. }
  226514. void excludeClipRectangle (const Rectangle<int>& r)
  226515. {
  226516. RectangleList remaining (getClipBounds());
  226517. remaining.subtract (r);
  226518. clipToRectangleList (remaining);
  226519. lastClipRectIsValid = false;
  226520. }
  226521. void clipToPath (const Path& path, const AffineTransform& transform)
  226522. {
  226523. createPath (path, transform);
  226524. CGContextClip (context);
  226525. lastClipRectIsValid = false;
  226526. }
  226527. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226528. {
  226529. if (! transform.isSingularity())
  226530. {
  226531. Image singleChannelImage (sourceImage);
  226532. if (sourceImage.getFormat() != Image::SingleChannel)
  226533. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226534. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  226535. flip();
  226536. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226537. applyTransform (t);
  226538. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226539. CGContextClipToMask (context, r, image);
  226540. applyTransform (t.inverted());
  226541. flip();
  226542. CGImageRelease (image);
  226543. lastClipRectIsValid = false;
  226544. }
  226545. }
  226546. bool clipRegionIntersects (const Rectangle<int>& r)
  226547. {
  226548. return getClipBounds().intersects (r);
  226549. }
  226550. const Rectangle<int> getClipBounds() const
  226551. {
  226552. if (! lastClipRectIsValid)
  226553. {
  226554. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226555. lastClipRectIsValid = true;
  226556. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226557. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226558. roundToInt (bounds.size.width),
  226559. roundToInt (bounds.size.height));
  226560. }
  226561. return lastClipRect;
  226562. }
  226563. bool isClipEmpty() const
  226564. {
  226565. return getClipBounds().isEmpty();
  226566. }
  226567. void saveState()
  226568. {
  226569. CGContextSaveGState (context);
  226570. stateStack.add (new SavedState (*state));
  226571. }
  226572. void restoreState()
  226573. {
  226574. CGContextRestoreGState (context);
  226575. SavedState* const top = stateStack.getLast();
  226576. if (top != 0)
  226577. {
  226578. state = top;
  226579. stateStack.removeLast (1, false);
  226580. lastClipRectIsValid = false;
  226581. }
  226582. else
  226583. {
  226584. jassertfalse; // trying to pop with an empty stack!
  226585. }
  226586. }
  226587. void beginTransparencyLayer (float opacity)
  226588. {
  226589. saveState();
  226590. CGContextSetAlpha (context, opacity);
  226591. CGContextBeginTransparencyLayer (context, 0);
  226592. }
  226593. void endTransparencyLayer()
  226594. {
  226595. CGContextEndTransparencyLayer (context);
  226596. restoreState();
  226597. }
  226598. void setFill (const FillType& fillType)
  226599. {
  226600. state->fillType = fillType;
  226601. if (fillType.isColour())
  226602. {
  226603. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226604. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226605. CGContextSetAlpha (context, 1.0f);
  226606. }
  226607. }
  226608. void setOpacity (float newOpacity)
  226609. {
  226610. state->fillType.setOpacity (newOpacity);
  226611. setFill (state->fillType);
  226612. }
  226613. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226614. {
  226615. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226616. ? kCGInterpolationLow
  226617. : kCGInterpolationHigh);
  226618. }
  226619. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226620. {
  226621. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226622. }
  226623. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226624. {
  226625. if (replaceExistingContents)
  226626. {
  226627. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226628. CGContextClearRect (context, cgRect);
  226629. #else
  226630. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226631. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226632. CGContextClearRect (context, cgRect);
  226633. else
  226634. #endif
  226635. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226636. #endif
  226637. fillCGRect (cgRect, false);
  226638. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226639. }
  226640. else
  226641. {
  226642. if (state->fillType.isColour())
  226643. {
  226644. CGContextFillRect (context, cgRect);
  226645. }
  226646. else if (state->fillType.isGradient())
  226647. {
  226648. CGContextSaveGState (context);
  226649. CGContextClipToRect (context, cgRect);
  226650. drawGradient();
  226651. CGContextRestoreGState (context);
  226652. }
  226653. else
  226654. {
  226655. CGContextSaveGState (context);
  226656. CGContextClipToRect (context, cgRect);
  226657. drawImage (state->fillType.image, state->fillType.transform, true);
  226658. CGContextRestoreGState (context);
  226659. }
  226660. }
  226661. }
  226662. void fillPath (const Path& path, const AffineTransform& transform)
  226663. {
  226664. CGContextSaveGState (context);
  226665. if (state->fillType.isColour())
  226666. {
  226667. flip();
  226668. applyTransform (transform);
  226669. createPath (path);
  226670. if (path.isUsingNonZeroWinding())
  226671. CGContextFillPath (context);
  226672. else
  226673. CGContextEOFillPath (context);
  226674. }
  226675. else
  226676. {
  226677. createPath (path, transform);
  226678. if (path.isUsingNonZeroWinding())
  226679. CGContextClip (context);
  226680. else
  226681. CGContextEOClip (context);
  226682. if (state->fillType.isGradient())
  226683. drawGradient();
  226684. else
  226685. drawImage (state->fillType.image, state->fillType.transform, true);
  226686. }
  226687. CGContextRestoreGState (context);
  226688. }
  226689. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226690. {
  226691. const int iw = sourceImage.getWidth();
  226692. const int ih = sourceImage.getHeight();
  226693. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  226694. CGContextSaveGState (context);
  226695. CGContextSetAlpha (context, state->fillType.getOpacity());
  226696. flip();
  226697. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226698. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226699. if (fillEntireClipAsTiles)
  226700. {
  226701. #if JUCE_IOS
  226702. CGContextDrawTiledImage (context, imageRect, image);
  226703. #else
  226704. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226705. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226706. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226707. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226708. CGContextDrawTiledImage (context, imageRect, image);
  226709. else
  226710. #endif
  226711. {
  226712. // Fallback to manually doing a tiled fill on 10.4
  226713. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226714. int x = 0, y = 0;
  226715. while (x > clip.origin.x) x -= iw;
  226716. while (y > clip.origin.y) y -= ih;
  226717. const int right = (int) (clip.origin.x + clip.size.width);
  226718. const int bottom = (int) (clip.origin.y + clip.size.height);
  226719. while (y < bottom)
  226720. {
  226721. for (int x2 = x; x2 < right; x2 += iw)
  226722. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226723. y += ih;
  226724. }
  226725. }
  226726. #endif
  226727. }
  226728. else
  226729. {
  226730. CGContextDrawImage (context, imageRect, image);
  226731. }
  226732. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226733. CGContextRestoreGState (context);
  226734. }
  226735. void drawLine (const Line<float>& line)
  226736. {
  226737. if (state->fillType.isColour())
  226738. {
  226739. CGContextSetLineCap (context, kCGLineCapSquare);
  226740. CGContextSetLineWidth (context, 1.0f);
  226741. CGContextSetRGBStrokeColor (context,
  226742. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226743. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226744. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226745. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226746. CGContextStrokeLineSegments (context, cgLine, 1);
  226747. }
  226748. else
  226749. {
  226750. Path p;
  226751. p.addLineSegment (line, 1.0f);
  226752. fillPath (p, AffineTransform::identity);
  226753. }
  226754. }
  226755. void drawVerticalLine (const int x, float top, float bottom)
  226756. {
  226757. if (state->fillType.isColour())
  226758. {
  226759. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226760. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226761. #else
  226762. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226763. // the x co-ord slightly to trick it..
  226764. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226765. #endif
  226766. }
  226767. else
  226768. {
  226769. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226770. }
  226771. }
  226772. void drawHorizontalLine (const int y, float left, float right)
  226773. {
  226774. if (state->fillType.isColour())
  226775. {
  226776. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226777. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226778. #else
  226779. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226780. // the x co-ord slightly to trick it..
  226781. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226782. #endif
  226783. }
  226784. else
  226785. {
  226786. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226787. }
  226788. }
  226789. void setFont (const Font& newFont)
  226790. {
  226791. if (state->font != newFont)
  226792. {
  226793. state->fontRef = 0;
  226794. state->font = newFont;
  226795. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226796. if (mf != 0)
  226797. {
  226798. state->fontRef = mf->fontRef;
  226799. CGContextSetFont (context, state->fontRef);
  226800. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226801. state->fontTransform = mf->renderingTransform;
  226802. state->fontTransform.a *= state->font.getHorizontalScale();
  226803. CGContextSetTextMatrix (context, state->fontTransform);
  226804. }
  226805. }
  226806. }
  226807. const Font getFont()
  226808. {
  226809. return state->font;
  226810. }
  226811. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226812. {
  226813. if (state->fontRef != 0 && state->fillType.isColour())
  226814. {
  226815. if (transform.isOnlyTranslation())
  226816. {
  226817. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226818. CGGlyph g = glyphNumber;
  226819. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226820. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226821. }
  226822. else
  226823. {
  226824. CGContextSaveGState (context);
  226825. flip();
  226826. applyTransform (transform);
  226827. CGAffineTransform t = state->fontTransform;
  226828. t.d = -t.d;
  226829. CGContextSetTextMatrix (context, t);
  226830. CGGlyph g = glyphNumber;
  226831. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226832. CGContextRestoreGState (context);
  226833. }
  226834. }
  226835. else
  226836. {
  226837. Path p;
  226838. Font& f = state->font;
  226839. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226840. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226841. .followedBy (transform));
  226842. }
  226843. }
  226844. private:
  226845. CGContextRef context;
  226846. const CGFloat flipHeight;
  226847. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226848. CGFunctionCallbacks gradientCallbacks;
  226849. mutable Rectangle<int> lastClipRect;
  226850. mutable bool lastClipRectIsValid;
  226851. struct SavedState
  226852. {
  226853. SavedState()
  226854. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226855. {
  226856. }
  226857. SavedState (const SavedState& other)
  226858. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226859. fontTransform (other.fontTransform)
  226860. {
  226861. }
  226862. FillType fillType;
  226863. Font font;
  226864. CGFontRef fontRef;
  226865. CGAffineTransform fontTransform;
  226866. };
  226867. ScopedPointer <SavedState> state;
  226868. OwnedArray <SavedState> stateStack;
  226869. HeapBlock <PixelARGB> gradientLookupTable;
  226870. int numGradientLookupEntries;
  226871. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226872. {
  226873. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226874. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226875. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226876. colour.unpremultiply();
  226877. outData[0] = colour.getRed() / 255.0f;
  226878. outData[1] = colour.getGreen() / 255.0f;
  226879. outData[2] = colour.getBlue() / 255.0f;
  226880. outData[3] = colour.getAlpha() / 255.0f;
  226881. }
  226882. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226883. {
  226884. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  226885. CGShadingRef result = 0;
  226886. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226887. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226888. if (gradient.isRadial)
  226889. {
  226890. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226891. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226892. function, true, true);
  226893. }
  226894. else
  226895. {
  226896. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226897. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226898. function, true, true);
  226899. }
  226900. CGFunctionRelease (function);
  226901. return result;
  226902. }
  226903. void drawGradient()
  226904. {
  226905. flip();
  226906. applyTransform (state->fillType.transform);
  226907. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226908. // you draw a gradient with high quality interp enabled).
  226909. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226910. CGContextSetAlpha (context, state->fillType.getOpacity());
  226911. CGContextDrawShading (context, shading);
  226912. CGShadingRelease (shading);
  226913. }
  226914. void createPath (const Path& path) const
  226915. {
  226916. CGContextBeginPath (context);
  226917. Path::Iterator i (path);
  226918. while (i.next())
  226919. {
  226920. switch (i.elementType)
  226921. {
  226922. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226923. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226924. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226925. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226926. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226927. default: jassertfalse; break;
  226928. }
  226929. }
  226930. }
  226931. void createPath (const Path& path, const AffineTransform& transform) const
  226932. {
  226933. CGContextBeginPath (context);
  226934. Path::Iterator i (path);
  226935. while (i.next())
  226936. {
  226937. switch (i.elementType)
  226938. {
  226939. case Path::Iterator::startNewSubPath:
  226940. transform.transformPoint (i.x1, i.y1);
  226941. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226942. break;
  226943. case Path::Iterator::lineTo:
  226944. transform.transformPoint (i.x1, i.y1);
  226945. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226946. break;
  226947. case Path::Iterator::quadraticTo:
  226948. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226949. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226950. break;
  226951. case Path::Iterator::cubicTo:
  226952. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226953. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226954. break;
  226955. case Path::Iterator::closePath:
  226956. CGContextClosePath (context); break;
  226957. default:
  226958. jassertfalse;
  226959. break;
  226960. }
  226961. }
  226962. }
  226963. void flip() const
  226964. {
  226965. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226966. }
  226967. void applyTransform (const AffineTransform& transform) const
  226968. {
  226969. CGAffineTransform t;
  226970. t.a = transform.mat00;
  226971. t.b = transform.mat10;
  226972. t.c = transform.mat01;
  226973. t.d = transform.mat11;
  226974. t.tx = transform.mat02;
  226975. t.ty = transform.mat12;
  226976. CGContextConcatCTM (context, t);
  226977. }
  226978. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226979. };
  226980. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226981. {
  226982. return new CoreGraphicsContext (context, height);
  226983. }
  226984. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226985. const Image juce_loadWithCoreImage (InputStream& input)
  226986. {
  226987. MemoryBlock data;
  226988. input.readIntoMemoryBlock (data, -1);
  226989. #if JUCE_IOS
  226990. JUCE_AUTORELEASEPOOL
  226991. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226992. length: data.getSize()
  226993. freeWhenDone: NO]];
  226994. if (image != nil)
  226995. {
  226996. CGImageRef loadedImage = image.CGImage;
  226997. #else
  226998. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226999. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227000. CGDataProviderRelease (provider);
  227001. if (imageSource != 0)
  227002. {
  227003. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227004. CFRelease (imageSource);
  227005. #endif
  227006. if (loadedImage != 0)
  227007. {
  227008. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  227009. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  227010. && alphaInfo != kCGImageAlphaNoneSkipLast
  227011. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  227012. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  227013. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227014. hasAlphaChan, Image::NativeImage);
  227015. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227016. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227017. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227018. CGContextFlush (cgImage->context);
  227019. #if ! JUCE_IOS
  227020. CFRelease (loadedImage);
  227021. #endif
  227022. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  227023. // to find out whether the file they just loaded the image from had an alpha channel or not.
  227024. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  227025. return image;
  227026. }
  227027. }
  227028. return Image::null;
  227029. }
  227030. #endif
  227031. #endif
  227032. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227033. /*** Start of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  227034. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227035. // compiled on its own).
  227036. #if JUCE_INCLUDED_FILE
  227037. class UIViewComponentPeer;
  227038. END_JUCE_NAMESPACE
  227039. #define JuceUIView MakeObjCClassName(JuceUIView)
  227040. @interface JuceUIView : UIView <UITextViewDelegate>
  227041. {
  227042. @public
  227043. UIViewComponentPeer* owner;
  227044. UITextView* hiddenTextView;
  227045. }
  227046. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227047. - (void) dealloc;
  227048. - (void) drawRect: (CGRect) r;
  227049. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227050. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227051. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227052. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227053. - (BOOL) becomeFirstResponder;
  227054. - (BOOL) resignFirstResponder;
  227055. - (BOOL) canBecomeFirstResponder;
  227056. - (void) asyncRepaint: (id) rect;
  227057. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227058. @end
  227059. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  227060. @interface JuceUIViewController : UIViewController
  227061. {
  227062. }
  227063. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  227064. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  227065. @end
  227066. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227067. @interface JuceUIWindow : UIWindow
  227068. {
  227069. @private
  227070. UIViewComponentPeer* owner;
  227071. bool isZooming;
  227072. }
  227073. - (void) setOwner: (UIViewComponentPeer*) owner;
  227074. - (void) becomeKeyWindow;
  227075. @end
  227076. BEGIN_JUCE_NAMESPACE
  227077. class UIViewComponentPeer : public ComponentPeer,
  227078. public FocusChangeListener
  227079. {
  227080. public:
  227081. UIViewComponentPeer (Component* const component,
  227082. const int windowStyleFlags,
  227083. UIView* viewToAttachTo);
  227084. ~UIViewComponentPeer();
  227085. void* getNativeHandle() const;
  227086. void setVisible (bool shouldBeVisible);
  227087. void setTitle (const String& title);
  227088. void setPosition (int x, int y);
  227089. void setSize (int w, int h);
  227090. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227091. const Rectangle<int> getBounds() const;
  227092. const Rectangle<int> getBounds (const bool global) const;
  227093. const Point<int> getScreenPosition() const;
  227094. const Point<int> localToGlobal (const Point<int>& relativePosition);
  227095. const Point<int> globalToLocal (const Point<int>& screenPosition);
  227096. void setAlpha (float newAlpha);
  227097. void setMinimised (bool shouldBeMinimised);
  227098. bool isMinimised() const;
  227099. void setFullScreen (bool shouldBeFullScreen);
  227100. bool isFullScreen() const;
  227101. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227102. const BorderSize<int> getFrameSize() const;
  227103. bool setAlwaysOnTop (bool alwaysOnTop);
  227104. void toFront (bool makeActiveWindow);
  227105. void toBehind (ComponentPeer* other);
  227106. void setIcon (const Image& newIcon);
  227107. virtual void drawRect (CGRect r);
  227108. virtual bool canBecomeKeyWindow();
  227109. virtual bool windowShouldClose();
  227110. virtual void redirectMovedOrResized();
  227111. virtual CGRect constrainRect (CGRect r);
  227112. virtual void viewFocusGain();
  227113. virtual void viewFocusLoss();
  227114. bool isFocused() const;
  227115. void grabFocus();
  227116. void textInputRequired (const Point<int>& position);
  227117. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227118. void updateHiddenTextContent (TextInputTarget* target);
  227119. void globalFocusChanged (Component*);
  227120. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  227121. virtual void displayRotated();
  227122. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227123. void repaint (const Rectangle<int>& area);
  227124. void performAnyPendingRepaintsNow();
  227125. UIWindow* window;
  227126. JuceUIView* view;
  227127. JuceUIViewController* controller;
  227128. bool isSharedWindow, fullScreen, insideDrawRect;
  227129. static ModifierKeys currentModifiers;
  227130. static int64 getMouseTime (UIEvent* e)
  227131. {
  227132. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227133. + (int64) ([e timestamp] * 1000.0);
  227134. }
  227135. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  227136. {
  227137. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227138. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227139. {
  227140. case UIInterfaceOrientationPortrait:
  227141. return r;
  227142. case UIInterfaceOrientationPortraitUpsideDown:
  227143. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227144. r.getWidth(), r.getHeight());
  227145. case UIInterfaceOrientationLandscapeLeft:
  227146. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  227147. r.getHeight(), r.getWidth());
  227148. case UIInterfaceOrientationLandscapeRight:
  227149. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  227150. r.getHeight(), r.getWidth());
  227151. default: jassertfalse; // unknown orientation!
  227152. }
  227153. return r;
  227154. }
  227155. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  227156. {
  227157. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227158. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227159. {
  227160. case UIInterfaceOrientationPortrait:
  227161. return r;
  227162. case UIInterfaceOrientationPortraitUpsideDown:
  227163. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227164. r.getWidth(), r.getHeight());
  227165. case UIInterfaceOrientationLandscapeLeft:
  227166. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  227167. r.getHeight(), r.getWidth());
  227168. case UIInterfaceOrientationLandscapeRight:
  227169. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  227170. r.getHeight(), r.getWidth());
  227171. default: jassertfalse; // unknown orientation!
  227172. }
  227173. return r;
  227174. }
  227175. Array <UITouch*> currentTouches;
  227176. private:
  227177. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  227178. };
  227179. END_JUCE_NAMESPACE
  227180. @implementation JuceUIViewController
  227181. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  227182. {
  227183. JuceUIView* juceView = (JuceUIView*) [self view];
  227184. jassert (juceView != 0 && juceView->owner != 0);
  227185. return juceView->owner->shouldRotate (interfaceOrientation);
  227186. }
  227187. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  227188. {
  227189. JuceUIView* juceView = (JuceUIView*) [self view];
  227190. jassert (juceView != 0 && juceView->owner != 0);
  227191. juceView->owner->displayRotated();
  227192. }
  227193. @end
  227194. @implementation JuceUIView
  227195. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227196. withFrame: (CGRect) frame
  227197. {
  227198. [super initWithFrame: frame];
  227199. owner = owner_;
  227200. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227201. [self addSubview: hiddenTextView];
  227202. hiddenTextView.delegate = self;
  227203. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227204. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227205. return self;
  227206. }
  227207. - (void) dealloc
  227208. {
  227209. [hiddenTextView removeFromSuperview];
  227210. [hiddenTextView release];
  227211. [super dealloc];
  227212. }
  227213. - (void) drawRect: (CGRect) r
  227214. {
  227215. if (owner != 0)
  227216. owner->drawRect (r);
  227217. }
  227218. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227219. {
  227220. return false;
  227221. }
  227222. ModifierKeys UIViewComponentPeer::currentModifiers;
  227223. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227224. {
  227225. return UIViewComponentPeer::currentModifiers;
  227226. }
  227227. void ModifierKeys::updateCurrentModifiers() throw()
  227228. {
  227229. currentModifiers = UIViewComponentPeer::currentModifiers;
  227230. }
  227231. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227232. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227233. {
  227234. if (owner != 0)
  227235. owner->handleTouches (event, true, false, false);
  227236. }
  227237. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227238. {
  227239. if (owner != 0)
  227240. owner->handleTouches (event, false, false, false);
  227241. }
  227242. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227243. {
  227244. if (owner != 0)
  227245. owner->handleTouches (event, false, true, false);
  227246. }
  227247. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227248. {
  227249. if (owner != 0)
  227250. owner->handleTouches (event, false, true, true);
  227251. [self touchesEnded: touches withEvent: event];
  227252. }
  227253. - (BOOL) becomeFirstResponder
  227254. {
  227255. if (owner != 0)
  227256. owner->viewFocusGain();
  227257. return true;
  227258. }
  227259. - (BOOL) resignFirstResponder
  227260. {
  227261. if (owner != 0)
  227262. owner->viewFocusLoss();
  227263. return true;
  227264. }
  227265. - (BOOL) canBecomeFirstResponder
  227266. {
  227267. return owner != 0 && owner->canBecomeKeyWindow();
  227268. }
  227269. - (void) asyncRepaint: (id) rect
  227270. {
  227271. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227272. [self setNeedsDisplayInRect: *r];
  227273. }
  227274. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227275. {
  227276. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227277. nsStringToJuce (text));
  227278. }
  227279. @end
  227280. @implementation JuceUIWindow
  227281. - (void) setOwner: (UIViewComponentPeer*) owner_
  227282. {
  227283. owner = owner_;
  227284. isZooming = false;
  227285. }
  227286. - (void) becomeKeyWindow
  227287. {
  227288. [super becomeKeyWindow];
  227289. if (owner != 0)
  227290. owner->grabFocus();
  227291. }
  227292. @end
  227293. BEGIN_JUCE_NAMESPACE
  227294. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227295. const int windowStyleFlags,
  227296. UIView* viewToAttachTo)
  227297. : ComponentPeer (component, windowStyleFlags),
  227298. window (0),
  227299. view (0), controller (0),
  227300. isSharedWindow (viewToAttachTo != 0),
  227301. fullScreen (false),
  227302. insideDrawRect (false)
  227303. {
  227304. CGRect r = convertToCGRect (component->getLocalBounds());
  227305. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227306. if (isSharedWindow)
  227307. {
  227308. window = [viewToAttachTo window];
  227309. [viewToAttachTo addSubview: view];
  227310. setVisible (component->isVisible());
  227311. }
  227312. else
  227313. {
  227314. controller = [[JuceUIViewController alloc] init];
  227315. controller.view = view;
  227316. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  227317. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227318. window = [[JuceUIWindow alloc] init];
  227319. window.frame = r;
  227320. window.opaque = component->isOpaque();
  227321. view.opaque = component->isOpaque();
  227322. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227323. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227324. [((JuceUIWindow*) window) setOwner: this];
  227325. if (component->isAlwaysOnTop())
  227326. window.windowLevel = UIWindowLevelAlert;
  227327. [window addSubview: view];
  227328. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227329. view.hidden = ! component->isVisible();
  227330. window.hidden = ! component->isVisible();
  227331. view.multipleTouchEnabled = YES;
  227332. }
  227333. setTitle (component->getName());
  227334. Desktop::getInstance().addFocusChangeListener (this);
  227335. }
  227336. UIViewComponentPeer::~UIViewComponentPeer()
  227337. {
  227338. Desktop::getInstance().removeFocusChangeListener (this);
  227339. view->owner = 0;
  227340. [view removeFromSuperview];
  227341. [view release];
  227342. [controller release];
  227343. if (! isSharedWindow)
  227344. {
  227345. [((JuceUIWindow*) window) setOwner: 0];
  227346. [window release];
  227347. }
  227348. }
  227349. void* UIViewComponentPeer::getNativeHandle() const
  227350. {
  227351. return view;
  227352. }
  227353. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227354. {
  227355. view.hidden = ! shouldBeVisible;
  227356. if (! isSharedWindow)
  227357. window.hidden = ! shouldBeVisible;
  227358. }
  227359. void UIViewComponentPeer::setTitle (const String& title)
  227360. {
  227361. // xxx is this possible?
  227362. }
  227363. void UIViewComponentPeer::setPosition (int x, int y)
  227364. {
  227365. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227366. }
  227367. void UIViewComponentPeer::setSize (int w, int h)
  227368. {
  227369. setBounds (component->getX(), component->getY(), w, h, false);
  227370. }
  227371. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227372. {
  227373. fullScreen = isNowFullScreen;
  227374. w = jmax (0, w);
  227375. h = jmax (0, h);
  227376. if (isSharedWindow)
  227377. {
  227378. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  227379. if ([view frame].size.width != r.size.width
  227380. || [view frame].size.height != r.size.height)
  227381. [view setNeedsDisplay];
  227382. view.frame = r;
  227383. }
  227384. else
  227385. {
  227386. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  227387. window.frame = convertToCGRect (bounds);
  227388. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  227389. handleMovedOrResized();
  227390. }
  227391. }
  227392. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227393. {
  227394. CGRect r = [view frame];
  227395. if (global && [view window] != 0)
  227396. {
  227397. r = [view convertRect: r toView: nil];
  227398. CGRect wr = [[view window] frame];
  227399. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  227400. r.origin.x = windowBounds.getX();
  227401. r.origin.y = windowBounds.getY();
  227402. }
  227403. return convertToRectInt (r);
  227404. }
  227405. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227406. {
  227407. return getBounds (! isSharedWindow);
  227408. }
  227409. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227410. {
  227411. return getBounds (true).getPosition();
  227412. }
  227413. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  227414. {
  227415. return relativePosition + getScreenPosition();
  227416. }
  227417. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  227418. {
  227419. return screenPosition - getScreenPosition();
  227420. }
  227421. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227422. {
  227423. if (constrainer != 0)
  227424. {
  227425. CGRect current = [window frame];
  227426. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227427. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227428. Rectangle<int> pos (convertToRectInt (r));
  227429. Rectangle<int> original (convertToRectInt (current));
  227430. constrainer->checkBounds (pos, original,
  227431. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227432. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227433. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227434. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227435. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227436. r.origin.x = pos.getX();
  227437. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227438. r.size.width = pos.getWidth();
  227439. r.size.height = pos.getHeight();
  227440. }
  227441. return r;
  227442. }
  227443. void UIViewComponentPeer::setAlpha (float newAlpha)
  227444. {
  227445. [[view window] setAlpha: (CGFloat) newAlpha];
  227446. }
  227447. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227448. {
  227449. }
  227450. bool UIViewComponentPeer::isMinimised() const
  227451. {
  227452. return false;
  227453. }
  227454. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227455. {
  227456. if (! isSharedWindow)
  227457. {
  227458. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227459. : lastNonFullscreenBounds);
  227460. if ((! shouldBeFullScreen) && r.isEmpty())
  227461. r = getBounds();
  227462. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227463. if (! r.isEmpty())
  227464. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227465. component->repaint();
  227466. }
  227467. }
  227468. bool UIViewComponentPeer::isFullScreen() const
  227469. {
  227470. return fullScreen;
  227471. }
  227472. namespace
  227473. {
  227474. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227475. {
  227476. switch (interfaceOrientation)
  227477. {
  227478. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227479. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227480. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227481. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227482. default: jassertfalse; // unknown orientation!
  227483. }
  227484. return Desktop::upright;
  227485. }
  227486. }
  227487. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227488. {
  227489. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227490. }
  227491. void UIViewComponentPeer::displayRotated()
  227492. {
  227493. const Rectangle<int> oldArea (component->getBounds());
  227494. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227495. Desktop::getInstance().refreshMonitorSizes();
  227496. if (fullScreen)
  227497. {
  227498. fullScreen = false;
  227499. setFullScreen (true);
  227500. }
  227501. else
  227502. {
  227503. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227504. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227505. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227506. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227507. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227508. setBounds ((int) (l * newDesktop.getWidth()),
  227509. (int) (t * newDesktop.getHeight()),
  227510. (int) ((r - l) * newDesktop.getWidth()),
  227511. (int) ((b - t) * newDesktop.getHeight()),
  227512. false);
  227513. }
  227514. }
  227515. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227516. {
  227517. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  227518. && isPositiveAndBelow (position.getY(), component->getHeight())))
  227519. return false;
  227520. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  227521. withEvent: nil];
  227522. if (trueIfInAChildWindow)
  227523. return v != nil;
  227524. return v == view;
  227525. }
  227526. const BorderSize<int> UIViewComponentPeer::getFrameSize() const
  227527. {
  227528. return BorderSize<int>();
  227529. }
  227530. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227531. {
  227532. if (! isSharedWindow)
  227533. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227534. return true;
  227535. }
  227536. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227537. {
  227538. if (isSharedWindow)
  227539. [[view superview] bringSubviewToFront: view];
  227540. if (window != 0 && component->isVisible())
  227541. [window makeKeyAndVisible];
  227542. }
  227543. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227544. {
  227545. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227546. jassert (otherPeer != 0); // wrong type of window?
  227547. if (otherPeer != 0)
  227548. {
  227549. if (isSharedWindow)
  227550. {
  227551. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227552. }
  227553. else
  227554. {
  227555. jassertfalse; // don't know how to do this
  227556. }
  227557. }
  227558. }
  227559. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227560. {
  227561. // to do..
  227562. }
  227563. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227564. {
  227565. NSArray* touches = [[event touchesForView: view] allObjects];
  227566. for (unsigned int i = 0; i < [touches count]; ++i)
  227567. {
  227568. UITouch* touch = [touches objectAtIndex: i];
  227569. CGPoint p = [touch locationInView: view];
  227570. const Point<int> pos ((int) p.x, (int) p.y);
  227571. juce_lastMousePos = pos + getScreenPosition();
  227572. const int64 time = getMouseTime (event);
  227573. int touchIndex = currentTouches.indexOf (touch);
  227574. if (touchIndex < 0)
  227575. {
  227576. touchIndex = currentTouches.size();
  227577. currentTouches.add (touch);
  227578. }
  227579. if (isDown)
  227580. {
  227581. currentModifiers = currentModifiers.withoutMouseButtons();
  227582. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227583. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227584. }
  227585. else if (isUp)
  227586. {
  227587. currentModifiers = currentModifiers.withoutMouseButtons();
  227588. currentTouches.remove (touchIndex);
  227589. }
  227590. if (isCancel)
  227591. currentTouches.clear();
  227592. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227593. }
  227594. }
  227595. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227596. void UIViewComponentPeer::viewFocusGain()
  227597. {
  227598. if (currentlyFocusedPeer != this)
  227599. {
  227600. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227601. currentlyFocusedPeer->handleFocusLoss();
  227602. currentlyFocusedPeer = this;
  227603. handleFocusGain();
  227604. }
  227605. }
  227606. void UIViewComponentPeer::viewFocusLoss()
  227607. {
  227608. if (currentlyFocusedPeer == this)
  227609. {
  227610. currentlyFocusedPeer = 0;
  227611. handleFocusLoss();
  227612. }
  227613. }
  227614. void juce_HandleProcessFocusChange()
  227615. {
  227616. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227617. {
  227618. if (Process::isForegroundProcess())
  227619. {
  227620. currentlyFocusedPeer->handleFocusGain();
  227621. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227622. }
  227623. else
  227624. {
  227625. currentlyFocusedPeer->handleFocusLoss();
  227626. // turn kiosk mode off if we lose focus..
  227627. Desktop::getInstance().setKioskModeComponent (0);
  227628. }
  227629. }
  227630. }
  227631. bool UIViewComponentPeer::isFocused() const
  227632. {
  227633. return isSharedWindow ? this == currentlyFocusedPeer
  227634. : (window != 0 && [window isKeyWindow]);
  227635. }
  227636. void UIViewComponentPeer::grabFocus()
  227637. {
  227638. if (window != 0)
  227639. {
  227640. [window makeKeyWindow];
  227641. viewFocusGain();
  227642. }
  227643. }
  227644. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227645. {
  227646. }
  227647. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227648. {
  227649. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227650. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227651. }
  227652. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227653. {
  227654. TextInputTarget* const target = findCurrentTextInputTarget();
  227655. if (target != 0)
  227656. {
  227657. const Range<int> currentSelection (target->getHighlightedRegion());
  227658. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227659. if (currentSelection.isEmpty())
  227660. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227661. target->insertTextAtCaret (text);
  227662. updateHiddenTextContent (target);
  227663. }
  227664. return NO;
  227665. }
  227666. void UIViewComponentPeer::globalFocusChanged (Component*)
  227667. {
  227668. TextInputTarget* const target = findCurrentTextInputTarget();
  227669. if (target != 0)
  227670. {
  227671. Component* comp = dynamic_cast<Component*> (target);
  227672. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227673. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227674. updateHiddenTextContent (target);
  227675. [view->hiddenTextView becomeFirstResponder];
  227676. }
  227677. else
  227678. {
  227679. [view->hiddenTextView resignFirstResponder];
  227680. }
  227681. }
  227682. void UIViewComponentPeer::drawRect (CGRect r)
  227683. {
  227684. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227685. return;
  227686. CGContextRef cg = UIGraphicsGetCurrentContext();
  227687. if (! component->isOpaque())
  227688. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227689. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227690. CoreGraphicsContext g (cg, view.bounds.size.height);
  227691. insideDrawRect = true;
  227692. handlePaint (g);
  227693. insideDrawRect = false;
  227694. }
  227695. bool UIViewComponentPeer::canBecomeKeyWindow()
  227696. {
  227697. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227698. }
  227699. bool UIViewComponentPeer::windowShouldClose()
  227700. {
  227701. if (! isValidPeer (this))
  227702. return YES;
  227703. handleUserClosingWindow();
  227704. return NO;
  227705. }
  227706. void UIViewComponentPeer::redirectMovedOrResized()
  227707. {
  227708. handleMovedOrResized();
  227709. }
  227710. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227711. {
  227712. }
  227713. class AsyncRepaintMessage : public CallbackMessage
  227714. {
  227715. public:
  227716. UIViewComponentPeer* const peer;
  227717. const Rectangle<int> rect;
  227718. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227719. : peer (peer_), rect (rect_)
  227720. {
  227721. }
  227722. void messageCallback()
  227723. {
  227724. if (ComponentPeer::isValidPeer (peer))
  227725. peer->repaint (rect);
  227726. }
  227727. };
  227728. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227729. {
  227730. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227731. {
  227732. (new AsyncRepaintMessage (this, area))->post();
  227733. }
  227734. else
  227735. {
  227736. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227737. }
  227738. }
  227739. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227740. {
  227741. }
  227742. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227743. {
  227744. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227745. }
  227746. const Image juce_createIconForFile (const File& file)
  227747. {
  227748. return Image::null;
  227749. }
  227750. void Desktop::createMouseInputSources()
  227751. {
  227752. for (int i = 0; i < 10; ++i)
  227753. mouseSources.add (new MouseInputSource (i, false));
  227754. }
  227755. bool Desktop::canUseSemiTransparentWindows() throw()
  227756. {
  227757. return true;
  227758. }
  227759. const Point<int> MouseInputSource::getCurrentMousePosition()
  227760. {
  227761. return juce_lastMousePos;
  227762. }
  227763. void Desktop::setMousePosition (const Point<int>&)
  227764. {
  227765. }
  227766. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227767. {
  227768. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227769. }
  227770. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227771. {
  227772. const ScopedAutoReleasePool pool;
  227773. monitorCoords.clear();
  227774. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227775. : [[UIScreen mainScreen] bounds];
  227776. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227777. }
  227778. const int KeyPress::spaceKey = ' ';
  227779. const int KeyPress::returnKey = 0x0d;
  227780. const int KeyPress::escapeKey = 0x1b;
  227781. const int KeyPress::backspaceKey = 0x7f;
  227782. const int KeyPress::leftKey = 0x1000;
  227783. const int KeyPress::rightKey = 0x1001;
  227784. const int KeyPress::upKey = 0x1002;
  227785. const int KeyPress::downKey = 0x1003;
  227786. const int KeyPress::pageUpKey = 0x1004;
  227787. const int KeyPress::pageDownKey = 0x1005;
  227788. const int KeyPress::endKey = 0x1006;
  227789. const int KeyPress::homeKey = 0x1007;
  227790. const int KeyPress::deleteKey = 0x1008;
  227791. const int KeyPress::insertKey = -1;
  227792. const int KeyPress::tabKey = 9;
  227793. const int KeyPress::F1Key = 0x2001;
  227794. const int KeyPress::F2Key = 0x2002;
  227795. const int KeyPress::F3Key = 0x2003;
  227796. const int KeyPress::F4Key = 0x2004;
  227797. const int KeyPress::F5Key = 0x2005;
  227798. const int KeyPress::F6Key = 0x2006;
  227799. const int KeyPress::F7Key = 0x2007;
  227800. const int KeyPress::F8Key = 0x2008;
  227801. const int KeyPress::F9Key = 0x2009;
  227802. const int KeyPress::F10Key = 0x200a;
  227803. const int KeyPress::F11Key = 0x200b;
  227804. const int KeyPress::F12Key = 0x200c;
  227805. const int KeyPress::F13Key = 0x200d;
  227806. const int KeyPress::F14Key = 0x200e;
  227807. const int KeyPress::F15Key = 0x200f;
  227808. const int KeyPress::F16Key = 0x2010;
  227809. const int KeyPress::numberPad0 = 0x30020;
  227810. const int KeyPress::numberPad1 = 0x30021;
  227811. const int KeyPress::numberPad2 = 0x30022;
  227812. const int KeyPress::numberPad3 = 0x30023;
  227813. const int KeyPress::numberPad4 = 0x30024;
  227814. const int KeyPress::numberPad5 = 0x30025;
  227815. const int KeyPress::numberPad6 = 0x30026;
  227816. const int KeyPress::numberPad7 = 0x30027;
  227817. const int KeyPress::numberPad8 = 0x30028;
  227818. const int KeyPress::numberPad9 = 0x30029;
  227819. const int KeyPress::numberPadAdd = 0x3002a;
  227820. const int KeyPress::numberPadSubtract = 0x3002b;
  227821. const int KeyPress::numberPadMultiply = 0x3002c;
  227822. const int KeyPress::numberPadDivide = 0x3002d;
  227823. const int KeyPress::numberPadSeparator = 0x3002e;
  227824. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227825. const int KeyPress::numberPadEquals = 0x30030;
  227826. const int KeyPress::numberPadDelete = 0x30031;
  227827. const int KeyPress::playKey = 0x30000;
  227828. const int KeyPress::stopKey = 0x30001;
  227829. const int KeyPress::fastForwardKey = 0x30002;
  227830. const int KeyPress::rewindKey = 0x30003;
  227831. #endif
  227832. /*** End of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  227833. /*** Start of inlined file: juce_ios_MessageManager.mm ***/
  227834. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227835. // compiled on its own).
  227836. #if JUCE_INCLUDED_FILE
  227837. struct CallbackMessagePayload
  227838. {
  227839. MessageCallbackFunction* function;
  227840. void* parameter;
  227841. void* volatile result;
  227842. bool volatile hasBeenExecuted;
  227843. };
  227844. END_JUCE_NAMESPACE
  227845. @interface JuceCustomMessageHandler : NSObject
  227846. {
  227847. }
  227848. - (void) performCallback: (id) info;
  227849. @end
  227850. @implementation JuceCustomMessageHandler
  227851. - (void) performCallback: (id) info
  227852. {
  227853. if ([info isKindOfClass: [NSData class]])
  227854. {
  227855. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227856. if (pl != 0)
  227857. {
  227858. pl->result = (*pl->function) (pl->parameter);
  227859. pl->hasBeenExecuted = true;
  227860. }
  227861. }
  227862. else
  227863. {
  227864. jassertfalse; // should never get here!
  227865. }
  227866. }
  227867. @end
  227868. BEGIN_JUCE_NAMESPACE
  227869. void MessageManager::runDispatchLoop()
  227870. {
  227871. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227872. runDispatchLoopUntil (-1);
  227873. }
  227874. void MessageManager::stopDispatchLoop()
  227875. {
  227876. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227877. exit (0); // iPhone apps get no mercy..
  227878. }
  227879. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227880. {
  227881. const ScopedAutoReleasePool pool;
  227882. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227883. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227884. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227885. while (! quitMessagePosted)
  227886. {
  227887. const ScopedAutoReleasePool pool;
  227888. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227889. beforeDate: endDate];
  227890. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227891. break;
  227892. }
  227893. return ! quitMessagePosted;
  227894. }
  227895. struct MessageDispatchSystem
  227896. {
  227897. MessageDispatchSystem()
  227898. : juceCustomMessageHandler (0)
  227899. {
  227900. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227901. }
  227902. ~MessageDispatchSystem()
  227903. {
  227904. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227905. [juceCustomMessageHandler release];
  227906. }
  227907. JuceCustomMessageHandler* juceCustomMessageHandler;
  227908. MessageQueue messageQueue;
  227909. };
  227910. static MessageDispatchSystem* dispatcher = 0;
  227911. void MessageManager::doPlatformSpecificInitialisation()
  227912. {
  227913. if (dispatcher == 0)
  227914. dispatcher = new MessageDispatchSystem();
  227915. }
  227916. void MessageManager::doPlatformSpecificShutdown()
  227917. {
  227918. deleteAndZero (dispatcher);
  227919. }
  227920. bool juce_postMessageToSystemQueue (Message* message)
  227921. {
  227922. if (dispatcher != 0)
  227923. dispatcher->messageQueue.post (message);
  227924. return true;
  227925. }
  227926. void MessageManager::broadcastMessage (const String& value)
  227927. {
  227928. }
  227929. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227930. {
  227931. if (isThisTheMessageThread())
  227932. {
  227933. return (*callback) (data);
  227934. }
  227935. else
  227936. {
  227937. jassert (dispatcher != 0); // trying to call this when the juce system isn't initialised..
  227938. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227939. // deadlock because the message manager is blocked from running, so can never
  227940. // call your function..
  227941. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227942. const ScopedAutoReleasePool pool;
  227943. CallbackMessagePayload cmp;
  227944. cmp.function = callback;
  227945. cmp.parameter = data;
  227946. cmp.result = 0;
  227947. cmp.hasBeenExecuted = false;
  227948. [dispatcher->juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227949. withObject: [NSData dataWithBytesNoCopy: &cmp
  227950. length: sizeof (cmp)
  227951. freeWhenDone: NO]
  227952. waitUntilDone: YES];
  227953. return cmp.result;
  227954. }
  227955. }
  227956. #endif
  227957. /*** End of inlined file: juce_ios_MessageManager.mm ***/
  227958. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227959. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227960. // compiled on its own).
  227961. #if JUCE_INCLUDED_FILE
  227962. #if JUCE_MAC
  227963. END_JUCE_NAMESPACE
  227964. using namespace JUCE_NAMESPACE;
  227965. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227966. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227967. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227968. #else
  227969. @interface JuceFileChooserDelegate : NSObject
  227970. #endif
  227971. {
  227972. StringArray* filters;
  227973. }
  227974. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227975. - (void) dealloc;
  227976. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227977. @end
  227978. @implementation JuceFileChooserDelegate
  227979. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227980. {
  227981. [super init];
  227982. filters = filters_;
  227983. return self;
  227984. }
  227985. - (void) dealloc
  227986. {
  227987. delete filters;
  227988. [super dealloc];
  227989. }
  227990. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227991. {
  227992. (void) sender;
  227993. const File f (nsStringToJuce (filename));
  227994. for (int i = filters->size(); --i >= 0;)
  227995. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227996. return true;
  227997. return f.isDirectory();
  227998. }
  227999. @end
  228000. BEGIN_JUCE_NAMESPACE
  228001. void FileChooser::showPlatformDialog (Array<File>& results,
  228002. const String& title,
  228003. const File& currentFileOrDirectory,
  228004. const String& filter,
  228005. bool selectsDirectory,
  228006. bool selectsFiles,
  228007. bool isSaveDialogue,
  228008. bool /*warnAboutOverwritingExistingFiles*/,
  228009. bool selectMultipleFiles,
  228010. FilePreviewComponent* /*extraInfoComponent*/)
  228011. {
  228012. const ScopedAutoReleasePool pool;
  228013. StringArray* filters = new StringArray();
  228014. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228015. filters->trim();
  228016. filters->removeEmptyStrings();
  228017. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228018. [delegate autorelease];
  228019. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228020. : [NSOpenPanel openPanel];
  228021. [panel setTitle: juceStringToNS (title)];
  228022. if (! isSaveDialogue)
  228023. {
  228024. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228025. [openPanel setCanChooseDirectories: selectsDirectory];
  228026. [openPanel setCanChooseFiles: selectsFiles];
  228027. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228028. }
  228029. [panel setDelegate: delegate];
  228030. if (isSaveDialogue || selectsDirectory)
  228031. [panel setCanCreateDirectories: YES];
  228032. String directory, filename;
  228033. if (currentFileOrDirectory.isDirectory())
  228034. {
  228035. directory = currentFileOrDirectory.getFullPathName();
  228036. }
  228037. else
  228038. {
  228039. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228040. filename = currentFileOrDirectory.getFileName();
  228041. }
  228042. if ([panel runModalForDirectory: juceStringToNS (directory)
  228043. file: juceStringToNS (filename)]
  228044. == NSOKButton)
  228045. {
  228046. if (isSaveDialogue)
  228047. {
  228048. results.add (File (nsStringToJuce ([panel filename])));
  228049. }
  228050. else
  228051. {
  228052. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228053. NSArray* urls = [openPanel filenames];
  228054. for (unsigned int i = 0; i < [urls count]; ++i)
  228055. {
  228056. NSString* f = [urls objectAtIndex: i];
  228057. results.add (File (nsStringToJuce (f)));
  228058. }
  228059. }
  228060. }
  228061. [panel setDelegate: nil];
  228062. }
  228063. #else
  228064. void FileChooser::showPlatformDialog (Array<File>& results,
  228065. const String& title,
  228066. const File& currentFileOrDirectory,
  228067. const String& filter,
  228068. bool selectsDirectory,
  228069. bool selectsFiles,
  228070. bool isSaveDialogue,
  228071. bool warnAboutOverwritingExistingFiles,
  228072. bool selectMultipleFiles,
  228073. FilePreviewComponent* extraInfoComponent)
  228074. {
  228075. const ScopedAutoReleasePool pool;
  228076. jassertfalse; //xxx to do
  228077. }
  228078. #endif
  228079. #endif
  228080. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228081. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228082. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228083. // compiled on its own).
  228084. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228085. #if JUCE_MAC
  228086. END_JUCE_NAMESPACE
  228087. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228088. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228089. {
  228090. CriticalSection* contextLock;
  228091. bool needsUpdate;
  228092. }
  228093. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228094. - (bool) makeActive;
  228095. - (void) makeInactive;
  228096. - (void) reshape;
  228097. - (void) rightMouseDown: (NSEvent*) ev;
  228098. - (void) rightMouseUp: (NSEvent*) ev;
  228099. @end
  228100. @implementation ThreadSafeNSOpenGLView
  228101. - (id) initWithFrame: (NSRect) frameRect
  228102. pixelFormat: (NSOpenGLPixelFormat*) format
  228103. {
  228104. contextLock = new CriticalSection();
  228105. self = [super initWithFrame: frameRect pixelFormat: format];
  228106. if (self != nil)
  228107. [[NSNotificationCenter defaultCenter] addObserver: self
  228108. selector: @selector (_surfaceNeedsUpdate:)
  228109. name: NSViewGlobalFrameDidChangeNotification
  228110. object: self];
  228111. return self;
  228112. }
  228113. - (void) dealloc
  228114. {
  228115. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228116. delete contextLock;
  228117. [super dealloc];
  228118. }
  228119. - (bool) makeActive
  228120. {
  228121. const ScopedLock sl (*contextLock);
  228122. if ([self openGLContext] == 0)
  228123. return false;
  228124. [[self openGLContext] makeCurrentContext];
  228125. if (needsUpdate)
  228126. {
  228127. [super update];
  228128. needsUpdate = false;
  228129. }
  228130. return true;
  228131. }
  228132. - (void) makeInactive
  228133. {
  228134. const ScopedLock sl (*contextLock);
  228135. [NSOpenGLContext clearCurrentContext];
  228136. }
  228137. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228138. {
  228139. (void) notification;
  228140. const ScopedLock sl (*contextLock);
  228141. needsUpdate = true;
  228142. }
  228143. - (void) update
  228144. {
  228145. const ScopedLock sl (*contextLock);
  228146. needsUpdate = true;
  228147. }
  228148. - (void) reshape
  228149. {
  228150. const ScopedLock sl (*contextLock);
  228151. needsUpdate = true;
  228152. }
  228153. - (void) rightMouseDown: (NSEvent*) ev
  228154. {
  228155. [[self superview] rightMouseDown: ev];
  228156. }
  228157. - (void) rightMouseUp: (NSEvent*) ev
  228158. {
  228159. [[self superview] rightMouseUp: ev];
  228160. }
  228161. @end
  228162. BEGIN_JUCE_NAMESPACE
  228163. class WindowedGLContext : public OpenGLContext
  228164. {
  228165. public:
  228166. WindowedGLContext (Component& component,
  228167. const OpenGLPixelFormat& pixelFormat_,
  228168. NSOpenGLContext* sharedContext)
  228169. : renderContext (0),
  228170. pixelFormat (pixelFormat_)
  228171. {
  228172. NSOpenGLPixelFormatAttribute attribs[] =
  228173. {
  228174. NSOpenGLPFADoubleBuffer,
  228175. NSOpenGLPFAAccelerated,
  228176. NSOpenGLPFAMPSafe,
  228177. NSOpenGLPFAClosestPolicy,
  228178. NSOpenGLPFANoRecovery,
  228179. NSOpenGLPFAColorSize, (NSOpenGLPixelFormatAttribute) (pixelFormat.redBits
  228180. + pixelFormat.greenBits
  228181. + pixelFormat.blueBits),
  228182. NSOpenGLPFAAlphaSize, (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits,
  228183. NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits,
  228184. NSOpenGLPFAStencilSize, (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits,
  228185. NSOpenGLPFAAccumSize, (NSOpenGLPixelFormatAttribute) (pixelFormat.accumulationBufferRedBits
  228186. + pixelFormat.accumulationBufferGreenBits
  228187. + pixelFormat.accumulationBufferBlueBits
  228188. + pixelFormat.accumulationBufferAlphaBits),
  228189. NSOpenGLPFASampleBuffers, (NSOpenGLPixelFormatAttribute) 1,
  228190. 0
  228191. };
  228192. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228193. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228194. pixelFormat: format];
  228195. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228196. shareContext: sharedContext] autorelease];
  228197. const GLint swapInterval = 1;
  228198. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228199. [view setOpenGLContext: renderContext];
  228200. [format release];
  228201. viewHolder = new NSViewComponentInternal (view, component);
  228202. }
  228203. ~WindowedGLContext()
  228204. {
  228205. deleteContext();
  228206. viewHolder = 0;
  228207. }
  228208. void deleteContext()
  228209. {
  228210. makeInactive();
  228211. [renderContext clearDrawable];
  228212. [renderContext setView: nil];
  228213. [view setOpenGLContext: nil];
  228214. renderContext = nil;
  228215. }
  228216. bool makeActive() const throw()
  228217. {
  228218. jassert (renderContext != 0);
  228219. if ([renderContext view] != view)
  228220. [renderContext setView: view];
  228221. [view makeActive];
  228222. return isActive();
  228223. }
  228224. bool makeInactive() const throw()
  228225. {
  228226. [view makeInactive];
  228227. return true;
  228228. }
  228229. bool isActive() const throw()
  228230. {
  228231. return [NSOpenGLContext currentContext] == renderContext;
  228232. }
  228233. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228234. void* getRawContext() const throw() { return renderContext; }
  228235. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  228236. {
  228237. }
  228238. void swapBuffers()
  228239. {
  228240. [renderContext flushBuffer];
  228241. }
  228242. bool setSwapInterval (const int numFramesPerSwap)
  228243. {
  228244. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228245. forParameter: NSOpenGLCPSwapInterval];
  228246. return true;
  228247. }
  228248. int getSwapInterval() const
  228249. {
  228250. GLint numFrames = 0;
  228251. [renderContext getValues: &numFrames
  228252. forParameter: NSOpenGLCPSwapInterval];
  228253. return numFrames;
  228254. }
  228255. void repaint()
  228256. {
  228257. // we need to invalidate the juce view that holds this gl view, to make it
  228258. // cause a repaint callback
  228259. NSView* v = (NSView*) viewHolder->view;
  228260. NSRect r = [v frame];
  228261. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228262. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228263. // repaint message, thus never causing our paint() callback, and never repainting
  228264. // the comp. So invalidating just a little bit around the edge helps..
  228265. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228266. }
  228267. void* getNativeWindowHandle() const { return viewHolder->view; }
  228268. NSOpenGLContext* renderContext;
  228269. ThreadSafeNSOpenGLView* view;
  228270. private:
  228271. OpenGLPixelFormat pixelFormat;
  228272. ScopedPointer <NSViewComponentInternal> viewHolder;
  228273. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  228274. };
  228275. OpenGLContext* OpenGLComponent::createContext()
  228276. {
  228277. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  228278. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228279. return (c->renderContext != 0) ? c.release() : 0;
  228280. }
  228281. void* OpenGLComponent::getNativeWindowHandle() const
  228282. {
  228283. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228284. : 0;
  228285. }
  228286. void juce_glViewport (const int w, const int h)
  228287. {
  228288. glViewport (0, 0, w, h);
  228289. }
  228290. static int getPixelFormatAttribute (NSOpenGLPixelFormat* p, NSOpenGLPixelFormatAttribute att)
  228291. {
  228292. GLint val = 0;
  228293. [p getValues: &val forAttribute: att forVirtualScreen: 0];
  228294. return (int) val;
  228295. }
  228296. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228297. OwnedArray <OpenGLPixelFormat>& results)
  228298. {
  228299. NSOpenGLPixelFormatAttribute attributes[] =
  228300. {
  228301. NSOpenGLPFAWindow,
  228302. NSOpenGLPFADoubleBuffer,
  228303. NSOpenGLPFAAccelerated,
  228304. NSOpenGLPFANoRecovery,
  228305. NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute) 16,
  228306. NSOpenGLPFAAlphaSize, (NSOpenGLPixelFormatAttribute) 8,
  228307. NSOpenGLPFAColorSize, (NSOpenGLPixelFormatAttribute) 24,
  228308. NSOpenGLPFAAccumSize, (NSOpenGLPixelFormatAttribute) 32,
  228309. 0
  228310. };
  228311. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes: attributes];
  228312. if (format != nil)
  228313. {
  228314. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228315. pf->redBits = pf->greenBits = pf->blueBits = getPixelFormatAttribute (format, NSOpenGLPFAColorSize) / 3;
  228316. pf->alphaBits = getPixelFormatAttribute (format, NSOpenGLPFAAlphaSize);
  228317. pf->depthBufferBits = getPixelFormatAttribute (format, NSOpenGLPFADepthSize);
  228318. pf->stencilBufferBits = getPixelFormatAttribute (format, NSOpenGLPFAStencilSize);
  228319. pf->accumulationBufferRedBits = pf->accumulationBufferGreenBits
  228320. = pf->accumulationBufferBlueBits = pf->accumulationBufferAlphaBits
  228321. = getPixelFormatAttribute (format, NSOpenGLPFAAccumSize) / 4;
  228322. [format release];
  228323. results.add (pf);
  228324. }
  228325. }
  228326. #else
  228327. END_JUCE_NAMESPACE
  228328. @interface JuceGLView : UIView
  228329. {
  228330. }
  228331. + (Class) layerClass;
  228332. @end
  228333. @implementation JuceGLView
  228334. + (Class) layerClass
  228335. {
  228336. return [CAEAGLLayer class];
  228337. }
  228338. @end
  228339. BEGIN_JUCE_NAMESPACE
  228340. class GLESContext : public OpenGLContext
  228341. {
  228342. public:
  228343. GLESContext (UIViewComponentPeer* peer,
  228344. Component* const component_,
  228345. const OpenGLPixelFormat& pixelFormat_,
  228346. const GLESContext* const sharedContext,
  228347. NSUInteger apiType)
  228348. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228349. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228350. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228351. {
  228352. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228353. view.opaque = YES;
  228354. view.hidden = NO;
  228355. view.backgroundColor = [UIColor blackColor];
  228356. view.userInteractionEnabled = NO;
  228357. glLayer = (CAEAGLLayer*) [view layer];
  228358. [peer->view addSubview: view];
  228359. if (sharedContext != 0)
  228360. context = [[EAGLContext alloc] initWithAPI: apiType
  228361. sharegroup: [sharedContext->context sharegroup]];
  228362. else
  228363. context = [[EAGLContext alloc] initWithAPI: apiType];
  228364. createGLBuffers();
  228365. }
  228366. ~GLESContext()
  228367. {
  228368. deleteContext();
  228369. [view removeFromSuperview];
  228370. [view release];
  228371. freeGLBuffers();
  228372. }
  228373. void deleteContext()
  228374. {
  228375. makeInactive();
  228376. [context release];
  228377. context = nil;
  228378. }
  228379. bool makeActive() const throw()
  228380. {
  228381. jassert (context != 0);
  228382. [EAGLContext setCurrentContext: context];
  228383. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228384. return true;
  228385. }
  228386. void swapBuffers()
  228387. {
  228388. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228389. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228390. }
  228391. bool makeInactive() const throw()
  228392. {
  228393. return [EAGLContext setCurrentContext: nil];
  228394. }
  228395. bool isActive() const throw()
  228396. {
  228397. return [EAGLContext currentContext] == context;
  228398. }
  228399. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228400. void* getRawContext() const throw() { return glLayer; }
  228401. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228402. {
  228403. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228404. if (lastWidth != w || lastHeight != h)
  228405. {
  228406. lastWidth = w;
  228407. lastHeight = h;
  228408. freeGLBuffers();
  228409. createGLBuffers();
  228410. }
  228411. }
  228412. bool setSwapInterval (const int numFramesPerSwap)
  228413. {
  228414. numFrames = numFramesPerSwap;
  228415. return true;
  228416. }
  228417. int getSwapInterval() const
  228418. {
  228419. return numFrames;
  228420. }
  228421. void repaint()
  228422. {
  228423. }
  228424. void createGLBuffers()
  228425. {
  228426. makeActive();
  228427. glGenFramebuffersOES (1, &frameBufferHandle);
  228428. glGenRenderbuffersOES (1, &colorBufferHandle);
  228429. glGenRenderbuffersOES (1, &depthBufferHandle);
  228430. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228431. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228432. GLint width, height;
  228433. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228434. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228435. if (useDepthBuffer)
  228436. {
  228437. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228438. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228439. }
  228440. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228441. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228442. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228443. if (useDepthBuffer)
  228444. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228445. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228446. }
  228447. void freeGLBuffers()
  228448. {
  228449. if (frameBufferHandle != 0)
  228450. {
  228451. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228452. frameBufferHandle = 0;
  228453. }
  228454. if (colorBufferHandle != 0)
  228455. {
  228456. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228457. colorBufferHandle = 0;
  228458. }
  228459. if (depthBufferHandle != 0)
  228460. {
  228461. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228462. depthBufferHandle = 0;
  228463. }
  228464. }
  228465. private:
  228466. WeakReference<Component> component;
  228467. OpenGLPixelFormat pixelFormat;
  228468. JuceGLView* view;
  228469. CAEAGLLayer* glLayer;
  228470. EAGLContext* context;
  228471. bool useDepthBuffer;
  228472. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228473. int numFrames;
  228474. int lastWidth, lastHeight;
  228475. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  228476. };
  228477. OpenGLContext* OpenGLComponent::createContext()
  228478. {
  228479. ScopedAutoReleasePool pool;
  228480. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228481. if (peer != 0)
  228482. return new GLESContext (peer, this, preferredPixelFormat,
  228483. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228484. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228485. return 0;
  228486. }
  228487. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228488. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228489. {
  228490. }
  228491. void juce_glViewport (const int w, const int h)
  228492. {
  228493. glViewport (0, 0, w, h);
  228494. }
  228495. #endif
  228496. #endif
  228497. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228498. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228499. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228500. // compiled on its own).
  228501. #if JUCE_INCLUDED_FILE
  228502. #if JUCE_MAC
  228503. namespace MouseCursorHelpers
  228504. {
  228505. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228506. {
  228507. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228508. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228509. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228510. [im release];
  228511. return c;
  228512. }
  228513. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228514. {
  228515. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228516. BufferedInputStream buf (fileStream, 4096);
  228517. PNGImageFormat pngFormat;
  228518. Image im (pngFormat.decodeImage (buf));
  228519. if (im.isValid())
  228520. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228521. jassertfalse;
  228522. return 0;
  228523. }
  228524. }
  228525. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228526. {
  228527. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228528. }
  228529. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228530. {
  228531. const ScopedAutoReleasePool pool;
  228532. NSCursor* c = 0;
  228533. switch (type)
  228534. {
  228535. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228536. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228537. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228538. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228539. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228540. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228541. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228542. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228543. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228544. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228545. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228546. case UpDownResizeCursor:
  228547. case TopEdgeResizeCursor:
  228548. case BottomEdgeResizeCursor:
  228549. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228550. case TopLeftCornerResizeCursor:
  228551. case BottomRightCornerResizeCursor:
  228552. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228553. case TopRightCornerResizeCursor:
  228554. case BottomLeftCornerResizeCursor:
  228555. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228556. case UpDownLeftRightResizeCursor:
  228557. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228558. default:
  228559. jassertfalse;
  228560. break;
  228561. }
  228562. [c retain];
  228563. return c;
  228564. }
  228565. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228566. {
  228567. [((NSCursor*) cursorHandle) release];
  228568. }
  228569. void MouseCursor::showInAllWindows() const
  228570. {
  228571. showInWindow (0);
  228572. }
  228573. void MouseCursor::showInWindow (ComponentPeer*) const
  228574. {
  228575. NSCursor* c = (NSCursor*) getHandle();
  228576. if (c == 0)
  228577. c = [NSCursor arrowCursor];
  228578. [c set];
  228579. }
  228580. #else
  228581. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228582. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228583. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228584. void MouseCursor::showInAllWindows() const {}
  228585. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228586. #endif
  228587. #endif
  228588. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228589. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228590. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228591. // compiled on its own).
  228592. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228593. #if JUCE_MAC
  228594. END_JUCE_NAMESPACE
  228595. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228596. @interface DownloadClickDetector : NSObject
  228597. {
  228598. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228599. }
  228600. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228601. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228602. request: (NSURLRequest*) request
  228603. frame: (WebFrame*) frame
  228604. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228605. @end
  228606. @implementation DownloadClickDetector
  228607. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228608. {
  228609. [super init];
  228610. ownerComponent = ownerComponent_;
  228611. return self;
  228612. }
  228613. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228614. request: (NSURLRequest*) request
  228615. frame: (WebFrame*) frame
  228616. decisionListener: (id <WebPolicyDecisionListener>) listener
  228617. {
  228618. (void) sender;
  228619. (void) request;
  228620. (void) frame;
  228621. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228622. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228623. [listener use];
  228624. else
  228625. [listener ignore];
  228626. }
  228627. @end
  228628. BEGIN_JUCE_NAMESPACE
  228629. class WebBrowserComponentInternal : public NSViewComponent
  228630. {
  228631. public:
  228632. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228633. {
  228634. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228635. frameName: @""
  228636. groupName: @""];
  228637. setView (webView);
  228638. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228639. [webView setPolicyDelegate: clickListener];
  228640. }
  228641. ~WebBrowserComponentInternal()
  228642. {
  228643. [webView setPolicyDelegate: nil];
  228644. [clickListener release];
  228645. setView (0);
  228646. }
  228647. void goToURL (const String& url,
  228648. const StringArray* headers,
  228649. const MemoryBlock* postData)
  228650. {
  228651. NSMutableURLRequest* r
  228652. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228653. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228654. timeoutInterval: 30.0];
  228655. if (postData != 0 && postData->getSize() > 0)
  228656. {
  228657. [r setHTTPMethod: @"POST"];
  228658. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228659. length: postData->getSize()]];
  228660. }
  228661. if (headers != 0)
  228662. {
  228663. for (int i = 0; i < headers->size(); ++i)
  228664. {
  228665. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228666. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228667. [r setValue: juceStringToNS (headerValue)
  228668. forHTTPHeaderField: juceStringToNS (headerName)];
  228669. }
  228670. }
  228671. stop();
  228672. [[webView mainFrame] loadRequest: r];
  228673. }
  228674. void goBack()
  228675. {
  228676. [webView goBack];
  228677. }
  228678. void goForward()
  228679. {
  228680. [webView goForward];
  228681. }
  228682. void stop()
  228683. {
  228684. [webView stopLoading: nil];
  228685. }
  228686. void refresh()
  228687. {
  228688. [webView reload: nil];
  228689. }
  228690. void mouseMove (const MouseEvent&)
  228691. {
  228692. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228693. // them work is to push them via this non-public method..
  228694. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228695. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228696. }
  228697. private:
  228698. WebView* webView;
  228699. DownloadClickDetector* clickListener;
  228700. };
  228701. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228702. : browser (0),
  228703. blankPageShown (false),
  228704. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228705. {
  228706. setOpaque (true);
  228707. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228708. }
  228709. WebBrowserComponent::~WebBrowserComponent()
  228710. {
  228711. deleteAndZero (browser);
  228712. }
  228713. void WebBrowserComponent::goToURL (const String& url,
  228714. const StringArray* headers,
  228715. const MemoryBlock* postData)
  228716. {
  228717. lastURL = url;
  228718. lastHeaders.clear();
  228719. if (headers != 0)
  228720. lastHeaders = *headers;
  228721. lastPostData.setSize (0);
  228722. if (postData != 0)
  228723. lastPostData = *postData;
  228724. blankPageShown = false;
  228725. browser->goToURL (url, headers, postData);
  228726. }
  228727. void WebBrowserComponent::stop()
  228728. {
  228729. browser->stop();
  228730. }
  228731. void WebBrowserComponent::goBack()
  228732. {
  228733. lastURL = String::empty;
  228734. blankPageShown = false;
  228735. browser->goBack();
  228736. }
  228737. void WebBrowserComponent::goForward()
  228738. {
  228739. lastURL = String::empty;
  228740. browser->goForward();
  228741. }
  228742. void WebBrowserComponent::refresh()
  228743. {
  228744. browser->refresh();
  228745. }
  228746. void WebBrowserComponent::paint (Graphics&)
  228747. {
  228748. }
  228749. void WebBrowserComponent::checkWindowAssociation()
  228750. {
  228751. if (isShowing())
  228752. {
  228753. if (blankPageShown)
  228754. goBack();
  228755. }
  228756. else
  228757. {
  228758. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228759. {
  228760. // when the component becomes invisible, some stuff like flash
  228761. // carries on playing audio, so we need to force it onto a blank
  228762. // page to avoid this, (and send it back when it's made visible again).
  228763. blankPageShown = true;
  228764. browser->goToURL ("about:blank", 0, 0);
  228765. }
  228766. }
  228767. }
  228768. void WebBrowserComponent::reloadLastURL()
  228769. {
  228770. if (lastURL.isNotEmpty())
  228771. {
  228772. goToURL (lastURL, &lastHeaders, &lastPostData);
  228773. lastURL = String::empty;
  228774. }
  228775. }
  228776. void WebBrowserComponent::parentHierarchyChanged()
  228777. {
  228778. checkWindowAssociation();
  228779. }
  228780. void WebBrowserComponent::resized()
  228781. {
  228782. browser->setSize (getWidth(), getHeight());
  228783. }
  228784. void WebBrowserComponent::visibilityChanged()
  228785. {
  228786. checkWindowAssociation();
  228787. }
  228788. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228789. {
  228790. return true;
  228791. }
  228792. #else
  228793. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228794. {
  228795. }
  228796. WebBrowserComponent::~WebBrowserComponent()
  228797. {
  228798. }
  228799. void WebBrowserComponent::goToURL (const String& url,
  228800. const StringArray* headers,
  228801. const MemoryBlock* postData)
  228802. {
  228803. }
  228804. void WebBrowserComponent::stop()
  228805. {
  228806. }
  228807. void WebBrowserComponent::goBack()
  228808. {
  228809. }
  228810. void WebBrowserComponent::goForward()
  228811. {
  228812. }
  228813. void WebBrowserComponent::refresh()
  228814. {
  228815. }
  228816. void WebBrowserComponent::paint (Graphics& g)
  228817. {
  228818. }
  228819. void WebBrowserComponent::checkWindowAssociation()
  228820. {
  228821. }
  228822. void WebBrowserComponent::reloadLastURL()
  228823. {
  228824. }
  228825. void WebBrowserComponent::parentHierarchyChanged()
  228826. {
  228827. }
  228828. void WebBrowserComponent::resized()
  228829. {
  228830. }
  228831. void WebBrowserComponent::visibilityChanged()
  228832. {
  228833. }
  228834. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228835. {
  228836. return true;
  228837. }
  228838. #endif
  228839. #endif
  228840. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228841. /*** Start of inlined file: juce_ios_Audio.cpp ***/
  228842. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228843. // compiled on its own).
  228844. #if JUCE_INCLUDED_FILE
  228845. class IPhoneAudioIODevice : public AudioIODevice
  228846. {
  228847. public:
  228848. IPhoneAudioIODevice (const String& deviceName)
  228849. : AudioIODevice (deviceName, "Audio"),
  228850. actualBufferSize (0),
  228851. isRunning (false),
  228852. audioUnit (0),
  228853. callback (0),
  228854. floatData (1, 2)
  228855. {
  228856. numInputChannels = 2;
  228857. numOutputChannels = 2;
  228858. preferredBufferSize = 0;
  228859. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228860. updateDeviceInfo();
  228861. }
  228862. ~IPhoneAudioIODevice()
  228863. {
  228864. close();
  228865. }
  228866. const StringArray getOutputChannelNames()
  228867. {
  228868. StringArray s;
  228869. s.add ("Left");
  228870. s.add ("Right");
  228871. return s;
  228872. }
  228873. const StringArray getInputChannelNames()
  228874. {
  228875. StringArray s;
  228876. if (audioInputIsAvailable)
  228877. {
  228878. s.add ("Left");
  228879. s.add ("Right");
  228880. }
  228881. return s;
  228882. }
  228883. int getNumSampleRates()
  228884. {
  228885. return 1;
  228886. }
  228887. double getSampleRate (int index)
  228888. {
  228889. return sampleRate;
  228890. }
  228891. int getNumBufferSizesAvailable()
  228892. {
  228893. return 1;
  228894. }
  228895. int getBufferSizeSamples (int index)
  228896. {
  228897. return getDefaultBufferSize();
  228898. }
  228899. int getDefaultBufferSize()
  228900. {
  228901. return 1024;
  228902. }
  228903. const String open (const BigInteger& inputChannels,
  228904. const BigInteger& outputChannels,
  228905. double sampleRate,
  228906. int bufferSize)
  228907. {
  228908. close();
  228909. lastError = String::empty;
  228910. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228911. // xxx set up channel mapping
  228912. activeOutputChans = outputChannels;
  228913. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228914. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228915. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228916. activeInputChans = inputChannels;
  228917. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228918. numInputChannels = activeInputChans.countNumberOfSetBits();
  228919. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228920. AudioSessionSetActive (true);
  228921. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228922. : kAudioSessionCategory_MediaPlayback;
  228923. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228924. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228925. fixAudioRouteIfSetToReceiver();
  228926. updateDeviceInfo();
  228927. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228928. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228929. actualBufferSize = preferredBufferSize;
  228930. prepareFloatBuffers();
  228931. isRunning = true;
  228932. propertyChanged (0, 0, 0); // creates and starts the AU
  228933. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228934. return lastError;
  228935. }
  228936. void close()
  228937. {
  228938. if (isRunning)
  228939. {
  228940. isRunning = false;
  228941. AudioSessionSetActive (false);
  228942. if (audioUnit != 0)
  228943. {
  228944. AudioComponentInstanceDispose (audioUnit);
  228945. audioUnit = 0;
  228946. }
  228947. }
  228948. }
  228949. bool isOpen()
  228950. {
  228951. return isRunning;
  228952. }
  228953. int getCurrentBufferSizeSamples()
  228954. {
  228955. return actualBufferSize;
  228956. }
  228957. double getCurrentSampleRate()
  228958. {
  228959. return sampleRate;
  228960. }
  228961. int getCurrentBitDepth()
  228962. {
  228963. return 16;
  228964. }
  228965. const BigInteger getActiveOutputChannels() const
  228966. {
  228967. return activeOutputChans;
  228968. }
  228969. const BigInteger getActiveInputChannels() const
  228970. {
  228971. return activeInputChans;
  228972. }
  228973. int getOutputLatencyInSamples()
  228974. {
  228975. return 0; //xxx
  228976. }
  228977. int getInputLatencyInSamples()
  228978. {
  228979. return 0; //xxx
  228980. }
  228981. void start (AudioIODeviceCallback* callback_)
  228982. {
  228983. if (isRunning && callback != callback_)
  228984. {
  228985. if (callback_ != 0)
  228986. callback_->audioDeviceAboutToStart (this);
  228987. const ScopedLock sl (callbackLock);
  228988. callback = callback_;
  228989. }
  228990. }
  228991. void stop()
  228992. {
  228993. if (isRunning)
  228994. {
  228995. AudioIODeviceCallback* lastCallback;
  228996. {
  228997. const ScopedLock sl (callbackLock);
  228998. lastCallback = callback;
  228999. callback = 0;
  229000. }
  229001. if (lastCallback != 0)
  229002. lastCallback->audioDeviceStopped();
  229003. }
  229004. }
  229005. bool isPlaying()
  229006. {
  229007. return isRunning && callback != 0;
  229008. }
  229009. const String getLastError()
  229010. {
  229011. return lastError;
  229012. }
  229013. private:
  229014. CriticalSection callbackLock;
  229015. Float64 sampleRate;
  229016. int numInputChannels, numOutputChannels;
  229017. int preferredBufferSize;
  229018. int actualBufferSize;
  229019. bool isRunning;
  229020. String lastError;
  229021. AudioStreamBasicDescription format;
  229022. AudioUnit audioUnit;
  229023. UInt32 audioInputIsAvailable;
  229024. AudioIODeviceCallback* callback;
  229025. BigInteger activeOutputChans, activeInputChans;
  229026. AudioSampleBuffer floatData;
  229027. float* inputChannels[3];
  229028. float* outputChannels[3];
  229029. bool monoInputChannelNumber, monoOutputChannelNumber;
  229030. void prepareFloatBuffers()
  229031. {
  229032. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229033. zerostruct (inputChannels);
  229034. zerostruct (outputChannels);
  229035. for (int i = 0; i < numInputChannels; ++i)
  229036. inputChannels[i] = floatData.getSampleData (i);
  229037. for (int i = 0; i < numOutputChannels; ++i)
  229038. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229039. }
  229040. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229041. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229042. {
  229043. OSStatus err = noErr;
  229044. if (audioInputIsAvailable)
  229045. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229046. const ScopedLock sl (callbackLock);
  229047. if (callback != 0)
  229048. {
  229049. if (audioInputIsAvailable && numInputChannels > 0)
  229050. {
  229051. short* shortData = (short*) ioData->mBuffers[0].mData;
  229052. if (numInputChannels >= 2)
  229053. {
  229054. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229055. {
  229056. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229057. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229058. }
  229059. }
  229060. else
  229061. {
  229062. if (monoInputChannelNumber > 0)
  229063. ++shortData;
  229064. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229065. {
  229066. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229067. ++shortData;
  229068. }
  229069. }
  229070. }
  229071. else
  229072. {
  229073. for (int i = numInputChannels; --i >= 0;)
  229074. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229075. }
  229076. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229077. outputChannels, numOutputChannels,
  229078. (int) inNumberFrames);
  229079. short* shortData = (short*) ioData->mBuffers[0].mData;
  229080. int n = 0;
  229081. if (numOutputChannels >= 2)
  229082. {
  229083. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229084. {
  229085. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229086. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229087. }
  229088. }
  229089. else if (numOutputChannels == 1)
  229090. {
  229091. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229092. {
  229093. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229094. shortData [n++] = s;
  229095. shortData [n++] = s;
  229096. }
  229097. }
  229098. else
  229099. {
  229100. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229101. }
  229102. }
  229103. else
  229104. {
  229105. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229106. }
  229107. return err;
  229108. }
  229109. void updateDeviceInfo()
  229110. {
  229111. UInt32 size = sizeof (sampleRate);
  229112. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229113. size = sizeof (audioInputIsAvailable);
  229114. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229115. }
  229116. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229117. {
  229118. if (! isRunning)
  229119. return;
  229120. if (inPropertyValue != 0)
  229121. {
  229122. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229123. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229124. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229125. SInt32 routeChangeReason;
  229126. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229127. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229128. fixAudioRouteIfSetToReceiver();
  229129. }
  229130. updateDeviceInfo();
  229131. createAudioUnit();
  229132. AudioSessionSetActive (true);
  229133. if (audioUnit != 0)
  229134. {
  229135. UInt32 formatSize = sizeof (format);
  229136. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229137. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229138. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229139. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229140. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229141. AudioOutputUnitStart (audioUnit);
  229142. }
  229143. }
  229144. void interruptionListener (UInt32 inInterruption)
  229145. {
  229146. /*if (inInterruption == kAudioSessionBeginInterruption)
  229147. {
  229148. isRunning = false;
  229149. AudioOutputUnitStop (audioUnit);
  229150. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229151. "This could have been interrupted by another application or by unplugging a headset",
  229152. @"Resume",
  229153. @"Cancel"))
  229154. {
  229155. isRunning = true;
  229156. propertyChanged (0, 0, 0);
  229157. }
  229158. }*/
  229159. if (inInterruption == kAudioSessionEndInterruption)
  229160. {
  229161. isRunning = true;
  229162. AudioSessionSetActive (true);
  229163. AudioOutputUnitStart (audioUnit);
  229164. }
  229165. }
  229166. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229167. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229168. {
  229169. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229170. }
  229171. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229172. {
  229173. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229174. }
  229175. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229176. {
  229177. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229178. }
  229179. void resetFormat (const int numChannels)
  229180. {
  229181. memset (&format, 0, sizeof (format));
  229182. format.mFormatID = kAudioFormatLinearPCM;
  229183. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229184. format.mBitsPerChannel = 8 * sizeof (short);
  229185. format.mChannelsPerFrame = 2;
  229186. format.mFramesPerPacket = 1;
  229187. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229188. }
  229189. bool createAudioUnit()
  229190. {
  229191. if (audioUnit != 0)
  229192. {
  229193. AudioComponentInstanceDispose (audioUnit);
  229194. audioUnit = 0;
  229195. }
  229196. resetFormat (2);
  229197. AudioComponentDescription desc;
  229198. desc.componentType = kAudioUnitType_Output;
  229199. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229200. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229201. desc.componentFlags = 0;
  229202. desc.componentFlagsMask = 0;
  229203. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229204. AudioComponentInstanceNew (comp, &audioUnit);
  229205. if (audioUnit == 0)
  229206. return false;
  229207. const UInt32 one = 1;
  229208. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229209. AudioChannelLayout layout;
  229210. layout.mChannelBitmap = 0;
  229211. layout.mNumberChannelDescriptions = 0;
  229212. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229213. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229214. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229215. AURenderCallbackStruct inputProc;
  229216. inputProc.inputProc = processStatic;
  229217. inputProc.inputProcRefCon = this;
  229218. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229219. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229220. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229221. AudioUnitInitialize (audioUnit);
  229222. return true;
  229223. }
  229224. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229225. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229226. static void fixAudioRouteIfSetToReceiver()
  229227. {
  229228. CFStringRef audioRoute = 0;
  229229. UInt32 propertySize = sizeof (audioRoute);
  229230. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229231. {
  229232. NSString* route = (NSString*) audioRoute;
  229233. //DBG ("audio route: " + nsStringToJuce (route));
  229234. if ([route hasPrefix: @"Receiver"])
  229235. {
  229236. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229237. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229238. }
  229239. CFRelease (audioRoute);
  229240. }
  229241. }
  229242. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  229243. };
  229244. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229245. {
  229246. public:
  229247. IPhoneAudioIODeviceType()
  229248. : AudioIODeviceType ("iPhone Audio")
  229249. {
  229250. }
  229251. void scanForDevices()
  229252. {
  229253. }
  229254. const StringArray getDeviceNames (bool wantInputNames) const
  229255. {
  229256. StringArray s;
  229257. s.add ("iPhone Audio");
  229258. return s;
  229259. }
  229260. int getDefaultDeviceIndex (bool forInput) const
  229261. {
  229262. return 0;
  229263. }
  229264. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229265. {
  229266. return device != 0 ? 0 : -1;
  229267. }
  229268. bool hasSeparateInputsAndOutputs() const { return false; }
  229269. AudioIODevice* createDevice (const String& outputDeviceName,
  229270. const String& inputDeviceName)
  229271. {
  229272. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229273. {
  229274. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229275. : inputDeviceName);
  229276. }
  229277. return 0;
  229278. }
  229279. private:
  229280. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  229281. };
  229282. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio()
  229283. {
  229284. return new IPhoneAudioIODeviceType();
  229285. }
  229286. #endif
  229287. /*** End of inlined file: juce_ios_Audio.cpp ***/
  229288. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229289. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229290. // compiled on its own).
  229291. #if JUCE_INCLUDED_FILE
  229292. #if JUCE_MAC
  229293. namespace CoreMidiHelpers
  229294. {
  229295. bool logError (const OSStatus err, const int lineNum)
  229296. {
  229297. if (err == noErr)
  229298. return true;
  229299. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229300. jassertfalse;
  229301. return false;
  229302. }
  229303. #undef CHECK_ERROR
  229304. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229305. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229306. {
  229307. String result;
  229308. CFStringRef str = 0;
  229309. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229310. if (str != 0)
  229311. {
  229312. result = PlatformUtilities::cfStringToJuceString (str);
  229313. CFRelease (str);
  229314. str = 0;
  229315. }
  229316. MIDIEntityRef entity = 0;
  229317. MIDIEndpointGetEntity (endpoint, &entity);
  229318. if (entity == 0)
  229319. return result; // probably virtual
  229320. if (result.isEmpty())
  229321. {
  229322. // endpoint name has zero length - try the entity
  229323. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229324. if (str != 0)
  229325. {
  229326. result += PlatformUtilities::cfStringToJuceString (str);
  229327. CFRelease (str);
  229328. str = 0;
  229329. }
  229330. }
  229331. // now consider the device's name
  229332. MIDIDeviceRef device = 0;
  229333. MIDIEntityGetDevice (entity, &device);
  229334. if (device == 0)
  229335. return result;
  229336. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229337. if (str != 0)
  229338. {
  229339. const String s (PlatformUtilities::cfStringToJuceString (str));
  229340. CFRelease (str);
  229341. // if an external device has only one entity, throw away
  229342. // the endpoint name and just use the device name
  229343. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229344. {
  229345. result = s;
  229346. }
  229347. else if (! result.startsWithIgnoreCase (s))
  229348. {
  229349. // prepend the device name to the entity name
  229350. result = (s + " " + result).trimEnd();
  229351. }
  229352. }
  229353. return result;
  229354. }
  229355. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229356. {
  229357. String result;
  229358. // Does the endpoint have connections?
  229359. CFDataRef connections = 0;
  229360. int numConnections = 0;
  229361. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229362. if (connections != 0)
  229363. {
  229364. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229365. if (numConnections > 0)
  229366. {
  229367. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229368. for (int i = 0; i < numConnections; ++i, ++pid)
  229369. {
  229370. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229371. MIDIObjectRef connObject;
  229372. MIDIObjectType connObjectType;
  229373. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229374. if (err == noErr)
  229375. {
  229376. String s;
  229377. if (connObjectType == kMIDIObjectType_ExternalSource
  229378. || connObjectType == kMIDIObjectType_ExternalDestination)
  229379. {
  229380. // Connected to an external device's endpoint (10.3 and later).
  229381. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229382. }
  229383. else
  229384. {
  229385. // Connected to an external device (10.2) (or something else, catch-all)
  229386. CFStringRef str = 0;
  229387. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229388. if (str != 0)
  229389. {
  229390. s = PlatformUtilities::cfStringToJuceString (str);
  229391. CFRelease (str);
  229392. }
  229393. }
  229394. if (s.isNotEmpty())
  229395. {
  229396. if (result.isNotEmpty())
  229397. result += ", ";
  229398. result += s;
  229399. }
  229400. }
  229401. }
  229402. }
  229403. CFRelease (connections);
  229404. }
  229405. if (result.isNotEmpty())
  229406. return result;
  229407. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229408. return getEndpointName (endpoint, false);
  229409. }
  229410. MIDIClientRef getGlobalMidiClient()
  229411. {
  229412. static MIDIClientRef globalMidiClient = 0;
  229413. if (globalMidiClient == 0)
  229414. {
  229415. String name ("JUCE");
  229416. if (JUCEApplication::getInstance() != 0)
  229417. name = JUCEApplication::getInstance()->getApplicationName();
  229418. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229419. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229420. CFRelease (appName);
  229421. }
  229422. return globalMidiClient;
  229423. }
  229424. class MidiPortAndEndpoint
  229425. {
  229426. public:
  229427. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229428. : port (port_), endPoint (endPoint_)
  229429. {
  229430. }
  229431. ~MidiPortAndEndpoint()
  229432. {
  229433. if (port != 0)
  229434. MIDIPortDispose (port);
  229435. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229436. MIDIEndpointDispose (endPoint);
  229437. }
  229438. void send (const MIDIPacketList* const packets)
  229439. {
  229440. if (port != 0)
  229441. MIDISend (port, endPoint, packets);
  229442. else
  229443. MIDIReceived (endPoint, packets);
  229444. }
  229445. MIDIPortRef port;
  229446. MIDIEndpointRef endPoint;
  229447. };
  229448. class MidiPortAndCallback;
  229449. CriticalSection callbackLock;
  229450. Array<MidiPortAndCallback*> activeCallbacks;
  229451. class MidiPortAndCallback
  229452. {
  229453. public:
  229454. MidiPortAndCallback (MidiInputCallback& callback_)
  229455. : input (0), active (false), callback (callback_), concatenator (2048)
  229456. {
  229457. }
  229458. ~MidiPortAndCallback()
  229459. {
  229460. active = false;
  229461. {
  229462. const ScopedLock sl (callbackLock);
  229463. activeCallbacks.removeValue (this);
  229464. }
  229465. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229466. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229467. }
  229468. void handlePackets (const MIDIPacketList* const pktlist)
  229469. {
  229470. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229471. const ScopedLock sl (callbackLock);
  229472. if (activeCallbacks.contains (this) && active)
  229473. {
  229474. const MIDIPacket* packet = &pktlist->packet[0];
  229475. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229476. {
  229477. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229478. input, callback);
  229479. packet = MIDIPacketNext (packet);
  229480. }
  229481. }
  229482. }
  229483. MidiInput* input;
  229484. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229485. volatile bool active;
  229486. private:
  229487. MidiInputCallback& callback;
  229488. MidiDataConcatenator concatenator;
  229489. };
  229490. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229491. {
  229492. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229493. }
  229494. }
  229495. const StringArray MidiOutput::getDevices()
  229496. {
  229497. StringArray s;
  229498. const ItemCount num = MIDIGetNumberOfDestinations();
  229499. for (ItemCount i = 0; i < num; ++i)
  229500. {
  229501. MIDIEndpointRef dest = MIDIGetDestination (i);
  229502. if (dest != 0)
  229503. {
  229504. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229505. if (name.isEmpty())
  229506. name = "<error>";
  229507. s.add (name);
  229508. }
  229509. else
  229510. {
  229511. s.add ("<error>");
  229512. }
  229513. }
  229514. return s;
  229515. }
  229516. int MidiOutput::getDefaultDeviceIndex()
  229517. {
  229518. return 0;
  229519. }
  229520. MidiOutput* MidiOutput::openDevice (int index)
  229521. {
  229522. MidiOutput* mo = 0;
  229523. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  229524. {
  229525. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229526. CFStringRef pname;
  229527. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229528. {
  229529. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229530. MIDIPortRef port;
  229531. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229532. {
  229533. mo = new MidiOutput();
  229534. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229535. }
  229536. CFRelease (pname);
  229537. }
  229538. }
  229539. return mo;
  229540. }
  229541. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229542. {
  229543. MidiOutput* mo = 0;
  229544. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229545. MIDIEndpointRef endPoint;
  229546. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229547. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229548. {
  229549. mo = new MidiOutput();
  229550. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229551. }
  229552. CFRelease (name);
  229553. return mo;
  229554. }
  229555. MidiOutput::~MidiOutput()
  229556. {
  229557. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229558. }
  229559. void MidiOutput::reset()
  229560. {
  229561. }
  229562. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229563. {
  229564. return false;
  229565. }
  229566. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229567. {
  229568. }
  229569. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229570. {
  229571. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229572. if (message.isSysEx())
  229573. {
  229574. const int maxPacketSize = 256;
  229575. int pos = 0, bytesLeft = message.getRawDataSize();
  229576. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229577. HeapBlock <MIDIPacketList> packets;
  229578. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229579. packets->numPackets = numPackets;
  229580. MIDIPacket* p = packets->packet;
  229581. for (int i = 0; i < numPackets; ++i)
  229582. {
  229583. p->timeStamp = AudioGetCurrentHostTime();
  229584. p->length = jmin (maxPacketSize, bytesLeft);
  229585. memcpy (p->data, message.getRawData() + pos, p->length);
  229586. pos += p->length;
  229587. bytesLeft -= p->length;
  229588. p = MIDIPacketNext (p);
  229589. }
  229590. mpe->send (packets);
  229591. }
  229592. else
  229593. {
  229594. MIDIPacketList packets;
  229595. packets.numPackets = 1;
  229596. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  229597. packets.packet[0].length = message.getRawDataSize();
  229598. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229599. mpe->send (&packets);
  229600. }
  229601. }
  229602. const StringArray MidiInput::getDevices()
  229603. {
  229604. StringArray s;
  229605. const ItemCount num = MIDIGetNumberOfSources();
  229606. for (ItemCount i = 0; i < num; ++i)
  229607. {
  229608. MIDIEndpointRef source = MIDIGetSource (i);
  229609. if (source != 0)
  229610. {
  229611. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229612. if (name.isEmpty())
  229613. name = "<error>";
  229614. s.add (name);
  229615. }
  229616. else
  229617. {
  229618. s.add ("<error>");
  229619. }
  229620. }
  229621. return s;
  229622. }
  229623. int MidiInput::getDefaultDeviceIndex()
  229624. {
  229625. return 0;
  229626. }
  229627. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229628. {
  229629. jassert (callback != 0);
  229630. using namespace CoreMidiHelpers;
  229631. MidiInput* newInput = 0;
  229632. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  229633. {
  229634. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229635. if (endPoint != 0)
  229636. {
  229637. CFStringRef name;
  229638. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229639. {
  229640. MIDIClientRef client = getGlobalMidiClient();
  229641. if (client != 0)
  229642. {
  229643. MIDIPortRef port;
  229644. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229645. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229646. {
  229647. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229648. {
  229649. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229650. newInput = new MidiInput (getDevices() [index]);
  229651. mpc->input = newInput;
  229652. newInput->internal = mpc;
  229653. const ScopedLock sl (callbackLock);
  229654. activeCallbacks.add (mpc.release());
  229655. }
  229656. else
  229657. {
  229658. CHECK_ERROR (MIDIPortDispose (port));
  229659. }
  229660. }
  229661. }
  229662. }
  229663. CFRelease (name);
  229664. }
  229665. }
  229666. return newInput;
  229667. }
  229668. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229669. {
  229670. jassert (callback != 0);
  229671. using namespace CoreMidiHelpers;
  229672. MidiInput* mi = 0;
  229673. MIDIClientRef client = getGlobalMidiClient();
  229674. if (client != 0)
  229675. {
  229676. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229677. mpc->active = false;
  229678. MIDIEndpointRef endPoint;
  229679. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229680. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229681. {
  229682. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229683. mi = new MidiInput (deviceName);
  229684. mpc->input = mi;
  229685. mi->internal = mpc;
  229686. const ScopedLock sl (callbackLock);
  229687. activeCallbacks.add (mpc.release());
  229688. }
  229689. CFRelease (name);
  229690. }
  229691. return mi;
  229692. }
  229693. MidiInput::MidiInput (const String& name_)
  229694. : name (name_)
  229695. {
  229696. }
  229697. MidiInput::~MidiInput()
  229698. {
  229699. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229700. }
  229701. void MidiInput::start()
  229702. {
  229703. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229704. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229705. }
  229706. void MidiInput::stop()
  229707. {
  229708. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229709. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229710. }
  229711. #undef CHECK_ERROR
  229712. #else // Stubs for iOS...
  229713. MidiOutput::~MidiOutput() {}
  229714. void MidiOutput::reset() {}
  229715. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229716. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229717. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229718. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229719. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229720. const StringArray MidiInput::getDevices() { return StringArray(); }
  229721. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229722. #endif
  229723. #endif
  229724. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229725. #else
  229726. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229727. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229728. // compiled on its own).
  229729. #if JUCE_INCLUDED_FILE
  229730. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229731. #define SUPPORT_10_4_FONTS 1
  229732. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229733. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229734. #define SUPPORT_ONLY_10_4_FONTS 1
  229735. #endif
  229736. END_JUCE_NAMESPACE
  229737. @interface NSFont (PrivateHack)
  229738. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229739. @end
  229740. BEGIN_JUCE_NAMESPACE
  229741. #endif
  229742. class MacTypeface : public Typeface
  229743. {
  229744. public:
  229745. MacTypeface (const Font& font)
  229746. : Typeface (font.getTypefaceName())
  229747. {
  229748. const ScopedAutoReleasePool pool;
  229749. renderingTransform = CGAffineTransformIdentity;
  229750. bool needsItalicTransform = false;
  229751. #if JUCE_IOS
  229752. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229753. if (font.isItalic() || font.isBold())
  229754. {
  229755. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229756. for (NSString* i in familyFonts)
  229757. {
  229758. const String fn (nsStringToJuce (i));
  229759. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229760. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229761. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229762. || afterDash.containsIgnoreCase ("italic")
  229763. || fn.endsWithIgnoreCase ("oblique")
  229764. || fn.endsWithIgnoreCase ("italic");
  229765. if (probablyBold == font.isBold()
  229766. && probablyItalic == font.isItalic())
  229767. {
  229768. fontName = i;
  229769. needsItalicTransform = false;
  229770. break;
  229771. }
  229772. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229773. {
  229774. fontName = i;
  229775. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229776. }
  229777. }
  229778. if (needsItalicTransform)
  229779. renderingTransform.c = 0.15f;
  229780. }
  229781. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229782. const int ascender = abs (CGFontGetAscent (fontRef));
  229783. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229784. ascent = ascender / totalHeight;
  229785. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229786. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229787. #else
  229788. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229789. if (font.isItalic())
  229790. {
  229791. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229792. toHaveTrait: NSItalicFontMask];
  229793. if (newFont == nsFont)
  229794. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229795. nsFont = newFont;
  229796. }
  229797. if (font.isBold())
  229798. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229799. [nsFont retain];
  229800. ascent = std::abs ((float) [nsFont ascender]);
  229801. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229802. ascent /= totalSize;
  229803. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229804. if (needsItalicTransform)
  229805. {
  229806. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229807. renderingTransform.c = 0.15f;
  229808. }
  229809. #if SUPPORT_ONLY_10_4_FONTS
  229810. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229811. if (atsFont == 0)
  229812. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229813. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229814. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229815. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229816. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229817. #else
  229818. #if SUPPORT_10_4_FONTS
  229819. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229820. {
  229821. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229822. if (atsFont == 0)
  229823. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229824. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229825. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229826. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229827. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229828. }
  229829. else
  229830. #endif
  229831. {
  229832. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229833. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229834. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229835. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229836. }
  229837. #endif
  229838. #endif
  229839. }
  229840. ~MacTypeface()
  229841. {
  229842. #if ! JUCE_IOS
  229843. [nsFont release];
  229844. #endif
  229845. if (fontRef != 0)
  229846. CGFontRelease (fontRef);
  229847. }
  229848. float getAscent() const
  229849. {
  229850. return ascent;
  229851. }
  229852. float getDescent() const
  229853. {
  229854. return 1.0f - ascent;
  229855. }
  229856. float getStringWidth (const String& text)
  229857. {
  229858. if (fontRef == 0 || text.isEmpty())
  229859. return 0;
  229860. const int length = text.length();
  229861. HeapBlock <CGGlyph> glyphs;
  229862. createGlyphsForString (text.getCharPointer(), length, glyphs);
  229863. float x = 0;
  229864. #if SUPPORT_ONLY_10_4_FONTS
  229865. HeapBlock <NSSize> advances (length);
  229866. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229867. for (int i = 0; i < length; ++i)
  229868. x += advances[i].width;
  229869. #else
  229870. #if SUPPORT_10_4_FONTS
  229871. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229872. {
  229873. HeapBlock <NSSize> advances (length);
  229874. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229875. for (int i = 0; i < length; ++i)
  229876. x += advances[i].width;
  229877. }
  229878. else
  229879. #endif
  229880. {
  229881. HeapBlock <int> advances (length);
  229882. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229883. for (int i = 0; i < length; ++i)
  229884. x += advances[i];
  229885. }
  229886. #endif
  229887. return x * unitsToHeightScaleFactor;
  229888. }
  229889. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229890. {
  229891. xOffsets.add (0);
  229892. if (fontRef == 0 || text.isEmpty())
  229893. return;
  229894. const int length = text.length();
  229895. HeapBlock <CGGlyph> glyphs;
  229896. createGlyphsForString (text.getCharPointer(), length, glyphs);
  229897. #if SUPPORT_ONLY_10_4_FONTS
  229898. HeapBlock <NSSize> advances (length);
  229899. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229900. int x = 0;
  229901. for (int i = 0; i < length; ++i)
  229902. {
  229903. x += advances[i].width;
  229904. xOffsets.add (x * unitsToHeightScaleFactor);
  229905. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229906. }
  229907. #else
  229908. #if SUPPORT_10_4_FONTS
  229909. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229910. {
  229911. HeapBlock <NSSize> advances (length);
  229912. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229913. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229914. float x = 0;
  229915. for (int i = 0; i < length; ++i)
  229916. {
  229917. x += advances[i].width;
  229918. xOffsets.add (x * unitsToHeightScaleFactor);
  229919. resultGlyphs.add (nsGlyphs[i]);
  229920. }
  229921. }
  229922. else
  229923. #endif
  229924. {
  229925. HeapBlock <int> advances (length);
  229926. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229927. {
  229928. int x = 0;
  229929. for (int i = 0; i < length; ++i)
  229930. {
  229931. x += advances [i];
  229932. xOffsets.add (x * unitsToHeightScaleFactor);
  229933. resultGlyphs.add (glyphs[i]);
  229934. }
  229935. }
  229936. }
  229937. #endif
  229938. }
  229939. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform)
  229940. {
  229941. Path path;
  229942. if (getOutlineForGlyph (glyphNumber, path) && ! path.isEmpty())
  229943. return new EdgeTable (path.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  229944. path, transform);
  229945. return 0;
  229946. }
  229947. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229948. {
  229949. #if JUCE_IOS
  229950. return false;
  229951. #else
  229952. if (nsFont == 0)
  229953. return false;
  229954. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229955. jassert (path.isEmpty());
  229956. const ScopedAutoReleasePool pool;
  229957. NSBezierPath* bez = [NSBezierPath bezierPath];
  229958. [bez moveToPoint: NSMakePoint (0, 0)];
  229959. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229960. inFont: nsFont];
  229961. for (int i = 0; i < [bez elementCount]; ++i)
  229962. {
  229963. NSPoint p[3];
  229964. switch ([bez elementAtIndex: i associatedPoints: p])
  229965. {
  229966. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229967. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229968. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229969. (float) p[1].x, (float) -p[1].y,
  229970. (float) p[2].x, (float) -p[2].y); break;
  229971. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229972. default: jassertfalse; break;
  229973. }
  229974. }
  229975. path.applyTransform (pathTransform);
  229976. return true;
  229977. #endif
  229978. }
  229979. CGFontRef fontRef;
  229980. float fontHeightToCGSizeFactor;
  229981. CGAffineTransform renderingTransform;
  229982. private:
  229983. float ascent, unitsToHeightScaleFactor;
  229984. #if JUCE_IOS
  229985. #else
  229986. NSFont* nsFont;
  229987. AffineTransform pathTransform;
  229988. #endif
  229989. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  229990. {
  229991. #if SUPPORT_10_4_FONTS
  229992. #if ! SUPPORT_ONLY_10_4_FONTS
  229993. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229994. #endif
  229995. {
  229996. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229997. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229998. for (int i = 0; i < length; ++i)
  229999. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  230000. return;
  230001. }
  230002. #endif
  230003. #if ! SUPPORT_ONLY_10_4_FONTS
  230004. if (charToGlyphMapper == 0)
  230005. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230006. glyphs.malloc (length);
  230007. for (int i = 0; i < length; ++i)
  230008. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  230009. #endif
  230010. }
  230011. #if ! SUPPORT_ONLY_10_4_FONTS
  230012. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230013. class CharToGlyphMapper
  230014. {
  230015. public:
  230016. CharToGlyphMapper (CGFontRef fontRef)
  230017. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230018. idRangeOffset (0), glyphIndexes (0)
  230019. {
  230020. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230021. if (cmapTable != 0)
  230022. {
  230023. const int numSubtables = getValue16 (cmapTable, 2);
  230024. for (int i = 0; i < numSubtables; ++i)
  230025. {
  230026. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230027. {
  230028. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230029. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230030. {
  230031. const int length = getValue16 (cmapTable, offset + 2);
  230032. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230033. segCount = segCountX2 / 2;
  230034. const int endCodeOffset = offset + 14;
  230035. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230036. const int idDeltaOffset = startCodeOffset + segCountX2;
  230037. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230038. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230039. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230040. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230041. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230042. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230043. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230044. }
  230045. break;
  230046. }
  230047. }
  230048. CFRelease (cmapTable);
  230049. }
  230050. }
  230051. ~CharToGlyphMapper()
  230052. {
  230053. if (endCode != 0)
  230054. {
  230055. CFRelease (endCode);
  230056. CFRelease (startCode);
  230057. CFRelease (idDelta);
  230058. CFRelease (idRangeOffset);
  230059. CFRelease (glyphIndexes);
  230060. }
  230061. }
  230062. int getGlyphForCharacter (const juce_wchar c) const
  230063. {
  230064. for (int i = 0; i < segCount; ++i)
  230065. {
  230066. if (getValue16 (endCode, i * 2) >= c)
  230067. {
  230068. const int start = getValue16 (startCode, i * 2);
  230069. if (start > c)
  230070. break;
  230071. const int delta = getValue16 (idDelta, i * 2);
  230072. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230073. if (rangeOffset == 0)
  230074. return delta + c;
  230075. else
  230076. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230077. }
  230078. }
  230079. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230080. return jmax (-1, (int) c - 29);
  230081. }
  230082. private:
  230083. int segCount;
  230084. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230085. static uint16 getValue16 (CFDataRef data, const int index)
  230086. {
  230087. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230088. }
  230089. static uint32 getValue32 (CFDataRef data, const int index)
  230090. {
  230091. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230092. }
  230093. };
  230094. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230095. #endif
  230096. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  230097. };
  230098. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230099. {
  230100. return new MacTypeface (font);
  230101. }
  230102. const StringArray Font::findAllTypefaceNames()
  230103. {
  230104. StringArray names;
  230105. const ScopedAutoReleasePool pool;
  230106. #if JUCE_IOS
  230107. NSArray* fonts = [UIFont familyNames];
  230108. #else
  230109. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230110. #endif
  230111. for (unsigned int i = 0; i < [fonts count]; ++i)
  230112. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230113. names.sort (true);
  230114. return names;
  230115. }
  230116. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  230117. {
  230118. #if JUCE_IOS
  230119. defaultSans = "Helvetica";
  230120. defaultSerif = "Times New Roman";
  230121. defaultFixed = "Courier New";
  230122. #else
  230123. defaultSans = "Lucida Grande";
  230124. defaultSerif = "Times New Roman";
  230125. defaultFixed = "Monaco";
  230126. #endif
  230127. defaultFallback = "Arial Unicode MS";
  230128. }
  230129. #endif
  230130. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230131. // (must go before juce_mac_CoreGraphicsContext.mm)
  230132. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230133. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230134. // compiled on its own).
  230135. #if JUCE_INCLUDED_FILE
  230136. class CoreGraphicsImage : public Image::SharedImage
  230137. {
  230138. public:
  230139. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230140. : Image::SharedImage (format_, width_, height_)
  230141. {
  230142. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230143. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230144. imageData.allocate (lineStride * jmax (1, height), clearImage);
  230145. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230146. : CGColorSpaceCreateDeviceRGB();
  230147. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230148. colourSpace, getCGImageFlags (format_));
  230149. CGColorSpaceRelease (colourSpace);
  230150. }
  230151. ~CoreGraphicsImage()
  230152. {
  230153. CGContextRelease (context);
  230154. }
  230155. Image::ImageType getType() const { return Image::NativeImage; }
  230156. LowLevelGraphicsContext* createLowLevelContext();
  230157. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/)
  230158. {
  230159. bitmap.data = imageData + x * pixelStride + y * lineStride;
  230160. bitmap.pixelFormat = format;
  230161. bitmap.lineStride = lineStride;
  230162. bitmap.pixelStride = pixelStride;
  230163. }
  230164. SharedImage* clone()
  230165. {
  230166. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230167. memcpy (im->imageData, imageData, lineStride * height);
  230168. return im;
  230169. }
  230170. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  230171. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  230172. {
  230173. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230174. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230175. {
  230176. return CGBitmapContextCreateImage (nativeImage->context);
  230177. }
  230178. else
  230179. {
  230180. const Image::BitmapData srcData (juceImage, Image::BitmapData::readOnly);
  230181. CGDataProviderRef provider;
  230182. if (mustOutliveSource)
  230183. {
  230184. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  230185. provider = CGDataProviderCreateWithCFData (data);
  230186. CFRelease (data);
  230187. }
  230188. else
  230189. {
  230190. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230191. }
  230192. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230193. 8, srcData.pixelStride * 8, srcData.lineStride,
  230194. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230195. 0, true, kCGRenderingIntentDefault);
  230196. CGDataProviderRelease (provider);
  230197. return imageRef;
  230198. }
  230199. }
  230200. #if JUCE_MAC
  230201. static NSImage* createNSImage (const Image& image)
  230202. {
  230203. const ScopedAutoReleasePool pool;
  230204. NSImage* im = [[NSImage alloc] init];
  230205. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230206. [im lockFocus];
  230207. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230208. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  230209. CGColorSpaceRelease (colourSpace);
  230210. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230211. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230212. CGImageRelease (imageRef);
  230213. [im unlockFocus];
  230214. return im;
  230215. }
  230216. #endif
  230217. CGContextRef context;
  230218. HeapBlock<uint8> imageData;
  230219. int pixelStride, lineStride;
  230220. private:
  230221. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230222. {
  230223. #if JUCE_BIG_ENDIAN
  230224. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230225. #else
  230226. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230227. #endif
  230228. }
  230229. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  230230. };
  230231. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230232. {
  230233. #if USE_COREGRAPHICS_RENDERING
  230234. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230235. #else
  230236. return createSoftwareImage (format, width, height, clearImage);
  230237. #endif
  230238. }
  230239. class CoreGraphicsContext : public LowLevelGraphicsContext
  230240. {
  230241. public:
  230242. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230243. : context (context_),
  230244. flipHeight (flipHeight_),
  230245. lastClipRectIsValid (false),
  230246. state (new SavedState()),
  230247. numGradientLookupEntries (0)
  230248. {
  230249. CGContextRetain (context);
  230250. CGContextSaveGState(context);
  230251. CGContextSetShouldSmoothFonts (context, true);
  230252. CGContextSetShouldAntialias (context, true);
  230253. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230254. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230255. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230256. gradientCallbacks.version = 0;
  230257. gradientCallbacks.evaluate = gradientCallback;
  230258. gradientCallbacks.releaseInfo = 0;
  230259. setFont (Font());
  230260. }
  230261. ~CoreGraphicsContext()
  230262. {
  230263. CGContextRestoreGState (context);
  230264. CGContextRelease (context);
  230265. CGColorSpaceRelease (rgbColourSpace);
  230266. CGColorSpaceRelease (greyColourSpace);
  230267. }
  230268. bool isVectorDevice() const { return false; }
  230269. void setOrigin (int x, int y)
  230270. {
  230271. CGContextTranslateCTM (context, x, -y);
  230272. if (lastClipRectIsValid)
  230273. lastClipRect.translate (-x, -y);
  230274. }
  230275. void addTransform (const AffineTransform& transform)
  230276. {
  230277. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  230278. .translated (0, flipHeight)
  230279. .followedBy (transform)
  230280. .translated (0, -flipHeight)
  230281. .scaled (1.0f, -1.0f));
  230282. lastClipRectIsValid = false;
  230283. }
  230284. float getScaleFactor()
  230285. {
  230286. CGAffineTransform t = CGContextGetCTM (context);
  230287. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  230288. }
  230289. bool clipToRectangle (const Rectangle<int>& r)
  230290. {
  230291. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230292. if (lastClipRectIsValid)
  230293. {
  230294. // This is actually incorrect, because the actual clip region may be complex, and
  230295. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230296. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230297. // when calculating the resultant clip bounds, and makes the same mistake!
  230298. lastClipRect = lastClipRect.getIntersection (r);
  230299. return ! lastClipRect.isEmpty();
  230300. }
  230301. return ! isClipEmpty();
  230302. }
  230303. bool clipToRectangleList (const RectangleList& clipRegion)
  230304. {
  230305. if (clipRegion.isEmpty())
  230306. {
  230307. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230308. lastClipRectIsValid = true;
  230309. lastClipRect = Rectangle<int>();
  230310. return false;
  230311. }
  230312. else
  230313. {
  230314. const int numRects = clipRegion.getNumRectangles();
  230315. HeapBlock <CGRect> rects (numRects);
  230316. for (int i = 0; i < numRects; ++i)
  230317. {
  230318. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230319. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230320. }
  230321. CGContextClipToRects (context, rects, numRects);
  230322. lastClipRectIsValid = false;
  230323. return ! isClipEmpty();
  230324. }
  230325. }
  230326. void excludeClipRectangle (const Rectangle<int>& r)
  230327. {
  230328. RectangleList remaining (getClipBounds());
  230329. remaining.subtract (r);
  230330. clipToRectangleList (remaining);
  230331. lastClipRectIsValid = false;
  230332. }
  230333. void clipToPath (const Path& path, const AffineTransform& transform)
  230334. {
  230335. createPath (path, transform);
  230336. CGContextClip (context);
  230337. lastClipRectIsValid = false;
  230338. }
  230339. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230340. {
  230341. if (! transform.isSingularity())
  230342. {
  230343. Image singleChannelImage (sourceImage);
  230344. if (sourceImage.getFormat() != Image::SingleChannel)
  230345. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230346. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  230347. flip();
  230348. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230349. applyTransform (t);
  230350. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230351. CGContextClipToMask (context, r, image);
  230352. applyTransform (t.inverted());
  230353. flip();
  230354. CGImageRelease (image);
  230355. lastClipRectIsValid = false;
  230356. }
  230357. }
  230358. bool clipRegionIntersects (const Rectangle<int>& r)
  230359. {
  230360. return getClipBounds().intersects (r);
  230361. }
  230362. const Rectangle<int> getClipBounds() const
  230363. {
  230364. if (! lastClipRectIsValid)
  230365. {
  230366. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230367. lastClipRectIsValid = true;
  230368. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230369. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230370. roundToInt (bounds.size.width),
  230371. roundToInt (bounds.size.height));
  230372. }
  230373. return lastClipRect;
  230374. }
  230375. bool isClipEmpty() const
  230376. {
  230377. return getClipBounds().isEmpty();
  230378. }
  230379. void saveState()
  230380. {
  230381. CGContextSaveGState (context);
  230382. stateStack.add (new SavedState (*state));
  230383. }
  230384. void restoreState()
  230385. {
  230386. CGContextRestoreGState (context);
  230387. SavedState* const top = stateStack.getLast();
  230388. if (top != 0)
  230389. {
  230390. state = top;
  230391. stateStack.removeLast (1, false);
  230392. lastClipRectIsValid = false;
  230393. }
  230394. else
  230395. {
  230396. jassertfalse; // trying to pop with an empty stack!
  230397. }
  230398. }
  230399. void beginTransparencyLayer (float opacity)
  230400. {
  230401. saveState();
  230402. CGContextSetAlpha (context, opacity);
  230403. CGContextBeginTransparencyLayer (context, 0);
  230404. }
  230405. void endTransparencyLayer()
  230406. {
  230407. CGContextEndTransparencyLayer (context);
  230408. restoreState();
  230409. }
  230410. void setFill (const FillType& fillType)
  230411. {
  230412. state->fillType = fillType;
  230413. if (fillType.isColour())
  230414. {
  230415. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230416. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230417. CGContextSetAlpha (context, 1.0f);
  230418. }
  230419. }
  230420. void setOpacity (float newOpacity)
  230421. {
  230422. state->fillType.setOpacity (newOpacity);
  230423. setFill (state->fillType);
  230424. }
  230425. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230426. {
  230427. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230428. ? kCGInterpolationLow
  230429. : kCGInterpolationHigh);
  230430. }
  230431. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230432. {
  230433. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230434. }
  230435. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230436. {
  230437. if (replaceExistingContents)
  230438. {
  230439. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230440. CGContextClearRect (context, cgRect);
  230441. #else
  230442. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230443. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230444. CGContextClearRect (context, cgRect);
  230445. else
  230446. #endif
  230447. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230448. #endif
  230449. fillCGRect (cgRect, false);
  230450. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230451. }
  230452. else
  230453. {
  230454. if (state->fillType.isColour())
  230455. {
  230456. CGContextFillRect (context, cgRect);
  230457. }
  230458. else if (state->fillType.isGradient())
  230459. {
  230460. CGContextSaveGState (context);
  230461. CGContextClipToRect (context, cgRect);
  230462. drawGradient();
  230463. CGContextRestoreGState (context);
  230464. }
  230465. else
  230466. {
  230467. CGContextSaveGState (context);
  230468. CGContextClipToRect (context, cgRect);
  230469. drawImage (state->fillType.image, state->fillType.transform, true);
  230470. CGContextRestoreGState (context);
  230471. }
  230472. }
  230473. }
  230474. void fillPath (const Path& path, const AffineTransform& transform)
  230475. {
  230476. CGContextSaveGState (context);
  230477. if (state->fillType.isColour())
  230478. {
  230479. flip();
  230480. applyTransform (transform);
  230481. createPath (path);
  230482. if (path.isUsingNonZeroWinding())
  230483. CGContextFillPath (context);
  230484. else
  230485. CGContextEOFillPath (context);
  230486. }
  230487. else
  230488. {
  230489. createPath (path, transform);
  230490. if (path.isUsingNonZeroWinding())
  230491. CGContextClip (context);
  230492. else
  230493. CGContextEOClip (context);
  230494. if (state->fillType.isGradient())
  230495. drawGradient();
  230496. else
  230497. drawImage (state->fillType.image, state->fillType.transform, true);
  230498. }
  230499. CGContextRestoreGState (context);
  230500. }
  230501. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230502. {
  230503. const int iw = sourceImage.getWidth();
  230504. const int ih = sourceImage.getHeight();
  230505. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  230506. CGContextSaveGState (context);
  230507. CGContextSetAlpha (context, state->fillType.getOpacity());
  230508. flip();
  230509. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230510. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230511. if (fillEntireClipAsTiles)
  230512. {
  230513. #if JUCE_IOS
  230514. CGContextDrawTiledImage (context, imageRect, image);
  230515. #else
  230516. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230517. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230518. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230519. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230520. CGContextDrawTiledImage (context, imageRect, image);
  230521. else
  230522. #endif
  230523. {
  230524. // Fallback to manually doing a tiled fill on 10.4
  230525. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230526. int x = 0, y = 0;
  230527. while (x > clip.origin.x) x -= iw;
  230528. while (y > clip.origin.y) y -= ih;
  230529. const int right = (int) (clip.origin.x + clip.size.width);
  230530. const int bottom = (int) (clip.origin.y + clip.size.height);
  230531. while (y < bottom)
  230532. {
  230533. for (int x2 = x; x2 < right; x2 += iw)
  230534. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230535. y += ih;
  230536. }
  230537. }
  230538. #endif
  230539. }
  230540. else
  230541. {
  230542. CGContextDrawImage (context, imageRect, image);
  230543. }
  230544. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230545. CGContextRestoreGState (context);
  230546. }
  230547. void drawLine (const Line<float>& line)
  230548. {
  230549. if (state->fillType.isColour())
  230550. {
  230551. CGContextSetLineCap (context, kCGLineCapSquare);
  230552. CGContextSetLineWidth (context, 1.0f);
  230553. CGContextSetRGBStrokeColor (context,
  230554. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230555. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230556. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230557. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230558. CGContextStrokeLineSegments (context, cgLine, 1);
  230559. }
  230560. else
  230561. {
  230562. Path p;
  230563. p.addLineSegment (line, 1.0f);
  230564. fillPath (p, AffineTransform::identity);
  230565. }
  230566. }
  230567. void drawVerticalLine (const int x, float top, float bottom)
  230568. {
  230569. if (state->fillType.isColour())
  230570. {
  230571. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230572. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230573. #else
  230574. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230575. // the x co-ord slightly to trick it..
  230576. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230577. #endif
  230578. }
  230579. else
  230580. {
  230581. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230582. }
  230583. }
  230584. void drawHorizontalLine (const int y, float left, float right)
  230585. {
  230586. if (state->fillType.isColour())
  230587. {
  230588. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230589. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230590. #else
  230591. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230592. // the x co-ord slightly to trick it..
  230593. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230594. #endif
  230595. }
  230596. else
  230597. {
  230598. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230599. }
  230600. }
  230601. void setFont (const Font& newFont)
  230602. {
  230603. if (state->font != newFont)
  230604. {
  230605. state->fontRef = 0;
  230606. state->font = newFont;
  230607. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230608. if (mf != 0)
  230609. {
  230610. state->fontRef = mf->fontRef;
  230611. CGContextSetFont (context, state->fontRef);
  230612. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230613. state->fontTransform = mf->renderingTransform;
  230614. state->fontTransform.a *= state->font.getHorizontalScale();
  230615. CGContextSetTextMatrix (context, state->fontTransform);
  230616. }
  230617. }
  230618. }
  230619. const Font getFont()
  230620. {
  230621. return state->font;
  230622. }
  230623. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230624. {
  230625. if (state->fontRef != 0 && state->fillType.isColour())
  230626. {
  230627. if (transform.isOnlyTranslation())
  230628. {
  230629. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230630. CGGlyph g = glyphNumber;
  230631. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230632. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230633. }
  230634. else
  230635. {
  230636. CGContextSaveGState (context);
  230637. flip();
  230638. applyTransform (transform);
  230639. CGAffineTransform t = state->fontTransform;
  230640. t.d = -t.d;
  230641. CGContextSetTextMatrix (context, t);
  230642. CGGlyph g = glyphNumber;
  230643. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230644. CGContextRestoreGState (context);
  230645. }
  230646. }
  230647. else
  230648. {
  230649. Path p;
  230650. Font& f = state->font;
  230651. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230652. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230653. .followedBy (transform));
  230654. }
  230655. }
  230656. private:
  230657. CGContextRef context;
  230658. const CGFloat flipHeight;
  230659. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230660. CGFunctionCallbacks gradientCallbacks;
  230661. mutable Rectangle<int> lastClipRect;
  230662. mutable bool lastClipRectIsValid;
  230663. struct SavedState
  230664. {
  230665. SavedState()
  230666. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230667. {
  230668. }
  230669. SavedState (const SavedState& other)
  230670. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230671. fontTransform (other.fontTransform)
  230672. {
  230673. }
  230674. FillType fillType;
  230675. Font font;
  230676. CGFontRef fontRef;
  230677. CGAffineTransform fontTransform;
  230678. };
  230679. ScopedPointer <SavedState> state;
  230680. OwnedArray <SavedState> stateStack;
  230681. HeapBlock <PixelARGB> gradientLookupTable;
  230682. int numGradientLookupEntries;
  230683. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230684. {
  230685. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230686. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230687. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230688. colour.unpremultiply();
  230689. outData[0] = colour.getRed() / 255.0f;
  230690. outData[1] = colour.getGreen() / 255.0f;
  230691. outData[2] = colour.getBlue() / 255.0f;
  230692. outData[3] = colour.getAlpha() / 255.0f;
  230693. }
  230694. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230695. {
  230696. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  230697. CGShadingRef result = 0;
  230698. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230699. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230700. if (gradient.isRadial)
  230701. {
  230702. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230703. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230704. function, true, true);
  230705. }
  230706. else
  230707. {
  230708. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230709. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230710. function, true, true);
  230711. }
  230712. CGFunctionRelease (function);
  230713. return result;
  230714. }
  230715. void drawGradient()
  230716. {
  230717. flip();
  230718. applyTransform (state->fillType.transform);
  230719. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230720. // you draw a gradient with high quality interp enabled).
  230721. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230722. CGContextSetAlpha (context, state->fillType.getOpacity());
  230723. CGContextDrawShading (context, shading);
  230724. CGShadingRelease (shading);
  230725. }
  230726. void createPath (const Path& path) const
  230727. {
  230728. CGContextBeginPath (context);
  230729. Path::Iterator i (path);
  230730. while (i.next())
  230731. {
  230732. switch (i.elementType)
  230733. {
  230734. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230735. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230736. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230737. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230738. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230739. default: jassertfalse; break;
  230740. }
  230741. }
  230742. }
  230743. void createPath (const Path& path, const AffineTransform& transform) const
  230744. {
  230745. CGContextBeginPath (context);
  230746. Path::Iterator i (path);
  230747. while (i.next())
  230748. {
  230749. switch (i.elementType)
  230750. {
  230751. case Path::Iterator::startNewSubPath:
  230752. transform.transformPoint (i.x1, i.y1);
  230753. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230754. break;
  230755. case Path::Iterator::lineTo:
  230756. transform.transformPoint (i.x1, i.y1);
  230757. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230758. break;
  230759. case Path::Iterator::quadraticTo:
  230760. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230761. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230762. break;
  230763. case Path::Iterator::cubicTo:
  230764. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230765. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230766. break;
  230767. case Path::Iterator::closePath:
  230768. CGContextClosePath (context); break;
  230769. default:
  230770. jassertfalse;
  230771. break;
  230772. }
  230773. }
  230774. }
  230775. void flip() const
  230776. {
  230777. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230778. }
  230779. void applyTransform (const AffineTransform& transform) const
  230780. {
  230781. CGAffineTransform t;
  230782. t.a = transform.mat00;
  230783. t.b = transform.mat10;
  230784. t.c = transform.mat01;
  230785. t.d = transform.mat11;
  230786. t.tx = transform.mat02;
  230787. t.ty = transform.mat12;
  230788. CGContextConcatCTM (context, t);
  230789. }
  230790. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230791. };
  230792. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230793. {
  230794. return new CoreGraphicsContext (context, height);
  230795. }
  230796. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230797. const Image juce_loadWithCoreImage (InputStream& input)
  230798. {
  230799. MemoryBlock data;
  230800. input.readIntoMemoryBlock (data, -1);
  230801. #if JUCE_IOS
  230802. JUCE_AUTORELEASEPOOL
  230803. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230804. length: data.getSize()
  230805. freeWhenDone: NO]];
  230806. if (image != nil)
  230807. {
  230808. CGImageRef loadedImage = image.CGImage;
  230809. #else
  230810. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230811. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230812. CGDataProviderRelease (provider);
  230813. if (imageSource != 0)
  230814. {
  230815. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230816. CFRelease (imageSource);
  230817. #endif
  230818. if (loadedImage != 0)
  230819. {
  230820. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230821. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230822. && alphaInfo != kCGImageAlphaNoneSkipLast
  230823. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230824. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230825. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230826. hasAlphaChan, Image::NativeImage);
  230827. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230828. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230829. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230830. CGContextFlush (cgImage->context);
  230831. #if ! JUCE_IOS
  230832. CFRelease (loadedImage);
  230833. #endif
  230834. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230835. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230836. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230837. return image;
  230838. }
  230839. }
  230840. return Image::null;
  230841. }
  230842. #endif
  230843. #endif
  230844. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230845. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230846. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230847. // compiled on its own).
  230848. #if JUCE_INCLUDED_FILE
  230849. class NSViewComponentPeer;
  230850. END_JUCE_NAMESPACE
  230851. @interface NSEvent (JuceDeviceDelta)
  230852. - (float) deviceDeltaX;
  230853. - (float) deviceDeltaY;
  230854. @end
  230855. #define JuceNSView MakeObjCClassName(JuceNSView)
  230856. @interface JuceNSView : NSView<NSTextInput>
  230857. {
  230858. @public
  230859. NSViewComponentPeer* owner;
  230860. NSNotificationCenter* notificationCenter;
  230861. String* stringBeingComposed;
  230862. bool textWasInserted;
  230863. }
  230864. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230865. - (void) dealloc;
  230866. - (BOOL) isOpaque;
  230867. - (void) drawRect: (NSRect) r;
  230868. - (void) mouseDown: (NSEvent*) ev;
  230869. - (void) asyncMouseDown: (NSEvent*) ev;
  230870. - (void) mouseUp: (NSEvent*) ev;
  230871. - (void) asyncMouseUp: (NSEvent*) ev;
  230872. - (void) mouseDragged: (NSEvent*) ev;
  230873. - (void) mouseMoved: (NSEvent*) ev;
  230874. - (void) mouseEntered: (NSEvent*) ev;
  230875. - (void) mouseExited: (NSEvent*) ev;
  230876. - (void) rightMouseDown: (NSEvent*) ev;
  230877. - (void) rightMouseDragged: (NSEvent*) ev;
  230878. - (void) rightMouseUp: (NSEvent*) ev;
  230879. - (void) otherMouseDown: (NSEvent*) ev;
  230880. - (void) otherMouseDragged: (NSEvent*) ev;
  230881. - (void) otherMouseUp: (NSEvent*) ev;
  230882. - (void) scrollWheel: (NSEvent*) ev;
  230883. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230884. - (void) frameChanged: (NSNotification*) n;
  230885. - (void) viewDidMoveToWindow;
  230886. - (void) keyDown: (NSEvent*) ev;
  230887. - (void) keyUp: (NSEvent*) ev;
  230888. // NSTextInput Methods
  230889. - (void) insertText: (id) aString;
  230890. - (void) doCommandBySelector: (SEL) aSelector;
  230891. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230892. - (void) unmarkText;
  230893. - (BOOL) hasMarkedText;
  230894. - (long) conversationIdentifier;
  230895. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230896. - (NSRange) markedRange;
  230897. - (NSRange) selectedRange;
  230898. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230899. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230900. - (NSArray*) validAttributesForMarkedText;
  230901. - (void) flagsChanged: (NSEvent*) ev;
  230902. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230903. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230904. #endif
  230905. - (BOOL) becomeFirstResponder;
  230906. - (BOOL) resignFirstResponder;
  230907. - (BOOL) acceptsFirstResponder;
  230908. - (void) asyncRepaint: (id) rect;
  230909. - (NSArray*) getSupportedDragTypes;
  230910. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230911. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230912. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230913. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230914. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230915. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230916. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230917. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230918. @end
  230919. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230920. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230921. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230922. #else
  230923. @interface JuceNSWindow : NSWindow
  230924. #endif
  230925. {
  230926. @private
  230927. NSViewComponentPeer* owner;
  230928. bool isZooming;
  230929. }
  230930. - (void) setOwner: (NSViewComponentPeer*) owner;
  230931. - (BOOL) canBecomeKeyWindow;
  230932. - (void) becomeKeyWindow;
  230933. - (BOOL) windowShouldClose: (id) window;
  230934. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230935. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230936. - (void) zoom: (id) sender;
  230937. @end
  230938. BEGIN_JUCE_NAMESPACE
  230939. class NSViewComponentPeer : public ComponentPeer
  230940. {
  230941. public:
  230942. NSViewComponentPeer (Component* const component,
  230943. const int windowStyleFlags,
  230944. NSView* viewToAttachTo);
  230945. ~NSViewComponentPeer();
  230946. void* getNativeHandle() const;
  230947. void setVisible (bool shouldBeVisible);
  230948. void setTitle (const String& title);
  230949. void setPosition (int x, int y);
  230950. void setSize (int w, int h);
  230951. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230952. const Rectangle<int> getBounds (const bool global) const;
  230953. const Rectangle<int> getBounds() const;
  230954. const Point<int> getScreenPosition() const;
  230955. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230956. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230957. void setAlpha (float newAlpha);
  230958. void setMinimised (bool shouldBeMinimised);
  230959. bool isMinimised() const;
  230960. void setFullScreen (bool shouldBeFullScreen);
  230961. bool isFullScreen() const;
  230962. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230963. const BorderSize<int> getFrameSize() const;
  230964. bool setAlwaysOnTop (bool alwaysOnTop);
  230965. void toFront (bool makeActiveWindow);
  230966. void toBehind (ComponentPeer* other);
  230967. void setIcon (const Image& newIcon);
  230968. const StringArray getAvailableRenderingEngines();
  230969. int getCurrentRenderingEngine() throw();
  230970. void setCurrentRenderingEngine (int index);
  230971. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230972. for example having more than one juce plugin loaded into a host, then when a
  230973. method is called, the actual code that runs might actually be in a different module
  230974. than the one you expect... So any calls to library functions or statics that are
  230975. made inside obj-c methods will probably end up getting executed in a different DLL's
  230976. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230977. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230978. virtual methods of an object that's known to live inside the right module's space.
  230979. */
  230980. virtual void redirectMouseDown (NSEvent* ev);
  230981. virtual void redirectMouseUp (NSEvent* ev);
  230982. virtual void redirectMouseDrag (NSEvent* ev);
  230983. virtual void redirectMouseMove (NSEvent* ev);
  230984. virtual void redirectMouseEnter (NSEvent* ev);
  230985. virtual void redirectMouseExit (NSEvent* ev);
  230986. virtual void redirectMouseWheel (NSEvent* ev);
  230987. void sendMouseEvent (NSEvent* ev);
  230988. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230989. virtual bool redirectKeyDown (NSEvent* ev);
  230990. virtual bool redirectKeyUp (NSEvent* ev);
  230991. virtual void redirectModKeyChange (NSEvent* ev);
  230992. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230993. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230994. #endif
  230995. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230996. virtual bool isOpaque();
  230997. virtual void drawRect (NSRect r);
  230998. virtual bool canBecomeKeyWindow();
  230999. virtual bool windowShouldClose();
  231000. virtual void redirectMovedOrResized();
  231001. virtual void viewMovedToWindow();
  231002. virtual NSRect constrainRect (NSRect r);
  231003. static void showArrowCursorIfNeeded();
  231004. static void updateModifiers (NSEvent* e);
  231005. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231006. static int getKeyCodeFromEvent (NSEvent* ev)
  231007. {
  231008. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231009. int keyCode = unmodified[0];
  231010. if (keyCode == 0x19) // (backwards-tab)
  231011. keyCode = '\t';
  231012. else if (keyCode == 0x03) // (enter)
  231013. keyCode = '\r';
  231014. else
  231015. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231016. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231017. {
  231018. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231019. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231020. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231021. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231022. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231023. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231024. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231025. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231026. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231027. if (keyCode == numPadConversions [i])
  231028. keyCode = numPadConversions [i + 1];
  231029. }
  231030. return keyCode;
  231031. }
  231032. static int64 getMouseTime (NSEvent* e)
  231033. {
  231034. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231035. + (int64) ([e timestamp] * 1000.0);
  231036. }
  231037. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231038. {
  231039. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231040. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231041. }
  231042. static int getModifierForButtonNumber (const NSInteger num)
  231043. {
  231044. return num == 0 ? ModifierKeys::leftButtonModifier
  231045. : (num == 1 ? ModifierKeys::rightButtonModifier
  231046. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231047. }
  231048. virtual void viewFocusGain();
  231049. virtual void viewFocusLoss();
  231050. bool isFocused() const;
  231051. void grabFocus();
  231052. void textInputRequired (const Point<int>& position);
  231053. void repaint (const Rectangle<int>& area);
  231054. void performAnyPendingRepaintsNow();
  231055. NSWindow* window;
  231056. JuceNSView* view;
  231057. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231058. static ModifierKeys currentModifiers;
  231059. static ComponentPeer* currentlyFocusedPeer;
  231060. static Array<int> keysCurrentlyDown;
  231061. private:
  231062. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  231063. };
  231064. END_JUCE_NAMESPACE
  231065. @implementation JuceNSView
  231066. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231067. withFrame: (NSRect) frame
  231068. {
  231069. [super initWithFrame: frame];
  231070. owner = owner_;
  231071. stringBeingComposed = 0;
  231072. textWasInserted = false;
  231073. notificationCenter = [NSNotificationCenter defaultCenter];
  231074. [notificationCenter addObserver: self
  231075. selector: @selector (frameChanged:)
  231076. name: NSViewFrameDidChangeNotification
  231077. object: self];
  231078. if (! owner_->isSharedWindow)
  231079. {
  231080. [notificationCenter addObserver: self
  231081. selector: @selector (frameChanged:)
  231082. name: NSWindowDidMoveNotification
  231083. object: owner_->window];
  231084. }
  231085. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231086. return self;
  231087. }
  231088. - (void) dealloc
  231089. {
  231090. [notificationCenter removeObserver: self];
  231091. delete stringBeingComposed;
  231092. [super dealloc];
  231093. }
  231094. - (void) drawRect: (NSRect) r
  231095. {
  231096. if (owner != 0)
  231097. owner->drawRect (r);
  231098. }
  231099. - (BOOL) isOpaque
  231100. {
  231101. return owner == 0 || owner->isOpaque();
  231102. }
  231103. - (void) mouseDown: (NSEvent*) ev
  231104. {
  231105. if (JUCEApplication::isStandaloneApp())
  231106. [self asyncMouseDown: ev];
  231107. else
  231108. // In some host situations, the host will stop modal loops from working
  231109. // correctly if they're called from a mouse event, so we'll trigger
  231110. // the event asynchronously..
  231111. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231112. withObject: ev
  231113. waitUntilDone: NO];
  231114. }
  231115. - (void) asyncMouseDown: (NSEvent*) ev
  231116. {
  231117. if (owner != 0)
  231118. owner->redirectMouseDown (ev);
  231119. }
  231120. - (void) mouseUp: (NSEvent*) ev
  231121. {
  231122. if (! JUCEApplication::isStandaloneApp())
  231123. [self asyncMouseUp: ev];
  231124. else
  231125. // In some host situations, the host will stop modal loops from working
  231126. // correctly if they're called from a mouse event, so we'll trigger
  231127. // the event asynchronously..
  231128. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231129. withObject: ev
  231130. waitUntilDone: NO];
  231131. }
  231132. - (void) asyncMouseUp: (NSEvent*) ev
  231133. {
  231134. if (owner != 0)
  231135. owner->redirectMouseUp (ev);
  231136. }
  231137. - (void) mouseDragged: (NSEvent*) ev
  231138. {
  231139. if (owner != 0)
  231140. owner->redirectMouseDrag (ev);
  231141. }
  231142. - (void) mouseMoved: (NSEvent*) ev
  231143. {
  231144. if (owner != 0)
  231145. owner->redirectMouseMove (ev);
  231146. }
  231147. - (void) mouseEntered: (NSEvent*) ev
  231148. {
  231149. if (owner != 0)
  231150. owner->redirectMouseEnter (ev);
  231151. }
  231152. - (void) mouseExited: (NSEvent*) ev
  231153. {
  231154. if (owner != 0)
  231155. owner->redirectMouseExit (ev);
  231156. }
  231157. - (void) rightMouseDown: (NSEvent*) ev
  231158. {
  231159. [self mouseDown: ev];
  231160. }
  231161. - (void) rightMouseDragged: (NSEvent*) ev
  231162. {
  231163. [self mouseDragged: ev];
  231164. }
  231165. - (void) rightMouseUp: (NSEvent*) ev
  231166. {
  231167. [self mouseUp: ev];
  231168. }
  231169. - (void) otherMouseDown: (NSEvent*) ev
  231170. {
  231171. [self mouseDown: ev];
  231172. }
  231173. - (void) otherMouseDragged: (NSEvent*) ev
  231174. {
  231175. [self mouseDragged: ev];
  231176. }
  231177. - (void) otherMouseUp: (NSEvent*) ev
  231178. {
  231179. [self mouseUp: ev];
  231180. }
  231181. - (void) scrollWheel: (NSEvent*) ev
  231182. {
  231183. if (owner != 0)
  231184. owner->redirectMouseWheel (ev);
  231185. }
  231186. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231187. {
  231188. (void) ev;
  231189. return YES;
  231190. }
  231191. - (void) frameChanged: (NSNotification*) n
  231192. {
  231193. (void) n;
  231194. if (owner != 0)
  231195. owner->redirectMovedOrResized();
  231196. }
  231197. - (void) viewDidMoveToWindow
  231198. {
  231199. if (owner != 0)
  231200. owner->viewMovedToWindow();
  231201. }
  231202. - (void) asyncRepaint: (id) rect
  231203. {
  231204. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231205. [self setNeedsDisplayInRect: *r];
  231206. }
  231207. - (void) keyDown: (NSEvent*) ev
  231208. {
  231209. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231210. textWasInserted = false;
  231211. if (target != 0)
  231212. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231213. else
  231214. deleteAndZero (stringBeingComposed);
  231215. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231216. [super keyDown: ev];
  231217. }
  231218. - (void) keyUp: (NSEvent*) ev
  231219. {
  231220. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231221. [super keyUp: ev];
  231222. }
  231223. - (void) insertText: (id) aString
  231224. {
  231225. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231226. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231227. if ([newText length] > 0)
  231228. {
  231229. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231230. if (target != 0)
  231231. {
  231232. target->insertTextAtCaret (nsStringToJuce (newText));
  231233. textWasInserted = true;
  231234. }
  231235. }
  231236. deleteAndZero (stringBeingComposed);
  231237. }
  231238. - (void) doCommandBySelector: (SEL) aSelector
  231239. {
  231240. (void) aSelector;
  231241. }
  231242. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231243. {
  231244. (void) selectionRange;
  231245. if (stringBeingComposed == 0)
  231246. stringBeingComposed = new String();
  231247. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231248. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231249. if (target != 0)
  231250. {
  231251. const Range<int> currentHighlight (target->getHighlightedRegion());
  231252. target->insertTextAtCaret (*stringBeingComposed);
  231253. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231254. textWasInserted = true;
  231255. }
  231256. }
  231257. - (void) unmarkText
  231258. {
  231259. if (stringBeingComposed != 0)
  231260. {
  231261. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231262. if (target != 0)
  231263. {
  231264. target->insertTextAtCaret (*stringBeingComposed);
  231265. textWasInserted = true;
  231266. }
  231267. }
  231268. deleteAndZero (stringBeingComposed);
  231269. }
  231270. - (BOOL) hasMarkedText
  231271. {
  231272. return stringBeingComposed != 0;
  231273. }
  231274. - (long) conversationIdentifier
  231275. {
  231276. return (long) (pointer_sized_int) self;
  231277. }
  231278. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231279. {
  231280. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231281. if (target != 0)
  231282. {
  231283. const Range<int> r ((int) theRange.location,
  231284. (int) (theRange.location + theRange.length));
  231285. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231286. }
  231287. return nil;
  231288. }
  231289. - (NSRange) markedRange
  231290. {
  231291. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231292. : NSMakeRange (NSNotFound, 0);
  231293. }
  231294. - (NSRange) selectedRange
  231295. {
  231296. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231297. if (target != 0)
  231298. {
  231299. const Range<int> highlight (target->getHighlightedRegion());
  231300. if (! highlight.isEmpty())
  231301. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231302. }
  231303. return NSMakeRange (NSNotFound, 0);
  231304. }
  231305. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231306. {
  231307. (void) theRange;
  231308. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231309. if (comp == 0)
  231310. return NSMakeRect (0, 0, 0, 0);
  231311. const Rectangle<int> bounds (comp->getScreenBounds());
  231312. return NSMakeRect (bounds.getX(),
  231313. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231314. bounds.getWidth(),
  231315. bounds.getHeight());
  231316. }
  231317. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231318. {
  231319. (void) thePoint;
  231320. return NSNotFound;
  231321. }
  231322. - (NSArray*) validAttributesForMarkedText
  231323. {
  231324. return [NSArray array];
  231325. }
  231326. - (void) flagsChanged: (NSEvent*) ev
  231327. {
  231328. if (owner != 0)
  231329. owner->redirectModKeyChange (ev);
  231330. }
  231331. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231332. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231333. {
  231334. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231335. return true;
  231336. return [super performKeyEquivalent: ev];
  231337. }
  231338. #endif
  231339. - (BOOL) becomeFirstResponder
  231340. {
  231341. if (owner != 0)
  231342. owner->viewFocusGain();
  231343. return true;
  231344. }
  231345. - (BOOL) resignFirstResponder
  231346. {
  231347. if (owner != 0)
  231348. owner->viewFocusLoss();
  231349. return true;
  231350. }
  231351. - (BOOL) acceptsFirstResponder
  231352. {
  231353. return owner != 0 && owner->canBecomeKeyWindow();
  231354. }
  231355. - (NSArray*) getSupportedDragTypes
  231356. {
  231357. return [NSArray arrayWithObjects: NSFilenamesPboardType, NSFilesPromisePboardType, /* NSStringPboardType,*/ nil];
  231358. }
  231359. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231360. {
  231361. return owner != 0 && owner->sendDragCallback (type, sender);
  231362. }
  231363. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231364. {
  231365. if ([self sendDragCallback: 0 sender: sender])
  231366. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231367. else
  231368. return NSDragOperationNone;
  231369. }
  231370. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231371. {
  231372. if ([self sendDragCallback: 0 sender: sender])
  231373. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231374. else
  231375. return NSDragOperationNone;
  231376. }
  231377. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231378. {
  231379. [self sendDragCallback: 1 sender: sender];
  231380. }
  231381. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231382. {
  231383. [self sendDragCallback: 1 sender: sender];
  231384. }
  231385. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231386. {
  231387. (void) sender;
  231388. return YES;
  231389. }
  231390. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231391. {
  231392. return [self sendDragCallback: 2 sender: sender];
  231393. }
  231394. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231395. {
  231396. (void) sender;
  231397. }
  231398. @end
  231399. @implementation JuceNSWindow
  231400. - (void) setOwner: (NSViewComponentPeer*) owner_
  231401. {
  231402. owner = owner_;
  231403. isZooming = false;
  231404. }
  231405. - (BOOL) canBecomeKeyWindow
  231406. {
  231407. return owner != 0 && owner->canBecomeKeyWindow();
  231408. }
  231409. - (void) becomeKeyWindow
  231410. {
  231411. [super becomeKeyWindow];
  231412. if (owner != 0)
  231413. owner->grabFocus();
  231414. }
  231415. - (BOOL) windowShouldClose: (id) window
  231416. {
  231417. (void) window;
  231418. return owner == 0 || owner->windowShouldClose();
  231419. }
  231420. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231421. {
  231422. (void) screen;
  231423. if (owner != 0)
  231424. frameRect = owner->constrainRect (frameRect);
  231425. return frameRect;
  231426. }
  231427. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231428. {
  231429. (void) window;
  231430. if (isZooming)
  231431. return proposedFrameSize;
  231432. NSRect frameRect = [self frame];
  231433. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231434. frameRect.size = proposedFrameSize;
  231435. if (owner != 0)
  231436. frameRect = owner->constrainRect (frameRect);
  231437. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231438. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231439. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231440. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231441. return frameRect.size;
  231442. }
  231443. - (void) zoom: (id) sender
  231444. {
  231445. isZooming = true;
  231446. [super zoom: sender];
  231447. isZooming = false;
  231448. }
  231449. - (void) windowWillMove: (NSNotification*) notification
  231450. {
  231451. (void) notification;
  231452. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231453. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231454. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231455. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231456. }
  231457. @end
  231458. BEGIN_JUCE_NAMESPACE
  231459. ModifierKeys NSViewComponentPeer::currentModifiers;
  231460. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231461. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231462. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231463. {
  231464. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231465. return true;
  231466. if (keyCode >= 'A' && keyCode <= 'Z'
  231467. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231468. return true;
  231469. if (keyCode >= 'a' && keyCode <= 'z'
  231470. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231471. return true;
  231472. return false;
  231473. }
  231474. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231475. {
  231476. int m = 0;
  231477. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231478. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231479. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231480. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231481. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231482. }
  231483. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231484. {
  231485. updateModifiers (ev);
  231486. int keyCode = getKeyCodeFromEvent (ev);
  231487. if (keyCode != 0)
  231488. {
  231489. if (isKeyDown)
  231490. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231491. else
  231492. keysCurrentlyDown.removeValue (keyCode);
  231493. }
  231494. }
  231495. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231496. {
  231497. return NSViewComponentPeer::currentModifiers;
  231498. }
  231499. void ModifierKeys::updateCurrentModifiers() throw()
  231500. {
  231501. currentModifiers = NSViewComponentPeer::currentModifiers;
  231502. }
  231503. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231504. const int windowStyleFlags,
  231505. NSView* viewToAttachTo)
  231506. : ComponentPeer (component_, windowStyleFlags),
  231507. window (0),
  231508. view (0),
  231509. isSharedWindow (viewToAttachTo != 0),
  231510. fullScreen (false),
  231511. insideDrawRect (false),
  231512. #if USE_COREGRAPHICS_RENDERING
  231513. usingCoreGraphics (true),
  231514. #else
  231515. usingCoreGraphics (false),
  231516. #endif
  231517. recursiveToFrontCall (false)
  231518. {
  231519. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231520. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231521. [view setPostsFrameChangedNotifications: YES];
  231522. if (isSharedWindow)
  231523. {
  231524. window = [viewToAttachTo window];
  231525. [viewToAttachTo addSubview: view];
  231526. }
  231527. else
  231528. {
  231529. r.origin.x = (float) component->getX();
  231530. r.origin.y = (float) component->getY();
  231531. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231532. unsigned int style = 0;
  231533. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231534. style = NSBorderlessWindowMask;
  231535. else
  231536. style = NSTitledWindowMask;
  231537. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231538. style |= NSMiniaturizableWindowMask;
  231539. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231540. style |= NSClosableWindowMask;
  231541. if ((windowStyleFlags & windowIsResizable) != 0)
  231542. style |= NSResizableWindowMask;
  231543. window = [[JuceNSWindow alloc] initWithContentRect: r
  231544. styleMask: style
  231545. backing: NSBackingStoreBuffered
  231546. defer: YES];
  231547. [((JuceNSWindow*) window) setOwner: this];
  231548. [window orderOut: nil];
  231549. [window setDelegate: (JuceNSWindow*) window];
  231550. [window setOpaque: component->isOpaque()];
  231551. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231552. if (component->isAlwaysOnTop())
  231553. [window setLevel: NSFloatingWindowLevel];
  231554. [window setContentView: view];
  231555. [window setAutodisplay: YES];
  231556. [window setAcceptsMouseMovedEvents: YES];
  231557. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231558. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231559. [window setReleasedWhenClosed: YES];
  231560. [window retain];
  231561. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231562. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231563. }
  231564. const float alpha = component->getAlpha();
  231565. if (alpha < 1.0f)
  231566. setAlpha (alpha);
  231567. setTitle (component->getName());
  231568. }
  231569. NSViewComponentPeer::~NSViewComponentPeer()
  231570. {
  231571. view->owner = 0;
  231572. [view removeFromSuperview];
  231573. [view release];
  231574. if (! isSharedWindow)
  231575. {
  231576. [((JuceNSWindow*) window) setOwner: 0];
  231577. [window close];
  231578. [window release];
  231579. }
  231580. }
  231581. void* NSViewComponentPeer::getNativeHandle() const
  231582. {
  231583. return view;
  231584. }
  231585. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231586. {
  231587. if (isSharedWindow)
  231588. {
  231589. [view setHidden: ! shouldBeVisible];
  231590. }
  231591. else
  231592. {
  231593. if (shouldBeVisible)
  231594. {
  231595. [window orderFront: nil];
  231596. handleBroughtToFront();
  231597. }
  231598. else
  231599. {
  231600. [window orderOut: nil];
  231601. }
  231602. }
  231603. }
  231604. void NSViewComponentPeer::setTitle (const String& title)
  231605. {
  231606. const ScopedAutoReleasePool pool;
  231607. if (! isSharedWindow)
  231608. [window setTitle: juceStringToNS (title)];
  231609. }
  231610. void NSViewComponentPeer::setPosition (int x, int y)
  231611. {
  231612. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231613. }
  231614. void NSViewComponentPeer::setSize (int w, int h)
  231615. {
  231616. setBounds (component->getX(), component->getY(), w, h, false);
  231617. }
  231618. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231619. {
  231620. fullScreen = isNowFullScreen;
  231621. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231622. if (isSharedWindow)
  231623. {
  231624. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231625. if ([view frame].size.width != r.size.width
  231626. || [view frame].size.height != r.size.height)
  231627. [view setNeedsDisplay: true];
  231628. [view setFrame: r];
  231629. }
  231630. else
  231631. {
  231632. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231633. [window setFrame: [window frameRectForContentRect: r]
  231634. display: true];
  231635. }
  231636. }
  231637. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231638. {
  231639. NSRect r = [view frame];
  231640. if (global && [view window] != 0)
  231641. {
  231642. r = [view convertRect: r toView: nil];
  231643. NSRect wr = [[view window] frame];
  231644. r.origin.x += wr.origin.x;
  231645. r.origin.y += wr.origin.y;
  231646. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231647. }
  231648. else
  231649. {
  231650. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231651. }
  231652. return Rectangle<int> (convertToRectInt (r));
  231653. }
  231654. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231655. {
  231656. return getBounds (! isSharedWindow);
  231657. }
  231658. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231659. {
  231660. return getBounds (true).getPosition();
  231661. }
  231662. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231663. {
  231664. return relativePosition + getScreenPosition();
  231665. }
  231666. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231667. {
  231668. return screenPosition - getScreenPosition();
  231669. }
  231670. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231671. {
  231672. if (constrainer != 0)
  231673. {
  231674. NSRect current = [window frame];
  231675. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231676. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231677. Rectangle<int> pos (convertToRectInt (r));
  231678. Rectangle<int> original (convertToRectInt (current));
  231679. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231680. if ([window inLiveResize])
  231681. #else
  231682. if ([window respondsToSelector: @selector (inLiveResize)]
  231683. && [window performSelector: @selector (inLiveResize)])
  231684. #endif
  231685. {
  231686. constrainer->checkBounds (pos, original,
  231687. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231688. false, false, true, true);
  231689. }
  231690. else
  231691. {
  231692. constrainer->checkBounds (pos, original,
  231693. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231694. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231695. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231696. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231697. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231698. }
  231699. r.origin.x = pos.getX();
  231700. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231701. r.size.width = pos.getWidth();
  231702. r.size.height = pos.getHeight();
  231703. }
  231704. return r;
  231705. }
  231706. void NSViewComponentPeer::setAlpha (float newAlpha)
  231707. {
  231708. if (! isSharedWindow)
  231709. {
  231710. [window setAlphaValue: (CGFloat) newAlpha];
  231711. }
  231712. else
  231713. {
  231714. #if defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5
  231715. [view setAlphaValue: (CGFloat) newAlpha];
  231716. #else
  231717. if ([view respondsToSelector: @selector (setAlphaValue:)])
  231718. {
  231719. // PITA dynamic invocation for 10.4 builds..
  231720. NSInvocation* inv = [NSInvocation invocationWithMethodSignature: [view methodSignatureForSelector: @selector (setAlphaValue:)]];
  231721. [inv setSelector: @selector (setAlphaValue:)];
  231722. [inv setTarget: view];
  231723. CGFloat cgNewAlpha = (CGFloat) newAlpha;
  231724. [inv setArgument: &cgNewAlpha atIndex: 2];
  231725. [inv invoke];
  231726. }
  231727. #endif
  231728. }
  231729. }
  231730. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231731. {
  231732. if (! isSharedWindow)
  231733. {
  231734. if (shouldBeMinimised)
  231735. [window miniaturize: nil];
  231736. else
  231737. [window deminiaturize: nil];
  231738. }
  231739. }
  231740. bool NSViewComponentPeer::isMinimised() const
  231741. {
  231742. return window != 0 && [window isMiniaturized];
  231743. }
  231744. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231745. {
  231746. if (! isSharedWindow)
  231747. {
  231748. Rectangle<int> r (lastNonFullscreenBounds);
  231749. setMinimised (false);
  231750. if (fullScreen != shouldBeFullScreen)
  231751. {
  231752. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231753. {
  231754. fullScreen = true;
  231755. [window performZoom: nil];
  231756. }
  231757. else
  231758. {
  231759. if (shouldBeFullScreen)
  231760. r = Desktop::getInstance().getMainMonitorArea();
  231761. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231762. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231763. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231764. }
  231765. }
  231766. }
  231767. }
  231768. bool NSViewComponentPeer::isFullScreen() const
  231769. {
  231770. return fullScreen;
  231771. }
  231772. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231773. {
  231774. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231775. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231776. return false;
  231777. NSPoint p;
  231778. p.x = (float) position.getX();
  231779. p.y = (float) position.getY();
  231780. NSView* v = [view hitTest: p];
  231781. if (trueIfInAChildWindow)
  231782. return v != nil;
  231783. return v == view;
  231784. }
  231785. const BorderSize<int> NSViewComponentPeer::getFrameSize() const
  231786. {
  231787. BorderSize<int> b;
  231788. if (! isSharedWindow)
  231789. {
  231790. NSRect v = [view convertRect: [view frame] toView: nil];
  231791. NSRect w = [window frame];
  231792. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231793. b.setBottom ((int) v.origin.y);
  231794. b.setLeft ((int) v.origin.x);
  231795. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231796. }
  231797. return b;
  231798. }
  231799. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231800. {
  231801. if (! isSharedWindow)
  231802. {
  231803. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231804. : NSNormalWindowLevel];
  231805. }
  231806. return true;
  231807. }
  231808. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231809. {
  231810. if (isSharedWindow)
  231811. {
  231812. [[view superview] addSubview: view
  231813. positioned: NSWindowAbove
  231814. relativeTo: nil];
  231815. }
  231816. if (window != 0 && component->isVisible())
  231817. {
  231818. if (makeActiveWindow)
  231819. [window makeKeyAndOrderFront: nil];
  231820. else
  231821. [window orderFront: nil];
  231822. if (! recursiveToFrontCall)
  231823. {
  231824. recursiveToFrontCall = true;
  231825. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231826. handleBroughtToFront();
  231827. recursiveToFrontCall = false;
  231828. }
  231829. }
  231830. }
  231831. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231832. {
  231833. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231834. jassert (otherPeer != 0); // wrong type of window?
  231835. if (otherPeer != 0)
  231836. {
  231837. if (isSharedWindow)
  231838. {
  231839. [[view superview] addSubview: view
  231840. positioned: NSWindowBelow
  231841. relativeTo: otherPeer->view];
  231842. }
  231843. else
  231844. {
  231845. [window orderWindow: NSWindowBelow
  231846. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231847. : nil ];
  231848. }
  231849. }
  231850. }
  231851. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231852. {
  231853. // to do..
  231854. }
  231855. void NSViewComponentPeer::viewFocusGain()
  231856. {
  231857. if (currentlyFocusedPeer != this)
  231858. {
  231859. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231860. currentlyFocusedPeer->handleFocusLoss();
  231861. currentlyFocusedPeer = this;
  231862. handleFocusGain();
  231863. }
  231864. }
  231865. void NSViewComponentPeer::viewFocusLoss()
  231866. {
  231867. if (currentlyFocusedPeer == this)
  231868. {
  231869. currentlyFocusedPeer = 0;
  231870. handleFocusLoss();
  231871. }
  231872. }
  231873. void juce_HandleProcessFocusChange()
  231874. {
  231875. NSViewComponentPeer::keysCurrentlyDown.clear();
  231876. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231877. {
  231878. if (Process::isForegroundProcess())
  231879. {
  231880. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231881. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231882. }
  231883. else
  231884. {
  231885. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231886. // turn kiosk mode off if we lose focus..
  231887. Desktop::getInstance().setKioskModeComponent (0);
  231888. }
  231889. }
  231890. }
  231891. bool NSViewComponentPeer::isFocused() const
  231892. {
  231893. return isSharedWindow ? this == currentlyFocusedPeer
  231894. : (window != 0 && [window isKeyWindow]);
  231895. }
  231896. void NSViewComponentPeer::grabFocus()
  231897. {
  231898. if (window != 0)
  231899. {
  231900. [window makeKeyWindow];
  231901. [window makeFirstResponder: view];
  231902. viewFocusGain();
  231903. }
  231904. }
  231905. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231906. {
  231907. }
  231908. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231909. {
  231910. String unicode (nsStringToJuce ([ev characters]));
  231911. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231912. int keyCode = getKeyCodeFromEvent (ev);
  231913. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231914. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231915. if (unicode.isNotEmpty() || keyCode != 0)
  231916. {
  231917. if (isKeyDown)
  231918. {
  231919. bool used = false;
  231920. while (unicode.length() > 0)
  231921. {
  231922. juce_wchar textCharacter = unicode[0];
  231923. unicode = unicode.substring (1);
  231924. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231925. textCharacter = 0;
  231926. used = handleKeyUpOrDown (true) || used;
  231927. used = handleKeyPress (keyCode, textCharacter) || used;
  231928. }
  231929. return used;
  231930. }
  231931. else
  231932. {
  231933. if (handleKeyUpOrDown (false))
  231934. return true;
  231935. }
  231936. }
  231937. return false;
  231938. }
  231939. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231940. {
  231941. updateKeysDown (ev, true);
  231942. bool used = handleKeyEvent (ev, true);
  231943. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231944. {
  231945. // for command keys, the key-up event is thrown away, so simulate one..
  231946. updateKeysDown (ev, false);
  231947. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231948. }
  231949. // (If we're running modally, don't allow unused keystrokes to be passed
  231950. // along to other blocked views..)
  231951. if (Component::getCurrentlyModalComponent() != 0)
  231952. used = true;
  231953. return used;
  231954. }
  231955. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231956. {
  231957. updateKeysDown (ev, false);
  231958. return handleKeyEvent (ev, false)
  231959. || Component::getCurrentlyModalComponent() != 0;
  231960. }
  231961. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231962. {
  231963. keysCurrentlyDown.clear();
  231964. handleKeyUpOrDown (true);
  231965. updateModifiers (ev);
  231966. handleModifierKeysChange();
  231967. }
  231968. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231969. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231970. {
  231971. if ([ev type] == NSKeyDown)
  231972. return redirectKeyDown (ev);
  231973. else if ([ev type] == NSKeyUp)
  231974. return redirectKeyUp (ev);
  231975. return false;
  231976. }
  231977. #endif
  231978. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231979. {
  231980. updateModifiers (ev);
  231981. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231982. }
  231983. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231984. {
  231985. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231986. sendMouseEvent (ev);
  231987. }
  231988. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231989. {
  231990. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231991. sendMouseEvent (ev);
  231992. showArrowCursorIfNeeded();
  231993. }
  231994. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231995. {
  231996. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231997. sendMouseEvent (ev);
  231998. }
  231999. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232000. {
  232001. currentModifiers = currentModifiers.withoutMouseButtons();
  232002. sendMouseEvent (ev);
  232003. showArrowCursorIfNeeded();
  232004. }
  232005. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232006. {
  232007. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232008. currentModifiers = currentModifiers.withoutMouseButtons();
  232009. sendMouseEvent (ev);
  232010. }
  232011. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232012. {
  232013. currentModifiers = currentModifiers.withoutMouseButtons();
  232014. sendMouseEvent (ev);
  232015. }
  232016. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232017. {
  232018. updateModifiers (ev);
  232019. float x = 0, y = 0;
  232020. @try
  232021. {
  232022. x = [ev deviceDeltaX] * 0.5f;
  232023. y = [ev deviceDeltaY] * 0.5f;
  232024. }
  232025. @catch (...)
  232026. {}
  232027. if (x == 0 && y == 0)
  232028. {
  232029. x = [ev deltaX] * 10.0f;
  232030. y = [ev deltaY] * 10.0f;
  232031. }
  232032. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232033. }
  232034. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232035. {
  232036. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232037. if (mouse.getComponentUnderMouse() == 0
  232038. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232039. {
  232040. [[NSCursor arrowCursor] set];
  232041. }
  232042. }
  232043. BOOL NSViewComponentPeer::sendDragCallback (const int type, id <NSDraggingInfo> sender)
  232044. {
  232045. NSString* bestType
  232046. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232047. if (bestType == nil)
  232048. return false;
  232049. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232050. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232051. NSPasteboard* pasteBoard = [sender draggingPasteboard];
  232052. StringArray files;
  232053. NSString* iTunesPasteboardType = @"CorePasteboardFlavorType 0x6974756E"; // 'itun'
  232054. if (bestType == NSFilesPromisePboardType
  232055. && [[pasteBoard types] containsObject: iTunesPasteboardType])
  232056. {
  232057. id list = [pasteBoard propertyListForType: iTunesPasteboardType];
  232058. if ([list isKindOfClass: [NSDictionary class]])
  232059. {
  232060. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  232061. NSArray* tracks = [iTunesDictionary valueForKey: @"Tracks"];
  232062. NSEnumerator* enumerator = [tracks objectEnumerator];
  232063. NSDictionary* track;
  232064. while ((track = [enumerator nextObject]) != nil)
  232065. {
  232066. NSURL* url = [NSURL URLWithString: [track valueForKey: @"Location"]];
  232067. if ([url isFileURL])
  232068. files.add (nsStringToJuce ([url path]));
  232069. }
  232070. }
  232071. }
  232072. else
  232073. {
  232074. id list = [pasteBoard propertyListForType: NSFilenamesPboardType];
  232075. if ([list isKindOfClass: [NSArray class]])
  232076. {
  232077. NSArray* items = (NSArray*) [pasteBoard propertyListForType: NSFilenamesPboardType];
  232078. for (unsigned int i = 0; i < [items count]; ++i)
  232079. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232080. }
  232081. }
  232082. if (files.size() > 0)
  232083. {
  232084. switch (type)
  232085. {
  232086. case 0: handleFileDragMove (files, pos); break;
  232087. case 1: handleFileDragExit (files); break;
  232088. case 2: handleFileDragDrop (files, pos); break;
  232089. default: jassertfalse; break;
  232090. }
  232091. return true;
  232092. }
  232093. return false;
  232094. }
  232095. bool NSViewComponentPeer::isOpaque()
  232096. {
  232097. return component == 0 || component->isOpaque();
  232098. }
  232099. void NSViewComponentPeer::drawRect (NSRect r)
  232100. {
  232101. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232102. return;
  232103. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232104. if (! component->isOpaque())
  232105. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232106. #if USE_COREGRAPHICS_RENDERING
  232107. if (usingCoreGraphics)
  232108. {
  232109. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232110. insideDrawRect = true;
  232111. handlePaint (context);
  232112. insideDrawRect = false;
  232113. }
  232114. else
  232115. #endif
  232116. {
  232117. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232118. (int) (r.size.width + 0.5f),
  232119. (int) (r.size.height + 0.5f),
  232120. ! getComponent()->isOpaque());
  232121. const int xOffset = -roundToInt (r.origin.x);
  232122. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232123. const NSRect* rects = 0;
  232124. NSInteger numRects = 0;
  232125. [view getRectsBeingDrawn: &rects count: &numRects];
  232126. const Rectangle<int> clipBounds (temp.getBounds());
  232127. RectangleList clip;
  232128. for (int i = 0; i < numRects; ++i)
  232129. {
  232130. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232131. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232132. roundToInt (rects[i].size.width),
  232133. roundToInt (rects[i].size.height))));
  232134. }
  232135. if (! clip.isEmpty())
  232136. {
  232137. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232138. insideDrawRect = true;
  232139. handlePaint (context);
  232140. insideDrawRect = false;
  232141. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232142. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace, false);
  232143. CGColorSpaceRelease (colourSpace);
  232144. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232145. CGImageRelease (image);
  232146. }
  232147. }
  232148. }
  232149. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232150. {
  232151. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232152. #if USE_COREGRAPHICS_RENDERING
  232153. s.add ("CoreGraphics Renderer");
  232154. #endif
  232155. return s;
  232156. }
  232157. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232158. {
  232159. return usingCoreGraphics ? 1 : 0;
  232160. }
  232161. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232162. {
  232163. #if USE_COREGRAPHICS_RENDERING
  232164. if (usingCoreGraphics != (index > 0))
  232165. {
  232166. usingCoreGraphics = index > 0;
  232167. [view setNeedsDisplay: true];
  232168. }
  232169. #endif
  232170. }
  232171. bool NSViewComponentPeer::canBecomeKeyWindow()
  232172. {
  232173. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232174. }
  232175. bool NSViewComponentPeer::windowShouldClose()
  232176. {
  232177. if (! isValidPeer (this))
  232178. return YES;
  232179. handleUserClosingWindow();
  232180. return NO;
  232181. }
  232182. void NSViewComponentPeer::redirectMovedOrResized()
  232183. {
  232184. handleMovedOrResized();
  232185. }
  232186. void NSViewComponentPeer::viewMovedToWindow()
  232187. {
  232188. if (isSharedWindow)
  232189. window = [view window];
  232190. }
  232191. void Desktop::createMouseInputSources()
  232192. {
  232193. mouseSources.add (new MouseInputSource (0, true));
  232194. }
  232195. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232196. {
  232197. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  232198. if (enableOrDisable)
  232199. {
  232200. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  232201. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  232202. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232203. }
  232204. else
  232205. {
  232206. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  232207. }
  232208. #else
  232209. if (enableOrDisable)
  232210. {
  232211. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232212. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232213. }
  232214. else
  232215. {
  232216. SetSystemUIMode (kUIModeNormal, 0);
  232217. }
  232218. #endif
  232219. }
  232220. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232221. {
  232222. if (insideDrawRect)
  232223. {
  232224. class AsyncRepaintMessage : public CallbackMessage
  232225. {
  232226. public:
  232227. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232228. : peer (peer_), rect (rect_)
  232229. {
  232230. }
  232231. void messageCallback()
  232232. {
  232233. if (ComponentPeer::isValidPeer (peer))
  232234. peer->repaint (rect);
  232235. }
  232236. private:
  232237. NSViewComponentPeer* const peer;
  232238. const Rectangle<int> rect;
  232239. };
  232240. (new AsyncRepaintMessage (this, area))->post();
  232241. }
  232242. else
  232243. {
  232244. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232245. (float) area.getWidth(), (float) area.getHeight())];
  232246. }
  232247. }
  232248. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232249. {
  232250. [view displayIfNeeded];
  232251. }
  232252. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232253. {
  232254. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232255. }
  232256. const Image juce_createIconForFile (const File& file)
  232257. {
  232258. const ScopedAutoReleasePool pool;
  232259. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232260. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232261. [NSGraphicsContext saveGraphicsState];
  232262. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232263. [image drawAtPoint: NSMakePoint (0, 0)
  232264. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232265. operation: NSCompositeSourceOver fraction: 1.0f];
  232266. [[NSGraphicsContext currentContext] flushGraphics];
  232267. [NSGraphicsContext restoreGraphicsState];
  232268. return Image (result);
  232269. }
  232270. const int KeyPress::spaceKey = ' ';
  232271. const int KeyPress::returnKey = 0x0d;
  232272. const int KeyPress::escapeKey = 0x1b;
  232273. const int KeyPress::backspaceKey = 0x7f;
  232274. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232275. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232276. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232277. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232278. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232279. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232280. const int KeyPress::endKey = NSEndFunctionKey;
  232281. const int KeyPress::homeKey = NSHomeFunctionKey;
  232282. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232283. const int KeyPress::insertKey = -1;
  232284. const int KeyPress::tabKey = 9;
  232285. const int KeyPress::F1Key = NSF1FunctionKey;
  232286. const int KeyPress::F2Key = NSF2FunctionKey;
  232287. const int KeyPress::F3Key = NSF3FunctionKey;
  232288. const int KeyPress::F4Key = NSF4FunctionKey;
  232289. const int KeyPress::F5Key = NSF5FunctionKey;
  232290. const int KeyPress::F6Key = NSF6FunctionKey;
  232291. const int KeyPress::F7Key = NSF7FunctionKey;
  232292. const int KeyPress::F8Key = NSF8FunctionKey;
  232293. const int KeyPress::F9Key = NSF9FunctionKey;
  232294. const int KeyPress::F10Key = NSF10FunctionKey;
  232295. const int KeyPress::F11Key = NSF1FunctionKey;
  232296. const int KeyPress::F12Key = NSF12FunctionKey;
  232297. const int KeyPress::F13Key = NSF13FunctionKey;
  232298. const int KeyPress::F14Key = NSF14FunctionKey;
  232299. const int KeyPress::F15Key = NSF15FunctionKey;
  232300. const int KeyPress::F16Key = NSF16FunctionKey;
  232301. const int KeyPress::numberPad0 = 0x30020;
  232302. const int KeyPress::numberPad1 = 0x30021;
  232303. const int KeyPress::numberPad2 = 0x30022;
  232304. const int KeyPress::numberPad3 = 0x30023;
  232305. const int KeyPress::numberPad4 = 0x30024;
  232306. const int KeyPress::numberPad5 = 0x30025;
  232307. const int KeyPress::numberPad6 = 0x30026;
  232308. const int KeyPress::numberPad7 = 0x30027;
  232309. const int KeyPress::numberPad8 = 0x30028;
  232310. const int KeyPress::numberPad9 = 0x30029;
  232311. const int KeyPress::numberPadAdd = 0x3002a;
  232312. const int KeyPress::numberPadSubtract = 0x3002b;
  232313. const int KeyPress::numberPadMultiply = 0x3002c;
  232314. const int KeyPress::numberPadDivide = 0x3002d;
  232315. const int KeyPress::numberPadSeparator = 0x3002e;
  232316. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232317. const int KeyPress::numberPadEquals = 0x30030;
  232318. const int KeyPress::numberPadDelete = 0x30031;
  232319. const int KeyPress::playKey = 0x30000;
  232320. const int KeyPress::stopKey = 0x30001;
  232321. const int KeyPress::fastForwardKey = 0x30002;
  232322. const int KeyPress::rewindKey = 0x30003;
  232323. #endif
  232324. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232325. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232326. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232327. // compiled on its own).
  232328. #if JUCE_INCLUDED_FILE
  232329. #if JUCE_MAC
  232330. namespace MouseCursorHelpers
  232331. {
  232332. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232333. {
  232334. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232335. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232336. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232337. [im release];
  232338. return c;
  232339. }
  232340. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232341. {
  232342. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232343. BufferedInputStream buf (fileStream, 4096);
  232344. PNGImageFormat pngFormat;
  232345. Image im (pngFormat.decodeImage (buf));
  232346. if (im.isValid())
  232347. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232348. jassertfalse;
  232349. return 0;
  232350. }
  232351. }
  232352. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232353. {
  232354. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232355. }
  232356. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232357. {
  232358. const ScopedAutoReleasePool pool;
  232359. NSCursor* c = 0;
  232360. switch (type)
  232361. {
  232362. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232363. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232364. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232365. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232366. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232367. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232368. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232369. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232370. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232371. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232372. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232373. case UpDownResizeCursor:
  232374. case TopEdgeResizeCursor:
  232375. case BottomEdgeResizeCursor:
  232376. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232377. case TopLeftCornerResizeCursor:
  232378. case BottomRightCornerResizeCursor:
  232379. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232380. case TopRightCornerResizeCursor:
  232381. case BottomLeftCornerResizeCursor:
  232382. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232383. case UpDownLeftRightResizeCursor:
  232384. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232385. default:
  232386. jassertfalse;
  232387. break;
  232388. }
  232389. [c retain];
  232390. return c;
  232391. }
  232392. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232393. {
  232394. [((NSCursor*) cursorHandle) release];
  232395. }
  232396. void MouseCursor::showInAllWindows() const
  232397. {
  232398. showInWindow (0);
  232399. }
  232400. void MouseCursor::showInWindow (ComponentPeer*) const
  232401. {
  232402. NSCursor* c = (NSCursor*) getHandle();
  232403. if (c == 0)
  232404. c = [NSCursor arrowCursor];
  232405. [c set];
  232406. }
  232407. #else
  232408. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232409. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232410. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232411. void MouseCursor::showInAllWindows() const {}
  232412. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232413. #endif
  232414. #endif
  232415. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232416. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232417. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232418. // compiled on its own).
  232419. #if JUCE_INCLUDED_FILE
  232420. class NSViewComponentInternal : public ComponentMovementWatcher
  232421. {
  232422. public:
  232423. NSViewComponentInternal (NSView* const view_, Component& owner_)
  232424. : ComponentMovementWatcher (&owner_),
  232425. owner (owner_),
  232426. currentPeer (0),
  232427. view (view_)
  232428. {
  232429. [view_ retain];
  232430. if (owner.isShowing())
  232431. componentPeerChanged();
  232432. }
  232433. ~NSViewComponentInternal()
  232434. {
  232435. [view removeFromSuperview];
  232436. [view release];
  232437. }
  232438. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232439. {
  232440. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232441. // The ComponentMovementWatcher version of this method avoids calling
  232442. // us when the top-level comp is resized, but for an NSView we need to know this
  232443. // because with inverted co-ords, we need to update the position even if the
  232444. // top-left pos hasn't changed
  232445. if (comp.isOnDesktop() && wasResized)
  232446. componentMovedOrResized (wasMoved, wasResized);
  232447. }
  232448. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232449. {
  232450. Component* const topComp = owner.getTopLevelComponent();
  232451. if (topComp->getPeer() != 0)
  232452. {
  232453. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  232454. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner.getWidth(), (float) owner.getHeight());
  232455. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232456. [view setFrame: r];
  232457. }
  232458. }
  232459. void componentPeerChanged()
  232460. {
  232461. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner.getPeer());
  232462. if (currentPeer != peer)
  232463. {
  232464. if ([view superview] != nil)
  232465. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  232466. // override the call and use it as a sign that they're being deleted, which breaks everything..
  232467. currentPeer = peer;
  232468. if (peer != 0)
  232469. {
  232470. [peer->view addSubview: view];
  232471. componentMovedOrResized (false, false);
  232472. }
  232473. }
  232474. [view setHidden: ! owner.isShowing()];
  232475. }
  232476. void componentVisibilityChanged()
  232477. {
  232478. componentPeerChanged();
  232479. }
  232480. const Rectangle<int> getViewBounds() const
  232481. {
  232482. NSRect r = [view frame];
  232483. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232484. }
  232485. private:
  232486. Component& owner;
  232487. NSViewComponentPeer* currentPeer;
  232488. public:
  232489. NSView* const view;
  232490. private:
  232491. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  232492. };
  232493. NSViewComponent::NSViewComponent()
  232494. {
  232495. }
  232496. NSViewComponent::~NSViewComponent()
  232497. {
  232498. }
  232499. void NSViewComponent::setView (void* view)
  232500. {
  232501. if (view != getView())
  232502. {
  232503. if (view != 0)
  232504. info = new NSViewComponentInternal ((NSView*) view, *this);
  232505. else
  232506. info = 0;
  232507. }
  232508. }
  232509. void* NSViewComponent::getView() const
  232510. {
  232511. return info == 0 ? 0 : info->view;
  232512. }
  232513. void NSViewComponent::resizeToFitView()
  232514. {
  232515. if (info != 0)
  232516. setBounds (info->getViewBounds());
  232517. }
  232518. void NSViewComponent::paint (Graphics&)
  232519. {
  232520. }
  232521. #endif
  232522. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232523. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232524. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232525. // compiled on its own).
  232526. #if JUCE_INCLUDED_FILE
  232527. AppleRemoteDevice::AppleRemoteDevice()
  232528. : device (0),
  232529. queue (0),
  232530. remoteId (0)
  232531. {
  232532. }
  232533. AppleRemoteDevice::~AppleRemoteDevice()
  232534. {
  232535. stop();
  232536. }
  232537. namespace
  232538. {
  232539. io_object_t getAppleRemoteDevice()
  232540. {
  232541. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232542. io_iterator_t iter = 0;
  232543. io_object_t iod = 0;
  232544. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232545. && iter != 0)
  232546. {
  232547. iod = IOIteratorNext (iter);
  232548. }
  232549. IOObjectRelease (iter);
  232550. return iod;
  232551. }
  232552. bool createAppleRemoteInterface (io_object_t iod, void** device)
  232553. {
  232554. jassert (*device == 0);
  232555. io_name_t classname;
  232556. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232557. {
  232558. IOCFPlugInInterface** cfPlugInInterface = 0;
  232559. SInt32 score = 0;
  232560. if (IOCreatePlugInInterfaceForService (iod,
  232561. kIOHIDDeviceUserClientTypeID,
  232562. kIOCFPlugInInterfaceID,
  232563. &cfPlugInInterface,
  232564. &score) == kIOReturnSuccess)
  232565. {
  232566. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232567. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232568. device);
  232569. (void) hr;
  232570. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232571. }
  232572. }
  232573. return *device != 0;
  232574. }
  232575. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232576. {
  232577. if (result == kIOReturnSuccess)
  232578. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232579. }
  232580. }
  232581. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232582. {
  232583. if (queue != 0)
  232584. return true;
  232585. stop();
  232586. bool result = false;
  232587. io_object_t iod = getAppleRemoteDevice();
  232588. if (iod != 0)
  232589. {
  232590. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232591. result = true;
  232592. else
  232593. stop();
  232594. IOObjectRelease (iod);
  232595. }
  232596. return result;
  232597. }
  232598. void AppleRemoteDevice::stop()
  232599. {
  232600. if (queue != 0)
  232601. {
  232602. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232603. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232604. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232605. queue = 0;
  232606. }
  232607. if (device != 0)
  232608. {
  232609. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232610. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232611. device = 0;
  232612. }
  232613. }
  232614. bool AppleRemoteDevice::isActive() const
  232615. {
  232616. return queue != 0;
  232617. }
  232618. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232619. {
  232620. Array <int> cookies;
  232621. CFArrayRef elements;
  232622. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232623. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232624. return false;
  232625. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232626. {
  232627. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232628. // get the cookie
  232629. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232630. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232631. continue;
  232632. long number;
  232633. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232634. continue;
  232635. cookies.add ((int) number);
  232636. }
  232637. CFRelease (elements);
  232638. if ((*(IOHIDDeviceInterface**) device)
  232639. ->open ((IOHIDDeviceInterface**) device,
  232640. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232641. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232642. {
  232643. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232644. if (queue != 0)
  232645. {
  232646. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232647. for (int i = 0; i < cookies.size(); ++i)
  232648. {
  232649. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232650. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232651. }
  232652. CFRunLoopSourceRef eventSource;
  232653. if ((*(IOHIDQueueInterface**) queue)
  232654. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232655. {
  232656. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232657. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232658. {
  232659. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232660. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232661. return true;
  232662. }
  232663. }
  232664. }
  232665. }
  232666. return false;
  232667. }
  232668. void AppleRemoteDevice::handleCallbackInternal()
  232669. {
  232670. int totalValues = 0;
  232671. AbsoluteTime nullTime = { 0, 0 };
  232672. char cookies [12];
  232673. int numCookies = 0;
  232674. while (numCookies < numElementsInArray (cookies))
  232675. {
  232676. IOHIDEventStruct e;
  232677. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232678. break;
  232679. if ((int) e.elementCookie == 19)
  232680. {
  232681. remoteId = e.value;
  232682. buttonPressed (switched, false);
  232683. }
  232684. else
  232685. {
  232686. totalValues += e.value;
  232687. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232688. }
  232689. }
  232690. cookies [numCookies++] = 0;
  232691. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232692. static const char buttonPatterns[] =
  232693. {
  232694. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232695. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232696. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232697. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232698. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232699. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232700. 0x1f, 0x12, 0x04, 0x02, 0,
  232701. 0x1f, 0x12, 0x03, 0x02, 0,
  232702. 0x1f, 0x12, 0x1f, 0x12, 0,
  232703. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232704. 19, 0
  232705. };
  232706. int buttonNum = (int) menuButton;
  232707. int i = 0;
  232708. while (i < numElementsInArray (buttonPatterns))
  232709. {
  232710. if (strcmp (cookies, buttonPatterns + i) == 0)
  232711. {
  232712. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232713. break;
  232714. }
  232715. i += (int) strlen (buttonPatterns + i) + 1;
  232716. ++buttonNum;
  232717. }
  232718. }
  232719. #endif
  232720. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232721. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232722. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232723. // compiled on its own).
  232724. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232725. #if JUCE_MAC
  232726. END_JUCE_NAMESPACE
  232727. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232728. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232729. {
  232730. CriticalSection* contextLock;
  232731. bool needsUpdate;
  232732. }
  232733. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232734. - (bool) makeActive;
  232735. - (void) makeInactive;
  232736. - (void) reshape;
  232737. - (void) rightMouseDown: (NSEvent*) ev;
  232738. - (void) rightMouseUp: (NSEvent*) ev;
  232739. @end
  232740. @implementation ThreadSafeNSOpenGLView
  232741. - (id) initWithFrame: (NSRect) frameRect
  232742. pixelFormat: (NSOpenGLPixelFormat*) format
  232743. {
  232744. contextLock = new CriticalSection();
  232745. self = [super initWithFrame: frameRect pixelFormat: format];
  232746. if (self != nil)
  232747. [[NSNotificationCenter defaultCenter] addObserver: self
  232748. selector: @selector (_surfaceNeedsUpdate:)
  232749. name: NSViewGlobalFrameDidChangeNotification
  232750. object: self];
  232751. return self;
  232752. }
  232753. - (void) dealloc
  232754. {
  232755. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232756. delete contextLock;
  232757. [super dealloc];
  232758. }
  232759. - (bool) makeActive
  232760. {
  232761. const ScopedLock sl (*contextLock);
  232762. if ([self openGLContext] == 0)
  232763. return false;
  232764. [[self openGLContext] makeCurrentContext];
  232765. if (needsUpdate)
  232766. {
  232767. [super update];
  232768. needsUpdate = false;
  232769. }
  232770. return true;
  232771. }
  232772. - (void) makeInactive
  232773. {
  232774. const ScopedLock sl (*contextLock);
  232775. [NSOpenGLContext clearCurrentContext];
  232776. }
  232777. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232778. {
  232779. (void) notification;
  232780. const ScopedLock sl (*contextLock);
  232781. needsUpdate = true;
  232782. }
  232783. - (void) update
  232784. {
  232785. const ScopedLock sl (*contextLock);
  232786. needsUpdate = true;
  232787. }
  232788. - (void) reshape
  232789. {
  232790. const ScopedLock sl (*contextLock);
  232791. needsUpdate = true;
  232792. }
  232793. - (void) rightMouseDown: (NSEvent*) ev
  232794. {
  232795. [[self superview] rightMouseDown: ev];
  232796. }
  232797. - (void) rightMouseUp: (NSEvent*) ev
  232798. {
  232799. [[self superview] rightMouseUp: ev];
  232800. }
  232801. @end
  232802. BEGIN_JUCE_NAMESPACE
  232803. class WindowedGLContext : public OpenGLContext
  232804. {
  232805. public:
  232806. WindowedGLContext (Component& component,
  232807. const OpenGLPixelFormat& pixelFormat_,
  232808. NSOpenGLContext* sharedContext)
  232809. : renderContext (0),
  232810. pixelFormat (pixelFormat_)
  232811. {
  232812. NSOpenGLPixelFormatAttribute attribs[] =
  232813. {
  232814. NSOpenGLPFADoubleBuffer,
  232815. NSOpenGLPFAAccelerated,
  232816. NSOpenGLPFAMPSafe,
  232817. NSOpenGLPFAClosestPolicy,
  232818. NSOpenGLPFANoRecovery,
  232819. NSOpenGLPFAColorSize, (NSOpenGLPixelFormatAttribute) (pixelFormat.redBits
  232820. + pixelFormat.greenBits
  232821. + pixelFormat.blueBits),
  232822. NSOpenGLPFAAlphaSize, (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits,
  232823. NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits,
  232824. NSOpenGLPFAStencilSize, (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits,
  232825. NSOpenGLPFAAccumSize, (NSOpenGLPixelFormatAttribute) (pixelFormat.accumulationBufferRedBits
  232826. + pixelFormat.accumulationBufferGreenBits
  232827. + pixelFormat.accumulationBufferBlueBits
  232828. + pixelFormat.accumulationBufferAlphaBits),
  232829. NSOpenGLPFASampleBuffers, (NSOpenGLPixelFormatAttribute) 1,
  232830. 0
  232831. };
  232832. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232833. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232834. pixelFormat: format];
  232835. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232836. shareContext: sharedContext] autorelease];
  232837. const GLint swapInterval = 1;
  232838. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232839. [view setOpenGLContext: renderContext];
  232840. [format release];
  232841. viewHolder = new NSViewComponentInternal (view, component);
  232842. }
  232843. ~WindowedGLContext()
  232844. {
  232845. deleteContext();
  232846. viewHolder = 0;
  232847. }
  232848. void deleteContext()
  232849. {
  232850. makeInactive();
  232851. [renderContext clearDrawable];
  232852. [renderContext setView: nil];
  232853. [view setOpenGLContext: nil];
  232854. renderContext = nil;
  232855. }
  232856. bool makeActive() const throw()
  232857. {
  232858. jassert (renderContext != 0);
  232859. if ([renderContext view] != view)
  232860. [renderContext setView: view];
  232861. [view makeActive];
  232862. return isActive();
  232863. }
  232864. bool makeInactive() const throw()
  232865. {
  232866. [view makeInactive];
  232867. return true;
  232868. }
  232869. bool isActive() const throw()
  232870. {
  232871. return [NSOpenGLContext currentContext] == renderContext;
  232872. }
  232873. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232874. void* getRawContext() const throw() { return renderContext; }
  232875. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  232876. {
  232877. }
  232878. void swapBuffers()
  232879. {
  232880. [renderContext flushBuffer];
  232881. }
  232882. bool setSwapInterval (const int numFramesPerSwap)
  232883. {
  232884. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232885. forParameter: NSOpenGLCPSwapInterval];
  232886. return true;
  232887. }
  232888. int getSwapInterval() const
  232889. {
  232890. GLint numFrames = 0;
  232891. [renderContext getValues: &numFrames
  232892. forParameter: NSOpenGLCPSwapInterval];
  232893. return numFrames;
  232894. }
  232895. void repaint()
  232896. {
  232897. // we need to invalidate the juce view that holds this gl view, to make it
  232898. // cause a repaint callback
  232899. NSView* v = (NSView*) viewHolder->view;
  232900. NSRect r = [v frame];
  232901. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232902. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232903. // repaint message, thus never causing our paint() callback, and never repainting
  232904. // the comp. So invalidating just a little bit around the edge helps..
  232905. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232906. }
  232907. void* getNativeWindowHandle() const { return viewHolder->view; }
  232908. NSOpenGLContext* renderContext;
  232909. ThreadSafeNSOpenGLView* view;
  232910. private:
  232911. OpenGLPixelFormat pixelFormat;
  232912. ScopedPointer <NSViewComponentInternal> viewHolder;
  232913. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232914. };
  232915. OpenGLContext* OpenGLComponent::createContext()
  232916. {
  232917. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  232918. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232919. return (c->renderContext != 0) ? c.release() : 0;
  232920. }
  232921. void* OpenGLComponent::getNativeWindowHandle() const
  232922. {
  232923. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232924. : 0;
  232925. }
  232926. void juce_glViewport (const int w, const int h)
  232927. {
  232928. glViewport (0, 0, w, h);
  232929. }
  232930. static int getPixelFormatAttribute (NSOpenGLPixelFormat* p, NSOpenGLPixelFormatAttribute att)
  232931. {
  232932. GLint val = 0;
  232933. [p getValues: &val forAttribute: att forVirtualScreen: 0];
  232934. return (int) val;
  232935. }
  232936. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232937. OwnedArray <OpenGLPixelFormat>& results)
  232938. {
  232939. NSOpenGLPixelFormatAttribute attributes[] =
  232940. {
  232941. NSOpenGLPFAWindow,
  232942. NSOpenGLPFADoubleBuffer,
  232943. NSOpenGLPFAAccelerated,
  232944. NSOpenGLPFANoRecovery,
  232945. NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute) 16,
  232946. NSOpenGLPFAAlphaSize, (NSOpenGLPixelFormatAttribute) 8,
  232947. NSOpenGLPFAColorSize, (NSOpenGLPixelFormatAttribute) 24,
  232948. NSOpenGLPFAAccumSize, (NSOpenGLPixelFormatAttribute) 32,
  232949. 0
  232950. };
  232951. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes: attributes];
  232952. if (format != nil)
  232953. {
  232954. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232955. pf->redBits = pf->greenBits = pf->blueBits = getPixelFormatAttribute (format, NSOpenGLPFAColorSize) / 3;
  232956. pf->alphaBits = getPixelFormatAttribute (format, NSOpenGLPFAAlphaSize);
  232957. pf->depthBufferBits = getPixelFormatAttribute (format, NSOpenGLPFADepthSize);
  232958. pf->stencilBufferBits = getPixelFormatAttribute (format, NSOpenGLPFAStencilSize);
  232959. pf->accumulationBufferRedBits = pf->accumulationBufferGreenBits
  232960. = pf->accumulationBufferBlueBits = pf->accumulationBufferAlphaBits
  232961. = getPixelFormatAttribute (format, NSOpenGLPFAAccumSize) / 4;
  232962. [format release];
  232963. results.add (pf);
  232964. }
  232965. }
  232966. #else
  232967. END_JUCE_NAMESPACE
  232968. @interface JuceGLView : UIView
  232969. {
  232970. }
  232971. + (Class) layerClass;
  232972. @end
  232973. @implementation JuceGLView
  232974. + (Class) layerClass
  232975. {
  232976. return [CAEAGLLayer class];
  232977. }
  232978. @end
  232979. BEGIN_JUCE_NAMESPACE
  232980. class GLESContext : public OpenGLContext
  232981. {
  232982. public:
  232983. GLESContext (UIViewComponentPeer* peer,
  232984. Component* const component_,
  232985. const OpenGLPixelFormat& pixelFormat_,
  232986. const GLESContext* const sharedContext,
  232987. NSUInteger apiType)
  232988. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232989. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232990. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232991. {
  232992. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232993. view.opaque = YES;
  232994. view.hidden = NO;
  232995. view.backgroundColor = [UIColor blackColor];
  232996. view.userInteractionEnabled = NO;
  232997. glLayer = (CAEAGLLayer*) [view layer];
  232998. [peer->view addSubview: view];
  232999. if (sharedContext != 0)
  233000. context = [[EAGLContext alloc] initWithAPI: apiType
  233001. sharegroup: [sharedContext->context sharegroup]];
  233002. else
  233003. context = [[EAGLContext alloc] initWithAPI: apiType];
  233004. createGLBuffers();
  233005. }
  233006. ~GLESContext()
  233007. {
  233008. deleteContext();
  233009. [view removeFromSuperview];
  233010. [view release];
  233011. freeGLBuffers();
  233012. }
  233013. void deleteContext()
  233014. {
  233015. makeInactive();
  233016. [context release];
  233017. context = nil;
  233018. }
  233019. bool makeActive() const throw()
  233020. {
  233021. jassert (context != 0);
  233022. [EAGLContext setCurrentContext: context];
  233023. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233024. return true;
  233025. }
  233026. void swapBuffers()
  233027. {
  233028. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233029. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233030. }
  233031. bool makeInactive() const throw()
  233032. {
  233033. return [EAGLContext setCurrentContext: nil];
  233034. }
  233035. bool isActive() const throw()
  233036. {
  233037. return [EAGLContext currentContext] == context;
  233038. }
  233039. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233040. void* getRawContext() const throw() { return glLayer; }
  233041. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233042. {
  233043. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233044. if (lastWidth != w || lastHeight != h)
  233045. {
  233046. lastWidth = w;
  233047. lastHeight = h;
  233048. freeGLBuffers();
  233049. createGLBuffers();
  233050. }
  233051. }
  233052. bool setSwapInterval (const int numFramesPerSwap)
  233053. {
  233054. numFrames = numFramesPerSwap;
  233055. return true;
  233056. }
  233057. int getSwapInterval() const
  233058. {
  233059. return numFrames;
  233060. }
  233061. void repaint()
  233062. {
  233063. }
  233064. void createGLBuffers()
  233065. {
  233066. makeActive();
  233067. glGenFramebuffersOES (1, &frameBufferHandle);
  233068. glGenRenderbuffersOES (1, &colorBufferHandle);
  233069. glGenRenderbuffersOES (1, &depthBufferHandle);
  233070. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233071. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233072. GLint width, height;
  233073. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233074. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233075. if (useDepthBuffer)
  233076. {
  233077. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233078. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233079. }
  233080. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233081. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233082. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233083. if (useDepthBuffer)
  233084. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233085. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233086. }
  233087. void freeGLBuffers()
  233088. {
  233089. if (frameBufferHandle != 0)
  233090. {
  233091. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233092. frameBufferHandle = 0;
  233093. }
  233094. if (colorBufferHandle != 0)
  233095. {
  233096. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233097. colorBufferHandle = 0;
  233098. }
  233099. if (depthBufferHandle != 0)
  233100. {
  233101. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233102. depthBufferHandle = 0;
  233103. }
  233104. }
  233105. private:
  233106. WeakReference<Component> component;
  233107. OpenGLPixelFormat pixelFormat;
  233108. JuceGLView* view;
  233109. CAEAGLLayer* glLayer;
  233110. EAGLContext* context;
  233111. bool useDepthBuffer;
  233112. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233113. int numFrames;
  233114. int lastWidth, lastHeight;
  233115. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  233116. };
  233117. OpenGLContext* OpenGLComponent::createContext()
  233118. {
  233119. ScopedAutoReleasePool pool;
  233120. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233121. if (peer != 0)
  233122. return new GLESContext (peer, this, preferredPixelFormat,
  233123. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233124. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233125. return 0;
  233126. }
  233127. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233128. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233129. {
  233130. }
  233131. void juce_glViewport (const int w, const int h)
  233132. {
  233133. glViewport (0, 0, w, h);
  233134. }
  233135. #endif
  233136. #endif
  233137. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233138. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233139. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233140. // compiled on its own).
  233141. #if JUCE_INCLUDED_FILE
  233142. class JuceMainMenuHandler;
  233143. END_JUCE_NAMESPACE
  233144. using namespace JUCE_NAMESPACE;
  233145. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233146. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233147. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233148. #else
  233149. @interface JuceMenuCallback : NSObject
  233150. #endif
  233151. {
  233152. JuceMainMenuHandler* owner;
  233153. }
  233154. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233155. - (void) dealloc;
  233156. - (void) menuItemInvoked: (id) menu;
  233157. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233158. @end
  233159. BEGIN_JUCE_NAMESPACE
  233160. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233161. private DeletedAtShutdown
  233162. {
  233163. public:
  233164. JuceMainMenuHandler()
  233165. : currentModel (0),
  233166. lastUpdateTime (0)
  233167. {
  233168. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233169. }
  233170. ~JuceMainMenuHandler()
  233171. {
  233172. setMenu (0);
  233173. jassert (instance == this);
  233174. instance = 0;
  233175. [callback release];
  233176. }
  233177. void setMenu (MenuBarModel* const newMenuBarModel)
  233178. {
  233179. if (currentModel != newMenuBarModel)
  233180. {
  233181. if (currentModel != 0)
  233182. currentModel->removeListener (this);
  233183. currentModel = newMenuBarModel;
  233184. if (currentModel != 0)
  233185. currentModel->addListener (this);
  233186. menuBarItemsChanged (0);
  233187. }
  233188. }
  233189. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233190. const String& name, const int menuId, const int tag)
  233191. {
  233192. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233193. action: nil
  233194. keyEquivalent: @""];
  233195. [item setTag: tag];
  233196. NSMenu* sub = createMenu (child, name, menuId, tag);
  233197. [parent setSubmenu: sub forItem: item];
  233198. [sub setAutoenablesItems: false];
  233199. [sub release];
  233200. }
  233201. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233202. const String& name, const int menuId, const int tag)
  233203. {
  233204. [parentItem setTag: tag];
  233205. NSMenu* menu = [parentItem submenu];
  233206. [menu setTitle: juceStringToNS (name)];
  233207. while ([menu numberOfItems] > 0)
  233208. [menu removeItemAtIndex: 0];
  233209. PopupMenu::MenuItemIterator iter (menuToCopy);
  233210. while (iter.next())
  233211. addMenuItem (iter, menu, menuId, tag);
  233212. [menu setAutoenablesItems: false];
  233213. [menu update];
  233214. }
  233215. void menuBarItemsChanged (MenuBarModel*)
  233216. {
  233217. lastUpdateTime = Time::getMillisecondCounter();
  233218. StringArray menuNames;
  233219. if (currentModel != 0)
  233220. menuNames = currentModel->getMenuBarNames();
  233221. NSMenu* menuBar = [NSApp mainMenu];
  233222. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233223. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233224. int menuId = 1;
  233225. for (int i = 0; i < menuNames.size(); ++i)
  233226. {
  233227. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233228. if (i >= [menuBar numberOfItems] - 1)
  233229. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233230. else
  233231. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233232. }
  233233. }
  233234. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233235. {
  233236. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233237. if (item != 0)
  233238. flashMenuBar ([item menu]);
  233239. }
  233240. void updateMenus (NSMenu* menu)
  233241. {
  233242. if (PopupMenu::dismissAllActiveMenus())
  233243. {
  233244. // If we were running a juce menu, then we should let that modal loop finish before allowing
  233245. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  233246. if ([menu respondsToSelector: @selector (cancelTracking)])
  233247. [menu performSelector: @selector (cancelTracking)];
  233248. }
  233249. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233250. menuBarItemsChanged (0);
  233251. }
  233252. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233253. {
  233254. if (currentModel != 0)
  233255. {
  233256. if (commandManager != 0)
  233257. {
  233258. ApplicationCommandTarget::InvocationInfo info (commandId);
  233259. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233260. commandManager->invoke (info, true);
  233261. }
  233262. currentModel->menuItemSelected (commandId, topLevelIndex);
  233263. }
  233264. }
  233265. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233266. const int topLevelMenuId, const int topLevelIndex)
  233267. {
  233268. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233269. if (text == 0)
  233270. text = @"";
  233271. if (iter.isSeparator)
  233272. {
  233273. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233274. }
  233275. else if (iter.isSectionHeader)
  233276. {
  233277. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233278. action: nil
  233279. keyEquivalent: @""];
  233280. [item setEnabled: false];
  233281. }
  233282. else if (iter.subMenu != 0)
  233283. {
  233284. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233285. action: nil
  233286. keyEquivalent: @""];
  233287. [item setTag: iter.itemId];
  233288. [item setEnabled: iter.isEnabled];
  233289. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233290. [sub setDelegate: nil];
  233291. [menuToAddTo setSubmenu: sub forItem: item];
  233292. [sub release];
  233293. }
  233294. else
  233295. {
  233296. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233297. action: @selector (menuItemInvoked:)
  233298. keyEquivalent: @""];
  233299. [item setTag: iter.itemId];
  233300. [item setEnabled: iter.isEnabled];
  233301. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233302. [item setTarget: (id) callback];
  233303. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233304. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233305. [item setRepresentedObject: info];
  233306. if (iter.commandManager != 0)
  233307. {
  233308. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233309. ->getKeyPressesAssignedToCommand (iter.itemId));
  233310. if (keyPresses.size() > 0)
  233311. {
  233312. const KeyPress& kp = keyPresses.getReference(0);
  233313. if (kp.getKeyCode() != KeyPress::backspaceKey
  233314. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233315. // every time you press the key while editing text)
  233316. {
  233317. juce_wchar key = kp.getTextCharacter();
  233318. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233319. key = NSBackspaceCharacter;
  233320. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233321. key = NSDeleteCharacter;
  233322. else if (key == 0)
  233323. key = (juce_wchar) kp.getKeyCode();
  233324. unsigned int mods = 0;
  233325. if (kp.getModifiers().isShiftDown())
  233326. mods |= NSShiftKeyMask;
  233327. if (kp.getModifiers().isCtrlDown())
  233328. mods |= NSControlKeyMask;
  233329. if (kp.getModifiers().isAltDown())
  233330. mods |= NSAlternateKeyMask;
  233331. if (kp.getModifiers().isCommandDown())
  233332. mods |= NSCommandKeyMask;
  233333. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233334. [item setKeyEquivalentModifierMask: mods];
  233335. }
  233336. }
  233337. }
  233338. }
  233339. }
  233340. static JuceMainMenuHandler* instance;
  233341. MenuBarModel* currentModel;
  233342. uint32 lastUpdateTime;
  233343. JuceMenuCallback* callback;
  233344. private:
  233345. NSMenu* createMenu (const PopupMenu menu,
  233346. const String& menuName,
  233347. const int topLevelMenuId,
  233348. const int topLevelIndex)
  233349. {
  233350. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233351. [m setAutoenablesItems: false];
  233352. [m setDelegate: callback];
  233353. PopupMenu::MenuItemIterator iter (menu);
  233354. while (iter.next())
  233355. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233356. [m update];
  233357. return m;
  233358. }
  233359. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233360. {
  233361. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233362. {
  233363. NSMenuItem* m = [menu itemAtIndex: i];
  233364. if ([m tag] == info.commandID)
  233365. return m;
  233366. if ([m submenu] != 0)
  233367. {
  233368. NSMenuItem* found = findMenuItem ([m submenu], info);
  233369. if (found != 0)
  233370. return found;
  233371. }
  233372. }
  233373. return 0;
  233374. }
  233375. static void flashMenuBar (NSMenu* menu)
  233376. {
  233377. if ([[menu title] isEqualToString: @"Apple"])
  233378. return;
  233379. [menu retain];
  233380. const unichar f35Key = NSF35FunctionKey;
  233381. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233382. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233383. action: nil
  233384. keyEquivalent: f35String];
  233385. [item setTarget: nil];
  233386. [menu insertItem: item atIndex: [menu numberOfItems]];
  233387. [item release];
  233388. if ([menu indexOfItem: item] >= 0)
  233389. {
  233390. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233391. location: NSZeroPoint
  233392. modifierFlags: NSCommandKeyMask
  233393. timestamp: 0
  233394. windowNumber: 0
  233395. context: [NSGraphicsContext currentContext]
  233396. characters: f35String
  233397. charactersIgnoringModifiers: f35String
  233398. isARepeat: NO
  233399. keyCode: 0];
  233400. [menu performKeyEquivalent: f35Event];
  233401. if ([menu indexOfItem: item] >= 0)
  233402. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233403. }
  233404. [menu release];
  233405. }
  233406. };
  233407. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233408. END_JUCE_NAMESPACE
  233409. @implementation JuceMenuCallback
  233410. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233411. {
  233412. [super init];
  233413. owner = owner_;
  233414. return self;
  233415. }
  233416. - (void) dealloc
  233417. {
  233418. [super dealloc];
  233419. }
  233420. - (void) menuItemInvoked: (id) menu
  233421. {
  233422. NSMenuItem* item = (NSMenuItem*) menu;
  233423. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233424. {
  233425. // 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
  233426. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233427. // into the focused component and let it trigger the menu item indirectly.
  233428. NSEvent* e = [NSApp currentEvent];
  233429. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233430. {
  233431. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233432. {
  233433. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233434. if (peer != 0)
  233435. {
  233436. if ([e type] == NSKeyDown)
  233437. peer->redirectKeyDown (e);
  233438. else
  233439. peer->redirectKeyUp (e);
  233440. return;
  233441. }
  233442. }
  233443. }
  233444. NSArray* info = (NSArray*) [item representedObject];
  233445. owner->invoke ((int) [item tag],
  233446. (ApplicationCommandManager*) (pointer_sized_int)
  233447. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233448. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233449. }
  233450. }
  233451. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233452. {
  233453. if (JuceMainMenuHandler::instance != 0)
  233454. JuceMainMenuHandler::instance->updateMenus (menu);
  233455. }
  233456. @end
  233457. BEGIN_JUCE_NAMESPACE
  233458. namespace MainMenuHelpers
  233459. {
  233460. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  233461. {
  233462. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233463. {
  233464. PopupMenu::MenuItemIterator iter (*extraItems);
  233465. while (iter.next())
  233466. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233467. [menu addItem: [NSMenuItem separatorItem]];
  233468. }
  233469. NSMenuItem* item;
  233470. // Services...
  233471. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233472. action: nil keyEquivalent: @""];
  233473. [menu addItem: item];
  233474. [item release];
  233475. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233476. [menu setSubmenu: servicesMenu forItem: item];
  233477. [NSApp setServicesMenu: servicesMenu];
  233478. [servicesMenu release];
  233479. [menu addItem: [NSMenuItem separatorItem]];
  233480. // Hide + Show stuff...
  233481. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233482. action: @selector (hide:) keyEquivalent: @"h"];
  233483. [item setTarget: NSApp];
  233484. [menu addItem: item];
  233485. [item release];
  233486. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233487. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233488. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233489. [item setTarget: NSApp];
  233490. [menu addItem: item];
  233491. [item release];
  233492. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233493. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233494. [item setTarget: NSApp];
  233495. [menu addItem: item];
  233496. [item release];
  233497. [menu addItem: [NSMenuItem separatorItem]];
  233498. // Quit item....
  233499. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233500. action: @selector (terminate:) keyEquivalent: @"q"];
  233501. [item setTarget: NSApp];
  233502. [menu addItem: item];
  233503. [item release];
  233504. return menu;
  233505. }
  233506. // Since our app has no NIB, this initialises a standard app menu...
  233507. void rebuildMainMenu (const PopupMenu* extraItems)
  233508. {
  233509. // this can't be used in a plugin!
  233510. jassert (JUCEApplication::isStandaloneApp());
  233511. if (JUCEApplication::getInstance() != 0)
  233512. {
  233513. const ScopedAutoReleasePool pool;
  233514. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233515. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233516. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233517. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233518. [mainMenu setSubmenu: appMenu forItem: item];
  233519. [NSApp setMainMenu: mainMenu];
  233520. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233521. [appMenu release];
  233522. [mainMenu release];
  233523. }
  233524. }
  233525. }
  233526. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233527. const PopupMenu* extraAppleMenuItems)
  233528. {
  233529. if (getMacMainMenu() != newMenuBarModel)
  233530. {
  233531. const ScopedAutoReleasePool pool;
  233532. if (newMenuBarModel == 0)
  233533. {
  233534. delete JuceMainMenuHandler::instance;
  233535. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233536. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233537. extraAppleMenuItems = 0;
  233538. }
  233539. else
  233540. {
  233541. if (JuceMainMenuHandler::instance == 0)
  233542. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233543. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233544. }
  233545. }
  233546. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  233547. if (newMenuBarModel != 0)
  233548. newMenuBarModel->menuItemsChanged();
  233549. }
  233550. MenuBarModel* MenuBarModel::getMacMainMenu()
  233551. {
  233552. return JuceMainMenuHandler::instance != 0
  233553. ? JuceMainMenuHandler::instance->currentModel : 0;
  233554. }
  233555. void juce_initialiseMacMainMenu()
  233556. {
  233557. if (JuceMainMenuHandler::instance == 0)
  233558. MainMenuHelpers::rebuildMainMenu (0);
  233559. }
  233560. #endif
  233561. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233562. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233563. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233564. // compiled on its own).
  233565. #if JUCE_INCLUDED_FILE
  233566. #if JUCE_MAC
  233567. END_JUCE_NAMESPACE
  233568. using namespace JUCE_NAMESPACE;
  233569. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233570. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233571. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233572. #else
  233573. @interface JuceFileChooserDelegate : NSObject
  233574. #endif
  233575. {
  233576. StringArray* filters;
  233577. }
  233578. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233579. - (void) dealloc;
  233580. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233581. @end
  233582. @implementation JuceFileChooserDelegate
  233583. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233584. {
  233585. [super init];
  233586. filters = filters_;
  233587. return self;
  233588. }
  233589. - (void) dealloc
  233590. {
  233591. delete filters;
  233592. [super dealloc];
  233593. }
  233594. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233595. {
  233596. (void) sender;
  233597. const File f (nsStringToJuce (filename));
  233598. for (int i = filters->size(); --i >= 0;)
  233599. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233600. return true;
  233601. return f.isDirectory();
  233602. }
  233603. @end
  233604. BEGIN_JUCE_NAMESPACE
  233605. void FileChooser::showPlatformDialog (Array<File>& results,
  233606. const String& title,
  233607. const File& currentFileOrDirectory,
  233608. const String& filter,
  233609. bool selectsDirectory,
  233610. bool selectsFiles,
  233611. bool isSaveDialogue,
  233612. bool /*warnAboutOverwritingExistingFiles*/,
  233613. bool selectMultipleFiles,
  233614. FilePreviewComponent* /*extraInfoComponent*/)
  233615. {
  233616. const ScopedAutoReleasePool pool;
  233617. StringArray* filters = new StringArray();
  233618. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233619. filters->trim();
  233620. filters->removeEmptyStrings();
  233621. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233622. [delegate autorelease];
  233623. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233624. : [NSOpenPanel openPanel];
  233625. [panel setTitle: juceStringToNS (title)];
  233626. if (! isSaveDialogue)
  233627. {
  233628. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233629. [openPanel setCanChooseDirectories: selectsDirectory];
  233630. [openPanel setCanChooseFiles: selectsFiles];
  233631. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233632. }
  233633. [panel setDelegate: delegate];
  233634. if (isSaveDialogue || selectsDirectory)
  233635. [panel setCanCreateDirectories: YES];
  233636. String directory, filename;
  233637. if (currentFileOrDirectory.isDirectory())
  233638. {
  233639. directory = currentFileOrDirectory.getFullPathName();
  233640. }
  233641. else
  233642. {
  233643. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233644. filename = currentFileOrDirectory.getFileName();
  233645. }
  233646. if ([panel runModalForDirectory: juceStringToNS (directory)
  233647. file: juceStringToNS (filename)]
  233648. == NSOKButton)
  233649. {
  233650. if (isSaveDialogue)
  233651. {
  233652. results.add (File (nsStringToJuce ([panel filename])));
  233653. }
  233654. else
  233655. {
  233656. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233657. NSArray* urls = [openPanel filenames];
  233658. for (unsigned int i = 0; i < [urls count]; ++i)
  233659. {
  233660. NSString* f = [urls objectAtIndex: i];
  233661. results.add (File (nsStringToJuce (f)));
  233662. }
  233663. }
  233664. }
  233665. [panel setDelegate: nil];
  233666. }
  233667. #else
  233668. void FileChooser::showPlatformDialog (Array<File>& results,
  233669. const String& title,
  233670. const File& currentFileOrDirectory,
  233671. const String& filter,
  233672. bool selectsDirectory,
  233673. bool selectsFiles,
  233674. bool isSaveDialogue,
  233675. bool warnAboutOverwritingExistingFiles,
  233676. bool selectMultipleFiles,
  233677. FilePreviewComponent* extraInfoComponent)
  233678. {
  233679. const ScopedAutoReleasePool pool;
  233680. jassertfalse; //xxx to do
  233681. }
  233682. #endif
  233683. #endif
  233684. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233685. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233686. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233687. // compiled on its own).
  233688. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233689. END_JUCE_NAMESPACE
  233690. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233691. @interface NonInterceptingQTMovieView : QTMovieView
  233692. {
  233693. }
  233694. - (id) initWithFrame: (NSRect) frame;
  233695. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233696. - (NSView*) hitTest: (NSPoint) p;
  233697. @end
  233698. @implementation NonInterceptingQTMovieView
  233699. - (id) initWithFrame: (NSRect) frame
  233700. {
  233701. self = [super initWithFrame: frame];
  233702. [self setNextResponder: [self superview]];
  233703. return self;
  233704. }
  233705. - (void) dealloc
  233706. {
  233707. [super dealloc];
  233708. }
  233709. - (NSView*) hitTest: (NSPoint) point
  233710. {
  233711. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233712. }
  233713. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233714. {
  233715. return YES;
  233716. }
  233717. @end
  233718. BEGIN_JUCE_NAMESPACE
  233719. #define theMovie (static_cast <QTMovie*> (movie))
  233720. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233721. : movie (0)
  233722. {
  233723. setOpaque (true);
  233724. setVisible (true);
  233725. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233726. setView (view);
  233727. [view release];
  233728. }
  233729. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233730. {
  233731. closeMovie();
  233732. setView (0);
  233733. }
  233734. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233735. {
  233736. return true;
  233737. }
  233738. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233739. {
  233740. // unfortunately, QTMovie objects can only be created on the main thread..
  233741. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233742. QTMovie* movie = 0;
  233743. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233744. if (fin != 0)
  233745. {
  233746. movieFile = fin->getFile();
  233747. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233748. error: nil];
  233749. }
  233750. else
  233751. {
  233752. MemoryBlock temp;
  233753. movieStream->readIntoMemoryBlock (temp);
  233754. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233755. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233756. {
  233757. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233758. length: temp.getSize()]
  233759. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233760. MIMEType: @""]
  233761. error: nil];
  233762. if (movie != 0)
  233763. break;
  233764. }
  233765. }
  233766. return movie;
  233767. }
  233768. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233769. const bool isControllerVisible_)
  233770. {
  233771. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233772. }
  233773. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233774. const bool controllerVisible_)
  233775. {
  233776. closeMovie();
  233777. if (getPeer() == 0)
  233778. {
  233779. // To open a movie, this component must be visible inside a functioning window, so that
  233780. // the QT control can be assigned to the window.
  233781. jassertfalse;
  233782. return false;
  233783. }
  233784. movie = openMovieFromStream (movieStream, movieFile);
  233785. [theMovie retain];
  233786. QTMovieView* view = (QTMovieView*) getView();
  233787. [view setMovie: theMovie];
  233788. [view setControllerVisible: controllerVisible_];
  233789. setLooping (looping);
  233790. return movie != nil;
  233791. }
  233792. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233793. const bool isControllerVisible_)
  233794. {
  233795. // unfortunately, QTMovie objects can only be created on the main thread..
  233796. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233797. closeMovie();
  233798. if (getPeer() == 0)
  233799. {
  233800. // To open a movie, this component must be visible inside a functioning window, so that
  233801. // the QT control can be assigned to the window.
  233802. jassertfalse;
  233803. return false;
  233804. }
  233805. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233806. NSError* err;
  233807. if ([QTMovie canInitWithURL: url])
  233808. movie = [QTMovie movieWithURL: url error: &err];
  233809. [theMovie retain];
  233810. QTMovieView* view = (QTMovieView*) getView();
  233811. [view setMovie: theMovie];
  233812. [view setControllerVisible: controllerVisible];
  233813. setLooping (looping);
  233814. return movie != nil;
  233815. }
  233816. void QuickTimeMovieComponent::closeMovie()
  233817. {
  233818. stop();
  233819. QTMovieView* view = (QTMovieView*) getView();
  233820. [view setMovie: nil];
  233821. [theMovie release];
  233822. movie = 0;
  233823. movieFile = File::nonexistent;
  233824. }
  233825. bool QuickTimeMovieComponent::isMovieOpen() const
  233826. {
  233827. return movie != nil;
  233828. }
  233829. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233830. {
  233831. return movieFile;
  233832. }
  233833. void QuickTimeMovieComponent::play()
  233834. {
  233835. [theMovie play];
  233836. }
  233837. void QuickTimeMovieComponent::stop()
  233838. {
  233839. [theMovie stop];
  233840. }
  233841. bool QuickTimeMovieComponent::isPlaying() const
  233842. {
  233843. return movie != 0 && [theMovie rate] != 0;
  233844. }
  233845. void QuickTimeMovieComponent::setPosition (const double seconds)
  233846. {
  233847. if (movie != 0)
  233848. {
  233849. QTTime t;
  233850. t.timeValue = (uint64) (100000.0 * seconds);
  233851. t.timeScale = 100000;
  233852. t.flags = 0;
  233853. [theMovie setCurrentTime: t];
  233854. }
  233855. }
  233856. double QuickTimeMovieComponent::getPosition() const
  233857. {
  233858. if (movie == 0)
  233859. return 0.0;
  233860. QTTime t = [theMovie currentTime];
  233861. return t.timeValue / (double) t.timeScale;
  233862. }
  233863. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233864. {
  233865. [theMovie setRate: newSpeed];
  233866. }
  233867. double QuickTimeMovieComponent::getMovieDuration() const
  233868. {
  233869. if (movie == 0)
  233870. return 0.0;
  233871. QTTime t = [theMovie duration];
  233872. return t.timeValue / (double) t.timeScale;
  233873. }
  233874. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233875. {
  233876. looping = shouldLoop;
  233877. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233878. forKey: QTMovieLoopsAttribute];
  233879. }
  233880. bool QuickTimeMovieComponent::isLooping() const
  233881. {
  233882. return looping;
  233883. }
  233884. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233885. {
  233886. [theMovie setVolume: newVolume];
  233887. }
  233888. float QuickTimeMovieComponent::getMovieVolume() const
  233889. {
  233890. return movie != 0 ? [theMovie volume] : 0.0f;
  233891. }
  233892. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233893. {
  233894. width = 0;
  233895. height = 0;
  233896. if (movie != 0)
  233897. {
  233898. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233899. width = (int) s.width;
  233900. height = (int) s.height;
  233901. }
  233902. }
  233903. void QuickTimeMovieComponent::paint (Graphics& g)
  233904. {
  233905. if (movie == 0)
  233906. g.fillAll (Colours::black);
  233907. }
  233908. bool QuickTimeMovieComponent::isControllerVisible() const
  233909. {
  233910. return controllerVisible;
  233911. }
  233912. void QuickTimeMovieComponent::goToStart()
  233913. {
  233914. setPosition (0.0);
  233915. }
  233916. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233917. const RectanglePlacement& placement)
  233918. {
  233919. int normalWidth, normalHeight;
  233920. getMovieNormalSize (normalWidth, normalHeight);
  233921. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  233922. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  233923. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  233924. else
  233925. setBounds (spaceToFitWithin);
  233926. }
  233927. #if ! (JUCE_MAC && JUCE_64BIT)
  233928. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233929. {
  233930. if (movieStream == 0)
  233931. return false;
  233932. File file;
  233933. QTMovie* movie = openMovieFromStream (movieStream, file);
  233934. if (movie != nil)
  233935. result = [movie quickTimeMovie];
  233936. return movie != nil;
  233937. }
  233938. #endif
  233939. #endif
  233940. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233941. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233942. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233943. // compiled on its own).
  233944. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233945. const int kilobytesPerSecond1x = 176;
  233946. END_JUCE_NAMESPACE
  233947. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233948. @interface OpenDiskDevice : NSObject
  233949. {
  233950. @public
  233951. DRDevice* device;
  233952. NSMutableArray* tracks;
  233953. bool underrunProtection;
  233954. }
  233955. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233956. - (void) dealloc;
  233957. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233958. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233959. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233960. @end
  233961. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233962. @interface AudioTrackProducer : NSObject
  233963. {
  233964. JUCE_NAMESPACE::AudioSource* source;
  233965. int readPosition, lengthInFrames;
  233966. }
  233967. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233968. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233969. - (void) dealloc;
  233970. - (void) setupTrackProperties: (DRTrack*) track;
  233971. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233972. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233973. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233974. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233975. toMedia:(NSDictionary*)mediaInfo;
  233976. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233977. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233978. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233979. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233980. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233981. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233982. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233983. ioFlags:(uint32_t*)flags;
  233984. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233985. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233986. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233987. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233988. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233989. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233990. ioFlags:(uint32_t*)flags;
  233991. @end
  233992. @implementation OpenDiskDevice
  233993. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233994. {
  233995. [super init];
  233996. device = device_;
  233997. tracks = [[NSMutableArray alloc] init];
  233998. underrunProtection = true;
  233999. return self;
  234000. }
  234001. - (void) dealloc
  234002. {
  234003. [tracks release];
  234004. [super dealloc];
  234005. }
  234006. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234007. {
  234008. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234009. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234010. [p setupTrackProperties: t];
  234011. [tracks addObject: t];
  234012. [t release];
  234013. [p release];
  234014. }
  234015. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234016. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234017. {
  234018. DRBurn* burn = [DRBurn burnForDevice: device];
  234019. if (! [device acquireExclusiveAccess])
  234020. {
  234021. *error = "Couldn't open or write to the CD device";
  234022. return;
  234023. }
  234024. [device acquireMediaReservation];
  234025. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234026. [d autorelease];
  234027. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234028. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234029. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234030. if (burnSpeed > 0)
  234031. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234032. if (! underrunProtection)
  234033. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234034. [burn setProperties: d];
  234035. [burn writeLayout: tracks];
  234036. for (;;)
  234037. {
  234038. JUCE_NAMESPACE::Thread::sleep (300);
  234039. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234040. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234041. {
  234042. [burn abort];
  234043. *error = "User cancelled the write operation";
  234044. break;
  234045. }
  234046. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234047. {
  234048. *error = "Write operation failed";
  234049. break;
  234050. }
  234051. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234052. {
  234053. break;
  234054. }
  234055. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234056. objectForKey: DRErrorStatusErrorStringKey];
  234057. if ([err length] > 0)
  234058. {
  234059. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234060. break;
  234061. }
  234062. }
  234063. [device releaseMediaReservation];
  234064. [device releaseExclusiveAccess];
  234065. }
  234066. @end
  234067. @implementation AudioTrackProducer
  234068. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234069. {
  234070. lengthInFrames = lengthInFrames_;
  234071. readPosition = 0;
  234072. return self;
  234073. }
  234074. - (void) setupTrackProperties: (DRTrack*) track
  234075. {
  234076. NSMutableDictionary* p = [[track properties] mutableCopy];
  234077. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234078. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234079. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234080. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234081. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234082. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234083. [track setProperties: p];
  234084. [p release];
  234085. }
  234086. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234087. {
  234088. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234089. if (s != nil)
  234090. s->source = source_;
  234091. return s;
  234092. }
  234093. - (void) dealloc
  234094. {
  234095. if (source != 0)
  234096. {
  234097. source->releaseResources();
  234098. delete source;
  234099. }
  234100. [super dealloc];
  234101. }
  234102. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234103. {
  234104. (void) track;
  234105. }
  234106. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234107. {
  234108. (void) track;
  234109. return true;
  234110. }
  234111. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234112. {
  234113. (void) track;
  234114. return lengthInFrames;
  234115. }
  234116. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234117. toMedia: (NSDictionary*) mediaInfo
  234118. {
  234119. (void) track; (void) burn; (void) mediaInfo;
  234120. if (source != 0)
  234121. source->prepareToPlay (44100 / 75, 44100);
  234122. readPosition = 0;
  234123. return true;
  234124. }
  234125. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234126. {
  234127. (void) track;
  234128. if (source != 0)
  234129. source->prepareToPlay (44100 / 75, 44100);
  234130. return true;
  234131. }
  234132. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234133. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234134. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234135. {
  234136. (void) track; (void) address; (void) blockSize; (void) flags;
  234137. if (source != 0)
  234138. {
  234139. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234140. if (numSamples > 0)
  234141. {
  234142. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234143. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234144. info.buffer = &tempBuffer;
  234145. info.startSample = 0;
  234146. info.numSamples = numSamples;
  234147. source->getNextAudioBlock (info);
  234148. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234149. JUCE_NAMESPACE::AudioData::LittleEndian,
  234150. JUCE_NAMESPACE::AudioData::Interleaved,
  234151. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234152. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234153. JUCE_NAMESPACE::AudioData::NativeEndian,
  234154. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234155. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234156. CDSampleFormat left (buffer, 2);
  234157. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234158. CDSampleFormat right (buffer + 2, 2);
  234159. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234160. readPosition += numSamples;
  234161. }
  234162. return numSamples * 4;
  234163. }
  234164. return 0;
  234165. }
  234166. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234167. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234168. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234169. ioFlags: (uint32_t*) flags
  234170. {
  234171. (void) track; (void) address; (void) blockSize; (void) flags;
  234172. zeromem (buffer, bufferLength);
  234173. return bufferLength;
  234174. }
  234175. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234176. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234177. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234178. {
  234179. (void) track; (void) buffer; (void) bufferLength; (void) address; (void) blockSize; (void) flags;
  234180. return true;
  234181. }
  234182. @end
  234183. BEGIN_JUCE_NAMESPACE
  234184. class AudioCDBurner::Pimpl : public Timer
  234185. {
  234186. public:
  234187. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234188. : device (0), owner (owner_)
  234189. {
  234190. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234191. if (dev != 0)
  234192. {
  234193. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234194. lastState = getDiskState();
  234195. startTimer (1000);
  234196. }
  234197. }
  234198. ~Pimpl()
  234199. {
  234200. stopTimer();
  234201. [device release];
  234202. }
  234203. void timerCallback()
  234204. {
  234205. const DiskState state = getDiskState();
  234206. if (state != lastState)
  234207. {
  234208. lastState = state;
  234209. owner.sendChangeMessage();
  234210. }
  234211. }
  234212. DiskState getDiskState() const
  234213. {
  234214. if ([device->device isValid])
  234215. {
  234216. NSDictionary* status = [device->device status];
  234217. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234218. if ([state isEqualTo: DRDeviceMediaStateNone])
  234219. {
  234220. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234221. return trayOpen;
  234222. return noDisc;
  234223. }
  234224. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234225. {
  234226. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234227. return writableDiskPresent;
  234228. else
  234229. return readOnlyDiskPresent;
  234230. }
  234231. }
  234232. return unknown;
  234233. }
  234234. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234235. const Array<int> getAvailableWriteSpeeds() const
  234236. {
  234237. Array<int> results;
  234238. if ([device->device isValid])
  234239. {
  234240. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234241. for (unsigned int i = 0; i < [speeds count]; ++i)
  234242. {
  234243. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234244. results.add (kbPerSec / kilobytesPerSecond1x);
  234245. }
  234246. }
  234247. return results;
  234248. }
  234249. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234250. {
  234251. if ([device->device isValid])
  234252. {
  234253. device->underrunProtection = shouldBeEnabled;
  234254. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234255. }
  234256. return false;
  234257. }
  234258. int getNumAvailableAudioBlocks() const
  234259. {
  234260. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234261. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234262. }
  234263. OpenDiskDevice* device;
  234264. private:
  234265. DiskState lastState;
  234266. AudioCDBurner& owner;
  234267. };
  234268. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234269. {
  234270. pimpl = new Pimpl (*this, deviceIndex);
  234271. }
  234272. AudioCDBurner::~AudioCDBurner()
  234273. {
  234274. }
  234275. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234276. {
  234277. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234278. if (b->pimpl->device == 0)
  234279. b = 0;
  234280. return b.release();
  234281. }
  234282. namespace
  234283. {
  234284. NSArray* findDiskBurnerDevices()
  234285. {
  234286. NSMutableArray* results = [NSMutableArray array];
  234287. NSArray* devs = [DRDevice devices];
  234288. for (int i = 0; i < [devs count]; ++i)
  234289. {
  234290. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234291. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234292. if (name != nil)
  234293. [results addObject: name];
  234294. }
  234295. return results;
  234296. }
  234297. }
  234298. const StringArray AudioCDBurner::findAvailableDevices()
  234299. {
  234300. NSArray* names = findDiskBurnerDevices();
  234301. StringArray s;
  234302. for (unsigned int i = 0; i < [names count]; ++i)
  234303. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234304. return s;
  234305. }
  234306. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234307. {
  234308. return pimpl->getDiskState();
  234309. }
  234310. bool AudioCDBurner::isDiskPresent() const
  234311. {
  234312. return getDiskState() == writableDiskPresent;
  234313. }
  234314. bool AudioCDBurner::openTray()
  234315. {
  234316. return pimpl->openTray();
  234317. }
  234318. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234319. {
  234320. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234321. DiskState oldState = getDiskState();
  234322. DiskState newState = oldState;
  234323. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234324. {
  234325. newState = getDiskState();
  234326. Thread::sleep (100);
  234327. }
  234328. return newState;
  234329. }
  234330. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234331. {
  234332. return pimpl->getAvailableWriteSpeeds();
  234333. }
  234334. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234335. {
  234336. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234337. }
  234338. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234339. {
  234340. return pimpl->getNumAvailableAudioBlocks();
  234341. }
  234342. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234343. {
  234344. if ([pimpl->device->device isValid])
  234345. {
  234346. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234347. return true;
  234348. }
  234349. return false;
  234350. }
  234351. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234352. bool ejectDiscAfterwards,
  234353. bool performFakeBurnForTesting,
  234354. int writeSpeed)
  234355. {
  234356. String error ("Couldn't open or write to the CD device");
  234357. if ([pimpl->device->device isValid])
  234358. {
  234359. error = String::empty;
  234360. [pimpl->device burn: listener
  234361. errorString: &error
  234362. ejectAfterwards: ejectDiscAfterwards
  234363. isFake: performFakeBurnForTesting
  234364. speed: writeSpeed];
  234365. }
  234366. return error;
  234367. }
  234368. #endif
  234369. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234370. void AudioCDReader::ejectDisk()
  234371. {
  234372. const ScopedAutoReleasePool p;
  234373. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234374. }
  234375. #endif
  234376. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234377. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234378. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234379. // compiled on its own).
  234380. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234381. namespace CDReaderHelpers
  234382. {
  234383. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234384. {
  234385. forEachXmlChildElementWithTagName (xml, child, "key")
  234386. if (child->getAllSubText().trim() == key)
  234387. return child->getNextElement();
  234388. return 0;
  234389. }
  234390. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234391. {
  234392. const XmlElement* const block = getElementForKey (xml, key);
  234393. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234394. }
  234395. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234396. // Returns NULL on success, otherwise a const char* representing an error.
  234397. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234398. {
  234399. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234400. if (xml == 0)
  234401. return "Couldn't parse XML in file";
  234402. const XmlElement* const dict = xml->getChildByName ("dict");
  234403. if (dict == 0)
  234404. return "Couldn't get top level dictionary";
  234405. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234406. if (sessions == 0)
  234407. return "Couldn't find sessions key";
  234408. const XmlElement* const session = sessions->getFirstChildElement();
  234409. if (session == 0)
  234410. return "Couldn't find first session";
  234411. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234412. if (leadOut < 0)
  234413. return "Couldn't find Leadout Block";
  234414. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234415. if (trackArray == 0)
  234416. return "Couldn't find Track Array";
  234417. forEachXmlChildElement (*trackArray, track)
  234418. {
  234419. const int trackValue = getIntValueForKey (*track, "Start Block");
  234420. if (trackValue < 0)
  234421. return "Couldn't find Start Block in the track";
  234422. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234423. }
  234424. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234425. return 0;
  234426. }
  234427. static void findDevices (Array<File>& cds)
  234428. {
  234429. File volumes ("/Volumes");
  234430. volumes.findChildFiles (cds, File::findDirectories, false);
  234431. for (int i = cds.size(); --i >= 0;)
  234432. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234433. cds.remove (i);
  234434. }
  234435. struct TrackSorter
  234436. {
  234437. static int getCDTrackNumber (const File& file)
  234438. {
  234439. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234440. }
  234441. static int compareElements (const File& first, const File& second)
  234442. {
  234443. const int firstTrack = getCDTrackNumber (first);
  234444. const int secondTrack = getCDTrackNumber (second);
  234445. jassert (firstTrack > 0 && secondTrack > 0);
  234446. return firstTrack - secondTrack;
  234447. }
  234448. };
  234449. }
  234450. const StringArray AudioCDReader::getAvailableCDNames()
  234451. {
  234452. Array<File> cds;
  234453. CDReaderHelpers::findDevices (cds);
  234454. StringArray names;
  234455. for (int i = 0; i < cds.size(); ++i)
  234456. names.add (cds.getReference(i).getFileName());
  234457. return names;
  234458. }
  234459. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234460. {
  234461. Array<File> cds;
  234462. CDReaderHelpers::findDevices (cds);
  234463. if (cds[index].exists())
  234464. return new AudioCDReader (cds[index]);
  234465. return 0;
  234466. }
  234467. AudioCDReader::AudioCDReader (const File& volume)
  234468. : AudioFormatReader (0, "CD Audio"),
  234469. volumeDir (volume),
  234470. currentReaderTrack (-1),
  234471. reader (0)
  234472. {
  234473. sampleRate = 44100.0;
  234474. bitsPerSample = 16;
  234475. numChannels = 2;
  234476. usesFloatingPointData = false;
  234477. refreshTrackLengths();
  234478. }
  234479. AudioCDReader::~AudioCDReader()
  234480. {
  234481. }
  234482. void AudioCDReader::refreshTrackLengths()
  234483. {
  234484. tracks.clear();
  234485. trackStartSamples.clear();
  234486. lengthInSamples = 0;
  234487. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234488. CDReaderHelpers::TrackSorter sorter;
  234489. tracks.sort (sorter);
  234490. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234491. if (toc.exists())
  234492. {
  234493. XmlDocument doc (toc);
  234494. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234495. (void) error; // could be logged..
  234496. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234497. }
  234498. }
  234499. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234500. int64 startSampleInFile, int numSamples)
  234501. {
  234502. while (numSamples > 0)
  234503. {
  234504. int track = -1;
  234505. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234506. {
  234507. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234508. {
  234509. track = i;
  234510. break;
  234511. }
  234512. }
  234513. if (track < 0)
  234514. return false;
  234515. if (track != currentReaderTrack)
  234516. {
  234517. reader = 0;
  234518. FileInputStream* const in = tracks [track].createInputStream();
  234519. if (in != 0)
  234520. {
  234521. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234522. AiffAudioFormat format;
  234523. reader = format.createReaderFor (bin, true);
  234524. if (reader == 0)
  234525. currentReaderTrack = -1;
  234526. else
  234527. currentReaderTrack = track;
  234528. }
  234529. }
  234530. if (reader == 0)
  234531. return false;
  234532. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234533. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234534. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234535. numSamples -= numAvailable;
  234536. startSampleInFile += numAvailable;
  234537. }
  234538. return true;
  234539. }
  234540. bool AudioCDReader::isCDStillPresent() const
  234541. {
  234542. return volumeDir.exists();
  234543. }
  234544. bool AudioCDReader::isTrackAudio (int trackNum) const
  234545. {
  234546. return tracks [trackNum].hasFileExtension (".aiff");
  234547. }
  234548. void AudioCDReader::enableIndexScanning (bool)
  234549. {
  234550. // any way to do this on a Mac??
  234551. }
  234552. int AudioCDReader::getLastIndex() const
  234553. {
  234554. return 0;
  234555. }
  234556. const Array <int> AudioCDReader::findIndexesInTrack (const int /*trackNumber*/)
  234557. {
  234558. return Array <int>();
  234559. }
  234560. #endif
  234561. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234562. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234563. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234564. // compiled on its own).
  234565. #if JUCE_INCLUDED_FILE
  234566. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234567. for example having more than one juce plugin loaded into a host, then when a
  234568. method is called, the actual code that runs might actually be in a different module
  234569. than the one you expect... So any calls to library functions or statics that are
  234570. made inside obj-c methods will probably end up getting executed in a different DLL's
  234571. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234572. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234573. virtual methods of an object that's known to live inside the right module's space.
  234574. */
  234575. class AppDelegateRedirector
  234576. {
  234577. public:
  234578. AppDelegateRedirector()
  234579. {
  234580. }
  234581. virtual ~AppDelegateRedirector()
  234582. {
  234583. }
  234584. virtual NSApplicationTerminateReply shouldTerminate()
  234585. {
  234586. if (JUCEApplication::getInstance() != 0)
  234587. {
  234588. JUCEApplication::getInstance()->systemRequestedQuit();
  234589. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234590. return NSTerminateCancel;
  234591. }
  234592. return NSTerminateNow;
  234593. }
  234594. virtual void willTerminate()
  234595. {
  234596. JUCEApplication::appWillTerminateByForce();
  234597. }
  234598. virtual BOOL openFile (NSString* filename)
  234599. {
  234600. if (JUCEApplication::getInstance() != 0)
  234601. {
  234602. JUCEApplication::getInstance()->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  234603. return YES;
  234604. }
  234605. return NO;
  234606. }
  234607. virtual void openFiles (NSArray* filenames)
  234608. {
  234609. StringArray files;
  234610. for (unsigned int i = 0; i < [filenames count]; ++i)
  234611. files.add (quotedIfContainsSpaces ((NSString*) [filenames objectAtIndex: i]));
  234612. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234613. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234614. }
  234615. virtual void focusChanged()
  234616. {
  234617. juce_HandleProcessFocusChange();
  234618. }
  234619. struct CallbackMessagePayload
  234620. {
  234621. MessageCallbackFunction* function;
  234622. void* parameter;
  234623. void* volatile result;
  234624. bool volatile hasBeenExecuted;
  234625. };
  234626. virtual void performCallback (CallbackMessagePayload* pl)
  234627. {
  234628. pl->result = (*pl->function) (pl->parameter);
  234629. pl->hasBeenExecuted = true;
  234630. }
  234631. virtual void deleteSelf()
  234632. {
  234633. delete this;
  234634. }
  234635. void postMessage (Message* const m)
  234636. {
  234637. messageQueue.post (m);
  234638. }
  234639. private:
  234640. CFRunLoopRef runLoop;
  234641. CFRunLoopSourceRef runLoopSource;
  234642. MessageQueue messageQueue;
  234643. static const String quotedIfContainsSpaces (NSString* file)
  234644. {
  234645. String s (nsStringToJuce (file));
  234646. if (s.containsChar (' '))
  234647. s = s.quoted ('"');
  234648. return s;
  234649. }
  234650. };
  234651. END_JUCE_NAMESPACE
  234652. using namespace JUCE_NAMESPACE;
  234653. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234654. @interface JuceAppDelegate : NSObject
  234655. {
  234656. @private
  234657. id oldDelegate;
  234658. @public
  234659. AppDelegateRedirector* redirector;
  234660. }
  234661. - (JuceAppDelegate*) init;
  234662. - (void) dealloc;
  234663. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234664. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234665. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234666. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234667. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234668. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234669. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234670. - (void) performCallback: (id) info;
  234671. - (void) dummyMethod;
  234672. @end
  234673. @implementation JuceAppDelegate
  234674. - (JuceAppDelegate*) init
  234675. {
  234676. [super init];
  234677. redirector = new AppDelegateRedirector();
  234678. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234679. if (JUCEApplication::isStandaloneApp())
  234680. {
  234681. oldDelegate = [NSApp delegate];
  234682. [NSApp setDelegate: self];
  234683. }
  234684. else
  234685. {
  234686. oldDelegate = 0;
  234687. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234688. name: NSApplicationDidResignActiveNotification object: NSApp];
  234689. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234690. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234691. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234692. name: NSApplicationWillUnhideNotification object: NSApp];
  234693. }
  234694. return self;
  234695. }
  234696. - (void) dealloc
  234697. {
  234698. if (oldDelegate != 0)
  234699. [NSApp setDelegate: oldDelegate];
  234700. redirector->deleteSelf();
  234701. [super dealloc];
  234702. }
  234703. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234704. {
  234705. (void) app;
  234706. return redirector->shouldTerminate();
  234707. }
  234708. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234709. {
  234710. (void) aNotification;
  234711. redirector->willTerminate();
  234712. }
  234713. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234714. {
  234715. (void) app;
  234716. return redirector->openFile (filename);
  234717. }
  234718. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234719. {
  234720. (void) sender;
  234721. return redirector->openFiles (filenames);
  234722. }
  234723. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234724. {
  234725. (void) notification;
  234726. redirector->focusChanged();
  234727. }
  234728. - (void) applicationDidResignActive: (NSNotification*) notification
  234729. {
  234730. (void) notification;
  234731. redirector->focusChanged();
  234732. }
  234733. - (void) applicationWillUnhide: (NSNotification*) notification
  234734. {
  234735. (void) notification;
  234736. redirector->focusChanged();
  234737. }
  234738. - (void) performCallback: (id) info
  234739. {
  234740. if ([info isKindOfClass: [NSData class]])
  234741. {
  234742. AppDelegateRedirector::CallbackMessagePayload* pl
  234743. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234744. if (pl != 0)
  234745. redirector->performCallback (pl);
  234746. }
  234747. else
  234748. {
  234749. jassertfalse; // should never get here!
  234750. }
  234751. }
  234752. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234753. @end
  234754. BEGIN_JUCE_NAMESPACE
  234755. static JuceAppDelegate* juceAppDelegate = 0;
  234756. void MessageManager::runDispatchLoop()
  234757. {
  234758. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234759. {
  234760. const ScopedAutoReleasePool pool;
  234761. // must only be called by the message thread!
  234762. jassert (isThisTheMessageThread());
  234763. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234764. @try
  234765. {
  234766. [NSApp run];
  234767. }
  234768. @catch (NSException* e)
  234769. {
  234770. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234771. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234772. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234773. }
  234774. @finally
  234775. {
  234776. }
  234777. #else
  234778. [NSApp run];
  234779. #endif
  234780. }
  234781. }
  234782. void MessageManager::stopDispatchLoop()
  234783. {
  234784. quitMessagePosted = true;
  234785. [NSApp stop: nil];
  234786. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234787. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234788. }
  234789. namespace
  234790. {
  234791. bool isEventBlockedByModalComps (NSEvent* e)
  234792. {
  234793. if (Component::getNumCurrentlyModalComponents() == 0)
  234794. return false;
  234795. NSWindow* const w = [e window];
  234796. if (w == 0 || [w worksWhenModal])
  234797. return false;
  234798. bool isKey = false, isInputAttempt = false;
  234799. switch ([e type])
  234800. {
  234801. case NSKeyDown:
  234802. case NSKeyUp:
  234803. isKey = isInputAttempt = true;
  234804. break;
  234805. case NSLeftMouseDown:
  234806. case NSRightMouseDown:
  234807. case NSOtherMouseDown:
  234808. isInputAttempt = true;
  234809. break;
  234810. case NSLeftMouseDragged:
  234811. case NSRightMouseDragged:
  234812. case NSLeftMouseUp:
  234813. case NSRightMouseUp:
  234814. case NSOtherMouseUp:
  234815. case NSOtherMouseDragged:
  234816. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234817. return false;
  234818. break;
  234819. case NSMouseMoved:
  234820. case NSMouseEntered:
  234821. case NSMouseExited:
  234822. case NSCursorUpdate:
  234823. case NSScrollWheel:
  234824. case NSTabletPoint:
  234825. case NSTabletProximity:
  234826. break;
  234827. default:
  234828. return false;
  234829. }
  234830. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234831. {
  234832. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234833. NSView* const compView = (NSView*) peer->getNativeHandle();
  234834. if ([compView window] == w)
  234835. {
  234836. if (isKey)
  234837. {
  234838. if (compView == [w firstResponder])
  234839. return false;
  234840. }
  234841. else
  234842. {
  234843. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234844. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234845. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234846. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234847. return false;
  234848. }
  234849. }
  234850. }
  234851. if (isInputAttempt)
  234852. {
  234853. if (! [NSApp isActive])
  234854. [NSApp activateIgnoringOtherApps: YES];
  234855. Component* const modal = Component::getCurrentlyModalComponent (0);
  234856. if (modal != 0)
  234857. modal->inputAttemptWhenModal();
  234858. }
  234859. return true;
  234860. }
  234861. }
  234862. #if JUCE_MODAL_LOOPS_PERMITTED
  234863. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234864. {
  234865. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234866. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234867. while (! quitMessagePosted)
  234868. {
  234869. const ScopedAutoReleasePool pool;
  234870. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234871. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234872. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234873. inMode: NSDefaultRunLoopMode
  234874. dequeue: YES];
  234875. if (e != 0 && ! isEventBlockedByModalComps (e))
  234876. [NSApp sendEvent: e];
  234877. if (Time::getMillisecondCounter() >= endTime)
  234878. break;
  234879. }
  234880. return ! quitMessagePosted;
  234881. }
  234882. #endif
  234883. void MessageManager::doPlatformSpecificInitialisation()
  234884. {
  234885. if (juceAppDelegate == 0)
  234886. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234887. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234888. // correctly (needed prior to 10.5)
  234889. if (! [NSThread isMultiThreaded])
  234890. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234891. toTarget: juceAppDelegate
  234892. withObject: nil];
  234893. }
  234894. void MessageManager::doPlatformSpecificShutdown()
  234895. {
  234896. if (juceAppDelegate != 0)
  234897. {
  234898. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234899. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234900. [juceAppDelegate release];
  234901. juceAppDelegate = 0;
  234902. }
  234903. }
  234904. bool juce_postMessageToSystemQueue (Message* message)
  234905. {
  234906. juceAppDelegate->redirector->postMessage (message);
  234907. return true;
  234908. }
  234909. void MessageManager::broadcastMessage (const String&)
  234910. {
  234911. }
  234912. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234913. {
  234914. if (isThisTheMessageThread())
  234915. {
  234916. return (*callback) (data);
  234917. }
  234918. else
  234919. {
  234920. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234921. // deadlock because the message manager is blocked from running, so can never
  234922. // call your function..
  234923. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234924. const ScopedAutoReleasePool pool;
  234925. AppDelegateRedirector::CallbackMessagePayload cmp;
  234926. cmp.function = callback;
  234927. cmp.parameter = data;
  234928. cmp.result = 0;
  234929. cmp.hasBeenExecuted = false;
  234930. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234931. withObject: [NSData dataWithBytesNoCopy: &cmp
  234932. length: sizeof (cmp)
  234933. freeWhenDone: NO]
  234934. waitUntilDone: YES];
  234935. return cmp.result;
  234936. }
  234937. }
  234938. #endif
  234939. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234940. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234941. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234942. // compiled on its own).
  234943. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234944. #if JUCE_MAC
  234945. END_JUCE_NAMESPACE
  234946. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234947. @interface DownloadClickDetector : NSObject
  234948. {
  234949. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234950. }
  234951. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234952. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234953. request: (NSURLRequest*) request
  234954. frame: (WebFrame*) frame
  234955. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234956. @end
  234957. @implementation DownloadClickDetector
  234958. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234959. {
  234960. [super init];
  234961. ownerComponent = ownerComponent_;
  234962. return self;
  234963. }
  234964. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234965. request: (NSURLRequest*) request
  234966. frame: (WebFrame*) frame
  234967. decisionListener: (id <WebPolicyDecisionListener>) listener
  234968. {
  234969. (void) sender;
  234970. (void) request;
  234971. (void) frame;
  234972. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234973. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234974. [listener use];
  234975. else
  234976. [listener ignore];
  234977. }
  234978. @end
  234979. BEGIN_JUCE_NAMESPACE
  234980. class WebBrowserComponentInternal : public NSViewComponent
  234981. {
  234982. public:
  234983. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234984. {
  234985. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234986. frameName: @""
  234987. groupName: @""];
  234988. setView (webView);
  234989. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234990. [webView setPolicyDelegate: clickListener];
  234991. }
  234992. ~WebBrowserComponentInternal()
  234993. {
  234994. [webView setPolicyDelegate: nil];
  234995. [clickListener release];
  234996. setView (0);
  234997. }
  234998. void goToURL (const String& url,
  234999. const StringArray* headers,
  235000. const MemoryBlock* postData)
  235001. {
  235002. NSMutableURLRequest* r
  235003. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235004. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235005. timeoutInterval: 30.0];
  235006. if (postData != 0 && postData->getSize() > 0)
  235007. {
  235008. [r setHTTPMethod: @"POST"];
  235009. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235010. length: postData->getSize()]];
  235011. }
  235012. if (headers != 0)
  235013. {
  235014. for (int i = 0; i < headers->size(); ++i)
  235015. {
  235016. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235017. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235018. [r setValue: juceStringToNS (headerValue)
  235019. forHTTPHeaderField: juceStringToNS (headerName)];
  235020. }
  235021. }
  235022. stop();
  235023. [[webView mainFrame] loadRequest: r];
  235024. }
  235025. void goBack()
  235026. {
  235027. [webView goBack];
  235028. }
  235029. void goForward()
  235030. {
  235031. [webView goForward];
  235032. }
  235033. void stop()
  235034. {
  235035. [webView stopLoading: nil];
  235036. }
  235037. void refresh()
  235038. {
  235039. [webView reload: nil];
  235040. }
  235041. void mouseMove (const MouseEvent&)
  235042. {
  235043. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  235044. // them work is to push them via this non-public method..
  235045. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  235046. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  235047. }
  235048. private:
  235049. WebView* webView;
  235050. DownloadClickDetector* clickListener;
  235051. };
  235052. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235053. : browser (0),
  235054. blankPageShown (false),
  235055. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235056. {
  235057. setOpaque (true);
  235058. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235059. }
  235060. WebBrowserComponent::~WebBrowserComponent()
  235061. {
  235062. deleteAndZero (browser);
  235063. }
  235064. void WebBrowserComponent::goToURL (const String& url,
  235065. const StringArray* headers,
  235066. const MemoryBlock* postData)
  235067. {
  235068. lastURL = url;
  235069. lastHeaders.clear();
  235070. if (headers != 0)
  235071. lastHeaders = *headers;
  235072. lastPostData.setSize (0);
  235073. if (postData != 0)
  235074. lastPostData = *postData;
  235075. blankPageShown = false;
  235076. browser->goToURL (url, headers, postData);
  235077. }
  235078. void WebBrowserComponent::stop()
  235079. {
  235080. browser->stop();
  235081. }
  235082. void WebBrowserComponent::goBack()
  235083. {
  235084. lastURL = String::empty;
  235085. blankPageShown = false;
  235086. browser->goBack();
  235087. }
  235088. void WebBrowserComponent::goForward()
  235089. {
  235090. lastURL = String::empty;
  235091. browser->goForward();
  235092. }
  235093. void WebBrowserComponent::refresh()
  235094. {
  235095. browser->refresh();
  235096. }
  235097. void WebBrowserComponent::paint (Graphics&)
  235098. {
  235099. }
  235100. void WebBrowserComponent::checkWindowAssociation()
  235101. {
  235102. if (isShowing())
  235103. {
  235104. if (blankPageShown)
  235105. goBack();
  235106. }
  235107. else
  235108. {
  235109. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235110. {
  235111. // when the component becomes invisible, some stuff like flash
  235112. // carries on playing audio, so we need to force it onto a blank
  235113. // page to avoid this, (and send it back when it's made visible again).
  235114. blankPageShown = true;
  235115. browser->goToURL ("about:blank", 0, 0);
  235116. }
  235117. }
  235118. }
  235119. void WebBrowserComponent::reloadLastURL()
  235120. {
  235121. if (lastURL.isNotEmpty())
  235122. {
  235123. goToURL (lastURL, &lastHeaders, &lastPostData);
  235124. lastURL = String::empty;
  235125. }
  235126. }
  235127. void WebBrowserComponent::parentHierarchyChanged()
  235128. {
  235129. checkWindowAssociation();
  235130. }
  235131. void WebBrowserComponent::resized()
  235132. {
  235133. browser->setSize (getWidth(), getHeight());
  235134. }
  235135. void WebBrowserComponent::visibilityChanged()
  235136. {
  235137. checkWindowAssociation();
  235138. }
  235139. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235140. {
  235141. return true;
  235142. }
  235143. #else
  235144. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235145. {
  235146. }
  235147. WebBrowserComponent::~WebBrowserComponent()
  235148. {
  235149. }
  235150. void WebBrowserComponent::goToURL (const String& url,
  235151. const StringArray* headers,
  235152. const MemoryBlock* postData)
  235153. {
  235154. }
  235155. void WebBrowserComponent::stop()
  235156. {
  235157. }
  235158. void WebBrowserComponent::goBack()
  235159. {
  235160. }
  235161. void WebBrowserComponent::goForward()
  235162. {
  235163. }
  235164. void WebBrowserComponent::refresh()
  235165. {
  235166. }
  235167. void WebBrowserComponent::paint (Graphics& g)
  235168. {
  235169. }
  235170. void WebBrowserComponent::checkWindowAssociation()
  235171. {
  235172. }
  235173. void WebBrowserComponent::reloadLastURL()
  235174. {
  235175. }
  235176. void WebBrowserComponent::parentHierarchyChanged()
  235177. {
  235178. }
  235179. void WebBrowserComponent::resized()
  235180. {
  235181. }
  235182. void WebBrowserComponent::visibilityChanged()
  235183. {
  235184. }
  235185. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235186. {
  235187. return true;
  235188. }
  235189. #endif
  235190. #endif
  235191. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235192. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235193. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235194. // compiled on its own).
  235195. #if JUCE_INCLUDED_FILE
  235196. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235197. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235198. #endif
  235199. #undef log
  235200. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235201. #define log(a) Logger::writeToLog (a)
  235202. #else
  235203. #define log(a)
  235204. #endif
  235205. #undef OK
  235206. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235207. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235208. {
  235209. if (err == noErr)
  235210. return true;
  235211. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235212. return false;
  235213. }
  235214. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235215. #else
  235216. #define OK(a) (a == noErr)
  235217. #endif
  235218. class CoreAudioInternal : public Timer
  235219. {
  235220. public:
  235221. CoreAudioInternal (AudioDeviceID id)
  235222. : inputLatency (0),
  235223. outputLatency (0),
  235224. callback (0),
  235225. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235226. audioProcID (0),
  235227. #endif
  235228. isSlaveDevice (false),
  235229. deviceID (id),
  235230. started (false),
  235231. sampleRate (0),
  235232. bufferSize (512),
  235233. numInputChans (0),
  235234. numOutputChans (0),
  235235. callbacksAllowed (true),
  235236. numInputChannelInfos (0),
  235237. numOutputChannelInfos (0)
  235238. {
  235239. jassert (deviceID != 0);
  235240. updateDetailsFromDevice();
  235241. AudioObjectPropertyAddress pa;
  235242. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235243. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235244. pa.mElement = kAudioObjectPropertyElementWildcard;
  235245. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235246. }
  235247. ~CoreAudioInternal()
  235248. {
  235249. AudioObjectPropertyAddress pa;
  235250. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235251. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235252. pa.mElement = kAudioObjectPropertyElementWildcard;
  235253. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235254. stop (false);
  235255. }
  235256. void allocateTempBuffers()
  235257. {
  235258. const int tempBufSize = bufferSize + 4;
  235259. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235260. tempInputBuffers.calloc (numInputChans + 2);
  235261. tempOutputBuffers.calloc (numOutputChans + 2);
  235262. int i, count = 0;
  235263. for (i = 0; i < numInputChans; ++i)
  235264. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235265. for (i = 0; i < numOutputChans; ++i)
  235266. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235267. }
  235268. // returns the number of actual available channels
  235269. void fillInChannelInfo (const bool input)
  235270. {
  235271. int chanNum = 0;
  235272. UInt32 size;
  235273. AudioObjectPropertyAddress pa;
  235274. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235275. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235276. pa.mElement = kAudioObjectPropertyElementMaster;
  235277. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235278. {
  235279. HeapBlock <AudioBufferList> bufList;
  235280. bufList.calloc (size, 1);
  235281. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235282. {
  235283. const int numStreams = bufList->mNumberBuffers;
  235284. for (int i = 0; i < numStreams; ++i)
  235285. {
  235286. const AudioBuffer& b = bufList->mBuffers[i];
  235287. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235288. {
  235289. String name;
  235290. {
  235291. char channelName [256];
  235292. zerostruct (channelName);
  235293. UInt32 nameSize = sizeof (channelName);
  235294. UInt32 channelNum = chanNum + 1;
  235295. pa.mSelector = kAudioDevicePropertyChannelName;
  235296. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235297. name = String::fromUTF8 (channelName, nameSize);
  235298. }
  235299. if (input)
  235300. {
  235301. if (activeInputChans[chanNum])
  235302. {
  235303. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235304. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235305. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235306. ++numInputChannelInfos;
  235307. }
  235308. if (name.isEmpty())
  235309. name << "Input " << (chanNum + 1);
  235310. inChanNames.add (name);
  235311. }
  235312. else
  235313. {
  235314. if (activeOutputChans[chanNum])
  235315. {
  235316. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235317. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235318. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235319. ++numOutputChannelInfos;
  235320. }
  235321. if (name.isEmpty())
  235322. name << "Output " << (chanNum + 1);
  235323. outChanNames.add (name);
  235324. }
  235325. ++chanNum;
  235326. }
  235327. }
  235328. }
  235329. }
  235330. }
  235331. void updateDetailsFromDevice()
  235332. {
  235333. stopTimer();
  235334. if (deviceID == 0)
  235335. return;
  235336. const ScopedLock sl (callbackLock);
  235337. Float64 sr;
  235338. UInt32 size = sizeof (Float64);
  235339. AudioObjectPropertyAddress pa;
  235340. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235341. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235342. pa.mElement = kAudioObjectPropertyElementMaster;
  235343. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235344. sampleRate = sr;
  235345. UInt32 framesPerBuf;
  235346. size = sizeof (framesPerBuf);
  235347. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235348. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235349. {
  235350. bufferSize = framesPerBuf;
  235351. allocateTempBuffers();
  235352. }
  235353. bufferSizes.clear();
  235354. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235355. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235356. {
  235357. HeapBlock <AudioValueRange> ranges;
  235358. ranges.calloc (size, 1);
  235359. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235360. {
  235361. bufferSizes.add ((int) ranges[0].mMinimum);
  235362. for (int i = 32; i < 2048; i += 32)
  235363. {
  235364. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235365. {
  235366. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235367. {
  235368. bufferSizes.addIfNotAlreadyThere (i);
  235369. break;
  235370. }
  235371. }
  235372. }
  235373. if (bufferSize > 0)
  235374. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235375. }
  235376. }
  235377. if (bufferSizes.size() == 0 && bufferSize > 0)
  235378. bufferSizes.add (bufferSize);
  235379. sampleRates.clear();
  235380. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235381. String rates;
  235382. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235383. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235384. {
  235385. HeapBlock <AudioValueRange> ranges;
  235386. ranges.calloc (size, 1);
  235387. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235388. {
  235389. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235390. {
  235391. bool ok = false;
  235392. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235393. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235394. ok = true;
  235395. if (ok)
  235396. {
  235397. sampleRates.add (possibleRates[i]);
  235398. rates << possibleRates[i] << ' ';
  235399. }
  235400. }
  235401. }
  235402. }
  235403. if (sampleRates.size() == 0 && sampleRate > 0)
  235404. {
  235405. sampleRates.add (sampleRate);
  235406. rates << sampleRate;
  235407. }
  235408. log ("sr: " + rates);
  235409. inputLatency = 0;
  235410. outputLatency = 0;
  235411. UInt32 lat;
  235412. size = sizeof (lat);
  235413. pa.mSelector = kAudioDevicePropertyLatency;
  235414. pa.mScope = kAudioDevicePropertyScopeInput;
  235415. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235416. inputLatency = (int) lat;
  235417. pa.mScope = kAudioDevicePropertyScopeOutput;
  235418. size = sizeof (lat);
  235419. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235420. outputLatency = (int) lat;
  235421. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235422. inChanNames.clear();
  235423. outChanNames.clear();
  235424. inputChannelInfo.calloc (numInputChans + 2);
  235425. numInputChannelInfos = 0;
  235426. outputChannelInfo.calloc (numOutputChans + 2);
  235427. numOutputChannelInfos = 0;
  235428. fillInChannelInfo (true);
  235429. fillInChannelInfo (false);
  235430. }
  235431. const StringArray getSources (bool input)
  235432. {
  235433. StringArray s;
  235434. HeapBlock <OSType> types;
  235435. const int num = getAllDataSourcesForDevice (deviceID, types);
  235436. for (int i = 0; i < num; ++i)
  235437. {
  235438. AudioValueTranslation avt;
  235439. char buffer[256];
  235440. avt.mInputData = &(types[i]);
  235441. avt.mInputDataSize = sizeof (UInt32);
  235442. avt.mOutputData = buffer;
  235443. avt.mOutputDataSize = 256;
  235444. UInt32 transSize = sizeof (avt);
  235445. AudioObjectPropertyAddress pa;
  235446. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235447. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235448. pa.mElement = kAudioObjectPropertyElementMaster;
  235449. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235450. {
  235451. DBG (buffer);
  235452. s.add (buffer);
  235453. }
  235454. }
  235455. return s;
  235456. }
  235457. int getCurrentSourceIndex (bool input) const
  235458. {
  235459. OSType currentSourceID = 0;
  235460. UInt32 size = sizeof (currentSourceID);
  235461. int result = -1;
  235462. AudioObjectPropertyAddress pa;
  235463. pa.mSelector = kAudioDevicePropertyDataSource;
  235464. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235465. pa.mElement = kAudioObjectPropertyElementMaster;
  235466. if (deviceID != 0)
  235467. {
  235468. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235469. {
  235470. HeapBlock <OSType> types;
  235471. const int num = getAllDataSourcesForDevice (deviceID, types);
  235472. for (int i = 0; i < num; ++i)
  235473. {
  235474. if (types[num] == currentSourceID)
  235475. {
  235476. result = i;
  235477. break;
  235478. }
  235479. }
  235480. }
  235481. }
  235482. return result;
  235483. }
  235484. void setCurrentSourceIndex (int index, bool input)
  235485. {
  235486. if (deviceID != 0)
  235487. {
  235488. HeapBlock <OSType> types;
  235489. const int num = getAllDataSourcesForDevice (deviceID, types);
  235490. if (isPositiveAndBelow (index, num))
  235491. {
  235492. AudioObjectPropertyAddress pa;
  235493. pa.mSelector = kAudioDevicePropertyDataSource;
  235494. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235495. pa.mElement = kAudioObjectPropertyElementMaster;
  235496. OSType typeId = types[index];
  235497. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235498. }
  235499. }
  235500. }
  235501. const String reopen (const BigInteger& inputChannels,
  235502. const BigInteger& outputChannels,
  235503. double newSampleRate,
  235504. int bufferSizeSamples)
  235505. {
  235506. String error;
  235507. log ("CoreAudio reopen");
  235508. callbacksAllowed = false;
  235509. stopTimer();
  235510. stop (false);
  235511. activeInputChans = inputChannels;
  235512. activeInputChans.setRange (inChanNames.size(),
  235513. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235514. false);
  235515. activeOutputChans = outputChannels;
  235516. activeOutputChans.setRange (outChanNames.size(),
  235517. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235518. false);
  235519. numInputChans = activeInputChans.countNumberOfSetBits();
  235520. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235521. // set sample rate
  235522. AudioObjectPropertyAddress pa;
  235523. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235524. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235525. pa.mElement = kAudioObjectPropertyElementMaster;
  235526. Float64 sr = newSampleRate;
  235527. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235528. {
  235529. error = "Couldn't change sample rate";
  235530. }
  235531. else
  235532. {
  235533. // change buffer size
  235534. UInt32 framesPerBuf = bufferSizeSamples;
  235535. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235536. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235537. {
  235538. error = "Couldn't change buffer size";
  235539. }
  235540. else
  235541. {
  235542. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235543. // correctly report their new settings until some random time in the future, so
  235544. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235545. // to make sure we're using the correct numbers..
  235546. updateDetailsFromDevice();
  235547. sampleRate = newSampleRate;
  235548. bufferSize = bufferSizeSamples;
  235549. if (sampleRates.size() == 0)
  235550. error = "Device has no available sample-rates";
  235551. else if (bufferSizes.size() == 0)
  235552. error = "Device has no available buffer-sizes";
  235553. else if (inputDevice != 0)
  235554. error = inputDevice->reopen (inputChannels,
  235555. outputChannels,
  235556. newSampleRate,
  235557. bufferSizeSamples);
  235558. }
  235559. }
  235560. callbacksAllowed = true;
  235561. return error;
  235562. }
  235563. bool start (AudioIODeviceCallback* cb)
  235564. {
  235565. if (! started)
  235566. {
  235567. callback = 0;
  235568. if (deviceID != 0)
  235569. {
  235570. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235571. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235572. #else
  235573. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235574. #endif
  235575. {
  235576. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235577. {
  235578. started = true;
  235579. }
  235580. else
  235581. {
  235582. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235583. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235584. #else
  235585. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235586. audioProcID = 0;
  235587. #endif
  235588. }
  235589. }
  235590. }
  235591. }
  235592. if (started)
  235593. {
  235594. const ScopedLock sl (callbackLock);
  235595. callback = cb;
  235596. }
  235597. if (inputDevice != 0)
  235598. return started && inputDevice->start (cb);
  235599. else
  235600. return started;
  235601. }
  235602. void stop (bool leaveInterruptRunning)
  235603. {
  235604. {
  235605. const ScopedLock sl (callbackLock);
  235606. callback = 0;
  235607. }
  235608. if (started
  235609. && (deviceID != 0)
  235610. && ! leaveInterruptRunning)
  235611. {
  235612. OK (AudioDeviceStop (deviceID, audioIOProc));
  235613. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235614. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235615. #else
  235616. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235617. audioProcID = 0;
  235618. #endif
  235619. started = false;
  235620. { const ScopedLock sl (callbackLock); }
  235621. // wait until it's definately stopped calling back..
  235622. for (int i = 40; --i >= 0;)
  235623. {
  235624. Thread::sleep (50);
  235625. UInt32 running = 0;
  235626. UInt32 size = sizeof (running);
  235627. AudioObjectPropertyAddress pa;
  235628. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235629. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235630. pa.mElement = kAudioObjectPropertyElementMaster;
  235631. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235632. if (running == 0)
  235633. break;
  235634. }
  235635. const ScopedLock sl (callbackLock);
  235636. }
  235637. if (inputDevice != 0)
  235638. inputDevice->stop (leaveInterruptRunning);
  235639. }
  235640. double getSampleRate() const
  235641. {
  235642. return sampleRate;
  235643. }
  235644. int getBufferSize() const
  235645. {
  235646. return bufferSize;
  235647. }
  235648. void audioCallback (const AudioBufferList* inInputData,
  235649. AudioBufferList* outOutputData)
  235650. {
  235651. int i;
  235652. const ScopedLock sl (callbackLock);
  235653. if (callback != 0)
  235654. {
  235655. if (inputDevice == 0)
  235656. {
  235657. for (i = numInputChans; --i >= 0;)
  235658. {
  235659. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235660. float* dest = tempInputBuffers [i];
  235661. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235662. + info.dataOffsetSamples;
  235663. const int stride = info.dataStrideSamples;
  235664. if (stride != 0) // if this is zero, info is invalid
  235665. {
  235666. for (int j = bufferSize; --j >= 0;)
  235667. {
  235668. *dest++ = *src;
  235669. src += stride;
  235670. }
  235671. }
  235672. }
  235673. }
  235674. if (! isSlaveDevice)
  235675. {
  235676. if (inputDevice == 0)
  235677. {
  235678. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235679. numInputChans,
  235680. tempOutputBuffers,
  235681. numOutputChans,
  235682. bufferSize);
  235683. }
  235684. else
  235685. {
  235686. jassert (inputDevice->bufferSize == bufferSize);
  235687. // Sometimes the two linked devices seem to get their callbacks in
  235688. // parallel, so we need to lock both devices to stop the input data being
  235689. // changed while inside our callback..
  235690. const ScopedLock sl2 (inputDevice->callbackLock);
  235691. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235692. inputDevice->numInputChans,
  235693. tempOutputBuffers,
  235694. numOutputChans,
  235695. bufferSize);
  235696. }
  235697. for (i = numOutputChans; --i >= 0;)
  235698. {
  235699. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235700. const float* src = tempOutputBuffers [i];
  235701. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235702. + info.dataOffsetSamples;
  235703. const int stride = info.dataStrideSamples;
  235704. if (stride != 0) // if this is zero, info is invalid
  235705. {
  235706. for (int j = bufferSize; --j >= 0;)
  235707. {
  235708. *dest = *src++;
  235709. dest += stride;
  235710. }
  235711. }
  235712. }
  235713. }
  235714. }
  235715. else
  235716. {
  235717. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235718. {
  235719. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235720. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235721. + info.dataOffsetSamples;
  235722. const int stride = info.dataStrideSamples;
  235723. if (stride != 0) // if this is zero, info is invalid
  235724. {
  235725. for (int j = bufferSize; --j >= 0;)
  235726. {
  235727. *dest = 0.0f;
  235728. dest += stride;
  235729. }
  235730. }
  235731. }
  235732. }
  235733. }
  235734. // called by callbacks
  235735. void deviceDetailsChanged()
  235736. {
  235737. if (callbacksAllowed)
  235738. startTimer (100);
  235739. }
  235740. void timerCallback()
  235741. {
  235742. stopTimer();
  235743. log ("CoreAudio device changed callback");
  235744. const double oldSampleRate = sampleRate;
  235745. const int oldBufferSize = bufferSize;
  235746. updateDetailsFromDevice();
  235747. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235748. {
  235749. callbacksAllowed = false;
  235750. stop (false);
  235751. updateDetailsFromDevice();
  235752. callbacksAllowed = true;
  235753. }
  235754. }
  235755. CoreAudioInternal* getRelatedDevice() const
  235756. {
  235757. UInt32 size = 0;
  235758. ScopedPointer <CoreAudioInternal> result;
  235759. AudioObjectPropertyAddress pa;
  235760. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235761. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235762. pa.mElement = kAudioObjectPropertyElementMaster;
  235763. if (deviceID != 0
  235764. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235765. && size > 0)
  235766. {
  235767. HeapBlock <AudioDeviceID> devs;
  235768. devs.calloc (size, 1);
  235769. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235770. {
  235771. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235772. {
  235773. if (devs[i] != deviceID && devs[i] != 0)
  235774. {
  235775. result = new CoreAudioInternal (devs[i]);
  235776. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235777. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235778. if (thisIsInput != otherIsInput
  235779. || (inChanNames.size() + outChanNames.size() == 0)
  235780. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235781. break;
  235782. result = 0;
  235783. }
  235784. }
  235785. }
  235786. }
  235787. return result.release();
  235788. }
  235789. int inputLatency, outputLatency;
  235790. BigInteger activeInputChans, activeOutputChans;
  235791. StringArray inChanNames, outChanNames;
  235792. Array <double> sampleRates;
  235793. Array <int> bufferSizes;
  235794. AudioIODeviceCallback* callback;
  235795. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235796. AudioDeviceIOProcID audioProcID;
  235797. #endif
  235798. ScopedPointer<CoreAudioInternal> inputDevice;
  235799. bool isSlaveDevice;
  235800. private:
  235801. CriticalSection callbackLock;
  235802. AudioDeviceID deviceID;
  235803. bool started;
  235804. double sampleRate;
  235805. int bufferSize;
  235806. HeapBlock <float> audioBuffer;
  235807. int numInputChans, numOutputChans;
  235808. bool callbacksAllowed;
  235809. struct CallbackDetailsForChannel
  235810. {
  235811. int streamNum;
  235812. int dataOffsetSamples;
  235813. int dataStrideSamples;
  235814. };
  235815. int numInputChannelInfos, numOutputChannelInfos;
  235816. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235817. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235818. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235819. const AudioTimeStamp* /*inNow*/,
  235820. const AudioBufferList* inInputData,
  235821. const AudioTimeStamp* /*inInputTime*/,
  235822. AudioBufferList* outOutputData,
  235823. const AudioTimeStamp* /*inOutputTime*/,
  235824. void* device)
  235825. {
  235826. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235827. return noErr;
  235828. }
  235829. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235830. {
  235831. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235832. switch (pa->mSelector)
  235833. {
  235834. case kAudioDevicePropertyBufferSize:
  235835. case kAudioDevicePropertyBufferFrameSize:
  235836. case kAudioDevicePropertyNominalSampleRate:
  235837. case kAudioDevicePropertyStreamFormat:
  235838. case kAudioDevicePropertyDeviceIsAlive:
  235839. intern->deviceDetailsChanged();
  235840. break;
  235841. case kAudioDevicePropertyBufferSizeRange:
  235842. case kAudioDevicePropertyVolumeScalar:
  235843. case kAudioDevicePropertyMute:
  235844. case kAudioDevicePropertyPlayThru:
  235845. case kAudioDevicePropertyDataSource:
  235846. case kAudioDevicePropertyDeviceIsRunning:
  235847. break;
  235848. }
  235849. return noErr;
  235850. }
  235851. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235852. {
  235853. AudioObjectPropertyAddress pa;
  235854. pa.mSelector = kAudioDevicePropertyDataSources;
  235855. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235856. pa.mElement = kAudioObjectPropertyElementMaster;
  235857. UInt32 size = 0;
  235858. if (deviceID != 0
  235859. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235860. {
  235861. types.calloc (size, 1);
  235862. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235863. return size / (int) sizeof (OSType);
  235864. }
  235865. return 0;
  235866. }
  235867. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235868. };
  235869. class CoreAudioIODevice : public AudioIODevice
  235870. {
  235871. public:
  235872. CoreAudioIODevice (const String& deviceName,
  235873. AudioDeviceID inputDeviceId,
  235874. const int inputIndex_,
  235875. AudioDeviceID outputDeviceId,
  235876. const int outputIndex_)
  235877. : AudioIODevice (deviceName, "CoreAudio"),
  235878. inputIndex (inputIndex_),
  235879. outputIndex (outputIndex_),
  235880. isOpen_ (false),
  235881. isStarted (false)
  235882. {
  235883. CoreAudioInternal* device = 0;
  235884. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235885. {
  235886. jassert (inputDeviceId != 0);
  235887. device = new CoreAudioInternal (inputDeviceId);
  235888. }
  235889. else
  235890. {
  235891. device = new CoreAudioInternal (outputDeviceId);
  235892. if (inputDeviceId != 0)
  235893. {
  235894. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235895. device->inputDevice = secondDevice;
  235896. secondDevice->isSlaveDevice = true;
  235897. }
  235898. }
  235899. internal = device;
  235900. AudioObjectPropertyAddress pa;
  235901. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235902. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235903. pa.mElement = kAudioObjectPropertyElementWildcard;
  235904. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235905. }
  235906. ~CoreAudioIODevice()
  235907. {
  235908. close();
  235909. AudioObjectPropertyAddress pa;
  235910. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235911. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235912. pa.mElement = kAudioObjectPropertyElementWildcard;
  235913. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235914. }
  235915. const StringArray getOutputChannelNames()
  235916. {
  235917. return internal->outChanNames;
  235918. }
  235919. const StringArray getInputChannelNames()
  235920. {
  235921. if (internal->inputDevice != 0)
  235922. return internal->inputDevice->inChanNames;
  235923. else
  235924. return internal->inChanNames;
  235925. }
  235926. int getNumSampleRates()
  235927. {
  235928. return internal->sampleRates.size();
  235929. }
  235930. double getSampleRate (int index)
  235931. {
  235932. return internal->sampleRates [index];
  235933. }
  235934. int getNumBufferSizesAvailable()
  235935. {
  235936. return internal->bufferSizes.size();
  235937. }
  235938. int getBufferSizeSamples (int index)
  235939. {
  235940. return internal->bufferSizes [index];
  235941. }
  235942. int getDefaultBufferSize()
  235943. {
  235944. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235945. if (getBufferSizeSamples(i) >= 512)
  235946. return getBufferSizeSamples(i);
  235947. return 512;
  235948. }
  235949. const String open (const BigInteger& inputChannels,
  235950. const BigInteger& outputChannels,
  235951. double sampleRate,
  235952. int bufferSizeSamples)
  235953. {
  235954. isOpen_ = true;
  235955. if (bufferSizeSamples <= 0)
  235956. bufferSizeSamples = getDefaultBufferSize();
  235957. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235958. isOpen_ = lastError.isEmpty();
  235959. return lastError;
  235960. }
  235961. void close()
  235962. {
  235963. isOpen_ = false;
  235964. internal->stop (false);
  235965. }
  235966. bool isOpen()
  235967. {
  235968. return isOpen_;
  235969. }
  235970. int getCurrentBufferSizeSamples()
  235971. {
  235972. return internal != 0 ? internal->getBufferSize() : 512;
  235973. }
  235974. double getCurrentSampleRate()
  235975. {
  235976. return internal != 0 ? internal->getSampleRate() : 0;
  235977. }
  235978. int getCurrentBitDepth()
  235979. {
  235980. return 32; // no way to find out, so just assume it's high..
  235981. }
  235982. const BigInteger getActiveOutputChannels() const
  235983. {
  235984. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235985. }
  235986. const BigInteger getActiveInputChannels() const
  235987. {
  235988. BigInteger chans;
  235989. if (internal != 0)
  235990. {
  235991. chans = internal->activeInputChans;
  235992. if (internal->inputDevice != 0)
  235993. chans |= internal->inputDevice->activeInputChans;
  235994. }
  235995. return chans;
  235996. }
  235997. int getOutputLatencyInSamples()
  235998. {
  235999. if (internal == 0)
  236000. return 0;
  236001. // this seems like a good guess at getting the latency right - comparing
  236002. // this with a round-trip measurement, it gets it to within a few millisecs
  236003. // for the built-in mac soundcard
  236004. return internal->outputLatency + internal->getBufferSize() * 2;
  236005. }
  236006. int getInputLatencyInSamples()
  236007. {
  236008. if (internal == 0)
  236009. return 0;
  236010. return internal->inputLatency + internal->getBufferSize() * 2;
  236011. }
  236012. void start (AudioIODeviceCallback* callback)
  236013. {
  236014. if (internal != 0 && ! isStarted)
  236015. {
  236016. if (callback != 0)
  236017. callback->audioDeviceAboutToStart (this);
  236018. isStarted = true;
  236019. internal->start (callback);
  236020. }
  236021. }
  236022. void stop()
  236023. {
  236024. if (isStarted && internal != 0)
  236025. {
  236026. AudioIODeviceCallback* const lastCallback = internal->callback;
  236027. isStarted = false;
  236028. internal->stop (true);
  236029. if (lastCallback != 0)
  236030. lastCallback->audioDeviceStopped();
  236031. }
  236032. }
  236033. bool isPlaying()
  236034. {
  236035. if (internal->callback == 0)
  236036. isStarted = false;
  236037. return isStarted;
  236038. }
  236039. const String getLastError()
  236040. {
  236041. return lastError;
  236042. }
  236043. int inputIndex, outputIndex;
  236044. private:
  236045. ScopedPointer<CoreAudioInternal> internal;
  236046. bool isOpen_, isStarted;
  236047. String lastError;
  236048. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236049. {
  236050. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236051. switch (pa->mSelector)
  236052. {
  236053. case kAudioHardwarePropertyDevices:
  236054. intern->deviceDetailsChanged();
  236055. break;
  236056. case kAudioHardwarePropertyDefaultOutputDevice:
  236057. case kAudioHardwarePropertyDefaultInputDevice:
  236058. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236059. break;
  236060. }
  236061. return noErr;
  236062. }
  236063. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  236064. };
  236065. class CoreAudioIODeviceType : public AudioIODeviceType
  236066. {
  236067. public:
  236068. CoreAudioIODeviceType()
  236069. : AudioIODeviceType ("CoreAudio"),
  236070. hasScanned (false)
  236071. {
  236072. }
  236073. ~CoreAudioIODeviceType()
  236074. {
  236075. }
  236076. void scanForDevices()
  236077. {
  236078. hasScanned = true;
  236079. inputDeviceNames.clear();
  236080. outputDeviceNames.clear();
  236081. inputIds.clear();
  236082. outputIds.clear();
  236083. UInt32 size;
  236084. AudioObjectPropertyAddress pa;
  236085. pa.mSelector = kAudioHardwarePropertyDevices;
  236086. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236087. pa.mElement = kAudioObjectPropertyElementMaster;
  236088. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236089. {
  236090. HeapBlock <AudioDeviceID> devs;
  236091. devs.calloc (size, 1);
  236092. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236093. {
  236094. const int num = size / (int) sizeof (AudioDeviceID);
  236095. for (int i = 0; i < num; ++i)
  236096. {
  236097. char name [1024];
  236098. size = sizeof (name);
  236099. pa.mSelector = kAudioDevicePropertyDeviceName;
  236100. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236101. {
  236102. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236103. const int numIns = getNumChannels (devs[i], true);
  236104. const int numOuts = getNumChannels (devs[i], false);
  236105. if (numIns > 0)
  236106. {
  236107. inputDeviceNames.add (nameString);
  236108. inputIds.add (devs[i]);
  236109. }
  236110. if (numOuts > 0)
  236111. {
  236112. outputDeviceNames.add (nameString);
  236113. outputIds.add (devs[i]);
  236114. }
  236115. }
  236116. }
  236117. }
  236118. }
  236119. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236120. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236121. }
  236122. const StringArray getDeviceNames (bool wantInputNames) const
  236123. {
  236124. jassert (hasScanned); // need to call scanForDevices() before doing this
  236125. if (wantInputNames)
  236126. return inputDeviceNames;
  236127. else
  236128. return outputDeviceNames;
  236129. }
  236130. int getDefaultDeviceIndex (bool forInput) const
  236131. {
  236132. jassert (hasScanned); // need to call scanForDevices() before doing this
  236133. AudioDeviceID deviceID;
  236134. UInt32 size = sizeof (deviceID);
  236135. // if they're asking for any input channels at all, use the default input, so we
  236136. // get the built-in mic rather than the built-in output with no inputs..
  236137. AudioObjectPropertyAddress pa;
  236138. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236139. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236140. pa.mElement = kAudioObjectPropertyElementMaster;
  236141. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236142. {
  236143. if (forInput)
  236144. {
  236145. for (int i = inputIds.size(); --i >= 0;)
  236146. if (inputIds[i] == deviceID)
  236147. return i;
  236148. }
  236149. else
  236150. {
  236151. for (int i = outputIds.size(); --i >= 0;)
  236152. if (outputIds[i] == deviceID)
  236153. return i;
  236154. }
  236155. }
  236156. return 0;
  236157. }
  236158. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236159. {
  236160. jassert (hasScanned); // need to call scanForDevices() before doing this
  236161. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236162. if (d == 0)
  236163. return -1;
  236164. return asInput ? d->inputIndex
  236165. : d->outputIndex;
  236166. }
  236167. bool hasSeparateInputsAndOutputs() const { return true; }
  236168. AudioIODevice* createDevice (const String& outputDeviceName,
  236169. const String& inputDeviceName)
  236170. {
  236171. jassert (hasScanned); // need to call scanForDevices() before doing this
  236172. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236173. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236174. String deviceName (outputDeviceName);
  236175. if (deviceName.isEmpty())
  236176. deviceName = inputDeviceName;
  236177. if (index >= 0)
  236178. return new CoreAudioIODevice (deviceName,
  236179. inputIds [inputIndex],
  236180. inputIndex,
  236181. outputIds [outputIndex],
  236182. outputIndex);
  236183. return 0;
  236184. }
  236185. private:
  236186. StringArray inputDeviceNames, outputDeviceNames;
  236187. Array <AudioDeviceID> inputIds, outputIds;
  236188. bool hasScanned;
  236189. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236190. {
  236191. int total = 0;
  236192. UInt32 size;
  236193. AudioObjectPropertyAddress pa;
  236194. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236195. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236196. pa.mElement = kAudioObjectPropertyElementMaster;
  236197. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236198. {
  236199. HeapBlock <AudioBufferList> bufList;
  236200. bufList.calloc (size, 1);
  236201. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236202. {
  236203. const int numStreams = bufList->mNumberBuffers;
  236204. for (int i = 0; i < numStreams; ++i)
  236205. {
  236206. const AudioBuffer& b = bufList->mBuffers[i];
  236207. total += b.mNumberChannels;
  236208. }
  236209. }
  236210. }
  236211. return total;
  236212. }
  236213. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  236214. };
  236215. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_CoreAudio()
  236216. {
  236217. return new CoreAudioIODeviceType();
  236218. }
  236219. #undef log
  236220. #endif
  236221. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236222. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236223. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236224. // compiled on its own).
  236225. #if JUCE_INCLUDED_FILE
  236226. #if JUCE_MAC
  236227. namespace CoreMidiHelpers
  236228. {
  236229. bool logError (const OSStatus err, const int lineNum)
  236230. {
  236231. if (err == noErr)
  236232. return true;
  236233. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236234. jassertfalse;
  236235. return false;
  236236. }
  236237. #undef CHECK_ERROR
  236238. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236239. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236240. {
  236241. String result;
  236242. CFStringRef str = 0;
  236243. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236244. if (str != 0)
  236245. {
  236246. result = PlatformUtilities::cfStringToJuceString (str);
  236247. CFRelease (str);
  236248. str = 0;
  236249. }
  236250. MIDIEntityRef entity = 0;
  236251. MIDIEndpointGetEntity (endpoint, &entity);
  236252. if (entity == 0)
  236253. return result; // probably virtual
  236254. if (result.isEmpty())
  236255. {
  236256. // endpoint name has zero length - try the entity
  236257. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236258. if (str != 0)
  236259. {
  236260. result += PlatformUtilities::cfStringToJuceString (str);
  236261. CFRelease (str);
  236262. str = 0;
  236263. }
  236264. }
  236265. // now consider the device's name
  236266. MIDIDeviceRef device = 0;
  236267. MIDIEntityGetDevice (entity, &device);
  236268. if (device == 0)
  236269. return result;
  236270. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236271. if (str != 0)
  236272. {
  236273. const String s (PlatformUtilities::cfStringToJuceString (str));
  236274. CFRelease (str);
  236275. // if an external device has only one entity, throw away
  236276. // the endpoint name and just use the device name
  236277. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236278. {
  236279. result = s;
  236280. }
  236281. else if (! result.startsWithIgnoreCase (s))
  236282. {
  236283. // prepend the device name to the entity name
  236284. result = (s + " " + result).trimEnd();
  236285. }
  236286. }
  236287. return result;
  236288. }
  236289. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236290. {
  236291. String result;
  236292. // Does the endpoint have connections?
  236293. CFDataRef connections = 0;
  236294. int numConnections = 0;
  236295. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236296. if (connections != 0)
  236297. {
  236298. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236299. if (numConnections > 0)
  236300. {
  236301. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236302. for (int i = 0; i < numConnections; ++i, ++pid)
  236303. {
  236304. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236305. MIDIObjectRef connObject;
  236306. MIDIObjectType connObjectType;
  236307. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236308. if (err == noErr)
  236309. {
  236310. String s;
  236311. if (connObjectType == kMIDIObjectType_ExternalSource
  236312. || connObjectType == kMIDIObjectType_ExternalDestination)
  236313. {
  236314. // Connected to an external device's endpoint (10.3 and later).
  236315. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236316. }
  236317. else
  236318. {
  236319. // Connected to an external device (10.2) (or something else, catch-all)
  236320. CFStringRef str = 0;
  236321. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236322. if (str != 0)
  236323. {
  236324. s = PlatformUtilities::cfStringToJuceString (str);
  236325. CFRelease (str);
  236326. }
  236327. }
  236328. if (s.isNotEmpty())
  236329. {
  236330. if (result.isNotEmpty())
  236331. result += ", ";
  236332. result += s;
  236333. }
  236334. }
  236335. }
  236336. }
  236337. CFRelease (connections);
  236338. }
  236339. if (result.isNotEmpty())
  236340. return result;
  236341. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236342. return getEndpointName (endpoint, false);
  236343. }
  236344. MIDIClientRef getGlobalMidiClient()
  236345. {
  236346. static MIDIClientRef globalMidiClient = 0;
  236347. if (globalMidiClient == 0)
  236348. {
  236349. String name ("JUCE");
  236350. if (JUCEApplication::getInstance() != 0)
  236351. name = JUCEApplication::getInstance()->getApplicationName();
  236352. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236353. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236354. CFRelease (appName);
  236355. }
  236356. return globalMidiClient;
  236357. }
  236358. class MidiPortAndEndpoint
  236359. {
  236360. public:
  236361. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236362. : port (port_), endPoint (endPoint_)
  236363. {
  236364. }
  236365. ~MidiPortAndEndpoint()
  236366. {
  236367. if (port != 0)
  236368. MIDIPortDispose (port);
  236369. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236370. MIDIEndpointDispose (endPoint);
  236371. }
  236372. void send (const MIDIPacketList* const packets)
  236373. {
  236374. if (port != 0)
  236375. MIDISend (port, endPoint, packets);
  236376. else
  236377. MIDIReceived (endPoint, packets);
  236378. }
  236379. MIDIPortRef port;
  236380. MIDIEndpointRef endPoint;
  236381. };
  236382. class MidiPortAndCallback;
  236383. CriticalSection callbackLock;
  236384. Array<MidiPortAndCallback*> activeCallbacks;
  236385. class MidiPortAndCallback
  236386. {
  236387. public:
  236388. MidiPortAndCallback (MidiInputCallback& callback_)
  236389. : input (0), active (false), callback (callback_), concatenator (2048)
  236390. {
  236391. }
  236392. ~MidiPortAndCallback()
  236393. {
  236394. active = false;
  236395. {
  236396. const ScopedLock sl (callbackLock);
  236397. activeCallbacks.removeValue (this);
  236398. }
  236399. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236400. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236401. }
  236402. void handlePackets (const MIDIPacketList* const pktlist)
  236403. {
  236404. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236405. const ScopedLock sl (callbackLock);
  236406. if (activeCallbacks.contains (this) && active)
  236407. {
  236408. const MIDIPacket* packet = &pktlist->packet[0];
  236409. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236410. {
  236411. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236412. input, callback);
  236413. packet = MIDIPacketNext (packet);
  236414. }
  236415. }
  236416. }
  236417. MidiInput* input;
  236418. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236419. volatile bool active;
  236420. private:
  236421. MidiInputCallback& callback;
  236422. MidiDataConcatenator concatenator;
  236423. };
  236424. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236425. {
  236426. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236427. }
  236428. }
  236429. const StringArray MidiOutput::getDevices()
  236430. {
  236431. StringArray s;
  236432. const ItemCount num = MIDIGetNumberOfDestinations();
  236433. for (ItemCount i = 0; i < num; ++i)
  236434. {
  236435. MIDIEndpointRef dest = MIDIGetDestination (i);
  236436. if (dest != 0)
  236437. {
  236438. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236439. if (name.isEmpty())
  236440. name = "<error>";
  236441. s.add (name);
  236442. }
  236443. else
  236444. {
  236445. s.add ("<error>");
  236446. }
  236447. }
  236448. return s;
  236449. }
  236450. int MidiOutput::getDefaultDeviceIndex()
  236451. {
  236452. return 0;
  236453. }
  236454. MidiOutput* MidiOutput::openDevice (int index)
  236455. {
  236456. MidiOutput* mo = 0;
  236457. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  236458. {
  236459. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236460. CFStringRef pname;
  236461. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236462. {
  236463. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236464. MIDIPortRef port;
  236465. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236466. {
  236467. mo = new MidiOutput();
  236468. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236469. }
  236470. CFRelease (pname);
  236471. }
  236472. }
  236473. return mo;
  236474. }
  236475. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236476. {
  236477. MidiOutput* mo = 0;
  236478. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236479. MIDIEndpointRef endPoint;
  236480. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236481. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236482. {
  236483. mo = new MidiOutput();
  236484. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236485. }
  236486. CFRelease (name);
  236487. return mo;
  236488. }
  236489. MidiOutput::~MidiOutput()
  236490. {
  236491. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236492. }
  236493. void MidiOutput::reset()
  236494. {
  236495. }
  236496. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236497. {
  236498. return false;
  236499. }
  236500. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236501. {
  236502. }
  236503. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236504. {
  236505. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236506. if (message.isSysEx())
  236507. {
  236508. const int maxPacketSize = 256;
  236509. int pos = 0, bytesLeft = message.getRawDataSize();
  236510. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236511. HeapBlock <MIDIPacketList> packets;
  236512. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236513. packets->numPackets = numPackets;
  236514. MIDIPacket* p = packets->packet;
  236515. for (int i = 0; i < numPackets; ++i)
  236516. {
  236517. p->timeStamp = AudioGetCurrentHostTime();
  236518. p->length = jmin (maxPacketSize, bytesLeft);
  236519. memcpy (p->data, message.getRawData() + pos, p->length);
  236520. pos += p->length;
  236521. bytesLeft -= p->length;
  236522. p = MIDIPacketNext (p);
  236523. }
  236524. mpe->send (packets);
  236525. }
  236526. else
  236527. {
  236528. MIDIPacketList packets;
  236529. packets.numPackets = 1;
  236530. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  236531. packets.packet[0].length = message.getRawDataSize();
  236532. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236533. mpe->send (&packets);
  236534. }
  236535. }
  236536. const StringArray MidiInput::getDevices()
  236537. {
  236538. StringArray s;
  236539. const ItemCount num = MIDIGetNumberOfSources();
  236540. for (ItemCount i = 0; i < num; ++i)
  236541. {
  236542. MIDIEndpointRef source = MIDIGetSource (i);
  236543. if (source != 0)
  236544. {
  236545. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236546. if (name.isEmpty())
  236547. name = "<error>";
  236548. s.add (name);
  236549. }
  236550. else
  236551. {
  236552. s.add ("<error>");
  236553. }
  236554. }
  236555. return s;
  236556. }
  236557. int MidiInput::getDefaultDeviceIndex()
  236558. {
  236559. return 0;
  236560. }
  236561. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236562. {
  236563. jassert (callback != 0);
  236564. using namespace CoreMidiHelpers;
  236565. MidiInput* newInput = 0;
  236566. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  236567. {
  236568. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236569. if (endPoint != 0)
  236570. {
  236571. CFStringRef name;
  236572. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236573. {
  236574. MIDIClientRef client = getGlobalMidiClient();
  236575. if (client != 0)
  236576. {
  236577. MIDIPortRef port;
  236578. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236579. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236580. {
  236581. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236582. {
  236583. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236584. newInput = new MidiInput (getDevices() [index]);
  236585. mpc->input = newInput;
  236586. newInput->internal = mpc;
  236587. const ScopedLock sl (callbackLock);
  236588. activeCallbacks.add (mpc.release());
  236589. }
  236590. else
  236591. {
  236592. CHECK_ERROR (MIDIPortDispose (port));
  236593. }
  236594. }
  236595. }
  236596. }
  236597. CFRelease (name);
  236598. }
  236599. }
  236600. return newInput;
  236601. }
  236602. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236603. {
  236604. jassert (callback != 0);
  236605. using namespace CoreMidiHelpers;
  236606. MidiInput* mi = 0;
  236607. MIDIClientRef client = getGlobalMidiClient();
  236608. if (client != 0)
  236609. {
  236610. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236611. mpc->active = false;
  236612. MIDIEndpointRef endPoint;
  236613. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236614. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236615. {
  236616. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236617. mi = new MidiInput (deviceName);
  236618. mpc->input = mi;
  236619. mi->internal = mpc;
  236620. const ScopedLock sl (callbackLock);
  236621. activeCallbacks.add (mpc.release());
  236622. }
  236623. CFRelease (name);
  236624. }
  236625. return mi;
  236626. }
  236627. MidiInput::MidiInput (const String& name_)
  236628. : name (name_)
  236629. {
  236630. }
  236631. MidiInput::~MidiInput()
  236632. {
  236633. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236634. }
  236635. void MidiInput::start()
  236636. {
  236637. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236638. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236639. }
  236640. void MidiInput::stop()
  236641. {
  236642. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236643. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236644. }
  236645. #undef CHECK_ERROR
  236646. #else // Stubs for iOS...
  236647. MidiOutput::~MidiOutput() {}
  236648. void MidiOutput::reset() {}
  236649. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236650. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236651. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236652. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236653. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236654. const StringArray MidiInput::getDevices() { return StringArray(); }
  236655. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236656. #endif
  236657. #endif
  236658. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236659. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236660. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236661. // compiled on its own).
  236662. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236663. #if ! JUCE_QUICKTIME
  236664. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236665. #endif
  236666. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236667. class QTCameraDeviceInteral;
  236668. END_JUCE_NAMESPACE
  236669. @interface QTCaptureCallbackDelegate : NSObject
  236670. {
  236671. @public
  236672. CameraDevice* owner;
  236673. QTCameraDeviceInteral* internal;
  236674. int64 firstPresentationTime;
  236675. int64 averageTimeOffset;
  236676. }
  236677. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236678. - (void) dealloc;
  236679. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236680. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236681. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236682. fromConnection: (QTCaptureConnection*) connection;
  236683. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236684. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236685. fromConnection: (QTCaptureConnection*) connection;
  236686. @end
  236687. BEGIN_JUCE_NAMESPACE
  236688. class QTCameraDeviceInteral
  236689. {
  236690. public:
  236691. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236692. {
  236693. const ScopedAutoReleasePool pool;
  236694. session = [[QTCaptureSession alloc] init];
  236695. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236696. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236697. input = 0;
  236698. audioInput = 0;
  236699. audioDevice = 0;
  236700. fileOutput = 0;
  236701. imageOutput = 0;
  236702. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236703. internalDev: this];
  236704. NSError* err = 0;
  236705. [device retain];
  236706. [device open: &err];
  236707. if (err == 0)
  236708. {
  236709. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236710. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236711. [session addInput: input error: &err];
  236712. if (err == 0)
  236713. {
  236714. resetFile();
  236715. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236716. [imageOutput setDelegate: callbackDelegate];
  236717. if (err == 0)
  236718. {
  236719. [session startRunning];
  236720. return;
  236721. }
  236722. }
  236723. }
  236724. openingError = nsStringToJuce ([err description]);
  236725. DBG (openingError);
  236726. }
  236727. ~QTCameraDeviceInteral()
  236728. {
  236729. [session stopRunning];
  236730. [session removeOutput: imageOutput];
  236731. [session release];
  236732. [input release];
  236733. [device release];
  236734. [audioDevice release];
  236735. [audioInput release];
  236736. [fileOutput release];
  236737. [imageOutput release];
  236738. [callbackDelegate release];
  236739. }
  236740. void resetFile()
  236741. {
  236742. [fileOutput recordToOutputFileURL: nil];
  236743. [session removeOutput: fileOutput];
  236744. [fileOutput release];
  236745. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236746. [session removeInput: audioInput];
  236747. [audioInput release];
  236748. audioInput = 0;
  236749. [audioDevice release];
  236750. audioDevice = 0;
  236751. [fileOutput setDelegate: callbackDelegate];
  236752. }
  236753. void addDefaultAudioInput()
  236754. {
  236755. NSError* err = nil;
  236756. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236757. if ([audioDevice open: &err])
  236758. [audioDevice retain];
  236759. else
  236760. audioDevice = nil;
  236761. if (audioDevice != 0)
  236762. {
  236763. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236764. [session addInput: audioInput error: &err];
  236765. }
  236766. }
  236767. void addListener (CameraDevice::Listener* listenerToAdd)
  236768. {
  236769. const ScopedLock sl (listenerLock);
  236770. if (listeners.size() == 0)
  236771. [session addOutput: imageOutput error: nil];
  236772. listeners.addIfNotAlreadyThere (listenerToAdd);
  236773. }
  236774. void removeListener (CameraDevice::Listener* listenerToRemove)
  236775. {
  236776. const ScopedLock sl (listenerLock);
  236777. listeners.removeValue (listenerToRemove);
  236778. if (listeners.size() == 0)
  236779. [session removeOutput: imageOutput];
  236780. }
  236781. void callListeners (CIImage* frame, int w, int h)
  236782. {
  236783. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236784. Image image (cgImage);
  236785. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236786. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236787. CGContextFlush (cgImage->context);
  236788. const ScopedLock sl (listenerLock);
  236789. for (int i = listeners.size(); --i >= 0;)
  236790. {
  236791. CameraDevice::Listener* const l = listeners[i];
  236792. if (l != 0)
  236793. l->imageReceived (image);
  236794. }
  236795. }
  236796. QTCaptureDevice* device;
  236797. QTCaptureDeviceInput* input;
  236798. QTCaptureDevice* audioDevice;
  236799. QTCaptureDeviceInput* audioInput;
  236800. QTCaptureSession* session;
  236801. QTCaptureMovieFileOutput* fileOutput;
  236802. QTCaptureDecompressedVideoOutput* imageOutput;
  236803. QTCaptureCallbackDelegate* callbackDelegate;
  236804. String openingError;
  236805. Array<CameraDevice::Listener*> listeners;
  236806. CriticalSection listenerLock;
  236807. };
  236808. END_JUCE_NAMESPACE
  236809. @implementation QTCaptureCallbackDelegate
  236810. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236811. internalDev: (QTCameraDeviceInteral*) d
  236812. {
  236813. [super init];
  236814. owner = owner_;
  236815. internal = d;
  236816. firstPresentationTime = 0;
  236817. averageTimeOffset = 0;
  236818. return self;
  236819. }
  236820. - (void) dealloc
  236821. {
  236822. [super dealloc];
  236823. }
  236824. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236825. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236826. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236827. fromConnection: (QTCaptureConnection*) connection
  236828. {
  236829. if (internal->listeners.size() > 0)
  236830. {
  236831. const ScopedAutoReleasePool pool;
  236832. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236833. CVPixelBufferGetWidth (videoFrame),
  236834. CVPixelBufferGetHeight (videoFrame));
  236835. }
  236836. }
  236837. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236838. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236839. fromConnection: (QTCaptureConnection*) connection
  236840. {
  236841. const Time now (Time::getCurrentTime());
  236842. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236843. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236844. #else
  236845. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236846. #endif
  236847. int64 presentationTime = (hosttime != nil)
  236848. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236849. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236850. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236851. if (firstPresentationTime == 0)
  236852. {
  236853. firstPresentationTime = presentationTime;
  236854. averageTimeOffset = timeDiff;
  236855. }
  236856. else
  236857. {
  236858. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236859. }
  236860. }
  236861. @end
  236862. BEGIN_JUCE_NAMESPACE
  236863. class QTCaptureViewerComp : public NSViewComponent
  236864. {
  236865. public:
  236866. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236867. {
  236868. const ScopedAutoReleasePool pool;
  236869. captureView = [[QTCaptureView alloc] init];
  236870. [captureView setCaptureSession: internal->session];
  236871. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236872. setView (captureView);
  236873. }
  236874. ~QTCaptureViewerComp()
  236875. {
  236876. setView (0);
  236877. [captureView setCaptureSession: nil];
  236878. [captureView release];
  236879. }
  236880. QTCaptureView* captureView;
  236881. };
  236882. CameraDevice::CameraDevice (const String& name_, int index)
  236883. : name (name_)
  236884. {
  236885. isRecording = false;
  236886. internal = new QTCameraDeviceInteral (this, index);
  236887. }
  236888. CameraDevice::~CameraDevice()
  236889. {
  236890. stopRecording();
  236891. delete static_cast <QTCameraDeviceInteral*> (internal);
  236892. internal = 0;
  236893. }
  236894. Component* CameraDevice::createViewerComponent()
  236895. {
  236896. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236897. }
  236898. const String CameraDevice::getFileExtension()
  236899. {
  236900. return ".mov";
  236901. }
  236902. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236903. {
  236904. stopRecording();
  236905. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236906. d->callbackDelegate->firstPresentationTime = 0;
  236907. file.deleteFile();
  236908. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236909. // out wrong, so we'll put some audio in there too..,
  236910. d->addDefaultAudioInput();
  236911. [d->session addOutput: d->fileOutput error: nil];
  236912. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236913. for (;;)
  236914. {
  236915. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236916. if (connection == 0)
  236917. break;
  236918. QTCompressionOptions* options = 0;
  236919. NSString* mediaType = [connection mediaType];
  236920. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236921. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236922. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236923. : @"QTCompressionOptions240SizeH264Video"];
  236924. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236925. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236926. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236927. }
  236928. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236929. isRecording = true;
  236930. }
  236931. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236932. {
  236933. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236934. if (d->callbackDelegate->firstPresentationTime != 0)
  236935. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236936. return Time();
  236937. }
  236938. void CameraDevice::stopRecording()
  236939. {
  236940. if (isRecording)
  236941. {
  236942. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236943. isRecording = false;
  236944. }
  236945. }
  236946. void CameraDevice::addListener (Listener* listenerToAdd)
  236947. {
  236948. if (listenerToAdd != 0)
  236949. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236950. }
  236951. void CameraDevice::removeListener (Listener* listenerToRemove)
  236952. {
  236953. if (listenerToRemove != 0)
  236954. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236955. }
  236956. const StringArray CameraDevice::getAvailableDevices()
  236957. {
  236958. const ScopedAutoReleasePool pool;
  236959. StringArray results;
  236960. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236961. for (int i = 0; i < (int) [devs count]; ++i)
  236962. {
  236963. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236964. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236965. }
  236966. return results;
  236967. }
  236968. CameraDevice* CameraDevice::openDevice (int index,
  236969. int minWidth, int minHeight,
  236970. int maxWidth, int maxHeight)
  236971. {
  236972. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236973. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236974. return d.release();
  236975. return 0;
  236976. }
  236977. #endif
  236978. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236979. #endif
  236980. #endif
  236981. END_JUCE_NAMESPACE
  236982. #endif
  236983. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236984. #elif JUCE_ANDROID
  236985. /*** Start of inlined file: juce_android_NativeCode.cpp ***/
  236986. /*
  236987. This file wraps together all the android-specific code, so that
  236988. we can include all the native headers just once, and compile all our
  236989. platform-specific stuff in one big lump, keeping it out of the way of
  236990. the rest of the codebase.
  236991. */
  236992. #if JUCE_ANDROID
  236993. #undef JUCE_BUILD_NATIVE
  236994. #define JUCE_BUILD_NATIVE 1
  236995. BEGIN_JUCE_NAMESPACE
  236996. #define USE_ANDROID_CANVAS 0
  236997. #define JUCE_JNI_CALLBACK(className, methodName, returnType, params) \
  236998. extern "C" __attribute__ ((visibility("default"))) returnType Java_com_juce_ ## className ## _ ## methodName params
  236999. // List of basic required classes
  237000. #define JUCE_JNI_CLASSES_ESSENTIAL(JAVACLASS) \
  237001. JAVACLASS (activityClass, "com/juce/JuceAppActivity") \
  237002. JAVACLASS (componentPeerViewClass, "com/juce/ComponentPeerView") \
  237003. JAVACLASS (fileClass, "java/io/File") \
  237004. JAVACLASS (contextClass, "android/content/Context") \
  237005. JAVACLASS (canvasClass, "android/graphics/Canvas") \
  237006. JAVACLASS (paintClass, "android/graphics/Paint") \
  237007. JAVACLASS (matrixClass, "android/graphics/Matrix") \
  237008. JAVACLASS (rectClass, "android/graphics/Rect") \
  237009. JAVACLASS (typefaceClass, "android/graphics/Typeface") \
  237010. // List of extra classes needed when USE_ANDROID_CANVAS is enabled
  237011. #if ! USE_ANDROID_CANVAS
  237012. #define JUCE_JNI_CLASSES(JAVACLASS) JUCE_JNI_CLASSES_ESSENTIAL(JAVACLASS);
  237013. #else
  237014. #define JUCE_JNI_CLASSES(JAVACLASS) JUCE_JNI_CLASSES_ESSENTIAL(JAVACLASS); \
  237015. JAVACLASS (pathClass, "android/graphics/Path") \
  237016. JAVACLASS (regionClass, "android/graphics/Region") \
  237017. JAVACLASS (bitmapClass, "android/graphics/Bitmap") \
  237018. JAVACLASS (bitmapConfigClass, "android/graphics/Bitmap$Config") \
  237019. JAVACLASS (bitmapShaderClass, "android/graphics/BitmapShader") \
  237020. JAVACLASS (shaderClass, "android/graphics/Shader") \
  237021. JAVACLASS (shaderTileModeClass, "android/graphics/Shader$TileMode") \
  237022. JAVACLASS (linearGradientClass, "android/graphics/LinearGradient") \
  237023. JAVACLASS (radialGradientClass, "android/graphics/RadialGradient") \
  237024. #endif
  237025. // List of required methods
  237026. #define JUCE_JNI_METHODS_ESSENTIAL(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  237027. \
  237028. STATICMETHOD (activityClass, printToConsole, "printToConsole", "(Ljava/lang/String;)V") \
  237029. METHOD (activityClass, createNewView, "createNewView", "(Z)Lcom/juce/ComponentPeerView;") \
  237030. METHOD (activityClass, deleteView, "deleteView", "(Lcom/juce/ComponentPeerView;)V") \
  237031. METHOD (activityClass, postMessage, "postMessage", "(J)V") \
  237032. METHOD (activityClass, finish, "finish", "()V") \
  237033. METHOD (activityClass, getClipboardContent, "getClipboardContent", "()Ljava/lang/String;") \
  237034. METHOD (activityClass, setClipboardContent, "setClipboardContent", "(Ljava/lang/String;)V") \
  237035. METHOD (activityClass, excludeClipRegion, "excludeClipRegion", "(Landroid/graphics/Canvas;FFFF)V") \
  237036. METHOD (activityClass, renderGlyph, "renderGlyph", "(CLandroid/graphics/Paint;Landroid/graphics/Matrix;Landroid/graphics/Rect;)[I") \
  237037. \
  237038. METHOD (fileClass, fileExists, "exists", "()Z") \
  237039. \
  237040. METHOD (componentPeerViewClass, setViewName, "setViewName", "(Ljava/lang/String;)V") \
  237041. METHOD (componentPeerViewClass, layout, "layout", "(IIII)V") \
  237042. METHOD (componentPeerViewClass, getLeft, "getLeft", "()I") \
  237043. METHOD (componentPeerViewClass, getTop, "getTop", "()I") \
  237044. METHOD (componentPeerViewClass, getWidth, "getWidth", "()I") \
  237045. METHOD (componentPeerViewClass, getHeight, "getHeight", "()I") \
  237046. METHOD (componentPeerViewClass, getLocationOnScreen, "getLocationOnScreen", "([I)V") \
  237047. METHOD (componentPeerViewClass, bringToFront, "bringToFront", "()V") \
  237048. METHOD (componentPeerViewClass, requestFocus, "requestFocus", "()Z") \
  237049. METHOD (componentPeerViewClass, setVisible, "setVisible", "(Z)V") \
  237050. METHOD (componentPeerViewClass, isVisible, "isVisible", "()Z") \
  237051. METHOD (componentPeerViewClass, hasFocus, "hasFocus", "()Z") \
  237052. METHOD (componentPeerViewClass, invalidate, "invalidate", "(IIII)V") \
  237053. METHOD (componentPeerViewClass, containsPoint, "containsPoint", "(II)Z") \
  237054. \
  237055. METHOD (canvasClass, drawMemoryBitmap, "drawBitmap", "([IIIFFIIZLandroid/graphics/Paint;)V") \
  237056. METHOD (canvasClass, getClipBounds2, "getClipBounds", "()Landroid/graphics/Rect;") \
  237057. \
  237058. METHOD (paintClass, paintClassConstructor, "<init>", "(I)V") \
  237059. METHOD (paintClass, setColor, "setColor", "(I)V") \
  237060. METHOD (paintClass, setAlpha, "setAlpha", "(I)V") \
  237061. METHOD (paintClass, setTypeface, "setTypeface", "(Landroid/graphics/Typeface;)Landroid/graphics/Typeface;") \
  237062. METHOD (paintClass, ascent, "ascent", "()F") \
  237063. METHOD (paintClass, descent, "descent", "()F") \
  237064. METHOD (paintClass, setTextSize, "setTextSize", "(F)V") \
  237065. METHOD (paintClass, getTextWidths, "getTextWidths", "(Ljava/lang/String;[F)I") \
  237066. METHOD (paintClass, setTextScaleX, "setTextScaleX", "(F)V") \
  237067. METHOD (paintClass, getTextPath, "getTextPath", "(Ljava/lang/String;IIFFLandroid/graphics/Path;)V") \
  237068. \
  237069. METHOD (matrixClass, matrixClassConstructor, "<init>", "()V") \
  237070. METHOD (matrixClass, setValues, "setValues", "([F)V") \
  237071. \
  237072. STATICMETHOD (typefaceClass, create, "create", "(Ljava/lang/String;I)Landroid/graphics/Typeface;") \
  237073. STATICMETHOD (typefaceClass, createFromFile, "createFromFile", "(Ljava/lang/String;)Landroid/graphics/Typeface;") \
  237074. \
  237075. METHOD (rectClass, rectConstructor, "<init>", "(IIII)V") \
  237076. FIELD (rectClass, rectLeft, "left", "I") \
  237077. FIELD (rectClass, rectRight, "right", "I") \
  237078. FIELD (rectClass, rectTop, "top", "I") \
  237079. FIELD (rectClass, rectBottom, "bottom", "I") \
  237080. // List of extra methods needed when USE_ANDROID_CANVAS is enabled
  237081. #if ! USE_ANDROID_CANVAS
  237082. #define JUCE_JNI_METHODS(METHOD, STATICMETHOD, FIELD, STATICFIELD) JUCE_JNI_METHODS_ESSENTIAL(METHOD, STATICMETHOD, FIELD, STATICFIELD)
  237083. #else
  237084. #define JUCE_JNI_METHODS(METHOD, STATICMETHOD, FIELD, STATICFIELD) JUCE_JNI_METHODS_ESSENTIAL(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  237085. METHOD (pathClass, pathClassConstructor, "<init>", "()V") \
  237086. METHOD (pathClass, moveTo, "moveTo", "(FF)V") \
  237087. METHOD (pathClass, lineTo, "lineTo", "(FF)V") \
  237088. METHOD (pathClass, quadTo, "quadTo", "(FFFF)V") \
  237089. METHOD (pathClass, cubicTo, "cubicTo", "(FFFFFF)V") \
  237090. METHOD (pathClass, closePath, "close", "()V") \
  237091. METHOD (pathClass, computeBounds, "computeBounds", "(Landroid/graphics/RectF;Z)V") \
  237092. \
  237093. STATICMETHOD (bitmapClass, createBitmap, "createBitmap", "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;") \
  237094. STATICFIELD (bitmapConfigClass, ARGB_8888, "ARGB_8888", "Landroid/graphics/Bitmap$Config;") \
  237095. STATICFIELD (bitmapConfigClass, ALPHA_8, "ALPHA_8", "Landroid/graphics/Bitmap$Config;") \
  237096. METHOD (bitmapClass, bitmapCopy, "copy", "(Landroid/graphics/Bitmap$Config;Z)Landroid/graphics/Bitmap;") \
  237097. METHOD (bitmapClass, getPixels, "getPixels", "([IIIIIII)V") \
  237098. METHOD (bitmapClass, setPixels, "setPixels", "([IIIIIII)V") \
  237099. METHOD (bitmapClass, recycle, "recycle", "()V") \
  237100. \
  237101. METHOD (shaderClass, setLocalMatrix, "setLocalMatrix", "(Landroid/graphics/Matrix;)V") \
  237102. STATICFIELD (shaderTileModeClass, clampMode, "CLAMP", "Landroid/graphics/Shader$TileMode;") \
  237103. \
  237104. METHOD (bitmapShaderClass, bitmapShaderConstructor, "<init>", "(Landroid/graphics/Bitmap;Landroid/graphics/Shader$TileMode;Landroid/graphics/Shader$TileMode;)V") \
  237105. \
  237106. METHOD (paintClass, setShader, "setShader", "(Landroid/graphics/Shader;)Landroid/graphics/Shader;") \
  237107. \
  237108. METHOD (canvasClass, canvasBitmapConstructor, "<init>", "(Landroid/graphics/Bitmap;)V") \
  237109. METHOD (canvasClass, drawRect, "drawRect", "(FFFFLandroid/graphics/Paint;)V") \
  237110. METHOD (canvasClass, translate, "translate", "(FF)V") \
  237111. METHOD (canvasClass, clipPath, "clipPath", "(Landroid/graphics/Path;)Z") \
  237112. METHOD (canvasClass, clipRect, "clipRect", "(FFFF)Z") \
  237113. METHOD (canvasClass, clipRegion, "clipRegion", "(Landroid/graphics/Region;)Z") \
  237114. METHOD (canvasClass, concat, "concat", "(Landroid/graphics/Matrix;)V") \
  237115. METHOD (canvasClass, drawBitmap, "drawBitmap", "(Landroid/graphics/Bitmap;Landroid/graphics/Matrix;Landroid/graphics/Paint;)V") \
  237116. METHOD (canvasClass, drawBitmapAt, "drawBitmap", "(Landroid/graphics/Bitmap;FFLandroid/graphics/Paint;)V") \
  237117. METHOD (canvasClass, drawLine, "drawLine", "(FFFFLandroid/graphics/Paint;)V") \
  237118. METHOD (canvasClass, drawPath, "drawPath", "(Landroid/graphics/Path;Landroid/graphics/Paint;)V") \
  237119. METHOD (canvasClass, drawText, "drawText", "(Ljava/lang/String;FFLandroid/graphics/Paint;)V") \
  237120. METHOD (canvasClass, getClipBounds, "getClipBounds", "(Landroid/graphics/Rect;)Z") \
  237121. METHOD (canvasClass, getMatrix, "getMatrix", "()Landroid/graphics/Matrix;") \
  237122. METHOD (canvasClass, save, "save", "()I") \
  237123. METHOD (canvasClass, restore, "restore", "()V") \
  237124. METHOD (canvasClass, saveLayerAlpha, "saveLayerAlpha", "(FFFFII)I") \
  237125. \
  237126. METHOD (linearGradientClass, linearGradientConstructor, "<init>", "(FFFF[I[FLandroid/graphics/Shader$TileMode;)V") \
  237127. \
  237128. METHOD (radialGradientClass, radialGradientConstructor, "<init>", "(FFF[I[FLandroid/graphics/Shader$TileMode;)V") \
  237129. \
  237130. METHOD (regionClass, regionConstructor, "<init>", "()V"); \
  237131. METHOD (regionClass, regionUnion, "union", "(Landroid/graphics/Rect;)Z"); \
  237132. #endif
  237133. class ThreadLocalJNIEnvHolder
  237134. {
  237135. public:
  237136. ThreadLocalJNIEnvHolder()
  237137. : jvm (0)
  237138. {
  237139. zeromem (threads, sizeof (threads));
  237140. zeromem (envs, sizeof (envs));
  237141. }
  237142. void initialise (JNIEnv* env)
  237143. {
  237144. env->GetJavaVM (&jvm);
  237145. addEnv (env);
  237146. }
  237147. void attach()
  237148. {
  237149. JNIEnv* env = 0;
  237150. jvm->AttachCurrentThread (&env, 0);
  237151. if (env != 0)
  237152. addEnv (env);
  237153. }
  237154. void detach()
  237155. {
  237156. jvm->DetachCurrentThread();
  237157. const pthread_t thisThread = pthread_self();
  237158. ScopedLock sl (addRemoveLock);
  237159. for (int i = 0; i < maxThreads; ++i)
  237160. if (threads[i] == thisThread)
  237161. threads[i] = 0;
  237162. }
  237163. JNIEnv* get() const throw()
  237164. {
  237165. const pthread_t thisThread = pthread_self();
  237166. for (int i = 0; i < maxThreads; ++i)
  237167. if (threads[i] == thisThread)
  237168. return envs[i];
  237169. return 0;
  237170. }
  237171. enum { maxThreads = 16 };
  237172. private:
  237173. JavaVM* jvm;
  237174. pthread_t threads [maxThreads];
  237175. JNIEnv* envs [maxThreads];
  237176. CriticalSection addRemoveLock;
  237177. void addEnv (JNIEnv* env)
  237178. {
  237179. ScopedLock sl (addRemoveLock);
  237180. if (get() == 0)
  237181. {
  237182. const pthread_t thisThread = pthread_self();
  237183. for (int i = 0; i < maxThreads; ++i)
  237184. {
  237185. if (threads[i] == 0)
  237186. {
  237187. envs[i] = env;
  237188. threads[i] = thisThread;
  237189. return;
  237190. }
  237191. }
  237192. }
  237193. jassertfalse; // too many threads!
  237194. }
  237195. };
  237196. static ThreadLocalJNIEnvHolder threadLocalJNIEnvHolder;
  237197. struct AndroidThreadScope
  237198. {
  237199. AndroidThreadScope() { threadLocalJNIEnvHolder.attach(); }
  237200. ~AndroidThreadScope() { threadLocalJNIEnvHolder.detach(); }
  237201. };
  237202. static inline JNIEnv* getEnv() throw()
  237203. {
  237204. return threadLocalJNIEnvHolder.get();
  237205. }
  237206. class GlobalRef
  237207. {
  237208. public:
  237209. inline GlobalRef() throw()
  237210. : obj (0)
  237211. {
  237212. }
  237213. inline explicit GlobalRef (jobject obj_)
  237214. : obj (retain (obj_))
  237215. {
  237216. }
  237217. inline GlobalRef (const GlobalRef& other)
  237218. : obj (retain (other.obj))
  237219. {
  237220. }
  237221. ~GlobalRef()
  237222. {
  237223. clear();
  237224. }
  237225. inline void clear()
  237226. {
  237227. if (obj != 0)
  237228. {
  237229. getEnv()->DeleteGlobalRef (obj);
  237230. obj = 0;
  237231. }
  237232. }
  237233. inline GlobalRef& operator= (const GlobalRef& other)
  237234. {
  237235. clear();
  237236. obj = retain (other.obj);
  237237. return *this;
  237238. }
  237239. inline operator jobject() const throw() { return obj; }
  237240. inline jobject get() const throw() { return obj; }
  237241. #define DECLARE_CALL_TYPE_METHOD(returnType, typeName) \
  237242. returnType call##typeName##Method (jmethodID methodID, ... ) const \
  237243. { \
  237244. va_list args; \
  237245. va_start (args, methodID); \
  237246. returnType result = getEnv()->Call##typeName##MethodV (obj, methodID, args); \
  237247. va_end (args); \
  237248. return result; \
  237249. }
  237250. DECLARE_CALL_TYPE_METHOD (jobject, Object)
  237251. DECLARE_CALL_TYPE_METHOD (jboolean, Boolean)
  237252. DECLARE_CALL_TYPE_METHOD (jbyte, Byte)
  237253. DECLARE_CALL_TYPE_METHOD (jchar, Char)
  237254. DECLARE_CALL_TYPE_METHOD (jshort, Short)
  237255. DECLARE_CALL_TYPE_METHOD (jint, Int)
  237256. DECLARE_CALL_TYPE_METHOD (jlong, Long)
  237257. DECLARE_CALL_TYPE_METHOD (jfloat, Float)
  237258. DECLARE_CALL_TYPE_METHOD (jdouble, Double)
  237259. #undef DECLARE_CALL_TYPE_METHOD
  237260. void callVoidMethod (jmethodID methodID, ... ) const
  237261. {
  237262. va_list args;
  237263. va_start (args, methodID);
  237264. getEnv()->CallVoidMethodV (obj, methodID, args);
  237265. va_end (args);
  237266. }
  237267. private:
  237268. jobject obj;
  237269. static inline jobject retain (jobject obj_)
  237270. {
  237271. return obj_ == 0 ? 0 : getEnv()->NewGlobalRef (obj_);
  237272. }
  237273. };
  237274. template <typename JavaType>
  237275. class LocalRef
  237276. {
  237277. public:
  237278. explicit inline LocalRef (JavaType obj_) throw()
  237279. : obj (obj_)
  237280. {
  237281. }
  237282. inline LocalRef (const LocalRef& other) throw()
  237283. : obj (retain (other.obj))
  237284. {
  237285. }
  237286. ~LocalRef()
  237287. {
  237288. if (obj != 0)
  237289. getEnv()->DeleteLocalRef (obj);
  237290. }
  237291. LocalRef& operator= (const LocalRef& other)
  237292. {
  237293. if (obj != other.obj)
  237294. {
  237295. if (obj != 0)
  237296. getEnv()->DeleteLocalRef (obj);
  237297. obj = retain (other.obj);
  237298. }
  237299. return *this;
  237300. }
  237301. inline operator JavaType() const throw() { return obj; }
  237302. inline JavaType get() const throw() { return obj; }
  237303. private:
  237304. JavaType obj;
  237305. static JavaType retain (JavaType obj_)
  237306. {
  237307. return obj_ == 0 ? 0 : (JavaType) getEnv()->NewLocalRef (obj_);
  237308. }
  237309. };
  237310. static const String juceString (jstring s)
  237311. {
  237312. JNIEnv* env = getEnv();
  237313. jboolean isCopy;
  237314. const char* const utf8 = env->GetStringUTFChars (s, &isCopy);
  237315. CharPointer_UTF8 utf8CP (utf8);
  237316. const String result (utf8CP);
  237317. env->ReleaseStringUTFChars (s, utf8);
  237318. return result;
  237319. }
  237320. static const LocalRef<jstring> javaString (const String& s)
  237321. {
  237322. return LocalRef<jstring> (getEnv()->NewStringUTF (s.toUTF8()));
  237323. }
  237324. static const LocalRef<jstring> javaStringFromChar (const juce_wchar c)
  237325. {
  237326. char utf8[5] = { 0 };
  237327. CharPointer_UTF8 (utf8).write (c);
  237328. return LocalRef<jstring> (getEnv()->NewStringUTF (utf8));
  237329. }
  237330. class AndroidJavaCallbacks
  237331. {
  237332. public:
  237333. AndroidJavaCallbacks() : screenWidth (0), screenHeight (0)
  237334. {
  237335. }
  237336. void initialise (JNIEnv* env, jobject activity_,
  237337. jstring appFile_, jstring appDataDir_,
  237338. int screenWidth_, int screenHeight_)
  237339. {
  237340. threadLocalJNIEnvHolder.initialise (env);
  237341. activity = GlobalRef (activity_);
  237342. appFile = juceString (appFile_);
  237343. appDataDir = juceString (appDataDir_);
  237344. screenWidth = screenWidth_;
  237345. screenHeight = screenHeight_;
  237346. #define CREATE_JNI_CLASS(className, path) \
  237347. className = (jclass) env->NewGlobalRef (env->FindClass (path)); \
  237348. jassert (className != 0);
  237349. JUCE_JNI_CLASSES (CREATE_JNI_CLASS);
  237350. #undef CREATE_JNI_CLASS
  237351. #define CREATE_JNI_METHOD(ownerClass, methodID, stringName, params) \
  237352. methodID = env->GetMethodID (ownerClass, stringName, params); \
  237353. jassert (methodID != 0);
  237354. #define CREATE_JNI_STATICMETHOD(ownerClass, methodID, stringName, params) \
  237355. methodID = env->GetStaticMethodID (ownerClass, stringName, params); \
  237356. jassert (methodID != 0);
  237357. #define CREATE_JNI_FIELD(ownerClass, fieldID, stringName, signature) \
  237358. fieldID = env->GetFieldID (ownerClass, stringName, signature); \
  237359. jassert (fieldID != 0);
  237360. #define CREATE_JNI_STATICFIELD(ownerClass, fieldID, stringName, signature) \
  237361. fieldID = env->GetStaticFieldID (ownerClass, stringName, signature); \
  237362. jassert (fieldID != 0);
  237363. JUCE_JNI_METHODS (CREATE_JNI_METHOD, CREATE_JNI_STATICMETHOD, CREATE_JNI_FIELD, CREATE_JNI_STATICFIELD);
  237364. #undef CREATE_JNI_METHOD
  237365. }
  237366. void shutdown()
  237367. {
  237368. JNIEnv* env = getEnv();
  237369. if (env != 0)
  237370. {
  237371. #define RELEASE_JNI_CLASS(className, path) env->DeleteGlobalRef (className);
  237372. JUCE_JNI_CLASSES (RELEASE_JNI_CLASS);
  237373. #undef RELEASE_JNI_CLASS
  237374. activity.clear();
  237375. }
  237376. }
  237377. GlobalRef activity;
  237378. String appFile, appDataDir;
  237379. int screenWidth, screenHeight;
  237380. jobject createPaint (Graphics::ResamplingQuality quality)
  237381. {
  237382. jint constructorFlags = 1 /*ANTI_ALIAS_FLAG*/
  237383. | 4 /*DITHER_FLAG*/
  237384. | 128 /*SUBPIXEL_TEXT_FLAG*/;
  237385. if (quality > Graphics::lowResamplingQuality)
  237386. constructorFlags |= 2; /*FILTER_BITMAP_FLAG*/
  237387. return getEnv()->NewObject (paintClass, paintClassConstructor, constructorFlags);
  237388. }
  237389. const jobject createMatrix (JNIEnv* env, const AffineTransform& t)
  237390. {
  237391. jobject m = env->NewObject (matrixClass, matrixClassConstructor);
  237392. jfloat values[9] = { t.mat00, t.mat01, t.mat02,
  237393. t.mat10, t.mat11, t.mat12,
  237394. 0.0f, 0.0f, 1.0f };
  237395. jfloatArray javaArray = env->NewFloatArray (9);
  237396. env->SetFloatArrayRegion (javaArray, 0, 9, values);
  237397. env->CallVoidMethod (m, setValues, javaArray);
  237398. env->DeleteLocalRef (javaArray);
  237399. return m;
  237400. }
  237401. #define DECLARE_JNI_CLASS(className, path) jclass className;
  237402. JUCE_JNI_CLASSES (DECLARE_JNI_CLASS);
  237403. #undef DECLARE_JNI_CLASS
  237404. #define DECLARE_JNI_METHOD(ownerClass, methodID, stringName, params) jmethodID methodID;
  237405. #define DECLARE_JNI_FIELD(ownerClass, fieldID, stringName, signature) jfieldID fieldID;
  237406. JUCE_JNI_METHODS (DECLARE_JNI_METHOD, DECLARE_JNI_METHOD, DECLARE_JNI_FIELD, DECLARE_JNI_FIELD);
  237407. #undef DECLARE_JNI_METHOD
  237408. };
  237409. static AndroidJavaCallbacks android;
  237410. #define JUCE_INCLUDED_FILE 1
  237411. // Now include the actual code files..
  237412. /*** Start of inlined file: juce_android_Misc.cpp ***/
  237413. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237414. // compiled on its own).
  237415. #if JUCE_INCLUDED_FILE
  237416. END_JUCE_NAMESPACE
  237417. extern JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication(); // (from START_JUCE_APPLICATION)
  237418. BEGIN_JUCE_NAMESPACE
  237419. JUCE_JNI_CALLBACK (JuceAppActivity, launchApp, void, (JNIEnv* env, jobject activity,
  237420. jstring appFile, jstring appDataDir,
  237421. int screenWidth, int screenHeight))
  237422. {
  237423. android.initialise (env, activity, appFile, appDataDir, screenWidth, screenHeight);
  237424. JUCEApplication::createInstance = &juce_CreateApplication;
  237425. initialiseJuce_GUI();
  237426. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  237427. exit (0);
  237428. }
  237429. JUCE_JNI_CALLBACK (JuceAppActivity, quitApp, void, (JNIEnv* env, jobject activity))
  237430. {
  237431. JUCEApplication::appWillTerminateByForce();
  237432. android.shutdown();
  237433. }
  237434. void PlatformUtilities::beep()
  237435. {
  237436. }
  237437. void Logger::outputDebugString (const String& text)
  237438. {
  237439. getEnv()->CallStaticVoidMethod (android.activityClass, android.printToConsole,
  237440. javaString (text).get());
  237441. }
  237442. void SystemClipboard::copyTextToClipboard (const String& text)
  237443. {
  237444. const LocalRef<jstring> t (javaString (text));
  237445. android.activity.callVoidMethod (android.setClipboardContent, t.get());
  237446. }
  237447. const String SystemClipboard::getTextFromClipboard()
  237448. {
  237449. const LocalRef<jstring> text ((jstring) android.activity.callObjectMethod (android.getClipboardContent));
  237450. return juceString (text);
  237451. }
  237452. #endif
  237453. /*** End of inlined file: juce_android_Misc.cpp ***/
  237454. /*** Start of inlined file: juce_android_SystemStats.cpp ***/
  237455. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237456. // compiled on its own).
  237457. #if JUCE_INCLUDED_FILE
  237458. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  237459. {
  237460. return Android;
  237461. }
  237462. const String SystemStats::getOperatingSystemName()
  237463. {
  237464. return "Android";
  237465. }
  237466. bool SystemStats::isOperatingSystem64Bit()
  237467. {
  237468. #if JUCE_64BIT
  237469. return true;
  237470. #else
  237471. return false;
  237472. #endif
  237473. }
  237474. namespace AndroidStatsHelpers
  237475. {
  237476. // TODO
  237477. const String getCpuInfo (const char* const key)
  237478. {
  237479. StringArray lines;
  237480. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  237481. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  237482. if (lines[i].startsWithIgnoreCase (key))
  237483. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  237484. return String::empty;
  237485. }
  237486. }
  237487. const String SystemStats::getCpuVendor()
  237488. {
  237489. return AndroidStatsHelpers::getCpuInfo ("vendor_id");
  237490. }
  237491. int SystemStats::getCpuSpeedInMegaherz()
  237492. {
  237493. return roundToInt (AndroidStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  237494. }
  237495. int SystemStats::getMemorySizeInMegabytes()
  237496. {
  237497. struct sysinfo sysi;
  237498. if (sysinfo (&sysi) == 0)
  237499. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  237500. return 0;
  237501. }
  237502. int SystemStats::getPageSize()
  237503. {
  237504. // TODO
  237505. return sysconf (_SC_PAGESIZE);
  237506. }
  237507. const String SystemStats::getLogonName()
  237508. {
  237509. // TODO
  237510. const char* user = getenv ("USER");
  237511. if (user == 0)
  237512. {
  237513. struct passwd* const pw = getpwuid (getuid());
  237514. if (pw != 0)
  237515. user = pw->pw_name;
  237516. }
  237517. return String::fromUTF8 (user);
  237518. }
  237519. const String SystemStats::getFullUserName()
  237520. {
  237521. return getLogonName();
  237522. }
  237523. void SystemStats::initialiseStats()
  237524. {
  237525. // TODO
  237526. const String flags (AndroidStatsHelpers::getCpuInfo ("flags"));
  237527. cpuFlags.hasMMX = flags.contains ("mmx");
  237528. cpuFlags.hasSSE = flags.contains ("sse");
  237529. cpuFlags.hasSSE2 = flags.contains ("sse2");
  237530. cpuFlags.has3DNow = flags.contains ("3dnow");
  237531. cpuFlags.numCpus = jmax (1, sysconf (_SC_NPROCESSORS_ONLN));
  237532. }
  237533. void PlatformUtilities::fpuReset() {}
  237534. uint32 juce_millisecondsSinceStartup() throw()
  237535. {
  237536. // TODO
  237537. timespec t;
  237538. clock_gettime (CLOCK_MONOTONIC, &t);
  237539. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  237540. }
  237541. int64 Time::getHighResolutionTicks() throw()
  237542. {
  237543. // TODO
  237544. timespec t;
  237545. clock_gettime (CLOCK_MONOTONIC, &t);
  237546. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  237547. }
  237548. int64 Time::getHighResolutionTicksPerSecond() throw()
  237549. {
  237550. // TODO
  237551. return 1000000; // (microseconds)
  237552. }
  237553. double Time::getMillisecondCounterHiRes() throw()
  237554. {
  237555. return getHighResolutionTicks() * 0.001;
  237556. }
  237557. bool Time::setSystemTimeToThisTime() const
  237558. {
  237559. jassertfalse;
  237560. return false;
  237561. }
  237562. #endif
  237563. /*** End of inlined file: juce_android_SystemStats.cpp ***/
  237564. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  237565. /*
  237566. This file contains posix routines that are common to both the Linux and Mac builds.
  237567. It gets included directly in the cpp files for these platforms.
  237568. */
  237569. CriticalSection::CriticalSection() throw()
  237570. {
  237571. pthread_mutexattr_t atts;
  237572. pthread_mutexattr_init (&atts);
  237573. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  237574. #if ! JUCE_ANDROID
  237575. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  237576. #endif
  237577. pthread_mutex_init (&internal, &atts);
  237578. }
  237579. CriticalSection::~CriticalSection() throw()
  237580. {
  237581. pthread_mutex_destroy (&internal);
  237582. }
  237583. void CriticalSection::enter() const throw()
  237584. {
  237585. pthread_mutex_lock (&internal);
  237586. }
  237587. bool CriticalSection::tryEnter() const throw()
  237588. {
  237589. return pthread_mutex_trylock (&internal) == 0;
  237590. }
  237591. void CriticalSection::exit() const throw()
  237592. {
  237593. pthread_mutex_unlock (&internal);
  237594. }
  237595. class WaitableEventImpl
  237596. {
  237597. public:
  237598. WaitableEventImpl (const bool manualReset_)
  237599. : triggered (false),
  237600. manualReset (manualReset_)
  237601. {
  237602. pthread_cond_init (&condition, 0);
  237603. pthread_mutexattr_t atts;
  237604. pthread_mutexattr_init (&atts);
  237605. #if ! JUCE_ANDROID
  237606. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  237607. #endif
  237608. pthread_mutex_init (&mutex, &atts);
  237609. }
  237610. ~WaitableEventImpl()
  237611. {
  237612. pthread_cond_destroy (&condition);
  237613. pthread_mutex_destroy (&mutex);
  237614. }
  237615. bool wait (const int timeOutMillisecs) throw()
  237616. {
  237617. pthread_mutex_lock (&mutex);
  237618. if (! triggered)
  237619. {
  237620. if (timeOutMillisecs < 0)
  237621. {
  237622. do
  237623. {
  237624. pthread_cond_wait (&condition, &mutex);
  237625. }
  237626. while (! triggered);
  237627. }
  237628. else
  237629. {
  237630. struct timeval now;
  237631. gettimeofday (&now, 0);
  237632. struct timespec time;
  237633. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  237634. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  237635. if (time.tv_nsec >= 1000000000)
  237636. {
  237637. time.tv_nsec -= 1000000000;
  237638. time.tv_sec++;
  237639. }
  237640. do
  237641. {
  237642. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  237643. {
  237644. pthread_mutex_unlock (&mutex);
  237645. return false;
  237646. }
  237647. }
  237648. while (! triggered);
  237649. }
  237650. }
  237651. if (! manualReset)
  237652. triggered = false;
  237653. pthread_mutex_unlock (&mutex);
  237654. return true;
  237655. }
  237656. void signal() throw()
  237657. {
  237658. pthread_mutex_lock (&mutex);
  237659. triggered = true;
  237660. pthread_cond_broadcast (&condition);
  237661. pthread_mutex_unlock (&mutex);
  237662. }
  237663. void reset() throw()
  237664. {
  237665. pthread_mutex_lock (&mutex);
  237666. triggered = false;
  237667. pthread_mutex_unlock (&mutex);
  237668. }
  237669. private:
  237670. pthread_cond_t condition;
  237671. pthread_mutex_t mutex;
  237672. bool triggered;
  237673. const bool manualReset;
  237674. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  237675. };
  237676. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  237677. : internal (new WaitableEventImpl (manualReset))
  237678. {
  237679. }
  237680. WaitableEvent::~WaitableEvent() throw()
  237681. {
  237682. delete static_cast <WaitableEventImpl*> (internal);
  237683. }
  237684. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  237685. {
  237686. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  237687. }
  237688. void WaitableEvent::signal() const throw()
  237689. {
  237690. static_cast <WaitableEventImpl*> (internal)->signal();
  237691. }
  237692. void WaitableEvent::reset() const throw()
  237693. {
  237694. static_cast <WaitableEventImpl*> (internal)->reset();
  237695. }
  237696. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  237697. {
  237698. struct timespec time;
  237699. time.tv_sec = millisecs / 1000;
  237700. time.tv_nsec = (millisecs % 1000) * 1000000;
  237701. nanosleep (&time, 0);
  237702. }
  237703. const juce_wchar File::separator = '/';
  237704. const String File::separatorString ("/");
  237705. const File File::getCurrentWorkingDirectory()
  237706. {
  237707. HeapBlock<char> heapBuffer;
  237708. char localBuffer [1024];
  237709. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  237710. int bufferSize = 4096;
  237711. while (cwd == 0 && errno == ERANGE)
  237712. {
  237713. heapBuffer.malloc (bufferSize);
  237714. cwd = getcwd (heapBuffer, bufferSize - 1);
  237715. bufferSize += 1024;
  237716. }
  237717. return File (String::fromUTF8 (cwd));
  237718. }
  237719. bool File::setAsCurrentWorkingDirectory() const
  237720. {
  237721. return chdir (getFullPathName().toUTF8()) == 0;
  237722. }
  237723. namespace
  237724. {
  237725. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  237726. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  237727. #else
  237728. typedef struct stat juce_statStruct;
  237729. #endif
  237730. bool juce_stat (const String& fileName, juce_statStruct& info)
  237731. {
  237732. return fileName.isNotEmpty()
  237733. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  237734. && (stat64 (fileName.toUTF8(), &info) == 0);
  237735. #else
  237736. && (stat (fileName.toUTF8(), &info) == 0);
  237737. #endif
  237738. }
  237739. // if this file doesn't exist, find a parent of it that does..
  237740. bool juce_doStatFS (File f, struct statfs& result)
  237741. {
  237742. for (int i = 5; --i >= 0;)
  237743. {
  237744. if (f.exists())
  237745. break;
  237746. f = f.getParentDirectory();
  237747. }
  237748. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  237749. }
  237750. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  237751. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  237752. {
  237753. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  237754. {
  237755. juce_statStruct info;
  237756. const bool statOk = juce_stat (path, info);
  237757. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  237758. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  237759. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  237760. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  237761. }
  237762. if (isReadOnly != 0)
  237763. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  237764. }
  237765. }
  237766. bool File::isDirectory() const
  237767. {
  237768. juce_statStruct info;
  237769. return fullPath.isEmpty()
  237770. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  237771. }
  237772. bool File::exists() const
  237773. {
  237774. juce_statStruct info;
  237775. return fullPath.isNotEmpty()
  237776. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  237777. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  237778. #else
  237779. && (lstat (fullPath.toUTF8(), &info) == 0);
  237780. #endif
  237781. }
  237782. bool File::existsAsFile() const
  237783. {
  237784. return exists() && ! isDirectory();
  237785. }
  237786. int64 File::getSize() const
  237787. {
  237788. juce_statStruct info;
  237789. return juce_stat (fullPath, info) ? info.st_size : 0;
  237790. }
  237791. bool File::hasWriteAccess() const
  237792. {
  237793. if (exists())
  237794. return access (fullPath.toUTF8(), W_OK) == 0;
  237795. if ((! isDirectory()) && fullPath.containsChar (separator))
  237796. return getParentDirectory().hasWriteAccess();
  237797. return false;
  237798. }
  237799. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  237800. {
  237801. juce_statStruct info;
  237802. if (! juce_stat (fullPath, info))
  237803. return false;
  237804. info.st_mode &= 0777; // Just permissions
  237805. if (shouldBeReadOnly)
  237806. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  237807. else
  237808. // Give everybody write permission?
  237809. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  237810. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  237811. }
  237812. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  237813. {
  237814. modificationTime = 0;
  237815. accessTime = 0;
  237816. creationTime = 0;
  237817. juce_statStruct info;
  237818. if (juce_stat (fullPath, info))
  237819. {
  237820. modificationTime = (int64) info.st_mtime * 1000;
  237821. accessTime = (int64) info.st_atime * 1000;
  237822. creationTime = (int64) info.st_ctime * 1000;
  237823. }
  237824. }
  237825. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  237826. {
  237827. juce_statStruct info;
  237828. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  237829. {
  237830. struct utimbuf times;
  237831. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  237832. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  237833. return utime (fullPath.toUTF8(), &times) == 0;
  237834. }
  237835. return false;
  237836. }
  237837. bool File::deleteFile() const
  237838. {
  237839. if (! exists())
  237840. return true;
  237841. if (isDirectory())
  237842. return rmdir (fullPath.toUTF8()) == 0;
  237843. return remove (fullPath.toUTF8()) == 0;
  237844. }
  237845. bool File::moveInternal (const File& dest) const
  237846. {
  237847. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  237848. return true;
  237849. if (hasWriteAccess() && copyInternal (dest))
  237850. {
  237851. if (deleteFile())
  237852. return true;
  237853. dest.deleteFile();
  237854. }
  237855. return false;
  237856. }
  237857. void File::createDirectoryInternal (const String& fileName) const
  237858. {
  237859. mkdir (fileName.toUTF8(), 0777);
  237860. }
  237861. int64 juce_fileSetPosition (void* handle, int64 pos)
  237862. {
  237863. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  237864. return pos;
  237865. return -1;
  237866. }
  237867. void FileInputStream::openHandle()
  237868. {
  237869. totalSize = file.getSize();
  237870. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  237871. if (f != -1)
  237872. fileHandle = (void*) f;
  237873. }
  237874. void FileInputStream::closeHandle()
  237875. {
  237876. if (fileHandle != 0)
  237877. {
  237878. close ((int) (pointer_sized_int) fileHandle);
  237879. fileHandle = 0;
  237880. }
  237881. }
  237882. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  237883. {
  237884. if (fileHandle != 0)
  237885. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  237886. return 0;
  237887. }
  237888. void FileOutputStream::openHandle()
  237889. {
  237890. if (file.exists())
  237891. {
  237892. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  237893. if (f != -1)
  237894. {
  237895. currentPosition = lseek (f, 0, SEEK_END);
  237896. if (currentPosition >= 0)
  237897. fileHandle = (void*) f;
  237898. else
  237899. close (f);
  237900. }
  237901. }
  237902. else
  237903. {
  237904. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  237905. if (f != -1)
  237906. fileHandle = (void*) f;
  237907. }
  237908. }
  237909. void FileOutputStream::closeHandle()
  237910. {
  237911. if (fileHandle != 0)
  237912. {
  237913. close ((int) (pointer_sized_int) fileHandle);
  237914. fileHandle = 0;
  237915. }
  237916. }
  237917. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  237918. {
  237919. if (fileHandle != 0)
  237920. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  237921. return 0;
  237922. }
  237923. void FileOutputStream::flushInternal()
  237924. {
  237925. if (fileHandle != 0)
  237926. fsync ((int) (pointer_sized_int) fileHandle);
  237927. }
  237928. const File juce_getExecutableFile()
  237929. {
  237930. #if JUCE_ANDROID
  237931. return File (android.appFile);
  237932. #else
  237933. Dl_info exeInfo;
  237934. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  237935. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  237936. #endif
  237937. }
  237938. int64 File::getBytesFreeOnVolume() const
  237939. {
  237940. struct statfs buf;
  237941. if (juce_doStatFS (*this, buf))
  237942. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  237943. return 0;
  237944. }
  237945. int64 File::getVolumeTotalSize() const
  237946. {
  237947. struct statfs buf;
  237948. if (juce_doStatFS (*this, buf))
  237949. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  237950. return 0;
  237951. }
  237952. const String File::getVolumeLabel() const
  237953. {
  237954. #if JUCE_MAC
  237955. struct VolAttrBuf
  237956. {
  237957. u_int32_t length;
  237958. attrreference_t mountPointRef;
  237959. char mountPointSpace [MAXPATHLEN];
  237960. } attrBuf;
  237961. struct attrlist attrList;
  237962. zerostruct (attrList);
  237963. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  237964. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  237965. File f (*this);
  237966. for (;;)
  237967. {
  237968. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  237969. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  237970. (int) attrBuf.mountPointRef.attr_length);
  237971. const File parent (f.getParentDirectory());
  237972. if (f == parent)
  237973. break;
  237974. f = parent;
  237975. }
  237976. #endif
  237977. return String::empty;
  237978. }
  237979. int File::getVolumeSerialNumber() const
  237980. {
  237981. int result = 0;
  237982. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  237983. char info [512];
  237984. #ifndef HDIO_GET_IDENTITY
  237985. #define HDIO_GET_IDENTITY 0x030d
  237986. #endif
  237987. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  237988. {
  237989. DBG (String (info + 20, 20));
  237990. result = String (info + 20, 20).trim().getIntValue();
  237991. }
  237992. close (fd);*/
  237993. return result;
  237994. }
  237995. void juce_runSystemCommand (const String& command)
  237996. {
  237997. int result = system (command.toUTF8());
  237998. (void) result;
  237999. }
  238000. const String juce_getOutputFromCommand (const String& command)
  238001. {
  238002. // slight bodge here, as we just pipe the output into a temp file and read it...
  238003. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  238004. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  238005. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  238006. String result (tempFile.loadFileAsString());
  238007. tempFile.deleteFile();
  238008. return result;
  238009. }
  238010. class InterProcessLock::Pimpl
  238011. {
  238012. public:
  238013. Pimpl (const String& name, const int timeOutMillisecs)
  238014. : handle (0), refCount (1)
  238015. {
  238016. #if JUCE_MAC
  238017. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  238018. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  238019. #else
  238020. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  238021. #endif
  238022. temp.create();
  238023. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  238024. if (handle != 0)
  238025. {
  238026. struct flock fl;
  238027. zerostruct (fl);
  238028. fl.l_whence = SEEK_SET;
  238029. fl.l_type = F_WRLCK;
  238030. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  238031. for (;;)
  238032. {
  238033. const int result = fcntl (handle, F_SETLK, &fl);
  238034. if (result >= 0)
  238035. return;
  238036. if (errno != EINTR)
  238037. {
  238038. if (timeOutMillisecs == 0
  238039. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  238040. break;
  238041. Thread::sleep (10);
  238042. }
  238043. }
  238044. }
  238045. closeFile();
  238046. }
  238047. ~Pimpl()
  238048. {
  238049. closeFile();
  238050. }
  238051. void closeFile()
  238052. {
  238053. if (handle != 0)
  238054. {
  238055. struct flock fl;
  238056. zerostruct (fl);
  238057. fl.l_whence = SEEK_SET;
  238058. fl.l_type = F_UNLCK;
  238059. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  238060. {}
  238061. close (handle);
  238062. handle = 0;
  238063. }
  238064. }
  238065. int handle, refCount;
  238066. };
  238067. InterProcessLock::InterProcessLock (const String& name_)
  238068. : name (name_)
  238069. {
  238070. }
  238071. InterProcessLock::~InterProcessLock()
  238072. {
  238073. }
  238074. bool InterProcessLock::enter (const int timeOutMillisecs)
  238075. {
  238076. const ScopedLock sl (lock);
  238077. if (pimpl == 0)
  238078. {
  238079. pimpl = new Pimpl (name, timeOutMillisecs);
  238080. if (pimpl->handle == 0)
  238081. pimpl = 0;
  238082. }
  238083. else
  238084. {
  238085. pimpl->refCount++;
  238086. }
  238087. return pimpl != 0;
  238088. }
  238089. void InterProcessLock::exit()
  238090. {
  238091. const ScopedLock sl (lock);
  238092. // Trying to release the lock too many times!
  238093. jassert (pimpl != 0);
  238094. if (pimpl != 0 && --(pimpl->refCount) == 0)
  238095. pimpl = 0;
  238096. }
  238097. void JUCE_API juce_threadEntryPoint (void*);
  238098. void* threadEntryProc (void* userData)
  238099. {
  238100. JUCE_AUTORELEASEPOOL
  238101. #if JUCE_ANDROID
  238102. const AndroidThreadScope androidEnv;
  238103. #endif
  238104. juce_threadEntryPoint (userData);
  238105. return 0;
  238106. }
  238107. void Thread::launchThread()
  238108. {
  238109. threadHandle_ = 0;
  238110. pthread_t handle = 0;
  238111. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  238112. {
  238113. pthread_detach (handle);
  238114. threadHandle_ = (void*) handle;
  238115. threadId_ = (ThreadID) threadHandle_;
  238116. }
  238117. }
  238118. void Thread::closeThreadHandle()
  238119. {
  238120. threadId_ = 0;
  238121. threadHandle_ = 0;
  238122. }
  238123. void Thread::killThread()
  238124. {
  238125. if (threadHandle_ != 0)
  238126. {
  238127. #if JUCE_ANDROID
  238128. jassertfalse; // pthread_cancel not available!
  238129. #else
  238130. pthread_cancel ((pthread_t) threadHandle_);
  238131. #endif
  238132. }
  238133. }
  238134. void Thread::setCurrentThreadName (const String& name)
  238135. {
  238136. #if JUCE_MAC && defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  238137. pthread_setname_np (name.toUTF8());
  238138. #elif JUCE_LINUX
  238139. prctl (PR_SET_NAME, name.toUTF8().getAddress(), 0, 0, 0);
  238140. #endif
  238141. }
  238142. bool Thread::setThreadPriority (void* handle, int priority)
  238143. {
  238144. struct sched_param param;
  238145. int policy;
  238146. priority = jlimit (0, 10, priority);
  238147. if (handle == 0)
  238148. handle = (void*) pthread_self();
  238149. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  238150. return false;
  238151. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  238152. const int minPriority = sched_get_priority_min (policy);
  238153. const int maxPriority = sched_get_priority_max (policy);
  238154. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  238155. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  238156. }
  238157. Thread::ThreadID Thread::getCurrentThreadId()
  238158. {
  238159. return (ThreadID) pthread_self();
  238160. }
  238161. void Thread::yield()
  238162. {
  238163. sched_yield();
  238164. }
  238165. /* Remove this macro if you're having problems compiling the cpu affinity
  238166. calls (the API for these has changed about quite a bit in various Linux
  238167. versions, and a lot of distros seem to ship with obsolete versions)
  238168. */
  238169. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  238170. #define SUPPORT_AFFINITIES 1
  238171. #endif
  238172. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  238173. {
  238174. #if SUPPORT_AFFINITIES
  238175. cpu_set_t affinity;
  238176. CPU_ZERO (&affinity);
  238177. for (int i = 0; i < 32; ++i)
  238178. if ((affinityMask & (1 << i)) != 0)
  238179. CPU_SET (i, &affinity);
  238180. /*
  238181. N.B. If this line causes a compile error, then you've probably not got the latest
  238182. version of glibc installed.
  238183. If you don't want to update your copy of glibc and don't care about cpu affinities,
  238184. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  238185. */
  238186. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  238187. sched_yield();
  238188. #else
  238189. /* affinities aren't supported because either the appropriate header files weren't found,
  238190. or the SUPPORT_AFFINITIES macro was turned off
  238191. */
  238192. jassertfalse;
  238193. (void) affinityMask;
  238194. #endif
  238195. }
  238196. /*** End of inlined file: juce_posix_SharedCode.h ***/
  238197. /*** Start of inlined file: juce_android_Files.cpp ***/
  238198. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238199. // compiled on its own).
  238200. #if JUCE_INCLUDED_FILE
  238201. bool File::copyInternal (const File& dest) const
  238202. {
  238203. // TODO
  238204. FileInputStream in (*this);
  238205. if (dest.deleteFile())
  238206. {
  238207. {
  238208. FileOutputStream out (dest);
  238209. if (out.failedToOpen())
  238210. return false;
  238211. if (out.writeFromInputStream (in, -1) == getSize())
  238212. return true;
  238213. }
  238214. dest.deleteFile();
  238215. }
  238216. return false;
  238217. }
  238218. void File::findFileSystemRoots (Array<File>& destArray)
  238219. {
  238220. // TODO
  238221. destArray.add (File ("/"));
  238222. }
  238223. bool File::isOnCDRomDrive() const
  238224. {
  238225. return false;
  238226. }
  238227. bool File::isOnHardDisk() const
  238228. {
  238229. return true;
  238230. }
  238231. bool File::isOnRemovableDrive() const
  238232. {
  238233. return false;
  238234. }
  238235. bool File::isHidden() const
  238236. {
  238237. // TODO
  238238. return getFileName().startsWithChar ('.');
  238239. }
  238240. namespace
  238241. {
  238242. const File juce_readlink (const String& file, const File& defaultFile)
  238243. {
  238244. const int size = 8192;
  238245. HeapBlock<char> buffer;
  238246. buffer.malloc (size + 4);
  238247. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  238248. if (numBytes > 0 && numBytes <= size)
  238249. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  238250. return defaultFile;
  238251. }
  238252. }
  238253. const File File::getLinkedTarget() const
  238254. {
  238255. // TODO
  238256. return juce_readlink (getFullPathName().toUTF8(), *this);
  238257. }
  238258. const File File::getSpecialLocation (const SpecialLocationType type)
  238259. {
  238260. switch (type)
  238261. {
  238262. case userHomeDirectory:
  238263. case userDocumentsDirectory:
  238264. case userMusicDirectory:
  238265. case userMoviesDirectory:
  238266. case userApplicationDataDirectory:
  238267. return File (android.appDataDir);
  238268. case userDesktopDirectory:
  238269. return File ("~/Desktop");
  238270. case commonApplicationDataDirectory:
  238271. return File (android.appDataDir);
  238272. case globalApplicationsDirectory:
  238273. return File ("/usr");
  238274. case tempDirectory:
  238275. return File ("~/.temp");
  238276. case invokedExecutableFile:
  238277. case currentExecutableFile:
  238278. case currentApplicationFile:
  238279. case hostApplicationPath:
  238280. return juce_getExecutableFile();
  238281. default:
  238282. jassertfalse; // unknown type?
  238283. break;
  238284. }
  238285. return File::nonexistent;
  238286. }
  238287. const String File::getVersion() const
  238288. {
  238289. return String::empty;
  238290. }
  238291. bool File::moveToTrash() const
  238292. {
  238293. if (! exists())
  238294. return true;
  238295. // TODO
  238296. return false;
  238297. }
  238298. class DirectoryIterator::NativeIterator::Pimpl
  238299. {
  238300. public:
  238301. Pimpl (const File& directory, const String& wildCard_)
  238302. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  238303. wildCard (wildCard_),
  238304. dir (opendir (directory.getFullPathName().toUTF8()))
  238305. {
  238306. wildcardUTF8 = wildCard.toUTF8();
  238307. }
  238308. ~Pimpl()
  238309. {
  238310. if (dir != 0)
  238311. closedir (dir);
  238312. }
  238313. bool next (String& filenameFound,
  238314. bool* const isDir, bool* const isHidden, int64* const fileSize,
  238315. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  238316. {
  238317. if (dir != 0)
  238318. {
  238319. for (;;)
  238320. {
  238321. struct dirent* const de = readdir (dir);
  238322. if (de == 0)
  238323. break;
  238324. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  238325. {
  238326. filenameFound = String::fromUTF8 (de->d_name);
  238327. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  238328. if (isHidden != 0)
  238329. *isHidden = filenameFound.startsWithChar ('.');
  238330. return true;
  238331. }
  238332. }
  238333. }
  238334. return false;
  238335. }
  238336. private:
  238337. String parentDir, wildCard;
  238338. const char* wildcardUTF8;
  238339. DIR* dir;
  238340. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  238341. };
  238342. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  238343. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  238344. {
  238345. }
  238346. DirectoryIterator::NativeIterator::~NativeIterator()
  238347. {
  238348. }
  238349. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  238350. bool* const isDir, bool* const isHidden, int64* const fileSize,
  238351. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  238352. {
  238353. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  238354. }
  238355. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  238356. {
  238357. }
  238358. void File::revealToUser() const
  238359. {
  238360. }
  238361. #endif
  238362. /*** End of inlined file: juce_android_Files.cpp ***/
  238363. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  238364. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  238365. // compiled on its own).
  238366. #if JUCE_INCLUDED_FILE
  238367. struct NamedPipeInternal
  238368. {
  238369. String pipeInName, pipeOutName;
  238370. int pipeIn, pipeOut;
  238371. bool volatile createdPipe, blocked, stopReadOperation;
  238372. static void signalHandler (int) {}
  238373. };
  238374. void NamedPipe::cancelPendingReads()
  238375. {
  238376. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  238377. {
  238378. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  238379. intern->stopReadOperation = true;
  238380. char buffer [1] = { 0 };
  238381. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  238382. (void) bytesWritten;
  238383. int timeout = 2000;
  238384. while (intern->blocked && --timeout >= 0)
  238385. Thread::sleep (2);
  238386. intern->stopReadOperation = false;
  238387. }
  238388. }
  238389. void NamedPipe::close()
  238390. {
  238391. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  238392. if (intern != 0)
  238393. {
  238394. internal = 0;
  238395. if (intern->pipeIn != -1)
  238396. ::close (intern->pipeIn);
  238397. if (intern->pipeOut != -1)
  238398. ::close (intern->pipeOut);
  238399. if (intern->createdPipe)
  238400. {
  238401. unlink (intern->pipeInName.toUTF8());
  238402. unlink (intern->pipeOutName.toUTF8());
  238403. }
  238404. delete intern;
  238405. }
  238406. }
  238407. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  238408. {
  238409. close();
  238410. NamedPipeInternal* const intern = new NamedPipeInternal();
  238411. internal = intern;
  238412. intern->createdPipe = createPipe;
  238413. intern->blocked = false;
  238414. intern->stopReadOperation = false;
  238415. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  238416. siginterrupt (SIGPIPE, 1);
  238417. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  238418. intern->pipeInName = pipePath + "_in";
  238419. intern->pipeOutName = pipePath + "_out";
  238420. intern->pipeIn = -1;
  238421. intern->pipeOut = -1;
  238422. if (createPipe)
  238423. {
  238424. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  238425. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  238426. {
  238427. delete intern;
  238428. internal = 0;
  238429. return false;
  238430. }
  238431. }
  238432. return true;
  238433. }
  238434. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  238435. {
  238436. int bytesRead = -1;
  238437. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  238438. if (intern != 0)
  238439. {
  238440. intern->blocked = true;
  238441. if (intern->pipeIn == -1)
  238442. {
  238443. if (intern->createdPipe)
  238444. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  238445. else
  238446. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  238447. if (intern->pipeIn == -1)
  238448. {
  238449. intern->blocked = false;
  238450. return -1;
  238451. }
  238452. }
  238453. bytesRead = 0;
  238454. char* p = static_cast<char*> (destBuffer);
  238455. while (bytesRead < maxBytesToRead)
  238456. {
  238457. const int bytesThisTime = maxBytesToRead - bytesRead;
  238458. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  238459. if (numRead <= 0 || intern->stopReadOperation)
  238460. {
  238461. bytesRead = -1;
  238462. break;
  238463. }
  238464. bytesRead += numRead;
  238465. p += bytesRead;
  238466. }
  238467. intern->blocked = false;
  238468. }
  238469. return bytesRead;
  238470. }
  238471. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  238472. {
  238473. int bytesWritten = -1;
  238474. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  238475. if (intern != 0)
  238476. {
  238477. if (intern->pipeOut == -1)
  238478. {
  238479. if (intern->createdPipe)
  238480. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  238481. else
  238482. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  238483. if (intern->pipeOut == -1)
  238484. {
  238485. return -1;
  238486. }
  238487. }
  238488. const char* p = static_cast<const char*> (sourceBuffer);
  238489. bytesWritten = 0;
  238490. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  238491. while (bytesWritten < numBytesToWrite
  238492. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  238493. {
  238494. const int bytesThisTime = numBytesToWrite - bytesWritten;
  238495. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  238496. if (numWritten <= 0)
  238497. {
  238498. bytesWritten = -1;
  238499. break;
  238500. }
  238501. bytesWritten += numWritten;
  238502. p += bytesWritten;
  238503. }
  238504. }
  238505. return bytesWritten;
  238506. }
  238507. #endif
  238508. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  238509. /*** Start of inlined file: juce_android_Threads.cpp ***/
  238510. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238511. // compiled on its own).
  238512. #if JUCE_INCLUDED_FILE
  238513. /*
  238514. Note that a lot of methods that you'd expect to find in this file actually
  238515. live in juce_posix_SharedCode.h!
  238516. */
  238517. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  238518. void Process::setPriority (ProcessPriority prior)
  238519. {
  238520. // TODO
  238521. struct sched_param param;
  238522. int policy, maxp, minp;
  238523. const int p = (int) prior;
  238524. if (p <= 1)
  238525. policy = SCHED_OTHER;
  238526. else
  238527. policy = SCHED_RR;
  238528. minp = sched_get_priority_min (policy);
  238529. maxp = sched_get_priority_max (policy);
  238530. if (p < 2)
  238531. param.sched_priority = 0;
  238532. else if (p == 2 )
  238533. // Set to middle of lower realtime priority range
  238534. param.sched_priority = minp + (maxp - minp) / 4;
  238535. else
  238536. // Set to middle of higher realtime priority range
  238537. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  238538. pthread_setschedparam (pthread_self(), policy, &param);
  238539. }
  238540. void Process::terminate()
  238541. {
  238542. // TODO
  238543. exit (0);
  238544. }
  238545. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  238546. {
  238547. return false;
  238548. }
  238549. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  238550. {
  238551. return juce_isRunningUnderDebugger();
  238552. }
  238553. void Process::raisePrivilege() {}
  238554. void Process::lowerPrivilege() {}
  238555. #endif
  238556. /*** End of inlined file: juce_android_Threads.cpp ***/
  238557. /*** Start of inlined file: juce_android_Network.cpp ***/
  238558. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238559. // compiled on its own).
  238560. #if JUCE_INCLUDED_FILE
  238561. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  238562. {
  238563. // TODO
  238564. }
  238565. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  238566. const String& emailSubject,
  238567. const String& bodyText,
  238568. const StringArray& filesToAttach)
  238569. {
  238570. // TODO
  238571. return false;
  238572. }
  238573. class WebInputStream : public InputStream
  238574. {
  238575. public:
  238576. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  238577. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  238578. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  238579. {
  238580. // TODO
  238581. openedOk = false;
  238582. }
  238583. ~WebInputStream()
  238584. {
  238585. }
  238586. bool isExhausted()
  238587. {
  238588. return true; // TODO
  238589. }
  238590. int64 getPosition()
  238591. {
  238592. return 0; // TODO
  238593. }
  238594. int64 getTotalLength()
  238595. {
  238596. return -1; // TODO
  238597. }
  238598. int read (void* buffer, int bytesToRead)
  238599. {
  238600. // TODO
  238601. return 0;
  238602. }
  238603. bool setPosition (int64 wantedPos)
  238604. {
  238605. // TODO
  238606. return false;
  238607. }
  238608. bool openedOk;
  238609. private:
  238610. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  238611. };
  238612. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  238613. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  238614. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  238615. {
  238616. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  238617. progressCallback, progressCallbackContext,
  238618. headers, timeOutMs, responseHeaders));
  238619. return wi->openedOk ? wi.release() : 0;
  238620. }
  238621. #endif
  238622. /*** End of inlined file: juce_android_Network.cpp ***/
  238623. /*** Start of inlined file: juce_android_Messaging.cpp ***/
  238624. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238625. // compiled on its own).
  238626. #if JUCE_INCLUDED_FILE
  238627. void MessageManager::doPlatformSpecificInitialisation() {}
  238628. void MessageManager::doPlatformSpecificShutdown() {}
  238629. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  238630. {
  238631. Logger::outputDebugString ("*** Modal loops are not possible in Android!! Exiting...");
  238632. exit (1);
  238633. return true;
  238634. }
  238635. bool juce_postMessageToSystemQueue (Message* message)
  238636. {
  238637. message->incReferenceCount();
  238638. getEnv()->CallVoidMethod (android.activity, android.postMessage, (jlong) (pointer_sized_uint) message);
  238639. return true;
  238640. }
  238641. JUCE_JNI_CALLBACK (JuceAppActivity, deliverMessage, void, (jobject activity, jlong value))
  238642. {
  238643. Message* const message = (Message*) (pointer_sized_uint) value;
  238644. MessageManager::getInstance()->deliverMessage (message);
  238645. message->decReferenceCount();
  238646. }
  238647. class AsyncFunctionCaller : public AsyncUpdater
  238648. {
  238649. public:
  238650. static void* call (MessageCallbackFunction* func_, void* parameter_)
  238651. {
  238652. if (MessageManager::getInstance()->isThisTheMessageThread())
  238653. return func_ (parameter_);
  238654. AsyncFunctionCaller caller (func_, parameter_);
  238655. caller.triggerAsyncUpdate();
  238656. caller.finished.wait();
  238657. return caller.result;
  238658. }
  238659. void handleAsyncUpdate()
  238660. {
  238661. result = (*func) (parameter);
  238662. finished.signal();
  238663. }
  238664. private:
  238665. WaitableEvent finished;
  238666. MessageCallbackFunction* func;
  238667. void* parameter;
  238668. void* volatile result;
  238669. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  238670. : result (0), func (func_), parameter (parameter_)
  238671. {}
  238672. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  238673. };
  238674. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  238675. {
  238676. return AsyncFunctionCaller::call (func, parameter);
  238677. }
  238678. void MessageManager::broadcastMessage (const String&)
  238679. {
  238680. }
  238681. void MessageManager::runDispatchLoop()
  238682. {
  238683. }
  238684. class QuitCallback : public CallbackMessage
  238685. {
  238686. public:
  238687. QuitCallback() {}
  238688. void messageCallback()
  238689. {
  238690. android.activity.callVoidMethod (android.finish);
  238691. }
  238692. };
  238693. void MessageManager::stopDispatchLoop()
  238694. {
  238695. (new QuitCallback())->post();
  238696. quitMessagePosted = true;
  238697. }
  238698. #endif
  238699. /*** End of inlined file: juce_android_Messaging.cpp ***/
  238700. /*** Start of inlined file: juce_android_Fonts.cpp ***/
  238701. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238702. // compiled on its own).
  238703. #if JUCE_INCLUDED_FILE
  238704. const StringArray Font::findAllTypefaceNames()
  238705. {
  238706. StringArray results;
  238707. Array<File> fonts;
  238708. File ("/system/fonts").findChildFiles (fonts, File::findFiles, false, "*.ttf");
  238709. for (int i = 0; i < fonts.size(); ++i)
  238710. results.add (fonts.getReference(i).getFileNameWithoutExtension());
  238711. return results;
  238712. }
  238713. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  238714. {
  238715. defaultSans = "sans";
  238716. defaultSerif = "serif";
  238717. defaultFixed = "monospace";
  238718. defaultFallback = "sans";
  238719. }
  238720. class AndroidTypeface : public Typeface
  238721. {
  238722. public:
  238723. AndroidTypeface (const Font& font)
  238724. : Typeface (font.getTypefaceName()),
  238725. ascent (0),
  238726. descent (0)
  238727. {
  238728. jint flags = 0;
  238729. if (font.isBold()) flags = 1;
  238730. if (font.isItalic()) flags += 2;
  238731. JNIEnv* env = getEnv();
  238732. File fontFile (File ("/system/fonts").getChildFile (name).withFileExtension (".ttf"));
  238733. if (fontFile.exists())
  238734. typeface = GlobalRef (env->CallStaticObjectMethod (android.typefaceClass, android.createFromFile,
  238735. javaString (fontFile.getFullPathName()).get()));
  238736. else
  238737. typeface = GlobalRef (env->CallStaticObjectMethod (android.typefaceClass, android.create,
  238738. javaString (getName()).get(), flags));
  238739. rect = GlobalRef (env->NewObject (android.rectClass, android.rectConstructor, 0, 0, 0, 0));
  238740. paint = GlobalRef (android.createPaint (Graphics::highResamplingQuality));
  238741. const LocalRef<jobject> ignored (paint.callObjectMethod (android.setTypeface, typeface.get()));
  238742. const float standardSize = 256.0f;
  238743. paint.callVoidMethod (android.setTextSize, standardSize);
  238744. ascent = std::abs (paint.callFloatMethod (android.ascent)) / standardSize;
  238745. descent = paint.callFloatMethod (android.descent) / standardSize;
  238746. const float height = ascent + descent;
  238747. unitsToHeightScaleFactor = 1.0f / 256.0f;//(height * standardSize);
  238748. }
  238749. float getAscent() const { return ascent; }
  238750. float getDescent() const { return descent; }
  238751. float getStringWidth (const String& text)
  238752. {
  238753. JNIEnv* env = getEnv();
  238754. const int numChars = text.length();
  238755. jfloatArray widths = env->NewFloatArray (numChars);
  238756. const int numDone = paint.callIntMethod (android.getTextWidths, javaString (text).get(), widths);
  238757. HeapBlock<jfloat> localWidths (numDone);
  238758. env->GetFloatArrayRegion (widths, 0, numDone, localWidths);
  238759. env->DeleteLocalRef (widths);
  238760. float x = 0;
  238761. for (int i = 0; i < numDone; ++i)
  238762. x += localWidths[i];
  238763. return x * unitsToHeightScaleFactor;
  238764. }
  238765. void getGlyphPositions (const String& text, Array<int>& glyphs, Array<float>& xOffsets)
  238766. {
  238767. JNIEnv* env = getEnv();
  238768. const int numChars = text.length();
  238769. jfloatArray widths = env->NewFloatArray (numChars);
  238770. const int numDone = paint.callIntMethod (android.getTextWidths, javaString (text).get(), widths);
  238771. HeapBlock<jfloat> localWidths (numDone);
  238772. env->GetFloatArrayRegion (widths, 0, numDone, localWidths);
  238773. env->DeleteLocalRef (widths);
  238774. String::CharPointerType s (text.getCharPointer());
  238775. xOffsets.add (0);
  238776. float x = 0;
  238777. for (int i = 0; i < numDone; ++i)
  238778. {
  238779. glyphs.add ((int) s.getAndAdvance());
  238780. x += localWidths[i];
  238781. xOffsets.add (x * unitsToHeightScaleFactor);
  238782. }
  238783. }
  238784. bool getOutlineForGlyph (int /*glyphNumber*/, Path& /*destPath*/)
  238785. {
  238786. return false;
  238787. }
  238788. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& t)
  238789. {
  238790. JNIEnv* env = getEnv();
  238791. jobject matrix = android.createMatrix (env, AffineTransform::scale (unitsToHeightScaleFactor, unitsToHeightScaleFactor).followedBy (t));
  238792. jintArray maskData = (jintArray) android.activity.callObjectMethod (android.renderGlyph, (jchar) glyphNumber, paint.get(), matrix, rect.get());
  238793. env->DeleteLocalRef (matrix);
  238794. const int left = env->GetIntField (rect.get(), android.rectLeft);
  238795. const int top = env->GetIntField (rect.get(), android.rectTop);
  238796. const int right = env->GetIntField (rect.get(), android.rectRight);
  238797. const int bottom = env->GetIntField (rect.get(), android.rectBottom);
  238798. const Rectangle<int> bounds (left, top, right - left, bottom - top);
  238799. if (bounds.isEmpty())
  238800. return 0;
  238801. jint* const maskDataElements = env->GetIntArrayElements (maskData, 0);
  238802. EdgeTable* et = new EdgeTable (bounds);
  238803. const jint* mask = maskDataElements;
  238804. for (int y = top; y < bottom; ++y)
  238805. {
  238806. #if JUCE_LITTLE_ENDIAN
  238807. const uint8* const lineBytes = ((const uint8*) mask) + 3;
  238808. #else
  238809. const uint8* const lineBytes = (const uint8*) mask;
  238810. #endif
  238811. et->clipLineToMask (left, y, lineBytes, 4, bounds.getWidth());
  238812. mask += bounds.getWidth();
  238813. }
  238814. env->ReleaseIntArrayElements (maskData, maskDataElements, 0);
  238815. env->DeleteLocalRef (maskData);
  238816. return et;
  238817. }
  238818. GlobalRef typeface, paint, rect;
  238819. float ascent, descent, unitsToHeightScaleFactor;
  238820. private:
  238821. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidTypeface);
  238822. };
  238823. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  238824. {
  238825. return new AndroidTypeface (font);
  238826. }
  238827. #endif
  238828. /*** End of inlined file: juce_android_Fonts.cpp ***/
  238829. /*** Start of inlined file: juce_android_GraphicsContext.cpp ***/
  238830. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238831. // compiled on its own).
  238832. #if JUCE_INCLUDED_FILE
  238833. #if USE_ANDROID_CANVAS
  238834. class AndroidImage : public Image::SharedImage
  238835. {
  238836. public:
  238837. AndroidImage (const int width_, const int height_, const bool clearImage)
  238838. : Image::SharedImage (Image::ARGB, width_, height_),
  238839. bitmap (createBitmap (width_, height_, false))
  238840. {
  238841. }
  238842. AndroidImage (const int width_, const int height_, const GlobalRef& bitmap_)
  238843. : Image::SharedImage (Image::ARGB, width_, height_),
  238844. bitmap (bitmap_)
  238845. {
  238846. }
  238847. ~AndroidImage()
  238848. {
  238849. if (bitmap != 0)
  238850. bitmap.callVoidMethod (android.recycle);
  238851. }
  238852. Image::ImageType getType() const { return Image::NativeImage; }
  238853. LowLevelGraphicsContext* createLowLevelContext();
  238854. void initialiseBitmapData (Image::BitmapData& bm, int x, int y, Image::BitmapData::ReadWriteMode mode)
  238855. {
  238856. bm.lineStride = width * sizeof (jint);
  238857. bm.pixelStride = sizeof (jint);
  238858. bm.pixelFormat = Image::ARGB;
  238859. bm.dataReleaser = new CopyHandler (*this, bm, x, y, mode);
  238860. }
  238861. SharedImage* clone()
  238862. {
  238863. JNIEnv* env = getEnv();
  238864. jobject mode = env->GetStaticObjectField (android.bitmapConfigClass, android.ARGB_8888);
  238865. GlobalRef newCopy (bitmap.callObjectMethod (android.bitmapCopy, mode, true));
  238866. env->DeleteLocalRef (mode);
  238867. return new AndroidImage (width, height, newCopy);
  238868. }
  238869. static jobject createBitmap (int width, int height, bool asSingleChannel)
  238870. {
  238871. JNIEnv* env = getEnv();
  238872. jobject mode = env->GetStaticObjectField (android.bitmapConfigClass, asSingleChannel ? android.ALPHA_8 : android.ARGB_8888);
  238873. jobject result = env->CallStaticObjectMethod (android.bitmapClass, android.createBitmap, width, height, mode);
  238874. env->DeleteLocalRef (mode);
  238875. return result;
  238876. }
  238877. GlobalRef bitmap;
  238878. private:
  238879. class CopyHandler : public Image::BitmapData::BitmapDataReleaser
  238880. {
  238881. public:
  238882. CopyHandler (AndroidImage& owner_, Image::BitmapData& bitmapData_,
  238883. const int x_, const int y_, const Image::BitmapData::ReadWriteMode mode_)
  238884. : owner (owner_), bitmapData (bitmapData_), mode (mode_), x (x_), y (y_)
  238885. {
  238886. JNIEnv* env = getEnv();
  238887. intArray = env->NewIntArray (bitmapData.width * bitmapData.height);
  238888. if (mode != Image::BitmapData::writeOnly)
  238889. owner_.bitmap.callVoidMethod (android.getPixels, intArray, 0, bitmapData.width, x_, y_,
  238890. bitmapData.width, bitmapData.height);
  238891. bitmapData.data = (uint8*) env->GetIntArrayElements (intArray, 0);
  238892. if (mode != Image::BitmapData::writeOnly)
  238893. {
  238894. for (int yy = 0; yy < bitmapData.height; ++yy)
  238895. {
  238896. PixelARGB* p = (PixelARGB*) bitmapData.getLinePointer (yy);
  238897. for (int xx = 0; xx < bitmapData.width; ++xx)
  238898. p[xx].premultiply();
  238899. }
  238900. }
  238901. }
  238902. ~CopyHandler()
  238903. {
  238904. JNIEnv* env = getEnv();
  238905. if (mode != Image::BitmapData::readOnly)
  238906. {
  238907. for (int yy = 0; yy < bitmapData.height; ++yy)
  238908. {
  238909. PixelARGB* p = (PixelARGB*) bitmapData.getLinePointer (yy);
  238910. for (int xx = 0; xx < bitmapData.width; ++xx)
  238911. p[xx].unpremultiply();
  238912. }
  238913. }
  238914. env->ReleaseIntArrayElements (intArray, (jint*) bitmapData.data, 0);
  238915. if (mode != Image::BitmapData::readOnly)
  238916. owner.bitmap.callVoidMethod (android.setPixels, intArray, 0, bitmapData.width, x, y,
  238917. bitmapData.width, bitmapData.height);
  238918. env->DeleteLocalRef (intArray);
  238919. }
  238920. private:
  238921. AndroidImage& owner;
  238922. Image::BitmapData& bitmapData;
  238923. jintArray intArray;
  238924. const Image::BitmapData::ReadWriteMode mode;
  238925. const int x, y;
  238926. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CopyHandler);
  238927. };
  238928. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidImage);
  238929. };
  238930. #endif
  238931. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  238932. {
  238933. #if USE_ANDROID_CANVAS
  238934. if (format != Image::SingleChannel)
  238935. return new AndroidImage (width, height, clearImage);
  238936. #endif
  238937. return createSoftwareImage (format, width, height, clearImage);
  238938. }
  238939. #if USE_ANDROID_CANVAS
  238940. class AndroidLowLevelGraphicsContext : public LowLevelGraphicsContext
  238941. {
  238942. public:
  238943. AndroidLowLevelGraphicsContext (jobject canvas_)
  238944. : originalCanvas (canvas_),
  238945. currentState (new SavedState (canvas_))
  238946. {
  238947. setFill (Colours::black);
  238948. }
  238949. ~AndroidLowLevelGraphicsContext()
  238950. {
  238951. while (stateStack.size() > 0)
  238952. restoreState();
  238953. currentState->flattenImageClippingLayer (originalCanvas);
  238954. }
  238955. bool isVectorDevice() const { return false; }
  238956. void setOrigin (int x, int y)
  238957. {
  238958. getCanvas().callVoidMethod (android.translate, (float) x, (float) y);
  238959. }
  238960. void addTransform (const AffineTransform& transform)
  238961. {
  238962. getCanvas().callVoidMethod (android.concat, createMatrixRef (getEnv(), transform).get());
  238963. }
  238964. float getScaleFactor()
  238965. {
  238966. return 1.0f;
  238967. }
  238968. bool clipToRectangle (const Rectangle<int>& r)
  238969. {
  238970. return getCanvas().callBooleanMethod (android.clipRect, (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  238971. }
  238972. bool clipToRectangleList (const RectangleList& clipRegion)
  238973. {
  238974. RectangleList excluded (getClipBounds());
  238975. excluded.subtract (clipRegion);
  238976. const int numRects = excluded.getNumRectangles();
  238977. for (int i = 0; i < numRects; ++i)
  238978. excludeClipRectangle (excluded.getRectangle(i));
  238979. }
  238980. void excludeClipRectangle (const Rectangle<int>& r)
  238981. {
  238982. android.activity.callVoidMethod (android.excludeClipRegion, getCanvas().get(),
  238983. (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  238984. }
  238985. void clipToPath (const Path& path, const AffineTransform& transform)
  238986. {
  238987. (void) getCanvas().callBooleanMethod (android.clipPath, createPath (getEnv(), path, transform).get());
  238988. }
  238989. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  238990. {
  238991. // XXX couldn't get image clipping to work...
  238992. JNIEnv* env = getEnv();
  238993. {
  238994. Path p;
  238995. p.addRectangle (sourceImage.getBounds().toFloat());
  238996. clipToPath (p, transform);
  238997. }
  238998. Rectangle<int> bounds (getClipBounds());
  238999. jobject temporaryLayerBitmap = AndroidImage::createBitmap (bounds.getWidth(), bounds.getHeight(), false);
  239000. jobject temporaryCanvas = env->NewObject (android.canvasClass, android.canvasBitmapConstructor, temporaryLayerBitmap);
  239001. setFill (Colours::red);
  239002. env->CallVoidMethod (temporaryCanvas, android.drawRect,
  239003. (jfloat) 20, (jfloat) 20, (jfloat) 300, (jfloat) 200,
  239004. getCurrentPaint());
  239005. env->CallVoidMethod (temporaryCanvas, android.translate,
  239006. (jfloat) -bounds.getX(), (jfloat) -bounds.getY());
  239007. Image maskImage (Image::SingleChannel, bounds.getWidth(), bounds.getHeight(), true);
  239008. {
  239009. Graphics g (maskImage);
  239010. g.setOrigin (-bounds.getWidth(), -bounds.getHeight());
  239011. g.drawImageTransformed (sourceImage, transform);
  239012. }
  239013. SavedState* const top = stateStack.getLast();
  239014. currentState->clipToImage (top != 0 ? top->canvas.get() : originalCanvas,
  239015. temporaryCanvas, temporaryLayerBitmap, maskImage,
  239016. bounds.getX(), bounds.getY());
  239017. }
  239018. bool clipRegionIntersects (const Rectangle<int>& r)
  239019. {
  239020. return getClipBounds().intersects (r);
  239021. }
  239022. const Rectangle<int> getClipBounds() const
  239023. {
  239024. JNIEnv* env = getEnv();
  239025. jobject rect = getCanvas().callObjectMethod (android.getClipBounds2);
  239026. const int left = env->GetIntField (rect, android.rectLeft);
  239027. const int top = env->GetIntField (rect, android.rectTop);
  239028. const int right = env->GetIntField (rect, android.rectRight);
  239029. const int bottom = env->GetIntField (rect, android.rectBottom);
  239030. env->DeleteLocalRef (rect);
  239031. return Rectangle<int> (left, top, right - left, bottom - top);
  239032. }
  239033. bool isClipEmpty() const
  239034. {
  239035. LocalRef<jobject> tempRect (getEnv()->NewObject (android.rectClass, android.rectConstructor, 0, 0, 0, 0));
  239036. return ! getCanvas().callBooleanMethod (android.getClipBounds, tempRect.get());
  239037. }
  239038. void setFill (const FillType& fillType)
  239039. {
  239040. currentState->setFillType (fillType);
  239041. }
  239042. void setOpacity (float newOpacity)
  239043. {
  239044. currentState->setAlpha (newOpacity);
  239045. }
  239046. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  239047. {
  239048. currentState->setInterpolationQuality (quality);
  239049. }
  239050. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  239051. {
  239052. getCanvas().callVoidMethod (android.drawRect,
  239053. (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom(),
  239054. getCurrentPaint());
  239055. }
  239056. void fillPath (const Path& path, const AffineTransform& transform)
  239057. {
  239058. getCanvas().callVoidMethod (android.drawPath, createPath (getEnv(), path, transform).get(),
  239059. getCurrentPaint());
  239060. }
  239061. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles)
  239062. {
  239063. AndroidImage* androidImage = dynamic_cast <AndroidImage*> (sourceImage.getSharedImage());
  239064. if (androidImage != 0)
  239065. {
  239066. JNIEnv* env = getEnv();
  239067. getCanvas().callVoidMethod (android.drawBitmap, androidImage->bitmap.get(),
  239068. createMatrixRef (env, transform).get(), getImagePaint());
  239069. }
  239070. else
  239071. {
  239072. if (transform.isOnlyTranslation())
  239073. {
  239074. JNIEnv* env = getEnv();
  239075. Image::BitmapData bm (sourceImage, Image::BitmapData::readOnly);
  239076. jintArray imageData = env->NewIntArray (bm.width * bm.height);
  239077. jint* dest = env->GetIntArrayElements (imageData, 0);
  239078. if (dest != 0)
  239079. {
  239080. const uint8* srcLine = bm.getLinePointer (0);
  239081. jint* dstLine = dest;
  239082. for (int y = 0; y < bm.height; ++y)
  239083. {
  239084. switch (bm.pixelFormat)
  239085. {
  239086. case Image::ARGB: copyPixels (dstLine, (PixelARGB*) srcLine, bm.width, bm.pixelStride); break;
  239087. case Image::RGB: copyPixels (dstLine, (PixelRGB*) srcLine, bm.width, bm.pixelStride); break;
  239088. case Image::SingleChannel: copyPixels (dstLine, (PixelAlpha*) srcLine, bm.width, bm.pixelStride); break;
  239089. default: jassertfalse; break;
  239090. }
  239091. srcLine += bm.lineStride;
  239092. dstLine += bm.width;
  239093. }
  239094. env->ReleaseIntArrayElements (imageData, dest, 0);
  239095. getCanvas().callVoidMethod (android.drawMemoryBitmap, imageData, 0, bm.width,
  239096. transform.getTranslationX(), transform.getTranslationY(),
  239097. bm.width, bm.height, true, getImagePaint());
  239098. env->DeleteLocalRef (imageData);
  239099. }
  239100. }
  239101. else
  239102. {
  239103. saveState();
  239104. addTransform (transform);
  239105. drawImage (sourceImage, AffineTransform::identity, fillEntireClipAsTiles);
  239106. restoreState();
  239107. }
  239108. }
  239109. }
  239110. void drawLine (const Line <float>& line)
  239111. {
  239112. getCanvas().callVoidMethod (android.drawLine, line.getStartX(), line.getStartY(),
  239113. line.getEndX(), line.getEndY(), getCurrentPaint());
  239114. }
  239115. void drawVerticalLine (int x, float top, float bottom)
  239116. {
  239117. getCanvas().callVoidMethod (android.drawRect, (float) x, top, x + 1.0f, bottom, getCurrentPaint());
  239118. }
  239119. void drawHorizontalLine (int y, float left, float right)
  239120. {
  239121. getCanvas().callVoidMethod (android.drawRect, left, (float) y, right, y + 1.0f, getCurrentPaint());
  239122. }
  239123. void setFont (const Font& newFont)
  239124. {
  239125. if (currentState->font != newFont)
  239126. {
  239127. currentState->font = newFont;
  239128. currentState->typefaceNeedsUpdate = true;
  239129. }
  239130. }
  239131. const Font getFont()
  239132. {
  239133. return currentState->font;
  239134. }
  239135. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  239136. {
  239137. if (transform.isOnlyTranslation())
  239138. {
  239139. getCanvas().callVoidMethod (android.drawText, javaStringFromChar ((juce_wchar) glyphNumber).get(),
  239140. transform.getTranslationX(), transform.getTranslationY(),
  239141. currentState->getPaintForTypeface());
  239142. }
  239143. else
  239144. {
  239145. saveState();
  239146. addTransform (transform);
  239147. drawGlyph (glyphNumber, AffineTransform::identity);
  239148. restoreState();
  239149. }
  239150. }
  239151. void saveState()
  239152. {
  239153. (void) getCanvas().callIntMethod (android.save);
  239154. stateStack.add (new SavedState (*currentState));
  239155. }
  239156. void restoreState()
  239157. {
  239158. SavedState* const top = stateStack.getLast();
  239159. if (top != 0)
  239160. {
  239161. currentState->flattenImageClippingLayer (top->canvas);
  239162. currentState = top;
  239163. stateStack.removeLast (1, false);
  239164. }
  239165. else
  239166. {
  239167. jassertfalse; // trying to pop with an empty stack!
  239168. }
  239169. getCanvas().callVoidMethod (android.restore);
  239170. }
  239171. void beginTransparencyLayer (float opacity)
  239172. {
  239173. Rectangle<int> clip (getClipBounds());
  239174. (void) getCanvas().callIntMethod (android.saveLayerAlpha,
  239175. (float) clip.getX(),
  239176. (float) clip.getY(),
  239177. (float) clip.getRight(),
  239178. (float) clip.getBottom(),
  239179. jlimit (0, 255, roundToInt (opacity * 255.0f)),
  239180. 31 /*ALL_SAVE_FLAG*/);
  239181. stateStack.add (new SavedState (*currentState));
  239182. }
  239183. void endTransparencyLayer()
  239184. {
  239185. restoreState();
  239186. }
  239187. class SavedState
  239188. {
  239189. public:
  239190. SavedState (jobject canvas_)
  239191. : canvas (canvas_), font (1.0f), quality (Graphics::highResamplingQuality),
  239192. fillNeedsUpdate (true), typefaceNeedsUpdate (true)
  239193. {
  239194. }
  239195. SavedState (const SavedState& other)
  239196. : canvas (other.canvas), fillType (other.fillType), font (other.font),
  239197. quality (other.quality), fillNeedsUpdate (true), typefaceNeedsUpdate (true)
  239198. {
  239199. }
  239200. void setFillType (const FillType& newType)
  239201. {
  239202. fillNeedsUpdate = true;
  239203. fillType = newType;
  239204. }
  239205. void setAlpha (float alpha)
  239206. {
  239207. fillNeedsUpdate = true;
  239208. fillType.colour = fillType.colour.withAlpha (alpha);
  239209. }
  239210. void setInterpolationQuality (Graphics::ResamplingQuality quality_)
  239211. {
  239212. if (quality != quality_)
  239213. {
  239214. quality = quality_;
  239215. fillNeedsUpdate = true;
  239216. paint.clear();
  239217. }
  239218. }
  239219. jobject getPaint()
  239220. {
  239221. if (fillNeedsUpdate)
  239222. {
  239223. JNIEnv* env = getEnv();
  239224. if (paint.get() == 0)
  239225. paint = GlobalRef (android.createPaint (quality));
  239226. if (fillType.isColour())
  239227. {
  239228. env->DeleteLocalRef (paint.callObjectMethod (android.setShader, (jobject) 0));
  239229. paint.callVoidMethod (android.setColor, colourToInt (fillType.colour));
  239230. }
  239231. else if (fillType.isGradient())
  239232. {
  239233. const ColourGradient& g = *fillType.gradient;
  239234. const Point<float> p1 (g.point1);
  239235. const Point<float> p2 (g.point2);
  239236. const int numColours = g.getNumColours();
  239237. jintArray coloursArray = env->NewIntArray (numColours);
  239238. jfloatArray positionsArray = env->NewFloatArray (numColours);
  239239. {
  239240. HeapBlock<int> colours (numColours);
  239241. HeapBlock<float> positions (numColours);
  239242. for (int i = 0; i < numColours; ++i)
  239243. {
  239244. colours[i] = colourToInt (g.getColour (i));
  239245. positions[i] = (float) g.getColourPosition(i);
  239246. }
  239247. env->SetIntArrayRegion (coloursArray, 0, numColours, colours.getData());
  239248. env->SetFloatArrayRegion (positionsArray, 0, numColours, positions.getData());
  239249. }
  239250. jobject tileMode = env->GetStaticObjectField (android.shaderTileModeClass, android.clampMode);
  239251. jobject shader;
  239252. if (fillType.gradient->isRadial)
  239253. {
  239254. shader = env->NewObject (android.radialGradientClass,
  239255. android.radialGradientConstructor,
  239256. p1.getX(), p1.getY(),
  239257. p1.getDistanceFrom (p2),
  239258. coloursArray, positionsArray,
  239259. tileMode);
  239260. }
  239261. else
  239262. {
  239263. shader = env->NewObject (android.linearGradientClass,
  239264. android.linearGradientConstructor,
  239265. p1.getX(), p1.getY(), p2.getX(), p2.getY(),
  239266. coloursArray, positionsArray,
  239267. tileMode);
  239268. }
  239269. env->DeleteLocalRef (tileMode);
  239270. env->DeleteLocalRef (coloursArray);
  239271. env->DeleteLocalRef (positionsArray);
  239272. env->CallVoidMethod (shader, android.setLocalMatrix, createMatrixRef (env, fillType.transform).get());
  239273. env->DeleteLocalRef (paint.callObjectMethod (android.setShader, shader));
  239274. env->DeleteLocalRef (shader);
  239275. }
  239276. else
  239277. {
  239278. // TODO xxx
  239279. }
  239280. }
  239281. return paint.get();
  239282. }
  239283. jobject getPaintForTypeface()
  239284. {
  239285. jobject p = getPaint();
  239286. if (typefaceNeedsUpdate)
  239287. {
  239288. typefaceNeedsUpdate = false;
  239289. const Typeface::Ptr t (font.getTypeface());
  239290. AndroidTypeface* atf = dynamic_cast <AndroidTypeface*> (t.getObject());
  239291. if (atf != 0)
  239292. {
  239293. paint.callObjectMethod (android.setTypeface, atf->typeface.get());
  239294. paint.callVoidMethod (android.setTextSize, font.getHeight());
  239295. const float hScale = font.getHorizontalScale();
  239296. if (hScale < 0.99f || hScale > 1.01f)
  239297. paint.callVoidMethod (android.setTextScaleX, hScale);
  239298. }
  239299. fillNeedsUpdate = true;
  239300. paint.callVoidMethod (android.setAlpha, (jint) fillType.colour.getAlpha());
  239301. }
  239302. return p;
  239303. }
  239304. jobject getImagePaint()
  239305. {
  239306. jobject p = getPaint();
  239307. paint.callVoidMethod (android.setAlpha, (jint) fillType.colour.getAlpha());
  239308. fillNeedsUpdate = true;
  239309. return p;
  239310. }
  239311. void flattenImageClippingLayer (jobject previousCanvas)
  239312. {
  239313. // XXX couldn't get image clipping to work...
  239314. if (temporaryLayerBitmap != 0)
  239315. {
  239316. JNIEnv* env = getEnv();
  239317. jobject tileMode = env->GetStaticObjectField (android.shaderTileModeClass, android.clampMode);
  239318. jobject shader = env->NewObject (android.bitmapShaderClass, android.bitmapShaderConstructor,
  239319. temporaryLayerBitmap.get(), tileMode, tileMode);
  239320. env->DeleteLocalRef (tileMode);
  239321. jobject compositingPaint = android.createPaint (quality);
  239322. env->CallObjectMethod (compositingPaint, android.setShader, shader);
  239323. env->DeleteLocalRef (shader);
  239324. LocalRef<jobject> maskBitmap (createAlphaBitmap (env, maskImage));
  239325. maskImage = Image::null;
  239326. env->CallVoidMethod (previousCanvas, android.drawBitmapAt,
  239327. maskBitmap.get(), (jfloat) maskLayerX, (jfloat) maskLayerY, compositingPaint);
  239328. env->DeleteLocalRef (compositingPaint);
  239329. canvas = GlobalRef (previousCanvas);
  239330. env->CallVoidMethod (temporaryLayerBitmap.get(), android.recycle);
  239331. env->CallVoidMethod (maskBitmap.get(), android.recycle);
  239332. temporaryLayerBitmap.clear();
  239333. }
  239334. }
  239335. void clipToImage (jobject previousCanvas,
  239336. jobject temporaryCanvas, jobject temporaryLayerBitmap_,
  239337. const Image& maskImage_,
  239338. int maskLayerX_, int maskLayerY_)
  239339. {
  239340. // XXX couldn't get image clipping to work...
  239341. flattenImageClippingLayer (previousCanvas);
  239342. maskLayerX = maskLayerX_;
  239343. maskLayerY = maskLayerY_;
  239344. canvas = GlobalRef (temporaryCanvas);
  239345. temporaryLayerBitmap = GlobalRef (temporaryLayerBitmap_);
  239346. maskImage = maskImage_;
  239347. }
  239348. static jobject createAlphaBitmap (JNIEnv* env, const Image& image)
  239349. {
  239350. Image::BitmapData bm (image, Image::BitmapData::readOnly);
  239351. jobject bitmap = AndroidImage::createBitmap (bm.width, bm.height, true);
  239352. jintArray intArray = env->NewIntArray (bm.width * bm.height);
  239353. jint* const dest = env->GetIntArrayElements (intArray, 0);
  239354. for (int yy = 0; yy < bm.height; ++yy)
  239355. {
  239356. PixelAlpha* src = (PixelAlpha*) bm.getLinePointer (yy);
  239357. jint* destLine = dest + yy * bm.width;
  239358. for (int xx = 0; xx < bm.width; ++xx)
  239359. {
  239360. destLine[xx] = src->getAlpha();
  239361. src = addBytesToPointer (src, bm.pixelStride);
  239362. }
  239363. }
  239364. env->ReleaseIntArrayElements (intArray, (jint*) dest, 0);
  239365. env->CallVoidMethod (bitmap, android.setPixels, intArray, 0, bm.width, 0, 0, bm.width, bm.height);
  239366. env->DeleteLocalRef (intArray);
  239367. return bitmap;
  239368. }
  239369. GlobalRef canvas, temporaryLayerBitmap;
  239370. FillType fillType;
  239371. Font font;
  239372. GlobalRef paint;
  239373. bool fillNeedsUpdate, typefaceNeedsUpdate;
  239374. Graphics::ResamplingQuality quality;
  239375. Image maskImage;
  239376. int maskLayerX, maskLayerY;
  239377. };
  239378. private:
  239379. GlobalRef originalCanvas;
  239380. ScopedPointer <SavedState> currentState;
  239381. OwnedArray <SavedState> stateStack;
  239382. GlobalRef& getCanvas() const throw() { return currentState->canvas; }
  239383. jobject getCurrentPaint() const { return currentState->getPaint(); }
  239384. jobject getImagePaint() const { return currentState->getImagePaint(); }
  239385. static const LocalRef<jobject> createPath (JNIEnv* env, const Path& path)
  239386. {
  239387. jobject p = env->NewObject (android.pathClass, android.pathClassConstructor);
  239388. Path::Iterator i (path);
  239389. while (i.next())
  239390. {
  239391. switch (i.elementType)
  239392. {
  239393. case Path::Iterator::startNewSubPath: env->CallVoidMethod (p, android.moveTo, i.x1, i.y1); break;
  239394. case Path::Iterator::lineTo: env->CallVoidMethod (p, android.lineTo, i.x1, i.y1); break;
  239395. case Path::Iterator::quadraticTo: env->CallVoidMethod (p, android.quadTo, i.x1, i.y1, i.x2, i.y2); break;
  239396. case Path::Iterator::cubicTo: env->CallVoidMethod (p, android.cubicTo, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  239397. case Path::Iterator::closePath: env->CallVoidMethod (p, android.closePath); break;
  239398. default: jassertfalse; break;
  239399. }
  239400. }
  239401. return LocalRef<jobject> (p);
  239402. }
  239403. static const LocalRef<jobject> createPath (JNIEnv* env, const Path& path, const AffineTransform& transform)
  239404. {
  239405. if (transform.isIdentity())
  239406. return createPath (env, path);
  239407. Path tempPath (path);
  239408. tempPath.applyTransform (transform);
  239409. return createPath (env, tempPath);
  239410. }
  239411. static const LocalRef<jobject> createMatrixRef (JNIEnv* env, const AffineTransform& t)
  239412. {
  239413. return LocalRef<jobject> (android.createMatrix (*env, t));
  239414. }
  239415. static const LocalRef<jobject> createRect (JNIEnv* env, const Rectangle<int>& r)
  239416. {
  239417. return LocalRef<jobject> (env->NewObject (android.rectClass, android.rectConstructor,
  239418. r.getX(), r.getY(), r.getRight(), r.getBottom()));
  239419. }
  239420. static const LocalRef<jobject> createRegion (JNIEnv* env, const RectangleList& list)
  239421. {
  239422. jobject region = env->NewObject (android.regionClass, android.regionConstructor);
  239423. const int numRects = list.getNumRectangles();
  239424. for (int i = 0; i < numRects; ++i)
  239425. env->CallBooleanMethod (region, android.regionUnion, createRect (env, list.getRectangle(i)).get());
  239426. return LocalRef<jobject> (region);
  239427. }
  239428. static int colourToInt (const Colour& col) throw()
  239429. {
  239430. return col.getARGB();
  239431. }
  239432. template <class PixelType>
  239433. static void copyPixels (jint* const dest, const PixelType* src, const int width, const int pixelStride) throw()
  239434. {
  239435. for (int x = 0; x < width; ++x)
  239436. {
  239437. dest[x] = src->getUnpremultipliedARGB();
  239438. src = addBytesToPointer (src, pixelStride);
  239439. }
  239440. }
  239441. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidLowLevelGraphicsContext);
  239442. };
  239443. LowLevelGraphicsContext* AndroidImage::createLowLevelContext()
  239444. {
  239445. jobject canvas = getEnv()->NewObject (android.canvasClass, android.canvasBitmapConstructor, bitmap.get());
  239446. return new AndroidLowLevelGraphicsContext (canvas);
  239447. }
  239448. #endif
  239449. #endif
  239450. /*** End of inlined file: juce_android_GraphicsContext.cpp ***/
  239451. /*** Start of inlined file: juce_android_Windowing.cpp ***/
  239452. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  239453. // compiled on its own).
  239454. #if JUCE_INCLUDED_FILE
  239455. class AndroidComponentPeer : public ComponentPeer
  239456. {
  239457. public:
  239458. AndroidComponentPeer (Component* const component, const int windowStyleFlags)
  239459. : ComponentPeer (component, windowStyleFlags),
  239460. view (android.activity.callObjectMethod (android.createNewView, component->isOpaque())),
  239461. usingAndroidGraphics (false), sizeAllocated (0)
  239462. {
  239463. if (isFocused())
  239464. handleFocusGain();
  239465. }
  239466. ~AndroidComponentPeer()
  239467. {
  239468. if (MessageManager::getInstance()->isThisTheMessageThread())
  239469. {
  239470. android.activity.callVoidMethod (android.deleteView, view.get());
  239471. }
  239472. else
  239473. {
  239474. class ViewDeleter : public CallbackMessage
  239475. {
  239476. public:
  239477. ViewDeleter (const GlobalRef& view_)
  239478. : view (view_)
  239479. {
  239480. post();
  239481. }
  239482. void messageCallback()
  239483. {
  239484. android.activity.callVoidMethod (android.deleteView, view.get());
  239485. }
  239486. private:
  239487. GlobalRef view;
  239488. };
  239489. new ViewDeleter (view);
  239490. }
  239491. view.clear();
  239492. }
  239493. void* getNativeHandle() const
  239494. {
  239495. return (void*) view.get();
  239496. }
  239497. void setVisible (bool shouldBeVisible)
  239498. {
  239499. if (MessageManager::getInstance()->isThisTheMessageThread())
  239500. {
  239501. view.callVoidMethod (android.setVisible, shouldBeVisible);
  239502. }
  239503. else
  239504. {
  239505. class VisibilityChanger : public CallbackMessage
  239506. {
  239507. public:
  239508. VisibilityChanger (const GlobalRef& view_, bool shouldBeVisible_)
  239509. : view (view_), shouldBeVisible (shouldBeVisible_)
  239510. {
  239511. post();
  239512. }
  239513. void messageCallback()
  239514. {
  239515. view.callVoidMethod (android.setVisible, shouldBeVisible);
  239516. }
  239517. private:
  239518. GlobalRef view;
  239519. bool shouldBeVisible;
  239520. };
  239521. new VisibilityChanger (view, shouldBeVisible);
  239522. }
  239523. }
  239524. void setTitle (const String& title)
  239525. {
  239526. view.callVoidMethod (android.setViewName, javaString (title).get());
  239527. }
  239528. void setPosition (int x, int y)
  239529. {
  239530. const Rectangle<int> pos (getBounds());
  239531. setBounds (x, y, pos.getWidth(), pos.getHeight(), false);
  239532. }
  239533. void setSize (int w, int h)
  239534. {
  239535. const Rectangle<int> pos (getBounds());
  239536. setBounds (pos.getX(), pos.getY(), w, h, false);
  239537. }
  239538. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  239539. {
  239540. if (MessageManager::getInstance()->isThisTheMessageThread())
  239541. {
  239542. view.callVoidMethod (android.layout, x, y, x + w, y + h);
  239543. }
  239544. else
  239545. {
  239546. class ViewMover : public CallbackMessage
  239547. {
  239548. public:
  239549. ViewMover (const GlobalRef& view_, int x_, int y_, int w_, int h_)
  239550. : view (view_), x (x_), y (y_), w (w_), h (h_)
  239551. {
  239552. post();
  239553. }
  239554. void messageCallback()
  239555. {
  239556. view.callVoidMethod (android.layout, x, y, x + w, y + h);
  239557. }
  239558. private:
  239559. GlobalRef view;
  239560. int x, y, w, h;
  239561. };
  239562. new ViewMover (view, x, y, w, h);
  239563. }
  239564. }
  239565. const Rectangle<int> getBounds() const
  239566. {
  239567. return Rectangle<int> (view.callIntMethod (android.getLeft),
  239568. view.callIntMethod (android.getTop),
  239569. view.callIntMethod (android.getWidth),
  239570. view.callIntMethod (android.getHeight));
  239571. }
  239572. const Point<int> getScreenPosition() const
  239573. {
  239574. return Point<int> (view.callIntMethod (android.getLeft),
  239575. view.callIntMethod (android.getTop));
  239576. }
  239577. const Point<int> localToGlobal (const Point<int>& relativePosition)
  239578. {
  239579. return relativePosition + getScreenPosition();
  239580. }
  239581. const Point<int> globalToLocal (const Point<int>& screenPosition)
  239582. {
  239583. return screenPosition - getScreenPosition();
  239584. }
  239585. void setMinimised (bool shouldBeMinimised)
  239586. {
  239587. // TODO
  239588. }
  239589. bool isMinimised() const
  239590. {
  239591. return false;
  239592. }
  239593. void setFullScreen (bool shouldBeFullScreen)
  239594. {
  239595. // TODO
  239596. }
  239597. bool isFullScreen() const
  239598. {
  239599. // TODO
  239600. return false;
  239601. }
  239602. void setIcon (const Image& newIcon)
  239603. {
  239604. // TODO
  239605. }
  239606. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  239607. {
  239608. return isPositiveAndBelow (position.getX(), component->getWidth())
  239609. && isPositiveAndBelow (position.getY(), component->getHeight())
  239610. && ((! trueIfInAChildWindow) || view.callBooleanMethod (android.containsPoint, position.getX(), position.getY()));
  239611. }
  239612. const BorderSize<int> getFrameSize() const
  239613. {
  239614. // TODO
  239615. return BorderSize<int>();
  239616. }
  239617. bool setAlwaysOnTop (bool alwaysOnTop)
  239618. {
  239619. // TODO
  239620. return false;
  239621. }
  239622. void toFront (bool makeActive)
  239623. {
  239624. view.callVoidMethod (android.bringToFront);
  239625. if (makeActive)
  239626. grabFocus();
  239627. handleBroughtToFront();
  239628. }
  239629. void toBehind (ComponentPeer* other)
  239630. {
  239631. // TODO
  239632. }
  239633. void handleMouseDownCallback (float x, float y, int64 time)
  239634. {
  239635. lastMousePos.setXY ((int) x, (int) y);
  239636. currentModifiers = currentModifiers.withoutMouseButtons();
  239637. handleMouseEvent (0, lastMousePos, currentModifiers, time);
  239638. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  239639. handleMouseEvent (0, lastMousePos, currentModifiers, time);
  239640. }
  239641. void handleMouseDragCallback (float x, float y, int64 time)
  239642. {
  239643. lastMousePos.setXY ((int) x, (int) y);
  239644. handleMouseEvent (0, lastMousePos, currentModifiers, time);
  239645. }
  239646. void handleMouseUpCallback (float x, float y, int64 time)
  239647. {
  239648. lastMousePos.setXY ((int) x, (int) y);
  239649. currentModifiers = currentModifiers.withoutMouseButtons();
  239650. handleMouseEvent (0, lastMousePos, currentModifiers, time);
  239651. }
  239652. bool isFocused() const
  239653. {
  239654. return view.callBooleanMethod (android.hasFocus);
  239655. }
  239656. void grabFocus()
  239657. {
  239658. view.callBooleanMethod (android.requestFocus);
  239659. }
  239660. void handleFocusChangeCallback (bool hasFocus)
  239661. {
  239662. if (hasFocus)
  239663. handleFocusGain();
  239664. else
  239665. handleFocusLoss();
  239666. }
  239667. void textInputRequired (const Point<int>& position)
  239668. {
  239669. // TODO
  239670. }
  239671. void handlePaintCallback (JNIEnv* env, jobject canvas)
  239672. {
  239673. #if USE_ANDROID_CANVAS
  239674. if (usingAndroidGraphics)
  239675. {
  239676. AndroidLowLevelGraphicsContext g (canvas);
  239677. handlePaint (g);
  239678. }
  239679. else
  239680. #endif
  239681. {
  239682. jobject rect = env->CallObjectMethod (canvas, android.getClipBounds2);
  239683. const int left = env->GetIntField (rect, android.rectLeft);
  239684. const int top = env->GetIntField (rect, android.rectTop);
  239685. const int right = env->GetIntField (rect, android.rectRight);
  239686. const int bottom = env->GetIntField (rect, android.rectBottom);
  239687. env->DeleteLocalRef (rect);
  239688. const Rectangle<int> clip (left, top, right - left, bottom - top);
  239689. const int sizeNeeded = clip.getWidth() * clip.getHeight();
  239690. if (sizeAllocated < sizeNeeded)
  239691. {
  239692. buffer.clear();
  239693. sizeAllocated = sizeNeeded;
  239694. buffer = GlobalRef (env->NewIntArray (sizeNeeded));
  239695. }
  239696. jint* dest = env->GetIntArrayElements ((jintArray) buffer.get(), 0);
  239697. if (dest != 0)
  239698. {
  239699. {
  239700. Image temp (new PreallocatedImage (clip.getWidth(), clip.getHeight(),
  239701. dest, ! component->isOpaque()));
  239702. {
  239703. LowLevelGraphicsSoftwareRenderer g (temp);
  239704. g.setOrigin (-clip.getX(), -clip.getY());
  239705. handlePaint (g);
  239706. }
  239707. }
  239708. env->ReleaseIntArrayElements ((jintArray) buffer.get(), dest, 0);
  239709. env->CallVoidMethod (canvas, android.drawMemoryBitmap, (jintArray) buffer.get(), 0, clip.getWidth(),
  239710. (jfloat) clip.getX(), (jfloat) clip.getY(),
  239711. clip.getWidth(), clip.getHeight(), true, (jobject) 0);
  239712. }
  239713. }
  239714. }
  239715. void repaint (const Rectangle<int>& area)
  239716. {
  239717. if (MessageManager::getInstance()->isThisTheMessageThread())
  239718. {
  239719. view.callVoidMethod (android.invalidate, area.getX(), area.getY(), area.getRight(), area.getBottom());
  239720. }
  239721. else
  239722. {
  239723. class ViewRepainter : public CallbackMessage
  239724. {
  239725. public:
  239726. ViewRepainter (const GlobalRef& view_, const Rectangle<int>& area_)
  239727. : view (view_), area (area_)
  239728. {
  239729. post();
  239730. }
  239731. void messageCallback()
  239732. {
  239733. view.callVoidMethod (android.invalidate, area.getX(), area.getY(), area.getRight(), area.getBottom());
  239734. }
  239735. private:
  239736. GlobalRef view;
  239737. const Rectangle<int>& area;
  239738. };
  239739. new ViewRepainter (view, area);
  239740. }
  239741. }
  239742. void performAnyPendingRepaintsNow()
  239743. {
  239744. // TODO
  239745. }
  239746. void setAlpha (float newAlpha)
  239747. {
  239748. // TODO
  239749. }
  239750. const StringArray getAvailableRenderingEngines()
  239751. {
  239752. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  239753. s.add ("Android Canvas Renderer");
  239754. return s;
  239755. }
  239756. #if USE_ANDROID_CANVAS
  239757. int getCurrentRenderingEngine() throw()
  239758. {
  239759. return usingAndroidGraphics ? 1 : 0;
  239760. }
  239761. void setCurrentRenderingEngine (int index)
  239762. {
  239763. if (usingAndroidGraphics != (index > 0))
  239764. {
  239765. usingAndroidGraphics = index > 0;
  239766. component->repaint();
  239767. }
  239768. }
  239769. #endif
  239770. static AndroidComponentPeer* findPeerForJavaView (jobject viewToFind)
  239771. {
  239772. for (int i = getNumPeers(); --i >= 0;)
  239773. {
  239774. AndroidComponentPeer* const ap = static_cast <AndroidComponentPeer*> (getPeer(i));
  239775. jassert (dynamic_cast <AndroidComponentPeer*> (getPeer(i)) != 0);
  239776. if (ap->view == viewToFind)
  239777. return ap;
  239778. }
  239779. return 0;
  239780. }
  239781. static ModifierKeys currentModifiers;
  239782. static Point<int> lastMousePos;
  239783. private:
  239784. GlobalRef view;
  239785. GlobalRef buffer;
  239786. bool usingAndroidGraphics;
  239787. int sizeAllocated;
  239788. class PreallocatedImage : public Image::SharedImage
  239789. {
  239790. public:
  239791. PreallocatedImage (const int width_, const int height_, jint* data_, bool hasAlpha_)
  239792. : Image::SharedImage (Image::ARGB, width_, height_), data (data_), hasAlpha (hasAlpha_)
  239793. {
  239794. if (hasAlpha_)
  239795. zeromem (data_, width * height * sizeof (jint));
  239796. }
  239797. ~PreallocatedImage()
  239798. {
  239799. if (hasAlpha)
  239800. {
  239801. PixelARGB* pix = (PixelARGB*) data;
  239802. for (int i = width * height; --i >= 0;)
  239803. {
  239804. pix->unpremultiply();
  239805. ++pix;
  239806. }
  239807. }
  239808. }
  239809. Image::ImageType getType() const { return Image::SoftwareImage; }
  239810. LowLevelGraphicsContext* createLowLevelContext() { return new LowLevelGraphicsSoftwareRenderer (Image (this)); }
  239811. void initialiseBitmapData (Image::BitmapData& bm, int x, int y, Image::BitmapData::ReadWriteMode mode)
  239812. {
  239813. bm.lineStride = width * sizeof (jint);
  239814. bm.pixelStride = sizeof (jint);
  239815. bm.pixelFormat = Image::ARGB;
  239816. bm.data = (uint8*) (data + x + y * width);
  239817. }
  239818. SharedImage* clone()
  239819. {
  239820. PreallocatedImage* s = new PreallocatedImage (width, height, 0, hasAlpha);
  239821. s->allocatedData.malloc (sizeof (jint) * width * height);
  239822. s->data = s->allocatedData;
  239823. memcpy (s->data, data, sizeof (jint) * width * height);
  239824. return s;
  239825. }
  239826. private:
  239827. jint* data;
  239828. HeapBlock<jint> allocatedData;
  239829. bool hasAlpha;
  239830. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreallocatedImage);
  239831. };
  239832. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidComponentPeer);
  239833. };
  239834. ModifierKeys AndroidComponentPeer::currentModifiers = 0;
  239835. Point<int> AndroidComponentPeer::lastMousePos;
  239836. #define JUCE_VIEW_CALLBACK(returnType, javaMethodName, params, juceMethodInvocation) \
  239837. JUCE_JNI_CALLBACK (ComponentPeerView, javaMethodName, returnType, params) \
  239838. { \
  239839. AndroidComponentPeer* const peer = AndroidComponentPeer::findPeerForJavaView (view); \
  239840. if (peer != 0) \
  239841. peer->juceMethodInvocation; \
  239842. }
  239843. JUCE_VIEW_CALLBACK (void, handlePaint, (JNIEnv* env, jobject view, jobject canvas),
  239844. handlePaintCallback (env, canvas))
  239845. JUCE_VIEW_CALLBACK (void, handleMouseDown, (JNIEnv*, jobject view, jfloat x, jfloat y, jlong time),
  239846. handleMouseDownCallback ((float) x, (float) y, (int64) time))
  239847. JUCE_VIEW_CALLBACK (void, handleMouseDrag, (JNIEnv*, jobject view, jfloat x, jfloat y, jlong time),
  239848. handleMouseDragCallback ((float) x, (float) y, (int64) time))
  239849. JUCE_VIEW_CALLBACK (void, handleMouseUp, (JNIEnv*, jobject view, jfloat x, jfloat y, jlong time),
  239850. handleMouseUpCallback ((float) x, (float) y, (int64) time))
  239851. JUCE_VIEW_CALLBACK (void, viewSizeChanged, (JNIEnv*, jobject view),
  239852. handleMovedOrResized())
  239853. JUCE_VIEW_CALLBACK (void, focusChanged, (JNIEnv*, jobject view, jboolean hasFocus),
  239854. handleFocusChangeCallback (hasFocus))
  239855. ComponentPeer* Component::createNewPeer (int styleFlags, void*)
  239856. {
  239857. return new AndroidComponentPeer (this, styleFlags);
  239858. }
  239859. bool Desktop::canUseSemiTransparentWindows() throw()
  239860. {
  239861. return true; // TODO
  239862. }
  239863. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  239864. {
  239865. // TODO
  239866. return upright;
  239867. }
  239868. void Desktop::createMouseInputSources()
  239869. {
  239870. // This creates a mouse input source for each possible finger
  239871. for (int i = 0; i < 10; ++i)
  239872. mouseSources.add (new MouseInputSource (i, false));
  239873. }
  239874. const Point<int> MouseInputSource::getCurrentMousePosition()
  239875. {
  239876. return AndroidComponentPeer::lastMousePos;
  239877. }
  239878. void Desktop::setMousePosition (const Point<int>& newPosition)
  239879. {
  239880. // not needed
  239881. }
  239882. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  239883. {
  239884. // TODO
  239885. return false;
  239886. }
  239887. void ModifierKeys::updateCurrentModifiers() throw()
  239888. {
  239889. currentModifiers = AndroidComponentPeer::currentModifiers;
  239890. }
  239891. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  239892. {
  239893. return AndroidComponentPeer::currentModifiers;
  239894. }
  239895. bool Process::isForegroundProcess()
  239896. {
  239897. return true; // TODO
  239898. }
  239899. bool AlertWindow::showNativeDialogBox (const String& title,
  239900. const String& bodyText,
  239901. bool isOkCancel)
  239902. {
  239903. // TODO
  239904. }
  239905. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  239906. {
  239907. // TODO
  239908. }
  239909. bool Desktop::isScreenSaverEnabled()
  239910. {
  239911. return true;
  239912. }
  239913. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  239914. {
  239915. }
  239916. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  239917. {
  239918. monitorCoords.add (Rectangle<int> (0, 0, android.screenWidth, android.screenHeight));
  239919. }
  239920. const Image juce_createIconForFile (const File& file)
  239921. {
  239922. Image image;
  239923. // TODO
  239924. return image;
  239925. }
  239926. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  239927. {
  239928. return 0;
  239929. }
  239930. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  239931. {
  239932. }
  239933. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  239934. {
  239935. return 0;
  239936. }
  239937. void MouseCursor::showInWindow (ComponentPeer*) const {}
  239938. void MouseCursor::showInAllWindows() const {}
  239939. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  239940. {
  239941. return false;
  239942. }
  239943. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  239944. {
  239945. return false;
  239946. }
  239947. const int extendedKeyModifier = 0x10000;
  239948. const int KeyPress::spaceKey = ' ';
  239949. const int KeyPress::returnKey = 0x0d;
  239950. const int KeyPress::escapeKey = 0x1b;
  239951. const int KeyPress::backspaceKey = 0x7f;
  239952. const int KeyPress::leftKey = extendedKeyModifier + 1;
  239953. const int KeyPress::rightKey = extendedKeyModifier + 2;
  239954. const int KeyPress::upKey = extendedKeyModifier + 3;
  239955. const int KeyPress::downKey = extendedKeyModifier + 4;
  239956. const int KeyPress::pageUpKey = extendedKeyModifier + 5;
  239957. const int KeyPress::pageDownKey = extendedKeyModifier + 6;
  239958. const int KeyPress::endKey = extendedKeyModifier + 7;
  239959. const int KeyPress::homeKey = extendedKeyModifier + 8;
  239960. const int KeyPress::deleteKey = extendedKeyModifier + 9;
  239961. const int KeyPress::insertKey = -1;
  239962. const int KeyPress::tabKey = 9;
  239963. const int KeyPress::F1Key = extendedKeyModifier + 10;
  239964. const int KeyPress::F2Key = extendedKeyModifier + 11;
  239965. const int KeyPress::F3Key = extendedKeyModifier + 12;
  239966. const int KeyPress::F4Key = extendedKeyModifier + 13;
  239967. const int KeyPress::F5Key = extendedKeyModifier + 14;
  239968. const int KeyPress::F6Key = extendedKeyModifier + 16;
  239969. const int KeyPress::F7Key = extendedKeyModifier + 17;
  239970. const int KeyPress::F8Key = extendedKeyModifier + 18;
  239971. const int KeyPress::F9Key = extendedKeyModifier + 19;
  239972. const int KeyPress::F10Key = extendedKeyModifier + 20;
  239973. const int KeyPress::F11Key = extendedKeyModifier + 21;
  239974. const int KeyPress::F12Key = extendedKeyModifier + 22;
  239975. const int KeyPress::F13Key = extendedKeyModifier + 23;
  239976. const int KeyPress::F14Key = extendedKeyModifier + 24;
  239977. const int KeyPress::F15Key = extendedKeyModifier + 25;
  239978. const int KeyPress::F16Key = extendedKeyModifier + 26;
  239979. const int KeyPress::numberPad0 = extendedKeyModifier + 27;
  239980. const int KeyPress::numberPad1 = extendedKeyModifier + 28;
  239981. const int KeyPress::numberPad2 = extendedKeyModifier + 29;
  239982. const int KeyPress::numberPad3 = extendedKeyModifier + 30;
  239983. const int KeyPress::numberPad4 = extendedKeyModifier + 31;
  239984. const int KeyPress::numberPad5 = extendedKeyModifier + 32;
  239985. const int KeyPress::numberPad6 = extendedKeyModifier + 33;
  239986. const int KeyPress::numberPad7 = extendedKeyModifier + 34;
  239987. const int KeyPress::numberPad8 = extendedKeyModifier + 35;
  239988. const int KeyPress::numberPad9 = extendedKeyModifier + 36;
  239989. const int KeyPress::numberPadAdd = extendedKeyModifier + 37;
  239990. const int KeyPress::numberPadSubtract = extendedKeyModifier + 38;
  239991. const int KeyPress::numberPadMultiply = extendedKeyModifier + 39;
  239992. const int KeyPress::numberPadDivide = extendedKeyModifier + 40;
  239993. const int KeyPress::numberPadSeparator = extendedKeyModifier + 41;
  239994. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 42;
  239995. const int KeyPress::numberPadEquals = extendedKeyModifier + 43;
  239996. const int KeyPress::numberPadDelete = extendedKeyModifier + 44;
  239997. const int KeyPress::playKey = extendedKeyModifier + 45;
  239998. const int KeyPress::stopKey = extendedKeyModifier + 46;
  239999. const int KeyPress::fastForwardKey = extendedKeyModifier + 47;
  240000. const int KeyPress::rewindKey = extendedKeyModifier + 48;
  240001. #endif
  240002. /*** End of inlined file: juce_android_Windowing.cpp ***/
  240003. /*** Start of inlined file: juce_android_FileChooser.cpp ***/
  240004. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  240005. // compiled on its own).
  240006. #if JUCE_INCLUDED_FILE
  240007. void FileChooser::showPlatformDialog (Array<File>& results,
  240008. const String& title,
  240009. const File& currentFileOrDirectory,
  240010. const String& filter,
  240011. bool selectsDirectory,
  240012. bool selectsFiles,
  240013. bool isSaveDialogue,
  240014. bool warnAboutOverwritingExistingFiles,
  240015. bool selectMultipleFiles,
  240016. FilePreviewComponent* extraInfoComponent)
  240017. {
  240018. // TODO
  240019. }
  240020. #endif
  240021. /*** End of inlined file: juce_android_FileChooser.cpp ***/
  240022. /*** Start of inlined file: juce_android_WebBrowserComponent.cpp ***/
  240023. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  240024. // compiled on its own).
  240025. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  240026. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  240027. : browser (0),
  240028. blankPageShown (false),
  240029. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  240030. {
  240031. setOpaque (true);
  240032. }
  240033. WebBrowserComponent::~WebBrowserComponent()
  240034. {
  240035. }
  240036. void WebBrowserComponent::goToURL (const String& url,
  240037. const StringArray* headers,
  240038. const MemoryBlock* postData)
  240039. {
  240040. lastURL = url;
  240041. lastHeaders.clear();
  240042. if (headers != 0)
  240043. lastHeaders = *headers;
  240044. lastPostData.setSize (0);
  240045. if (postData != 0)
  240046. lastPostData = *postData;
  240047. blankPageShown = false;
  240048. }
  240049. void WebBrowserComponent::stop()
  240050. {
  240051. }
  240052. void WebBrowserComponent::goBack()
  240053. {
  240054. lastURL = String::empty;
  240055. blankPageShown = false;
  240056. }
  240057. void WebBrowserComponent::goForward()
  240058. {
  240059. lastURL = String::empty;
  240060. }
  240061. void WebBrowserComponent::refresh()
  240062. {
  240063. }
  240064. void WebBrowserComponent::paint (Graphics& g)
  240065. {
  240066. g.fillAll (Colours::white);
  240067. }
  240068. void WebBrowserComponent::checkWindowAssociation()
  240069. {
  240070. }
  240071. void WebBrowserComponent::reloadLastURL()
  240072. {
  240073. if (lastURL.isNotEmpty())
  240074. {
  240075. goToURL (lastURL, &lastHeaders, &lastPostData);
  240076. lastURL = String::empty;
  240077. }
  240078. }
  240079. void WebBrowserComponent::parentHierarchyChanged()
  240080. {
  240081. checkWindowAssociation();
  240082. }
  240083. void WebBrowserComponent::resized()
  240084. {
  240085. }
  240086. void WebBrowserComponent::visibilityChanged()
  240087. {
  240088. checkWindowAssociation();
  240089. }
  240090. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  240091. {
  240092. return true;
  240093. }
  240094. #endif
  240095. /*** End of inlined file: juce_android_WebBrowserComponent.cpp ***/
  240096. /*** Start of inlined file: juce_android_OpenGLComponent.cpp ***/
  240097. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  240098. // compiled on its own).
  240099. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  240100. // TODO
  240101. OpenGLContext* OpenGLComponent::createContext()
  240102. {
  240103. return 0;
  240104. }
  240105. void* OpenGLComponent::getNativeWindowHandle() const
  240106. {
  240107. return 0;
  240108. }
  240109. void juce_glViewport (const int w, const int h)
  240110. {
  240111. // glViewport (0, 0, w, h);
  240112. }
  240113. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  240114. OwnedArray <OpenGLPixelFormat>& results)
  240115. {
  240116. }
  240117. #endif
  240118. /*** End of inlined file: juce_android_OpenGLComponent.cpp ***/
  240119. /*** Start of inlined file: juce_android_Midi.cpp ***/
  240120. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  240121. // compiled on its own).
  240122. #if JUCE_INCLUDED_FILE
  240123. const StringArray MidiOutput::getDevices()
  240124. {
  240125. StringArray devices;
  240126. return devices;
  240127. }
  240128. int MidiOutput::getDefaultDeviceIndex()
  240129. {
  240130. return 0;
  240131. }
  240132. MidiOutput* MidiOutput::openDevice (int index)
  240133. {
  240134. return 0;
  240135. }
  240136. MidiOutput::~MidiOutput()
  240137. {
  240138. }
  240139. void MidiOutput::reset()
  240140. {
  240141. }
  240142. bool MidiOutput::getVolume (float&, float&)
  240143. {
  240144. return false;
  240145. }
  240146. void MidiOutput::setVolume (float, float)
  240147. {
  240148. }
  240149. void MidiOutput::sendMessageNow (const MidiMessage&)
  240150. {
  240151. }
  240152. MidiInput::MidiInput (const String& name_)
  240153. : name (name_),
  240154. internal (0)
  240155. {
  240156. }
  240157. MidiInput::~MidiInput()
  240158. {
  240159. }
  240160. void MidiInput::start()
  240161. {
  240162. }
  240163. void MidiInput::stop()
  240164. {
  240165. }
  240166. int MidiInput::getDefaultDeviceIndex()
  240167. {
  240168. return 0;
  240169. }
  240170. const StringArray MidiInput::getDevices()
  240171. {
  240172. StringArray devs;
  240173. return devs;
  240174. }
  240175. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  240176. {
  240177. return 0;
  240178. }
  240179. #endif
  240180. /*** End of inlined file: juce_android_Midi.cpp ***/
  240181. /*** Start of inlined file: juce_android_Audio.cpp ***/
  240182. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  240183. // compiled on its own).
  240184. #if JUCE_INCLUDED_FILE
  240185. class AndroidAudioIODevice : public AudioIODevice
  240186. {
  240187. public:
  240188. AndroidAudioIODevice (const String& deviceName)
  240189. : AudioIODevice (deviceName, "Audio"),
  240190. callback (0),
  240191. sampleRate (0),
  240192. numInputChannels (0),
  240193. numOutputChannels (0),
  240194. actualBufferSize (0),
  240195. isRunning (false)
  240196. {
  240197. numInputChannels = 2;
  240198. numOutputChannels = 2;
  240199. // TODO
  240200. }
  240201. ~AndroidAudioIODevice()
  240202. {
  240203. close();
  240204. }
  240205. const StringArray getOutputChannelNames()
  240206. {
  240207. StringArray s;
  240208. s.add ("Left"); // TODO
  240209. s.add ("Right");
  240210. return s;
  240211. }
  240212. const StringArray getInputChannelNames()
  240213. {
  240214. StringArray s;
  240215. s.add ("Left");
  240216. s.add ("Right");
  240217. return s;
  240218. }
  240219. int getNumSampleRates() { return 1;}
  240220. double getSampleRate (int index) { return sampleRate; }
  240221. int getNumBufferSizesAvailable() { return 1; }
  240222. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  240223. int getDefaultBufferSize() { return 1024; }
  240224. const String open (const BigInteger& inputChannels,
  240225. const BigInteger& outputChannels,
  240226. double sampleRate,
  240227. int bufferSize)
  240228. {
  240229. close();
  240230. lastError = String::empty;
  240231. int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  240232. activeOutputChans = outputChannels;
  240233. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  240234. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  240235. activeInputChans = inputChannels;
  240236. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  240237. numInputChannels = activeInputChans.countNumberOfSetBits();
  240238. // TODO
  240239. actualBufferSize = 0; // whatever is possible based on preferredBufferSize
  240240. isRunning = true;
  240241. return lastError;
  240242. }
  240243. void close()
  240244. {
  240245. if (isRunning)
  240246. {
  240247. isRunning = false;
  240248. // TODO
  240249. }
  240250. }
  240251. int getOutputLatencyInSamples()
  240252. {
  240253. return 0; // TODO
  240254. }
  240255. int getInputLatencyInSamples()
  240256. {
  240257. return 0; // TODO
  240258. }
  240259. bool isOpen() { return isRunning; }
  240260. int getCurrentBufferSizeSamples() { return actualBufferSize; }
  240261. int getCurrentBitDepth() { return 16; }
  240262. double getCurrentSampleRate() { return sampleRate; }
  240263. const BigInteger getActiveOutputChannels() const { return activeOutputChans; }
  240264. const BigInteger getActiveInputChannels() const { return activeInputChans; }
  240265. const String getLastError() { return lastError; }
  240266. bool isPlaying() { return isRunning && callback != 0; }
  240267. // TODO
  240268. void start (AudioIODeviceCallback* newCallback)
  240269. {
  240270. if (isRunning && callback != newCallback)
  240271. {
  240272. if (newCallback != 0)
  240273. newCallback->audioDeviceAboutToStart (this);
  240274. const ScopedLock sl (callbackLock);
  240275. callback = newCallback;
  240276. }
  240277. }
  240278. void stop()
  240279. {
  240280. if (isRunning)
  240281. {
  240282. AudioIODeviceCallback* lastCallback;
  240283. {
  240284. const ScopedLock sl (callbackLock);
  240285. lastCallback = callback;
  240286. callback = 0;
  240287. }
  240288. if (lastCallback != 0)
  240289. lastCallback->audioDeviceStopped();
  240290. }
  240291. }
  240292. private:
  240293. CriticalSection callbackLock;
  240294. AudioIODeviceCallback* callback;
  240295. double sampleRate;
  240296. int numInputChannels, numOutputChannels;
  240297. int actualBufferSize;
  240298. bool isRunning;
  240299. String lastError;
  240300. BigInteger activeOutputChans, activeInputChans;
  240301. JUCE_DECLARE_NON_COPYABLE (AndroidAudioIODevice);
  240302. };
  240303. // TODO
  240304. class AndroidAudioIODeviceType : public AudioIODeviceType
  240305. {
  240306. public:
  240307. AndroidAudioIODeviceType()
  240308. : AudioIODeviceType ("Android Audio")
  240309. {
  240310. }
  240311. void scanForDevices()
  240312. {
  240313. }
  240314. const StringArray getDeviceNames (bool wantInputNames) const
  240315. {
  240316. StringArray s;
  240317. s.add ("Android Audio");
  240318. return s;
  240319. }
  240320. int getDefaultDeviceIndex (bool forInput) const
  240321. {
  240322. return 0;
  240323. }
  240324. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  240325. {
  240326. return device != 0 ? 0 : -1;
  240327. }
  240328. bool hasSeparateInputsAndOutputs() const { return false; }
  240329. AudioIODevice* createDevice (const String& outputDeviceName,
  240330. const String& inputDeviceName)
  240331. {
  240332. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  240333. return new AndroidAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  240334. : inputDeviceName);
  240335. return 0;
  240336. }
  240337. private:
  240338. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidAudioIODeviceType);
  240339. };
  240340. AudioIODeviceType* juce_createAudioIODeviceType_Android()
  240341. {
  240342. return new AndroidAudioIODeviceType();
  240343. }
  240344. #endif
  240345. /*** End of inlined file: juce_android_Audio.cpp ***/
  240346. /*** Start of inlined file: juce_android_CameraDevice.cpp ***/
  240347. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  240348. // compiled on its own).
  240349. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  240350. // TODO
  240351. class AndroidCameraInternal
  240352. {
  240353. public:
  240354. AndroidCameraInternal()
  240355. {
  240356. }
  240357. ~AndroidCameraInternal()
  240358. {
  240359. }
  240360. private:
  240361. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidCameraInternal);
  240362. };
  240363. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  240364. : name (name_)
  240365. {
  240366. internal = new AndroidCameraInternal();
  240367. // TODO
  240368. }
  240369. CameraDevice::~CameraDevice()
  240370. {
  240371. stopRecording();
  240372. delete static_cast <AndroidCameraInternal*> (internal);
  240373. internal = 0;
  240374. }
  240375. Component* CameraDevice::createViewerComponent()
  240376. {
  240377. // TODO
  240378. return 0;
  240379. }
  240380. const String CameraDevice::getFileExtension()
  240381. {
  240382. return ".m4a"; // TODO correct?
  240383. }
  240384. void CameraDevice::startRecordingToFile (const File& file, int quality)
  240385. {
  240386. // TODO
  240387. }
  240388. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  240389. {
  240390. // TODO
  240391. return Time();
  240392. }
  240393. void CameraDevice::stopRecording()
  240394. {
  240395. // TODO
  240396. }
  240397. void CameraDevice::addListener (Listener* listenerToAdd)
  240398. {
  240399. // TODO
  240400. }
  240401. void CameraDevice::removeListener (Listener* listenerToRemove)
  240402. {
  240403. // TODO
  240404. }
  240405. const StringArray CameraDevice::getAvailableDevices()
  240406. {
  240407. StringArray devs;
  240408. // TODO
  240409. return devs;
  240410. }
  240411. CameraDevice* CameraDevice::openDevice (int index,
  240412. int minWidth, int minHeight,
  240413. int maxWidth, int maxHeight)
  240414. {
  240415. // TODO
  240416. return 0;
  240417. }
  240418. #endif
  240419. /*** End of inlined file: juce_android_CameraDevice.cpp ***/
  240420. END_JUCE_NAMESPACE
  240421. #endif
  240422. /*** End of inlined file: juce_android_NativeCode.cpp ***/
  240423. #endif
  240424. #endif